The Linux Kernel Mailing List
 help / color / mirror / Atom feed
* [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests
@ 2026-11-26  1:07 Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 01/43] sched/deadline: Keep departing bandwidth across a root domain rebuild Mathieu Desnoyers
                   ` (42 more replies)
  0 siblings, 43 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:07 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

Hi Ingo, Juri,

This series fixes bugs of SCHED_DEADLINE in 35 patches. It applies on
top of the first series [1], with its updated patch 10 [2]. This is
v11. The changes since v10 are at the end.

Most of the bugs are in the bandwidth accounting. They leave total_bw
of a root domain, or this_bw of a runqueue, wrong. The root domain then
admits deadline tasks beyond its capacity, or refuses tasks that would
fit. The other bugs give a task more runtime than its reservation, or
sort the waiters of an rt_mutex in the wrong order. Deadline tasks can
then miss their deadlines.

Three worse outcomes were found by reading, not reproduced:
- A rebuild would hit its BUG_ON() (patch 13).
- An rt_mutex owner can keep as its deadline donor a task that has
  exited. Its next refill would then read freed memory (patches 21 to
  23).
- A task would never run again (patch 27).

Patches 21 and 22 also fix the chain walk bug that patch 11 of the
first series describes.

As Juri asked, the patches come in groups, one per theme. Each group
except extra_bw ends with the test cases of deadline_bw_test that test
its fixes. The test cases of patches 25 and 26 are in patch 42.

Juri, patch 3 replaces your fix 1/4, which Ingo dropped from
sched/urgent. It records a CPU of the root domain that counts the
bandwidth, instead of taking the first active CPU of the mask. The
other three fixes are in the first series.

The groups
==========

The rebuild of the root domains' accounting (1-6):
 1  Keep the bandwidth of departing tasks across a root domain rebuild.
 2  Rebuild the root domains' accounting from the task list.
 3  Record the root domain that holds a task's bandwidth.
 4  Leave out of a rebuild a dying task that released its bandwidth.
 5  Add deadline_rebuild_test.
 6  Add the 7 test cases of deadline_bw_test for this group.

cpuset attach (7-12):
 7  Move a task's bandwidth only where an attach made room for it.
 8  Wait for an attach before rebuilding the sched domains.
 9  Make a policy or affinity change of a deadline task wait for a
    cpuset attach in progress.
 10 Give back the bandwidth an attach did not move.
 11 Reserve an attach's bandwidth in the root domain each task moves to.
 12 Add the 24 test cases of deadline_bw_test for this group.

The root domain of a task, with partitions and isolcpus=domain (13-18):
 13 Make a rebuild count a task in the root domain it runs in.
 14 Move a task's bandwidth to the root domain it runs in.
 15 Pick a CPU for a task in the root domain that counts its
    bandwidth, if the task's mask has a CPU there.
 16 Refuse to take offline the last CPU a task has in the root domain
    that counts its bandwidth. Also refuse an offline that makes a
    partition invalid and so moves a deadline task to another root
    domain.
 17 Refuse a cpuset change that leaves a deadline task no CPU in the
    root domain that counts its bandwidth.
 18 Add the 32 test cases of deadline_bw_test for this group.

extra_bw (19-20):
 19 Count only the active CPUs when a change of total_bw is spread over
    extra_bw, at an offline migration and at a rebuild.
 20 Divide that change on 64 bits: a sum of bandwidths can pass S32_MAX.

The rtmutex chain walk (21-24):
 21 Continue the chain walk when the deadline donor of a waiter
    changes, so that no owner keeps a donor that can exit.
 22 Do not stop the chain walk at an owner whose top waiter changed.
    The next owner then gets the new priority or donor.
 23 Hold a reference on the deadline donor of a boosted task.
 24 Add the 2 test cases of deadline_bw_test for this group.

Deadline boosts and the 0-lag time (25-33):
 25 Count the 0-lag time from the next period, not from the deadline.
    A constrained task then stays counted until it has paid for what it
    ran.
 26 Keep the bandwidth and the deadline of a constrained task that
    leaves the class until its next period.
 27 Replenish a throttled task that a waiter boosts while it sleeps, so
    that it runs again.
 28 When an owner refilled from its donor is deboosted and stays in the
    class, give it back the deadline and runtime of its own period.
 29 Count in this_bw the bandwidth that sched_setattr() gives a task
    already boosted into the class.
 30 Give a deadline to a task that enters the class while it waits on
    an rt_mutex.
 31 Do the same as 28 at a deboost out of the class, so that the
    task's 0-lag time comes from its own period.
 32 Give a sleeping task that FUTEX_CMP_REQUEUE_PI requeues onto an
    rt_mutex the deadline its wakeup would give it.
 33 Add the 10 test cases of deadline_bw_test for this group.

Parameter changes (34-42):
 34 Cancel the replenishment timer with the parameters.
 35 Cap the runtime left of a constrained task at dl_runtime when its
    parameters change.
 36 Check the runtime left of a task that comes back to the class
    runnable, as a wakeup does.
 37 Apply new parameters to the period in progress, at the change. A
    task that ran ahead of its reservation keeps that debt, and repays
    it at the new bandwidth. A task with no period to apply them to
    gets the check of a wakeup.
 38 Boost an owner that cannot run on its own reservation: one that is
    throttled, or past its deadline and before its next period. Run it
    on a period of its donor, at most one donor runtime per donor
    period.
 39 Boost an owner that is throttled after its waiter blocked.
 40 Reschedule a running task that its enqueue throttles.
 41 Run a boost held at its first refill on a donor period too.
 42 Add the 39 test cases of deadline_bw_test for this group.

Patch 43 moves the helpers that the three deadline selftests share to
a header.

Backporting
===========

The fixes carry Cc: stable. The test patches do not. Some fixes need
other commits:
- Patches 1 to 17 go together. Patch 3 records the root domain that
  counts a task's bandwidth. This record replaces dl_departed_cpu,
  which patch 1 adds. Patch 4 completes the task list walk of patch 2.
  Patches 4, 10, 11 and 13 to 17 use the record of patch 3. Patches 7
  to 9 fix bugs of v7.4-rc2 that patches 10 and 11 rely on.
- Patch 19 changes code that patches 1 to 17 rework, so it comes after
  them.
- Patches 21 to 23 go together. Patches 21 and 22 make the chain walk
  reach every owner. Patch 23 covers a walk that comes late.
- Patch 28 adds the held boost: dl_hold_refilled_boost(),
  dl_end_held_boost() and dl_deboost(). Patches 31, 37, 38 and 41
  build on it. Patch 27 relies on patch 21.
- Patches 23 and 39 need commit 8671bad873eb ("sched: Do not call
  __put_task_struct() on rt if pi_blocked_on is set") on stable trees
  older than v6.17.
- A backport of these patches of the first series needs patches 25
  and 26:
  - "sched/deadline: Reset the deadline and the runtime with the
    parameters" (patch 9).
  - "sched/deadline: Release the bandwidth of a task that leaves the
    class asleep" (patch 11).
  Without them, a constrained task can leave the class and come back
  before its next period. It then gets a new period at once, and more
  than its bandwidth. Patch 25 needs patch 10 of the first series,
  which adds dl_time_to_zerolag(). Neither needs another patch of this
  series. On the first series, they apply with git am -3 or a
  cherry-pick. Plain git am fails on a context line from patch 3 of
  this series.
- Patches 37 to 41 go together:
  - Patches 38 and 39 need patch 37. Patch 38 fits the saved period
    with the debt rule of patch 37. Patch 39 throttles an owner in
    dl_setattr_period(), which patch 37 adds.
  - Patch 40 needs patches 38 and 39. Patch 40 stops a running owner at
    once in its constrained gap, between its deadline and its next
    period. Without patches 38 and 39, no waiter boosts that owner. The
    waiter then waits for the owner's next period. So patch 40 comes
    after them.
  - Patch 41 needs patch 38, which adds the donor period.

Notes for the reviewers
=======================

Peter, these patches change the rtmutex code or rt_mutex_setprio():
- 21: a waiter records its deadline donor with its sort keys.
- 22: two early stops of the chain walk are removed. The first one
  also leaves an owner on an old RT priority.
- 23: a boosted task holds a reference on its donor. dl_set_donor()
  takes it with tryget_task_struct(), since it reads the donor without
  the waiter's locks.
- 28: the deadline that a deboost in the class gives back can be later
  than the deadline of the top waiter. rt_mutex_setprio() then boosts
  the task again right away.
- 30: rt_mutex_setprio() starts a period of the new donor for a
  blocked task with no parameters of its own, in dl_boost_blocked().
- 32: __rt_mutex_start_proxy_lock() refreshes the deadline of a task
  that FUTEX_CMP_REQUEUE_PI requeues, before its trylock.
- 37: rt_mutex_setprio() first deboosts a task whose parameters
  changed during the boost. It then compares the task with its top
  waiter.
- 38: rt_mutex_setprio() boosts a deadline owner that cannot run on its
  own reservation. dl_set_donor() now reports a top waiter whose donor
  is the owner itself, in a lock cycle. rt_mutex_setprio() then ends
  the boost of a deadline owner, and sets ENQUEUE_REPLENISH only when
  the owner has a donor. __setscheduler_dl_pi() does the same. A Spin
  model of the chain walk found the case.
- 39: an owner can also lose its own reservation after its waiter
  blocked. An irq_work then calls the new rt_mutex_adjust_owner(). It
  calls rt_mutex_setprio() with the top waiter, under the pi_lock, if
  that waiter must boost the owner. RT_MUTEXES now selects IRQ_WORK for
  this. try_to_take_rt_mutex() and the paths that clear pi_blocked_on
  queue the same irq_work for a deadline task with a deadline top
  waiter: it can be throttled already. The core scheduler change is in
  balance_push(): it returns in hard interrupt context, because the
  irq_work can interrupt the tail of a switch-in on a CPU going offline.

These patches also touch the core scheduler:
- 2: __sched_setscheduler() takes the new dl_accounting_mutex, without
  CONFIG_CPUSETS.
- 3: __sched_setscheduler() and dl_task_check_affinity() check a
  deadline task against the root domain that counts its bandwidth, not
  that of its runqueue.
- 7: the new set_cpus_allowed_bw_reserved() flags a move that reserved
  bandwidth, with SCA_DL_BW_RESERVED. __set_cpus_allowed_ptr_locked()
  does not skip such a move when the mask does not change.
- 9: __sched_setscheduler() and sched_setaffinity() wait for a cpuset
  attach in progress.
- 10: set_cpus_allowed_bw_reserved() reports the bandwidth it moved.
- 11: __set_cpus_allowed_ptr_locked() steers a task to the CPU that an
  attach reserved.
- 15: select_fallback_rq() and __set_cpus_allowed_ptr_locked() keep a
  deadline task in its root domain.
- 37: __setscheduler_params() marks a task that comes back to the
  deadline policy with the same parameters. Its runtime left is then
  checked as at a wakeup.

Waiman, patches 16 and 17 add refusals, with admission control on:
- A CPU offline or a cpuset.cpus write fails with EBUSY if it leaves a
  deadline task no CPU in the root domain that counts it. This needs a
  cpuset with CPUs of two root domains.
- A write that makes a partition root, or makes it grow, still
  succeeds in that case. cpuset then makes the partition invalid, and
  cpuset.cpus.partition reads "root invalid (Deadline task would leave
  its root domain)".
- Patch 16 also refuses an offline that makes a child or a sibling
  partition invalid, when a deadline task in it would change root
  domain.

An offline can leave a partition root with tasks and no CPU of its own.
cpuset then makes it invalid, and its tasks count in its parent. If the
parent has no CPU of its own either, the order of the cpuset updates
decides where the tasks end. cpuset updates a parent before its
children. So the parent stays valid, with tasks and no CPU. It takes
the CPUs of the next child partition that cpuset updates, if there is
one. Else a later hotplug event decides. In v11, patch 16 no longer
models that order. The known limits below say what it then refuses,
and what it misses.

Questions
=========

Waiman, two questions on patch 16:
- Would you prefer cpuset to offer a dry run of its hotplug update, as
  a follow-up? It would be exact, but too large for stable.
- An offline can leave a partition valid with tasks and no CPU, until
  the next hotplug event. Is that state intended?

Ingo, Juri, a question on patches 25 and 26. Would you rather have
them in the first series, after its patch 10? Patches 9 and 11 there
need them (see Backporting).

Peter, Juri, a question on patch 37. Would you take a follow-up for
tasks with an implicit deadline? It would keep the old bandwidth
counted until the 0-lag time, as the XXX in sched_dl_overflow()
suggests. A change could then start a new period at once. It would
fail with EBUSY when the old and the new bandwidth do not fit together.
In the user-space model of the CBS (see "How this was developed"),
this is sound for an implicit deadline only. For a constrained
deadline, admission by bandwidth needs a whole period between the
releases of two jobs. A period started at the change can release a job
sooner. So a constrained task would keep the rule of patch 37.

Peter, Juri, a question on patch 37. It is large: it adds about 600
lines. It is one rule, applied in several places that depend on each
other, so I kept it whole. Would you like it split?

Juri, a question on the waiters of an rt_mutex (see the known limits).
Should a waiter that gets the lock past its deadline go on with its
late job, as a queued task past its deadline does? That changes the
CBS rules, so I left it out.

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

These limits stay open:
- Patch 1: a rebuild still drops the bandwidth that a task keeps after
  it leaves the class or dies. This happens if the CPU recorded with
  that bandwidth is inactive. It also happens if the task dies, or a
  deboost takes it out of the class, while the rebuild runs.
- Patch 14 moves the bandwidth of a task to the root domain it runs in
  with no check for room. dl_task_offline_migration() does the same on
  v7.4-rc2.
- Patch 15: a wakeup inside a rebuild of the sched domains can still
  move a task's bandwidth to another root domain. It moves with no
  check for room. This was found by reading.
- Patches 16 and 17 refuse nothing during a suspend, or with admission
  control off.
- Patch 16 can refuse an offline that keeps each task in its root
  domain. This needs nested partitions whose parents have no CPU of
  their own.
- Patch 16 does not check a deadline task that enters a partition after
  an offline left a parent partition valid with tasks and no CPU. The
  next hotplug event, an online too, can then move it to another root
  domain with no check for room.
- Patch 16 does not see a task that sched_setattr() makes a deadline
  task during the offline. That task can then run in a root domain
  that did not admit it. The bandwidth test of dl_bw_deactivate() has
  the same window. This was found by reading.
- Patch 17 accepts a write that grows a partition root and makes a
  child partition valid. The child takes the CPUs on which the
  parent's deadline tasks were admitted. Those tasks then run on the
  CPUs that the parent just got, in a root domain that did not admit
  them. On v7.4-rc2,
  a rebuild does the same.
- Patch 17 does not count the CPUs that the rebuild gives to an
  isolated partition root. When such a root grows, the check can make
  a valid child partition of it invalid, until the next update of that
  child. So it refuses too much, never too little.
- The XXX in dl_bw_capacity(), which Juri pointed at in the v5 thread,
  stays open. In the default root domain, admission control counts the
  capacity of all its CPUs, not that of the CPU the task runs on. A
  deadline task in a cpuset with isolated and housekeeping CPUs is
  admitted that way.
- A cpuset attach frees the bandwidth of a task in the root domain it
  leaves at once, even before the task's 0-lag time. That root domain
  can then admit a task up to one period too early [3]. A task moved
  while runnable also keeps its runtime and deadline in the root domain
  it arrives in (Example 3 of [4]). Both are as on v7.4-rc2. A
  follow-up series can keep the bandwidth counted in the source until
  the 0-lag time.
- Patch 37: admission control releases the old bandwidth at the
  change. Right after a cut of bandwidth, a task admitted into the
  released bandwidth can rarely miss a deadline near the change.
- Patch 37: two costs fall on the task that changes its parameters.
  With a constrained deadline, a job that already used the new
  dl_runtime ends at the change. A task that waits for its next period
  and changes its constrained dl_deadline back and forth moves that
  period later at each shorter dl_deadline.
- Patch 37: a change of a boosted task applies at its deboost, or at
  the refill that holds the boost. Until then, a lower bandwidth is not
  enforced, as on v7.4-rc2.
- Patch 38 limits the boosts of each owner, not of each donor. A waiter
  that boosts N throttled owners in turn gives them N donor runtimes
  per donor period. The limit also needs a donor with an implicit
  deadline. With a constrained donor, a wakeup after the deadline of
  the donor period still starts a new one, as on v7.4-rc2.
- A waiter of an rt_mutex keeps the deadline it blocked with, as on
  v7.4-rc2. That deadline can pass while it waits, and the waiter still
  sorts first. An unlock wakes the top waiter, which must run to take
  the lock. A constrained waiter woken past its deadline is throttled
  until its next period. Meanwhile the lock has no owner, so no other
  waiter can boost anyone. This lasts up to dl_period - dl_deadline.
  Two other kinds of waiter also sort first with a passed deadline, in
  their constrained gap:
  - a task that FUTEX_CMP_REQUEUE_PI requeues (patch 32). In a test
    outside this series, another waiter then waited 442ms for the lock.
  - a task that comes back to the class while it waits (patch 30).
- Patch 39 does not boost an owner while it waits for another
  rt_mutex, with its pi_blocked_on set. Its new donor would need a
  chain walk, which cannot run in the hard interrupt context of the
  boost. The owner asks again when it takes that lock or stops waiting
  on it. If it is throttled before then, it cannot run to take the
  lock. Its waiters then wait for its next period, as on v7.4-rc2. The
  same holds for an owner throttled after a yield.

Testing
=======

On top of the first series, the 169 test cases of the three deadline
selftests pass wherever they run, with lockdep and no kernel warning.
deadline_bw_test has 161 of them. They ran in 20 QEMU guests of 4 to 8
vCPUs:
- with proxy execution on and off.
- with PREEMPT_RT.
- without CONFIG_CPUSETS.
- with CONFIG_RT_GROUP_SCHED.
- booted with isolcpus=domain on CPUs 1-2, 0-1 or 6-7, some with
  PREEMPT_RT.
The 26 test cases that need isolated CPUs skip in the guests without
them.
No guest combines isolcpus=domain with a kernel without CONFIG_CPUSETS:
such a kernel hits a BUG at boot on v7.4-rc2 [5].

At each test patch, the kernel and the test cases of that patch pass
in 12 guests of the same kinds. Three guests with kmemleak ran the
whole series: no leak.

On top of the first series, the series builds at each of its 43
patches. At each patch, it also builds with tinyconfig, without
CONFIG_RT_MUTEXES. At each test patch, the series also builds without
CONFIG_CPUSETS, with PREEMPT_RT and with CONFIG_RT_GROUP_SCHED. The
selftests build there with no warning. The cpuset selftest
test_cpuset_prs.sh passes, with and without PREEMPT_RT.

Each fix names the test cases that test it. Patch 42 names, for each
test case of its group, the fix it tests. The other test patches list
the test cases that fail on v7.4-rc2. These changes have no test case:
- patches 4, 19 and 27: they were found by reading.
- patch 20: it needs a machine with more than 2048 CPUs.
- the second early stop that patch 22 removes, and patch 23: they need
  a chain walk preempted at the right step.
- patch 29: a reproducer outside the selftests shows it.
- patch 34: it has no reproducer.
- patch 40: its test case passes from patch 37 on, which also
  reschedules a task that sched_setattr() throttles.
- the change of patch 15 in dl_task_offline_migration(): it needs a
  timer that fires between a CPU going inactive and the cpuset update.
- in patch 38, an owner past its deadline and not in its constrained
  gap: it was found by reading.
- one change of v11 in each of patches 3, 13, 16, 28 and 32. They were
  found by reading.

These were not tested:
- cgroup v1 cpusets.
- threaded cgroups: every move is a write to cgroup.procs.
- the sched_ext server.
- CPUs of unequal capacity.

How this was developed
======================

An LLM coding assistant wrote these patches, their messages and the
tests, under my direction and review. I know the concepts behind
SCHED_DEADLINE, but not its implementation well. So I ask those who
know this code for a careful reading of the fixes. A reproducer that
stops failing shows that the symptom goes away. It does not show that
the fix is the one you would have written.

The bugs came from:
- flaky cgroup selftests of a feature I am developing.
- the review of Juri's four fixes, and his review of v5.
- building deadline_bw_test, and reading the code.
- the Sashiko AI reviews of v1 to v10, and of the first series, plus a
  local run on the patches that changed for v11. Each finding was
  checked against the code first.
- second LLM reads of the fixes and of the harder findings. They found
  the gaps fixed in patches 15, 16, 23 and 30. One of them also
  proposed the design of patches 38 and 39.
- kmemleak, which found a leaked task_struct in an early version of
  patch 23.

The rule of patch 37 was first checked in a user-space model of the
CBS on one CPU. Two independent LLM reviews of that model found the
problem of a task that moves to a constrained deadline, which patch 37
now covers.

For v11, the assistant extended that model into a simulator of
SCHED_DEADLINE on one CPU. It models these parts:
- EDF over several tasks, and the CBS rules.
- admission control on total_bw.
- class changes, and rt_mutexes with priority inheritance.
It has the rules of this series, transcribed by hand from the code. A
search over small task sets, random and adversarial, checks two
properties:
- no task gets more than its bandwidth.
- an admitted task meets its deadlines.
Without rt_mutexes, the series shows two exceptions only:
- the transient after a cut of bandwidth, which the known limits
  state.
- misses in task sets with a density above 1, which admission by
  bandwidth does not exclude for constrained deadlines.
With rt_mutexes, the search found the cases that the caps of the
runtime in patches 28 and 38 now cover. The search was not run again
after those fixes. The simulator also replays several test cases, and
Example 1 of [4]. It is not part of this series. I can share it.

The assistant also wrote a Spin model of the priority inheritance
boost. It models rt_mutex_setprio(), dl_set_donor(), the rtmutex chain
walk and the boost flags of the series. It has three deadline tasks and
two or three locks, with a step per lock section. Spin found that a
lock cycle can make a boosted owner its own donor with its boost still
held: 9 steps, with no timeout. The fix is in patch 38. The model finds
no error with it, within the bounds searched: 13 steps for three tasks
and two locks. The model was first checked by finding a known bug of
the chain walk again. It is sequentially consistent, so it does not
cover the memory ordering of dl_set_donor(). It is not part of this
series either. I can share it.

Changes since v10
=================

Patch numbers are those of v11. These v10 patches have a new number:
- 25 is now 28, and 26 is now 27.
- 27 to 34 are now 29 to 36.
- 35 and 37 are merged into 37.
- 36 is now 40.
- 38 is now split into 38 and 39.
- 39 and 40 are now 42 and 43.
Patches 25, 26 and 41 are new. Most changes come from the Sashiko AI review
of v10, and most of these come with a new test case. Those marked
"(local)" come from a local Sashiko run on a draft of v11:
- 3: for a task asleep on a CPU that went offline, sched_setattr() now
  tests the root domain of an active CPU of the task's mask.
  sched_setaffinity() tests a task with a bandwidth of 0 the same way.
- 13: a rebuild no longer leaves out a task that left the class before
  its 0-lag time, when its mask has no active CPU. It counts the task
  on the CPU recorded, if that CPU is active. Its comments were also
  fixed (local).
- 14: follows the change of 13. The lock that 13 now takes covers the
  write of dl_bw_skip_gen.
- 16: the order of the cpuset updates is no longer modelled: see the
  paragraph to Waiman. A task with no root-domain bandwidth, such as a
  sugov kthread, does not count.
- 17: a dead task passes the check.
- 28 now gives an owner refilled from its donor the deadline and
  runtime of its own period back, instead of a new period. A new period
  gave it its runtime again, in a period whose runtime it had used.
  task_non_contending() takes a 0-lag time of exactly now as passed
  (local). A refill from a donor whose parameters were cleared counts
  as a refill.
- The order changed in two places, after a review of each patch on
  its own tree. 27 now comes before 28: at 28 alone, a sleeping owner
  could be left throttled with no timer. 40 now comes after 38 and 39:
  before them, a waiter would not boost an owner that 40 stops in its
  constrained gap.
- 30: a task can come back to the class in its constrained gap while
  it waits on an rt_mutex. It keeps its deadline, unless it is boosted.
- 31 does the same as 28 out of the class. The owner's bandwidth then
  stays counted until the 0-lag time of its own period, not released at
  once.
- 32: dl_proxy_block() runs before the trylock of a proxy lock, and
  applies the wakeup rule. futex_lock_pi() does not call it: its task
  is running. The message and a comment say that a requeued task in its
  constrained gap keeps its passed deadline (local).
- 33: three test cases now expect the owner's own period back after a
  refill.
- 37 merges v10's "Check the runtime of a task whose parameters change"
  and "Keep the start of the period across a change of dl_deadline".
  In v10, the first of them broke a test case that passes on v7.4-rc2,
  and the second fixed it again. A change now applies to the period in
  progress at once. A task that comes back to the class with new
  parameters gets its period fitted to them. It no longer also gets the
  check of a wakeup. 37 also changes the expectation of
  params_switched_asleep, a test case of the first series. A task that
  ran ahead and then leaves the class now stays counted by admission
  control until its debt is repaid. This holds for a boosted task too:
  its 0-lag time counts from its period fitted to the new parameters.
- 38 and 39 were one patch in v10, as 38. An owner boosted while it
  cannot run on its own reservation now gets a period of its donor at
  the boost (38). A new boost within that donor period resumes it. So
  repeated boosts give the owner at most one donor runtime per donor
  period, with the runtime capped by the donor's density. At the
  deboost, an owner whose saved runtime is used up is throttled again.
  It gets a period of its own if the saved one has ended. An owner that
  loses its own reservation after its waiter blocked is now boosted
  then (39). Four events do that:
  - it runs out of runtime.
  - an enqueue in its constrained gap throttles it.
  - sched_setattr() throttles it until it repays its debt.
  - it takes a lock with waiters while throttled, or stops waiting on
    another lock.
  A yield no longer discards the donor period of a held boost.
  A lock cycle can no longer leave the owner its own donor with its
  boost held (see "How this was developed").
- 41 is new. The first refill of any other boost also gets a donor
  period, resumed from the last held boost.
- Tests: deadline_bw_test has 29 new test cases. It drops
  boost_new_params_stale, which tested a boost from pi_top_task. That
  is no longer how patch 38 finds the donor. The test patches pin a
  test to its CPUs, add skips, and fix error paths that could hang. One
  of these fixes (local) ends a hang of deadline_bw_test when a waiter
  is refused the deadline policy. Patch 43 makes the Makefile rebuild
  the tests when their header changes.
- The messages of most fixes were reorganized: the problem and the fix
  first, then the cases as lists.

The first series is based on tip sched/urgent, ec6f6731538e (v7.4-rc2).

[1] https://lore.kernel.org/all/cover.1795115075.git.mathieu.desnoyers@efficios.com/
[2] https://lore.kernel.org/all/d975f317a4f9f79d2300b68ad76664755459ba36.1795181168.git.mathieu.desnoyers@efficios.com/
[3] T. Cucinotta, L. Abeni, "Migrating Constant Bandwidth Servers on
    Multi-Cores", RTNS 2021, section 4
[4] 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, https://doi.org/10.1145/3453417.3453440
[5] https://lore.kernel.org/lkml/20261117144817.265109-1-mathieu.desnoyers@efficios.com/
v10: https://lore.kernel.org/all/cover.1795207232.git.mathieu.desnoyers@efficios.com/
v9: https://lore.kernel.org/all/cover.1795181240.git.mathieu.desnoyers@efficios.com/
v8: https://lore.kernel.org/all/cover.1795116790.git.mathieu.desnoyers@efficios.com/
v7: https://lore.kernel.org/all/cover.1794922146.git.mathieu.desnoyers@efficios.com/
v6: https://lore.kernel.org/all/20261116190549.230119-1-mathieu.desnoyers@efficios.com/
v5: https://lore.kernel.org/all/20261108185406.1549770-1-mathieu.desnoyers@efficios.com/
v4: https://lore.kernel.org/all/20261107014451.1487825-1-mathieu.desnoyers@efficios.com/

Mathieu Desnoyers (43):
  sched/deadline: Keep departing bandwidth across a root domain rebuild
  sched/deadline: Rebuild the root domains' accounting from the task
    list
  sched/deadline: Record the root domain holding a task's bandwidth
  sched/deadline: Leave a dying task out of a rebuild of the accounting
  selftests/sched: Test SCHED_DEADLINE bandwidth across a root domain
    rebuild
  selftests/sched: Test the root domain rebuild in deadline_bw_test
  sched/deadline: Move a task's bandwidth only where room was made
  cgroup/cpuset: Wait for an attach before rebuilding the sched domains
  sched: Make deadline policy and affinity changes wait for a cpuset
    attach
  cgroup/cpuset: Give back the bandwidth an attach did not move
  cgroup/cpuset: Reserve the bandwidth in the root domain a task moves
    to
  selftests/sched: Test cpuset moves in deadline_bw_test
  sched/deadline: Make a rebuild count a task in the root domain it runs
    in
  sched/deadline: Move a task's bandwidth to the root domain it runs in
  sched/deadline: Keep a task in the root domain that counts its
    bandwidth
  sched/deadline: Keep the last CPU a task has in its root domain
  cgroup/cpuset: Refuse to take a deadline task out of its root domain
  selftests/sched: Test the root domain of a task in deadline_bw_test
  sched/deadline: Count only active CPUs when spreading extra_bw
  sched/deadline: Do not truncate a bandwidth to 32 bits in
    __dl_add/sub()
  rtmutex: Continue the chain walk when a waiter's deadline donor
    changes
  rtmutex: Do not stop the chain walk at an owner whose top waiter
    changed
  sched/deadline: Hold a reference on the deadline donor of a boosted
    task
  selftests/sched: Test the rtmutex chain walk in deadline_bw_test
  sched/deadline: Count the 0-lag time from the next period
  sched/deadline: Keep a departing constrained task until its next
    period
  sched/deadline: Replenish a throttled task boosted while asleep
  sched/deadline: Restore the owner's period at a deboost in the class
  sched/deadline: Count the bandwidth a boosted task is given
  sched/deadline: Start a period for a task that enters the class
    blocked
  sched/deadline: Restore the owner's period at a deboost out of the
    class
  sched/deadline: Start a period for a task requeued onto an rt_mutex
  selftests/sched: Test deadline boosts in deadline_bw_test
  sched/deadline: Cancel the replenishment timer with the parameters
  sched/deadline: Cap the runtime left of a constrained task at
    dl_runtime
  sched/deadline: Check the runtime of a task that comes back runnable
  sched/deadline: Keep the debt of a task across a change of parameters
  sched/deadline: Boost an owner that cannot run on its own reservation
  sched/deadline: Boost an owner throttled after its waiter blocked
  sched/deadline: Reschedule a running task throttled at its enqueue
  sched/deadline: Run a boost held at its first refill on a donor period
  selftests/sched: Test parameter changes in deadline_bw_test
  selftests/sched: Share the helpers of the deadline tests

 Documentation/scheduler/sched-deadline.rst    |    12 +-
 include/linux/cpuset.h                        |    28 +-
 include/linux/sched.h                         |   106 +
 include/linux/sched/deadline.h                |    42 +-
 include/linux/sched/rt.h                      |     4 +
 init/Kconfig                                  |     1 +
 kernel/cgroup/cgroup.c                        |     3 -
 kernel/cgroup/cpuset-internal.h               |    15 +-
 kernel/cgroup/cpuset.c                        |   825 +-
 kernel/locking/rtmutex.c                      |    76 +-
 kernel/locking/rtmutex_api.c                  |    41 +-
 kernel/locking/rtmutex_common.h               |     3 +
 kernel/sched/core.c                           |   193 +-
 kernel/sched/deadline.c                       |  2507 +++-
 kernel/sched/sched.h                          |    94 +
 kernel/sched/syscalls.c                       |   126 +-
 kernel/sched/topology.c                       |    11 +
 .../selftests/sched/deadline/.gitignore       |     1 +
 .../testing/selftests/sched/deadline/Makefile |     4 +-
 .../sched/deadline/deadline_bw_test.c         | 10849 +++++++++++++++-
 .../sched/deadline/deadline_rebuild_test.c    |   501 +
 .../sched/deadline/deadline_switch_test.c     |    36 +-
 .../selftests/sched/deadline/deadline_util.h  |   106 +
 23 files changed, 14998 insertions(+), 586 deletions(-)
 create mode 100644 tools/testing/selftests/sched/deadline/deadline_rebuild_test.c
 create mode 100644 tools/testing/selftests/sched/deadline/deadline_util.h


base-commit: ec6f6731538e0d45872eb279fdeb477bed152d6f
prerequisite-patch-id: 5e2478ffdfb7583751bf44bdf87fb930bc23551b
prerequisite-patch-id: d5e5ef986ff2d9bc39a87b56e96a2acbd3158687
prerequisite-patch-id: 99e47f80396008ee2b2576157d37842481ce52d2
prerequisite-patch-id: a10824f98c11a4c902dad55cab3ec03b3dbe2c8a
prerequisite-patch-id: 8959e5a408641b4fa81bc79737cd17d5f1b03389
prerequisite-patch-id: 16acf1d18f01d20310d6db767dfbec2f072e0372
prerequisite-patch-id: e1946bb015a7b14ed4e2cd0421e5e30b0c7afdda
prerequisite-patch-id: 4daf48a89779fbd8c8bc5fc1d7a7d6df9bca2d9d
prerequisite-patch-id: 980d8045f9fe8c3757bb3d82c61d68e321cf74bb
prerequisite-patch-id: b2d75d7b3eebbda11af43b3917b1c99e0cce2725
prerequisite-patch-id: fb69a0665dc38ca9022cc2bd75234a90e2035b7f
prerequisite-patch-id: 7a115ab83ad96ffaf8e833e0eaeb75f859af2e79
prerequisite-patch-id: 8574b50d81a09ec6091e42d65338adcab2986d71
prerequisite-patch-id: 1aa25df96d60d30f549c71fdfba5589cb239928f
prerequisite-patch-id: d38384e0b7d043a3556ee02fb09316a6227038da
prerequisite-patch-id: 83ded04a76ecf973e2b8c6e04ff83c2b7278915a
prerequisite-patch-id: b8f5d9f9146e887050bbd8ad30463fd81cad9411
-- 
2.47.3


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

* [PATCH v11 01/43] sched/deadline: Keep departing bandwidth across a root domain rebuild
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 02/43] sched/deadline: Rebuild the root domains' accounting from the task list Mathieu Desnoyers
                   ` (41 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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] 59+ messages in thread

* [PATCH v11 02/43] sched/deadline: Rebuild the root domains' accounting from the task list
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 01/43] sched/deadline: Keep departing bandwidth across a root domain rebuild Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 03/43] sched/deadline: Record the root domain holding a task's bandwidth Mathieu Desnoyers
                   ` (40 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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] 59+ messages in thread

* [PATCH v11 03/43] sched/deadline: Record the root domain holding a task's bandwidth
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 01/43] sched/deadline: Keep departing bandwidth across a root domain rebuild Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 02/43] sched/deadline: Rebuild the root domains' accounting from the task list Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 04/43] sched/deadline: Leave a dying task out of a rebuild of the accounting Mathieu Desnoyers
                   ` (39 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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] 59+ messages in thread

* [PATCH v11 04/43] sched/deadline: Leave a dying task out of a rebuild of the accounting
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (2 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 03/43] sched/deadline: Record the root domain holding a task's bandwidth Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 05/43] selftests/sched: Test SCHED_DEADLINE bandwidth across a root domain rebuild Mathieu Desnoyers
                   ` (38 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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] 59+ messages in thread

* [PATCH v11 05/43] selftests/sched: Test SCHED_DEADLINE bandwidth across a root domain rebuild
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (3 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 04/43] sched/deadline: Leave a dying task out of a rebuild of the accounting Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 06/43] selftests/sched: Test the root domain rebuild in deadline_bw_test Mathieu Desnoyers
                   ` (37 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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

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

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

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

P and Q take the two highest online CPUs that are not isolated. The test
skips without root, 3 such CPUs, the cgroup v2 cpuset controller or
deadline admission control. Admission control is off when
sched_rt_runtime_us is -1. The test sets its affinity to the online CPUs
that are not isolated. Otherwise, a change of partitions would let its
deadline tasks run on an isolated CPU.

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

Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
 .../selftests/sched/deadline/.gitignore       |   1 +
 .../testing/selftests/sched/deadline/Makefile |   2 +-
 .../sched/deadline/deadline_rebuild_test.c    | 587 ++++++++++++++++++
 3 files changed, 589 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/sched/deadline/deadline_rebuild_test.c

diff --git a/tools/testing/selftests/sched/deadline/.gitignore b/tools/testing/selftests/sched/deadline/.gitignore
index 5a572318e1ba..42f6b2945e96 100644
--- a/tools/testing/selftests/sched/deadline/.gitignore
+++ b/tools/testing/selftests/sched/deadline/.gitignore
@@ -1,2 +1,3 @@
 deadline_switch_test
+deadline_rebuild_test
 deadline_bw_test
diff --git a/tools/testing/selftests/sched/deadline/Makefile b/tools/testing/selftests/sched/deadline/Makefile
index c3156059bdcf..15f1e96a21e6 100644
--- a/tools/testing/selftests/sched/deadline/Makefile
+++ b/tools/testing/selftests/sched/deadline/Makefile
@@ -3,6 +3,6 @@
 CFLAGS += -O2 -Wall -g -I./ $(KHDR_INCLUDES)
 LDLIBS += -lpthread
 
-TEST_GEN_PROGS := deadline_switch_test deadline_bw_test
+TEST_GEN_PROGS := deadline_switch_test deadline_rebuild_test deadline_bw_test
 
 include ../../lib.mk
diff --git a/tools/testing/selftests/sched/deadline/deadline_rebuild_test.c b/tools/testing/selftests/sched/deadline/deadline_rebuild_test.c
new file mode 100644
index 000000000000..735c3c65e156
--- /dev/null
+++ b/tools/testing/selftests/sched/deadline/deadline_rebuild_test.c
@@ -0,0 +1,587 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Test the bandwidth of a SCHED_DEADLINE task that leaves the policy, or
+ * dies, before its 0-lag time. The bandwidth stays in the task's root
+ * domain until the inactive timer removes it. It must be removed once,
+ * from the root domain that holds it.
+ *
+ * P is a partition root of one CPU. In each case the task is a deadline
+ * task of 400ms every second, which first runs 380ms. The cases are:
+ * - dies_before_rebuild: the task is in P and exits. Before its 0-lag
+ *   time, the test makes a second partition root, Q. This rebuilds the
+ *   accounting of every root domain.
+ * - switched_out_before_rebuild: the same, but the task switches to
+ *   SCHED_OTHER and sleeps instead of exiting.
+ * - moved_after_switch_out: the task is outside P. It switches to
+ *   SCHED_OTHER and sleeps. Before its 0-lag time, the test moves it into
+ *   P and kills it there.
+ *
+ * Once the inactive timer has fired, P must admit one task of 600ms
+ * every second, and refuse a second one with EBUSY. A kernel with the
+ * bug removes the bandwidth from P's root domain after the rebuild
+ * dropped it, or when P never had it. total_bw of that root domain then
+ * wraps around, and P admits both tasks.
+ *
+ * P and Q take the two highest online CPUs that are not isolated. The
+ * test needs root, 3 such CPUs, the cgroup v2 cpuset controller and
+ * deadline admission control.
+ */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <sched.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "../../kselftest.h"
+
+#ifndef SCHED_DEADLINE
+#define SCHED_DEADLINE	6
+#endif
+
+#define NSEC_PER_MSEC	1000000ULL
+#define NSEC_PER_SEC	1000000000ULL
+
+struct dl_attr {
+	uint32_t size;
+	uint32_t sched_policy;
+	uint64_t sched_flags;
+	int32_t sched_nice;
+	uint32_t sched_priority;
+	uint64_t sched_runtime;
+	uint64_t sched_deadline;
+	uint64_t sched_period;
+};
+
+static char root[PATH_MAX], cg_p[PATH_MAX], cg_q[PATH_MAX];
+static int cpu_p, cpu_q;
+static pid_t test_pid;
+
+static int set_deadline(pid_t pid, uint64_t runtime)
+{
+	struct dl_attr attr = {
+		.size = sizeof(attr),
+		.sched_policy = SCHED_DEADLINE,
+		.sched_runtime = runtime,
+		.sched_deadline = NSEC_PER_SEC,
+		.sched_period = NSEC_PER_SEC,
+	};
+
+	return syscall(__NR_sched_setattr, pid, &attr, 0) ? -errno : 0;
+}
+
+static int set_other(pid_t pid)
+{
+	struct sched_param sp = { .sched_priority = 0 };
+
+	return sched_setscheduler(pid, SCHED_OTHER, &sp) ? -errno : 0;
+}
+
+/*
+ * Return the CLOCK_MONOTONIC time in ns. clock_gettime() cannot fail: the
+ * clock is always supported, and the pointer is valid.
+ */
+static uint64_t now_ns(void)
+{
+	struct timespec ts;
+
+	clock_gettime(CLOCK_MONOTONIC, &ts);
+	return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
+}
+
+static void sleep_ns(uint64_t ns)
+{
+	struct timespec ts = { .tv_sec = ns / NSEC_PER_SEC, .tv_nsec = ns % NSEC_PER_SEC };
+
+	while (nanosleep(&ts, &ts) && errno == EINTR)
+		;
+}
+
+static void reap(pid_t pid)
+{
+	int status;
+
+	if (pid <= 0)
+		return;
+	if (kill(pid, SIGKILL) && errno != ESRCH)
+		ksft_print_msg("kill %d: %s\n", pid, strerror(errno));
+	/* Ignore the result: the task may be dead already. */
+	set_other(pid);
+	while (waitpid(pid, &status, 0) != pid) {
+		if (errno == EINTR)
+			continue;
+		ksft_print_msg("waitpid %d: %s\n", pid, strerror(errno));
+		break;
+	}
+}
+
+static int write_file(const char *dir, const char *name, const char *val)
+{
+	char path[PATH_MAX];
+	int fd, err = 0;
+	ssize_t n;
+
+	if (snprintf(path, sizeof(path), "%s/%s", dir, name) >= (int)sizeof(path))
+		return -ENAMETOOLONG;
+	fd = open(path, O_WRONLY);
+	if (fd < 0)
+		return -errno;
+	n = write(fd, val, strlen(val));
+	if (n < 0)
+		err = -errno;
+	else if (n != (ssize_t)strlen(val))
+		err = -EIO;
+	if (close(fd) && !err)
+		err = -errno;
+	return err;
+}
+
+static int read_file(const char *path, char *buf, size_t len)
+{
+	int fd = open(path, O_RDONLY);
+	ssize_t n;
+
+	if (fd < 0)
+		return -1;
+	do {
+		n = read(fd, buf, len - 1);
+	} while (n < 0 && errno == EINTR);
+	close(fd);
+	if (n < 0)
+		return -1;
+	buf[n] = 0;
+	return 0;
+}
+
+static int enter(const char *cg, pid_t pid)
+{
+	char buf[16];
+
+	snprintf(buf, sizeof(buf), "%d", pid);
+	return write_file(cg, "cgroup.procs", buf);
+}
+
+/* Make @cg a partition root of CPU @cpu alone. Return 0, or -1 on error. */
+static int make_partition(const char *cg, int cpu)
+{
+	char path[PATH_MAX + 32], buf[32];
+
+	if (mkdir(cg, 0755) && errno != EEXIST)
+		return -1;
+	snprintf(buf, sizeof(buf), "%d", cpu);
+	if (write_file(cg, "cpuset.cpus", buf) || write_file(cg, "cpuset.cpus.partition", "root"))
+		return -1;
+	snprintf(path, sizeof(path), "%s/cpuset.cpus.partition", cg);
+	if (read_file(path, buf, sizeof(buf)) || strcmp(buf, "root\n"))
+		return -1;
+	return 0;
+}
+
+static void remove_partition(const char *cg)
+{
+	int err = write_file(cg, "cpuset.cpus.partition", "member");
+	uint64_t end;
+
+	if (err && err != -ENOENT)
+		ksft_print_msg("%s back to a member: %s\n", cg, strerror(-err));
+	/* A cgroup whose last task just died takes a moment to empty. */
+	end = now_ns() + NSEC_PER_SEC;
+	while (rmdir(cg)) {
+		if (errno == ENOENT)
+			return;
+		if (errno != EBUSY || now_ns() > end) {
+			ksft_print_msg("rmdir %s: %s\n", cg, strerror(errno));
+			return;
+		}
+		sleep_ns(10 * NSEC_PER_MSEC);
+	}
+}
+
+/*
+ * Return the CPU time of the calling thread in ns. clock_gettime() cannot
+ * fail: the clock is always supported, and the pointer is valid.
+ */
+static uint64_t cpu_time_ns(void)
+{
+	struct timespec ts;
+
+	clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
+	return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
+}
+
+enum depart { DIES, SWITCHED_OUT };
+
+/* Kill the calling child if the test exits, so that no deadline task stays. */
+static void die_with_parent(void)
+{
+	if (prctl(PR_SET_PDEATHSIG, SIGKILL) || getppid() != test_pid)
+		_exit(1);
+}
+
+/*
+ * Fork a child that enters @cg, if given, then SCHED_DEADLINE at 400ms
+ * every second. The child runs 380ms of its runtime. Then it dies if @how
+ * is DIES. Otherwise it switches to SCHED_OTHER, writes a byte to @fd and
+ * sleeps. Its 0-lag time is then about 570ms ahead. Return the pid of the
+ * child, or -1. Only the read end of @fd stays open in the caller.
+ */
+static pid_t departing(const char *cg, enum depart how, int fd[2])
+{
+	pid_t pid = fork();
+
+	if (pid < 0)
+		ksft_print_msg("fork: %s\n", strerror(errno));
+	if (!pid) {
+		uint64_t t0;
+
+		die_with_parent();
+		close(fd[0]);
+		if (cg && enter(cg, getpid()))
+			_exit(2);
+		if (set_deadline(0, 400 * NSEC_PER_MSEC))
+			_exit(3);
+		t0 = cpu_time_ns();
+		while (cpu_time_ns() - t0 < 380 * NSEC_PER_MSEC)
+			;
+		if (how == DIES)
+			_exit(0);
+		if (set_other(0) || write(fd[1], "x", 1) != 1)
+			_exit(4);
+		for (;;)
+			pause();
+	}
+	close(fd[1]);
+	fd[1] = -1;
+	return pid;
+}
+
+/*
+ * Wait until the child is out of SCHED_DEADLINE: dead or switched out.
+ * Return 0 on success. If the child failed, return its exit status, or
+ * -1. Set *@pid to -1 once the child is reaped.
+ */
+static int departed(pid_t *pid, enum depart how, int fd)
+{
+	int status;
+	char c;
+
+	if (*pid < 0)
+		return -1;
+	/*
+	 * A child that switches out sends a byte. Without the byte, the
+	 * child died or failed, and its exit status tells which.
+	 */
+	if (how == SWITCHED_OUT) {
+		ssize_t n;
+
+		do {
+			n = read(fd, &c, 1);
+		} while (n < 0 && errno == EINTR);
+		if (n == 1)
+			return 0;
+	}
+	if (waitpid(*pid, &status, 0) != *pid)
+		return -1;
+	*pid = -1;
+	return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
+}
+
+/*
+ * Fork a child that enters @cg and sleeps there. The child moves itself,
+ * so that it last ran on a CPU of @cg. Wait until it is there. Return its
+ * pid, or -1.
+ */
+static pid_t sleeper(const char *cg)
+{
+	int fd[2];
+	pid_t pid;
+	char c;
+
+	if (pipe(fd))
+		return -1;
+	pid = fork();
+	if (pid < 0)
+		ksft_print_msg("fork: %s\n", strerror(errno));
+	if (!pid) {
+		die_with_parent();
+		close(fd[0]);
+		if (enter(cg, getpid()) || write(fd[1], "x", 1) != 1)
+			_exit(1);
+		for (;;)
+			pause();
+	}
+	close(fd[1]);
+	if (pid > 0 && read(fd[0], &c, 1) != 1) {
+		reap(pid);
+		pid = -1;
+	}
+	close(fd[0]);
+	return pid;
+}
+
+/*
+ * Check that P admits one task of 600ms every second, but not two. The
+ * caller must wait until every inactive timer has fired.
+ */
+static int check_p(void)
+{
+	pid_t a = sleeper(cg_p), b = sleeper(cg_p);
+	int ret = KSFT_FAIL, e1, e2;
+
+	if (a < 0 || b < 0) {
+		ksft_print_msg("no task could enter P\n");
+		goto out;
+	}
+	e1 = set_deadline(a, 600 * NSEC_PER_MSEC);
+	e2 = set_deadline(b, 600 * NSEC_PER_MSEC);
+	if (e1)
+		ksft_print_msg("a first task refused in P: %s\n", strerror(-e1));
+	else if (!e2)
+		ksft_print_msg("1.2 CPUs of deadline tasks admitted in a partition of one CPU\n");
+	else if (e2 != -EBUSY)
+		ksft_print_msg("the second task refused with %s, not EBUSY\n", strerror(-e2));
+	else
+		ret = KSFT_PASS;
+out:
+	reap(a);
+	reap(b);
+	return ret;
+}
+
+/*
+ * Have a task of P die or switch out, as @how says. Make Q before its
+ * 0-lag time, then check P.
+ */
+static int test_rebuild(enum depart how)
+{
+	int ret = KSFT_FAIL, fd[2], err, ran = 0;
+	pid_t pid = -1;
+
+	if (pipe(fd))
+		return KSFT_FAIL;
+	if (make_partition(cg_p, cpu_p)) {
+		ksft_print_msg("no partition root on CPU %d\n", cpu_p);
+		ret = KSFT_SKIP;
+		goto out;
+	}
+	pid = departing(cg_p, how, fd);
+	err = departed(&pid, how, fd[0]);
+	if (err) {
+		ksft_print_msg("the deadline task failed (%d)\n", err);
+		goto out;
+	}
+	ran = 1;
+	if (make_partition(cg_q, cpu_q)) {
+		ksft_print_msg("no partition root on CPU %d\n", cpu_q);
+		ret = KSFT_SKIP;
+		goto out;
+	}
+	/*
+	 * Wait past the 0-lag time. In the SWITCHED_OUT case the task is still
+	 * alive then: it sleeps in P as a SCHED_OTHER task.
+	 */
+	sleep_ns(1500 * NSEC_PER_MSEC);
+	ran = 0;
+	ret = check_p();
+out:
+	reap(pid);
+	/* Let the next case start after the 0-lag time of the task. */
+	if (ran)
+		sleep_ns(1500 * NSEC_PER_MSEC);
+	remove_partition(cg_q);
+	remove_partition(cg_p);
+	close(fd[0]);
+	if (fd[1] >= 0)
+		close(fd[1]);
+	return ret;
+}
+
+/*
+ * Have a task outside P switch to SCHED_OTHER and sleep. Before its 0-lag
+ * time, move it into P and kill it. Then check P.
+ */
+static int test_move(void)
+{
+	int ret = KSFT_FAIL, fd[2], err, ran = 0;
+	pid_t pid = -1;
+
+	if (pipe(fd))
+		return KSFT_FAIL;
+	if (make_partition(cg_p, cpu_p)) {
+		ksft_print_msg("no partition root on CPU %d\n", cpu_p);
+		ret = KSFT_SKIP;
+		goto out;
+	}
+	pid = departing(NULL, SWITCHED_OUT, fd);
+	err = departed(&pid, SWITCHED_OUT, fd[0]);
+	if (err) {
+		ksft_print_msg("the deadline task failed (%d)\n", err);
+		goto out;
+	}
+	ran = 1;
+	if (enter(cg_p, pid)) {
+		ksft_print_msg("the task cannot move into P\n");
+		goto out;
+	}
+	/* The task wakes up and dies on P's CPU, before its 0-lag time. */
+	reap(pid);
+	pid = -1;
+	sleep_ns(1500 * NSEC_PER_MSEC);
+	ran = 0;
+	ret = check_p();
+out:
+	reap(pid);
+	/* Let the next case start after the 0-lag time of the task. */
+	if (ran)
+		sleep_ns(1500 * NSEC_PER_MSEC);
+	remove_partition(cg_p);
+	close(fd[0]);
+	if (fd[1] >= 0)
+		close(fd[1]);
+	return ret;
+}
+
+/*
+ * Mark in @set the CPUs of @list. The list has the sysfs form "0-2,5".
+ * @set has room for @n CPUs.
+ */
+static void parse_cpulist(const char *list, char *set, int n)
+{
+	const char *s = list;
+	char *end;
+	long a, b;
+
+	while (*s && *s != '\n') {
+		a = strtol(s, &end, 10);
+		if (end == s)
+			return;
+		b = a;
+		s = end;
+		if (*s == '-') {
+			b = strtol(s + 1, &end, 10);
+			s = end;
+		}
+		for (; a <= b && a < n; a++)
+			if (a >= 0)
+				set[a] = 1;
+		if (*s == ',')
+			s++;
+	}
+}
+
+/* The online CPUs that are not isolated */
+static cpu_set_t hk_set;
+
+/*
+ * Pick the two highest online CPUs that are not isolated, for P and Q.
+ * Put every online CPU that is not isolated in hk_set. Return the
+ * number of such CPUs.
+ */
+static int pick_cpus(void)
+{
+	static char online[CPU_SETSIZE], isol[CPU_SETSIZE];
+	char buf[4096];
+	int cpu, n = 0;
+
+	if (read_file("/sys/devices/system/cpu/online", buf, sizeof(buf)))
+		return 0;
+	parse_cpulist(buf, online, CPU_SETSIZE);
+	if (!read_file("/sys/devices/system/cpu/isolated", buf, sizeof(buf)))
+		parse_cpulist(buf, isol, CPU_SETSIZE);
+	cpu_p = cpu_q = -1;
+	CPU_ZERO(&hk_set);
+	for (cpu = CPU_SETSIZE - 1; cpu >= 0; cpu--) {
+		if (!online[cpu] || isol[cpu])
+			continue;
+		CPU_SET(cpu, &hk_set);
+		if (cpu_p < 0)
+			cpu_p = cpu;
+		else if (cpu_q < 0)
+			cpu_q = cpu;
+		n++;
+	}
+	return n;
+}
+
+static int find_cgroup2(void)
+{
+	char line[PATH_MAX + 64], dev[64], dir[PATH_MAX], type[64];
+	FILE *f = fopen("/proc/self/mounts", "r");
+	int found = 0;
+
+	while (f && !found && fgets(line, sizeof(line), f)) {
+		if (sscanf(line, "%63s %4095s %63s", dev, dir, type) == 3 &&
+		    !strcmp(type, "cgroup2")) {
+			snprintf(root, sizeof(root), "%s", dir);
+			found = 1;
+		}
+	}
+	if (f)
+		fclose(f);
+	return found ? 0 : -1;
+}
+
+static void report(const char *name, int ret)
+{
+	if (ret == KSFT_PASS)
+		ksft_test_result_pass("%s\n", name);
+	else if (ret == KSFT_SKIP)
+		ksft_test_result_skip("%s\n", name);
+	else
+		ksft_test_result_fail("%s\n", name);
+}
+
+int main(void)
+{
+	char buf[256], path[PATH_MAX + 32];
+	int added;
+
+	ksft_print_header();
+	test_pid = getpid();
+	if (geteuid())
+		ksft_exit_skip("needs root\n");
+	if (pick_cpus() < 3)
+		ksft_exit_skip("needs 3 online CPUs that are not isolated\n");
+	/*
+	 * A change of partitions lets a task of the root cgroup run on any
+	 * CPU outside the partitions, an isolated one too. It keeps an
+	 * affinity set by sched_setaffinity(), so set one.
+	 */
+	if (sched_setaffinity(0, sizeof(hk_set), &hk_set))
+		ksft_exit_skip("cannot run on the CPUs that are not isolated\n");
+	if (read_file("/proc/sys/kernel/sched_rt_runtime_us", buf, sizeof(buf)) || atol(buf) < 0)
+		ksft_exit_skip("no deadline admission control\n");
+	if (find_cgroup2())
+		ksft_exit_skip("cgroup v2 is not mounted\n");
+	if (snprintf(cg_p, sizeof(cg_p), "%s/deadline_rebuild_p", root) >= (int)sizeof(cg_p) ||
+	    snprintf(cg_q, sizeof(cg_q), "%s/deadline_rebuild_q", root) >= (int)sizeof(cg_q))
+		ksft_exit_skip("cgroup v2 mount path too long\n");
+	/*
+	 * Enable the cpuset controller for the root's children, if it is
+	 * off. It is turned off again at the end.
+	 */
+	snprintf(path, sizeof(path), "%s/cgroup.subtree_control", root);
+	if (read_file(path, buf, sizeof(buf)))
+		ksft_exit_skip("no cgroup.subtree_control\n");
+	added = !strstr(buf, "cpuset");
+	if (added && write_file(root, "cgroup.subtree_control", "+cpuset"))
+		ksft_exit_skip("no cpuset controller\n");
+
+	ksft_set_plan(3);
+	report("dies_before_rebuild", test_rebuild(DIES));
+	report("switched_out_before_rebuild", test_rebuild(SWITCHED_OUT));
+	report("moved_after_switch_out", test_move());
+	if (added && write_file(root, "cgroup.subtree_control", "-cpuset"))
+		ksft_print_msg("the cpuset controller stays enabled\n");
+	ksft_finished();
+}
-- 
2.47.3


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

* [PATCH v11 06/43] selftests/sched: Test the root domain rebuild in deadline_bw_test
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (4 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 05/43] selftests/sched: Test SCHED_DEADLINE bandwidth across a root domain rebuild Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 07/43] sched/deadline: Move a task's bandwidth only where room was made Mathieu Desnoyers
                   ` (36 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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

Add seven cases to deadline_bw_test. Most test the rebuild of the root
domains' accounting, earlier in this series. They cover:
- CPU hotplug with sleeping deadline tasks, and with tasks that left the
  class before their 0-lag time
- a zombie deadline task during a CPU hotplug (death_zombie_hotplug)
- a priority inheritance owner that left the class, then moves
  (pi_departed_moved)
- sched_setaffinity() racing with sched_setattr() (affinity_vs_setattr)

The comment above each case gives its scenario. Two cases follow
reproducers of Juri Lelli's sched-deadline-tests:
hotplug_sleeper_switched and hotplug_no_admission_pinned.

The message of each fix names the cases that test it. These cases are
not named there:
- hotplug_departed and hotplug_no_admission_pinned: "sched/deadline: Keep
  departing bandwidth across a root domain rebuild"
- affinity_vs_setattr tests "sched/deadline: Check SCHED_DEADLINE
  affinity under the rq lock", of the first series. It comes here
  because it fails without CONFIG_CPUSETS before these fixes.

On v7.4-rc2, in 8 VMs of 8 CPUs, six of these cases fail in every VM:
- affinity_vs_setattr
- death_zombie_hotplug
- hotplug_departed
- hotplug_no_admission_pinned
- hotplug_sleeper_switched
- pi_departed_moved

hotplug_sleepers passes there. It fails on v7.4-rc2 and with the first
series without CONFIG_CPUSETS. It also fails there when
isolcpus=domain,0,1 isolates the boot CPU. The rebuild fixes make it
pass.

With the fixes up to here, every case passes wherever it runs.

Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Link: https://github.com/jlelli/sched-deadline-tests
---
 .../sched/deadline/deadline_bw_test.c         | 654 +++++++++++++++++-
 1 file changed, 650 insertions(+), 4 deletions(-)

diff --git a/tools/testing/selftests/sched/deadline/deadline_bw_test.c b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
index 6ff9da964403..ba2a18f354d4 100644
--- a/tools/testing/selftests/sched/deadline/deadline_bw_test.c
+++ b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
@@ -31,8 +31,11 @@
  * housekeeping CPU. P is made anew for each case. Making it rebuilds the
  * accounting, which clears what an earlier case left.
  *
- * The cases of hp_cases[] run after them, without P. They take CPUs
- * offline. The test skips them if no CPU can go offline.
+ * The cases of hp_cases[] run after them, without P. These are the
+ * hotplug cases, and affinity_vs_setattr. The test skips the hotplug
+ * cases if no CPU can go offline. It still runs affinity_vs_setattr.
+ * death_zombie_hotplug takes CPUs offline too, but it is in p_cases[]: it
+ * needs the cpuset setup of those cases.
  *
  * The server cases change the fair server of a CPU through debugfs, and
  * the test then puts it back.
@@ -4554,7 +4557,10 @@ static int params_waking(void)
 	return ret;
 }
 
-/* CPU hotplug, from the main process, with no P */
+/*
+ * CPU hotplug, from the main process, with no P. Two cases below run with
+ * P instead: death_zombie_hotplug and pi_departed_moved.
+ */
 
 static int hp_cpu = -1;
 
@@ -4584,6 +4590,213 @@ static void cpu_up(int cpu)
 		ksft_print_msg("CPU %d cannot come back online: %s\n", cpu, strerror(-err));
 }
 
+/*
+ * Four deadline tasks of 30% sleep. Take hp_cpu offline and back. Once
+ * the sleepers are gone, the housekeeping root domain must admit what it
+ * did before. Skip unless 22 probe tasks fit: the sleepers take the room
+ * of 12, and the offline CPU that of about 10.
+ */
+static int hotplug_sleepers(void)
+{
+	int base = probe(NULL), after, i, ret = KSFT_PASS;
+	pid_t pid[4];
+
+	if (base < 22) {
+		ksft_print_msg("needs room for 22 probe tasks\n");
+		return KSFT_SKIP;
+	}
+	for (i = 0; i < 4; i++) {
+		mv_state[0] = 0;
+		pid[i] = mover(MV_ASLEEP, 30 * NSEC_PER_MSEC);
+		if (pid[i] < 0 || child_up("a deadline sleeper", 0)) {
+			while (i >= 0)
+				reap(pid[i--]);
+			return KSFT_FAIL;
+		}
+	}
+	if (cpu_online(hp_cpu, 0) || cpu_online(hp_cpu, 1)) {
+		ksft_print_msg("offline and online of CPU %d with deadline sleepers failed\n",
+			       hp_cpu);
+		ret = KSFT_FAIL;
+		cpu_up(hp_cpu);
+	}
+	for (i = 0; i < 4; i++)
+		reap(pid[i]);
+	sleep_ns(3 * PERIOD);
+	after = probe(NULL);
+	if (ret == KSFT_PASS && after != base) {
+		ksft_print_msg("hotplug with sleepers: %d probe tasks admitted before, %d after\n",
+			       base, after);
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
+/*
+ * Fork a task that runs on @cpu, then restores its affinity, becomes a
+ * deadline task of 30% and sleeps. A deadline task cannot have an
+ * affinity of one CPU, so the task goes to @cpu first. It sets
+ * mv_state[0] as mover() does. Return its pid, or -1.
+ */
+static pid_t sleeper_on(int cpu)
+{
+	pid_t pid = fork_child("a deadline sleeper");
+
+	if (!pid) {
+		cpu_set_t all, one;
+
+		CPU_ZERO(&one);
+		CPU_SET(cpu, &one);
+		if (sched_getaffinity(0, sizeof(all), &all) ||
+		    sched_setaffinity(0, sizeof(one), &one))
+			_exit(1);
+		spin_ns(NSEC_PER_MSEC);
+		if (sched_setaffinity(0, sizeof(all), &all) ||
+		    set_deadline(0, 30 * NSEC_PER_MSEC, PERIOD)) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		mv_state[0] = 1;
+		for (;;)
+			pause();
+	}
+	return pid;
+}
+
+/*
+ * A deadline task of 30% sleeps on hp_cpu. Take hp_cpu offline, then
+ * switch the task to SCHED_OTHER. hp_cpu has left the housekeeping root
+ * domain by then, but that root domain still counts the task. The switch
+ * must release the bandwidth there.
+ *
+ * Check this with hp_cpu still offline: bringing it back rebuilds the
+ * accounting, which would hide a bandwidth left behind. The reference is
+ * what the housekeeping root domain admits with hp_cpu offline and no
+ * task. Once the CPU is back and the task is gone, that root domain must
+ * also admit what it did at first.
+ */
+static int hotplug_sleeper_switched(void)
+{
+	int base = probe(NULL), base_off, after, cpu, ret = KSFT_PASS;
+	pid_t pid;
+
+	if (cpu_online(hp_cpu, 0)) {
+		ksft_print_msg("CPU %d cannot go offline\n", hp_cpu);
+		cpu_up(hp_cpu);
+		return KSFT_SKIP;
+	}
+	base_off = probe(NULL);
+	cpu_up(hp_cpu);
+	mv_state[0] = 0;
+	pid = sleeper_on(hp_cpu);
+	if (pid < 0 || child_up("a deadline sleeper", 0)) {
+		reap(pid);
+		return KSFT_FAIL;
+	}
+	sleep_ns(PERIOD);
+	cpu = task_cpu_of(pid);
+	if (cpu != hp_cpu) {
+		ksft_print_msg("the sleeper is on CPU %d, not on CPU %d\n", cpu, hp_cpu);
+		reap(pid);
+		return KSFT_SKIP;
+	}
+	if (cpu_online(hp_cpu, 0)) {
+		ksft_print_msg("CPU %d cannot go offline under a deadline sleeper\n", hp_cpu);
+		ret = KSFT_FAIL;
+	} else if (set_other(pid)) {
+		ksft_print_msg("the sleeper cannot leave SCHED_DEADLINE\n");
+		ret = KSFT_FAIL;
+	} else {
+		sleep_ns(3 * PERIOD);
+		after = probe(NULL);
+		if (after != base_off) {
+			ksft_print_msg("a sleeper switched out, its CPU still offline: %d probe tasks admitted, %d expected\n",
+				       after, base_off);
+			ret = KSFT_FAIL;
+		}
+	}
+	cpu_up(hp_cpu);
+	reap(pid);
+	sleep_ns(3 * PERIOD);
+	after = probe(NULL);
+	if (ret == KSFT_PASS && after != base) {
+		ksft_print_msg("a sleeper switched out on an offline CPU: %d probe tasks admitted before, %d after\n",
+			       base, after);
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
+/*
+ * Turn admission control off (sched_rt_runtime_us = -1). A task pins
+ * itself to hp_cpu, becomes a deadline task of 50% and spins. Without
+ * admission control, a deadline task can have an affinity of one CPU.
+ * Take hp_cpu offline: the mask of the task holds no active CPU. The
+ * task must go on running on another CPU. Once the CPU is back, the task
+ * is gone and admission control is on again, the housekeeping root domain
+ * must admit what it did before.
+ */
+static int hotplug_no_admission_pinned(void)
+{
+	int base = probe(NULL), after, ret = KSFT_PASS, last;
+	char saved[64];
+	pid_t pid;
+
+	if (read_file("/proc/sys/kernel/sched_rt_runtime_us", saved, sizeof(saved)) ||
+	    write_file("/proc/sys/kernel", "sched_rt_runtime_us", "-1")) {
+		ksft_print_msg("admission control cannot be turned off\n");
+		return KSFT_SKIP;
+	}
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = fork_child("a pinned deadline task");
+	if (!pid) {
+		cpu_set_t one;
+
+		CPU_ZERO(&one);
+		CPU_SET(hp_cpu, &one);
+		if (sched_setaffinity(0, sizeof(one), &one) ||
+		    set_deadline(0, 50 * NSEC_PER_MSEC, PERIOD)) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		mv_state[0] = 1;
+		for (;;)
+			mv_state[1]++;
+	}
+	if (pid < 0 || child_up("a pinned deadline task", 0)) {
+		ret = KSFT_FAIL;
+		goto out;
+	}
+	sleep_ns(PERIOD);
+	if (cpu_online(hp_cpu, 0)) {
+		ksft_print_msg("CPU %d cannot go offline under a pinned deadline task\n", hp_cpu);
+		ret = KSFT_FAIL;
+		goto out;
+	}
+	last = mv_state[1];
+	sleep_ns(3 * PERIOD);
+	if (mv_state[1] == last) {
+		ksft_print_msg("the pinned task does not run after its CPU went offline\n");
+		ret = KSFT_FAIL;
+	}
+out:
+	cpu_up(hp_cpu);
+	reap(pid);
+	if (write_file("/proc/sys/kernel", "sched_rt_runtime_us", saved)) {
+		ksft_print_msg("admission control cannot be turned on again\n");
+		return KSFT_FAIL;
+	}
+	sleep_ns(3 * PERIOD);
+	after = probe(NULL);
+	if (ret == KSFT_PASS && after != base) {
+		ksft_print_msg("a pinned task without admission control: %d probe tasks admitted before, %d after\n",
+			       base, after);
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
 /*
  * Deadline sleepers take most of the free bandwidth. Taking hp_cpu
  * offline must then fail with EBUSY. Once the sleepers are gone, the
@@ -4638,6 +4851,303 @@ static int hotplug_refused(void)
 	return ret;
 }
 
+/*
+ * A deadline task of 40% spins. The case switches it to SCHED_OTHER
+ * before its 0-lag time. Then it takes the CPU that the task is on
+ * offline, before that time too. Past the 0-lag time, with the CPU still
+ * offline, the housekeeping root domain must admit what it admits with a
+ * CPU offline and no task. Once the CPU is back and the task is gone, it
+ * must admit what it did at the start.
+ */
+static int hotplug_departed(void)
+{
+	int base = probe(NULL), base_off, after, cpu, ret = KSFT_PASS;
+	pid_t pid;
+
+	/*
+	 * Take the reference with hp_cpu offline and no task of ours. The
+	 * task may be on another CPU: the case assumes that any one CPU
+	 * offline leaves the same room. The case compares while that CPU
+	 * is still offline. Bringing it back rebuilds the accounting,
+	 * which would hide an error.
+	 */
+	if (cpu_online(hp_cpu, 0)) {
+		ksft_print_msg("offline of CPU %d refused\n", hp_cpu);
+		return KSFT_FAIL;
+	}
+	base_off = probe(NULL);
+	cpu_up(hp_cpu);
+	if (base <= 0 || base_off <= 0) {
+		ksft_print_msg("no room to probe with the CPU online or offline\n");
+		return KSFT_SKIP;
+	}
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = mover(MV_THROTTLED, 40 * NSEC_PER_MSEC);
+	if (pid < 0 || child_up("a departing deadline task", 0)) {
+		reap(pid);
+		return KSFT_FAIL;
+	}
+	sleep_ns(PERIOD / 2);
+	/* Not asleep: its bandwidth stays until its 0-lag time. */
+	if (set_other(pid))
+		ret = KSFT_FAIL;
+	cpu = task_cpu_of(pid);
+	if (cpu < 0 || !cpu_hotpluggable(cpu)) {
+		cpu_set_t set;
+
+		/* Out of the class now, it may be pinned to hp_cpu. */
+		cpu = hp_cpu;
+		CPU_ZERO(&set);
+		CPU_SET(cpu, &set);
+		if (sched_setaffinity(pid, sizeof(set), &set))
+			ret = KSFT_FAIL;
+	}
+	if (ret == KSFT_PASS && cpu_online(cpu, 0)) {
+		ksft_print_msg("offline of CPU %d refused\n", cpu);
+		ret = KSFT_FAIL;
+	}
+	sleep_ns(3 * PERIOD);		/* its 0-lag time, the CPU offline */
+	if (ret == KSFT_PASS) {
+		after = probe(NULL);
+		if (after != base_off) {
+			ksft_print_msg("departed, CPU %d offline: %d admitted, %d expected\n",
+				       cpu, after, base_off);
+			ret = KSFT_FAIL;
+		}
+	}
+	cpu_up(cpu);
+	reap(pid);
+	sleep_ns(3 * PERIOD);
+	after = probe(NULL);
+	if (ret == KSFT_PASS && after != base) {
+		ksft_print_msg("departed, CPU back online: %d admitted before, %d after\n",
+			       base, after);
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
+#define ZOMBIE_RUNTIME	(200 * NSEC_PER_MSEC)
+#define ZOMBIE_PERIOD	(2 * NSEC_PER_SEC)
+
+/*
+ * Q is a partition root of two CPUs. The kernel records, with the
+ * bandwidth of a task, a CPU of the root domain that counts it. The steps:
+ * 1. A task enters Q and becomes a deadline task of 200ms every 2s.
+ * 2. It runs 190ms and exits, its 0-lag time about 1.7s ahead. The case
+ *    does not reap it yet. A rebuild of the accounting still finds a
+ *    zombie in the task list.
+ * 3. total_bw of Q must count the zombie.
+ * 4. The case takes each CPU of Q offline and back, one after the other.
+ *    One of them is the CPU recorded with the bandwidth of the zombie.
+ *    The rebuild at its offline drops that bandwidth.
+ * 5. Before the 0-lag time, total_bw of Q must be what it was without
+ *    the task. No later rebuild may count the zombie again: the release
+ *    at the 0-lag time removes nothing by then.
+ * 6. The case reaps the zombie. Past the 0-lag time, total_bw of Q must
+ *    still be that value.
+ *
+ * The case runs with the cases in P, from the main process: Q needs the
+ * cpuset controller. Q has two CPUs because the last CPU of a root domain
+ * that holds deadline bandwidth cannot go offline.
+ */
+static int death_zombie_hotplug(void)
+{
+	int cpu[2] = { top_cpu(3), top_cpu(2) }, i, ret = KSFT_PASS;
+	long long base, bw, held, after;
+	char cpus[32];
+	uint64_t t;
+	pid_t pid;
+
+	if (ncpus < 4 || !cpu_hotpluggable(cpu[0]) || !cpu_hotpluggable(cpu[1])) {
+		ksft_print_msg("needs 4 non-isolated CPUs, 2 hotpluggable beside P\n");
+		return KSFT_SKIP;
+	}
+	snprintf(cpus, sizeof(cpus), "%d,%d", cpu[0], cpu[1]);
+	if (make_partition_cpus(cg_q, cpus)) {
+		ksft_print_msg("no partition root Q of CPUs %s\n", cpus);
+		remove_partition(cg_q);
+		return KSFT_SKIP;
+	}
+	base = total_bw_of(cpu[0]);
+	if (base < 0) {
+		ksft_print_msg("no total_bw in /sys/kernel/debug/sched/debug\n");
+		remove_partition(cg_q);
+		return KSFT_SKIP;
+	}
+	bw = (ZOMBIE_RUNTIME << 20) / ZOMBIE_PERIOD;	/* as to_ratio() */
+	mv_state[0] = 0;
+	pid = fork_child("a deadline task that exits");
+	if (!pid) {
+		if (enter(cg_q, getpid()) || set_deadline(0, ZOMBIE_RUNTIME, ZOMBIE_PERIOD))
+			_exit(1);
+		/* 10ms left: the 0-lag time is 100ms before the deadline. */
+		spin_ns(ZOMBIE_RUNTIME - 10 * NSEC_PER_MSEC);
+		mv_state[0] = 1;
+		_exit(0);
+	}
+	if (pid < 0 || child_up("a task of Q that exits", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'Z')) {
+		ksft_print_msg("no zombie deadline task\n");
+		reap(pid);
+		remove_partition(cg_q);
+		return KSFT_FAIL;
+	}
+	/* Its 0-lag time is about 1.7s ahead. Check total_bw within 1s. */
+	t = now_ns();
+	held = total_bw_of(cpu[0]);
+	if (held != base + bw) {
+		ksft_print_msg("total_bw of Q: %lld with the zombie, %lld expected\n",
+			       held, base + bw);
+		ret = KSFT_FAIL;
+	}
+	for (i = 0; i < 2 && ret == KSFT_PASS; i++) {
+		if (cpu_online(cpu[i], 0) || cpu_online(cpu[i], 1)) {
+			ksft_print_msg("offline and online of CPU %d failed\n", cpu[i]);
+			cpu_up(cpu[i]);
+			ret = KSFT_FAIL;
+		}
+	}
+	after = total_bw_of(cpu[0]);
+	if (ret == KSFT_PASS && now_ns() - t > NSEC_PER_SEC) {
+		ksft_print_msg("the hotplugs took over 1s: the 0-lag time may be past\n");
+		ret = KSFT_SKIP;
+	} else if (ret == KSFT_PASS && after != base) {
+		ksft_print_msg("total_bw of Q after the hotplugs: %lld, %lld expected%s\n",
+			       after, base,
+			       after == base + bw ? ": the zombie counted again" : "");
+		ret = KSFT_FAIL;
+	}
+	reap(pid);
+	sleep_ns(ZOMBIE_PERIOD);		/* past its 0-lag time */
+	after = total_bw_of(cpu[0]);
+	if (ret == KSFT_PASS && after != base) {
+		ksft_print_msg("total_bw of Q past the 0-lag time: %lld, %lld expected\n",
+			       after, base);
+		ret = KSFT_FAIL;
+	}
+	remove_partition(cg_q);
+	return ret;
+}
+
+/*
+ * Fork the owner of pi_departed_moved(). It takes shm_lock, becomes a
+ * deadline task and runs most of its runtime. It sets mv_state[0] to 1
+ * and sleeps 300ms. Then it sets mv_state[1] to 1 and sleeps with the
+ * lock. Return its pid, or -1.
+ */
+static pid_t departed_owner(void)
+{
+	pid_t pid = fork_child("the owner of the lock");
+
+	if (!pid) {
+		if (pthread_mutex_lock(shm_lock) ||
+		    set_deadline(0, ZOMBIE_RUNTIME, ZOMBIE_PERIOD)) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		/* 20ms left: the 0-lag time is 200ms before the deadline. */
+		spin_ns(ZOMBIE_RUNTIME - 20 * NSEC_PER_MSEC);
+		mv_state[0] = 1;
+		sleep_ns(300 * NSEC_PER_MSEC);
+		mv_state[1] = 1;
+		for (;;)
+			pause();
+	}
+	return pid;
+}
+
+/*
+ * The owner is a deadline task of 200ms every 2s, outside P. It holds
+ * shm_lock, runs 180ms and sleeps, its 0-lag time about 1.6s ahead. The
+ * steps:
+ * 1. The case switches the sleeping owner to SCHED_OTHER. The
+ *    housekeeping root domain keeps its bandwidth until the 0-lag time.
+ * 2. The case moves the owner into P. The owner wakes up and runs there.
+ * 3. A deadline waiter of 5ms every 50ms, outside P, blocks on shm_lock
+ *    and boosts the owner.
+ * 4. The case kills the waiter, which ends the boost.
+ *
+ * After step 4, total_bw of the housekeeping root domain must still count
+ * the bandwidth of the owner. total_bw of P never counted it and must be
+ * unchanged: the end of the boost must not subtract it there. Past the
+ * 0-lag time, both must be what they were at the start.
+ */
+static int pi_departed_moved(void)
+{
+	int p_cpu = top_cpu(1), r_cpu = online[0], ret = KSFT_PASS;
+	long long base_p, base_r, bw, in_p, in_r;
+	pid_t owner, waiter = -1;
+
+	base_p = total_bw_of(p_cpu);
+	base_r = total_bw_of(r_cpu);
+	if (base_p < 0 || base_r < 0) {
+		ksft_print_msg("no total_bw in /sys/kernel/debug/sched/debug\n");
+		return KSFT_SKIP;
+	}
+	if (shm_lock_init())
+		return KSFT_SKIP;
+	bw = (ZOMBIE_RUNTIME << 20) / ZOMBIE_PERIOD;	/* as to_ratio() */
+	mv_state[1] = 0;
+	owner = departed_owner();
+	if (owner < 0)
+		return KSFT_FAIL;
+	if (child_up("the owner of the lock", 0)) {
+		reap(owner);
+		return KSFT_FAIL;
+	}
+	/* The owner is asleep, about 1.6s before its 0-lag time. */
+	sleep_ns(20 * NSEC_PER_MSEC);
+	if (set_other(owner) || enter(cg_p, owner)) {
+		ksft_print_msg("the owner cannot leave the class and enter P\n");
+		ret = KSFT_FAIL;
+		goto out;
+	}
+	if (wait_state(&mv_state[1], 1) || task_cpu_of(owner) != p_cpu) {
+		ksft_print_msg("the owner did not run in P\n");
+		ret = KSFT_FAIL;
+		goto out;
+	}
+	waiter = lock_waiter();
+	if (waiter < 0) {
+		ret = KSFT_FAIL;
+		goto out;
+	}
+	if (wait_state(&mv_state[2], 1)) {
+		ksft_print_msg("no waiter\n");
+		ret = KSFT_FAIL;
+		goto out;
+	}
+	sleep_ns(50 * NSEC_PER_MSEC);	/* blocked, boosting the owner */
+	reap(waiter);
+	waiter = -1;
+	sleep_ns(150 * NSEC_PER_MSEC);	/* the waiter is past its 0-lag time */
+	in_p = total_bw_of(p_cpu);
+	in_r = total_bw_of(r_cpu);
+	if (in_p != base_p || in_r != base_r + bw) {
+		ksft_print_msg("after the boost: total_bw of P %lld, %lld expected\n",
+			       in_p, base_p);
+		ksft_print_msg("after the boost: total_bw outside %lld, %lld expected\n",
+			       in_r, base_r + bw);
+		ret = KSFT_FAIL;
+	}
+out:
+	reap(waiter);
+	reap(owner);
+	sleep_ns(ZOMBIE_PERIOD);	/* past the owner's 0-lag time */
+	in_p = total_bw_of(p_cpu);
+	in_r = total_bw_of(r_cpu);
+	if (ret == KSFT_PASS && (in_p != base_p || in_r != base_r)) {
+		ksft_print_msg("past the 0-lag time: total_bw of P %lld, %lld expected\n",
+			       in_p, base_p);
+		ksft_print_msg("past the 0-lag time: total_bw outside %lld, %lld expected\n",
+			       in_r, base_r);
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
 /*
  * The bandwidth of a fair server must leave the root domain with its CPU
  * and come back with it, whatever its size. Probe the housekeeping root
@@ -4743,6 +5253,134 @@ static void report(const char *name, int ret)
 		ksft_test_result_fail("%s\n", name);
 }
 
+/* sched_setaffinity() against sched_setattr(), with no P */
+
+/*
+ * The state that affinity_racer() shares with the case. pid and one are
+ * its target and its mask. go and done count the rounds. ret is the
+ * result of its last call.
+ */
+static struct {
+	pid_t pid;
+	cpu_set_t one;
+	atomic_int go;
+	atomic_int done;
+	atomic_int stop;
+	int ret;
+} aff;
+
+/*
+ * Give aff.pid the affinity aff.one, once for each new value of aff.go.
+ * Return when aff.stop is set.
+ */
+static void *affinity_racer(void *arg)
+{
+	int round;
+
+	for (round = 1; ; round++) {
+		while (aff.go < round && !aff.stop)
+			;
+		if (aff.stop)
+			break;
+		aff.ret = sched_setaffinity(aff.pid, sizeof(aff.one), &aff.one) ? -errno : 0;
+		aff.done = round;
+	}
+	return arg;
+}
+
+/*
+ * Race sched_setaffinity() against sched_setattr() on a sleeping task.
+ * One thread gives the task an affinity of one CPU. Another one makes it
+ * a deadline task. A deadline task must be allowed on its whole root
+ * domain, so at most one of the two calls may succeed:
+ * - sched_setattr() fails with EPERM if the affinity came first;
+ * - sched_setaffinity() fails with EBUSY if the policy came first.
+ *
+ * Do it 1000 times. Each round starts with the task back in SCHED_OTHER
+ * with its full affinity. Once the task is gone, the free bandwidth must
+ * be what it was. The case needs no cpuset: it runs without P, with the
+ * hotplug cases.
+ */
+static int affinity_vs_setattr(void)
+{
+	const char *name = "affinity_vs_setattr";
+	int base, i, cpu, both = 0, ret = KSFT_PASS;
+	cpu_set_t all;
+	pthread_t t;
+	pid_t pid;
+
+	base = probe(NULL);
+	pid = fork_child(name);
+	if (!pid) {
+		for (;;)
+			pause();
+	}
+	if (pid < 0)
+		return KSFT_FAIL;
+	/*
+	 * Wait until the task sleeps in pause(). A task that still runs
+	 * when it becomes a deadline task can overrun its 2us. Its
+	 * bandwidth then stays counted until its 0-lag time, seconds after
+	 * it is gone, and the next cases would see it.
+	 */
+	if (wait_for(1000, proc_state_of(pid) == 'S') ||
+	    sched_getaffinity(pid, sizeof(all), &all)) {
+		reap(pid);
+		return KSFT_FAIL;
+	}
+	CPU_ZERO(&aff.one);
+	for (cpu = 0; cpu < CPU_SETSIZE; cpu++) {
+		if (CPU_ISSET(cpu, &all)) {
+			CPU_SET(cpu, &aff.one);
+			break;
+		}
+	}
+	aff.pid = pid;
+	aff.go = 0;
+	aff.done = 0;
+	aff.stop = 0;
+	if (pthread_create(&t, NULL, affinity_racer, NULL)) {
+		reap(pid);
+		return KSFT_FAIL;
+	}
+
+	for (i = 1; i <= 1000 && ret == KSFT_PASS; i++) {
+		int err;
+
+		if (set_other(pid) || sched_setaffinity(pid, sizeof(all), &all)) {
+			ksft_print_msg("%s: the task cannot be reset: %s\n", name, strerror(errno));
+			ret = KSFT_FAIL;
+			break;
+		}
+		aff.go = i;
+		err = set_deadline(pid, 2 * NSEC_PER_USEC, PERIOD);
+		while (aff.done < i)
+			;
+		if (!err && !aff.ret) {
+			both++;
+		} else if ((err && err != -EPERM) || (aff.ret && aff.ret != -EBUSY)) {
+			ksft_print_msg("%s: round %d: sched_setattr: %s, sched_setaffinity: %s\n",
+				       name, i, strerror(-err), strerror(-aff.ret));
+			ret = KSFT_FAIL;
+		}
+	}
+	aff.stop = 1;
+	join(t);
+	if (both) {
+		ksft_print_msg("%s: %d rounds of %d: a deadline task with an affinity of one CPU\n",
+			       name, both, i - 1);
+		ret = KSFT_FAIL;
+	}
+	/* A deadline task of 2us every 100ms would take seconds to exit. */
+	if (set_other(pid))
+		ksft_print_msg("%s: the task stays a deadline task\n", name);
+	reap(pid);
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS && admits(base, "after the task is gone"))
+		ret = KSFT_FAIL;
+	return ret;
+}
+
 /* The tables of the cases, and main() */
 
 enum where {
@@ -4760,6 +5398,7 @@ static const struct p_case {
 	{ "pi_other_owner_asleep", pi_other_owner_asleep, MEASURED_IN_P },
 	{ "pi_unlock_running", pi_unlock_running, MEASURED_IN_P },
 	{ "pi_chain_two_owners", pi_chain_two_owners, MEASURED_IN_P },
+	{ "pi_departed_moved", pi_departed_moved, FROM_OUTSIDE },
 	{ "params_asleep", params_asleep, IN_P },
 	{ "params_non_contending", params_non_contending, MEASURED_IN_P },
 	{ "params_switched_asleep", params_switched_asleep, MEASURED_IN_P },
@@ -4790,6 +5429,7 @@ static const struct p_case {
 	{ "death_pi_deadline_owner", death_pi_deadline_owner, MEASURED_IN_P },
 	{ "death_group", death_group, MEASURED_IN_P },
 	{ "death_zombie_switched", death_zombie_switched, FROM_OUTSIDE },
+	{ "death_zombie_hotplug", death_zombie_hotplug, FROM_OUTSIDE },
 	{ "yield_switched_out", yield_switched_out, IN_P },
 	{ "yield_killed", yield_killed, MEASURED_IN_P },
 	{ "overrun_caught", overrun_caught, IN_P },
@@ -4808,9 +5448,15 @@ static const struct p_case {
 static const struct hp_case {
 	const char *name;
 	int (*fn)(void);
+	int no_hp;		/* takes no CPU offline */
 } hp_cases[] = {
+	{ "hotplug_sleepers", hotplug_sleepers },
+	{ "hotplug_sleeper_switched", hotplug_sleeper_switched },
+	{ "hotplug_no_admission_pinned", hotplug_no_admission_pinned },
 	{ "hotplug_refused", hotplug_refused },
+	{ "hotplug_departed", hotplug_departed },
 	{ "hotplug_server", hotplug_server },
+	{ "affinity_vs_setattr", affinity_vs_setattr, 1 },
 };
 
 #define N_HP_CASES	((int)ARRAY_SIZE(hp_cases))
@@ -4949,7 +5595,7 @@ int main(void)
 	if (hp_cpu < 0)
 		ksft_print_msg("no CPU hotplug: hotplug cases skipped\n");
 	for (i = 0; i < N_HP_CASES; i++) {
-		if (hp_cpu < 0) {
+		if (hp_cpu < 0 && !hp_cases[i].no_hp) {
 			ksft_test_result_skip("%s\n", hp_cases[i].name);
 			continue;
 		}
-- 
2.47.3


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

* [PATCH v11 07/43] sched/deadline: Move a task's bandwidth only where room was made
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (5 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 06/43] selftests/sched: Test the root domain rebuild in deadline_bw_test Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 08/43] cgroup/cpuset: Wait for an attach before rebuilding the sched domains Mathieu Desnoyers
                   ` (35 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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] 59+ messages in thread

* [PATCH v11 08/43] cgroup/cpuset: Wait for an attach before rebuilding the sched domains
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (6 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 07/43] sched/deadline: Move a task's bandwidth only where room was made Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 09/43] sched: Make deadline policy and affinity changes wait for a cpuset attach Mathieu Desnoyers
                   ` (34 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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] 59+ messages in thread

* [PATCH v11 09/43] sched: Make deadline policy and affinity changes wait for a cpuset attach
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (7 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 08/43] cgroup/cpuset: Wait for an attach before rebuilding the sched domains Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 10/43] cgroup/cpuset: Give back the bandwidth an attach did not move Mathieu Desnoyers
                   ` (33 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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] 59+ messages in thread

* [PATCH v11 10/43] cgroup/cpuset: Give back the bandwidth an attach did not move
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (8 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 09/43] sched: Make deadline policy and affinity changes wait for a cpuset attach Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 11/43] cgroup/cpuset: Reserve the bandwidth in the root domain a task moves to Mathieu Desnoyers
                   ` (32 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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] 59+ messages in thread

* [PATCH v11 11/43] cgroup/cpuset: Reserve the bandwidth in the root domain a task moves to
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (9 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 10/43] cgroup/cpuset: Give back the bandwidth an attach did not move Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 12/43] selftests/sched: Test cpuset moves in deadline_bw_test Mathieu Desnoyers
                   ` (31 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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] 59+ messages in thread

* [PATCH v11 12/43] selftests/sched: Test cpuset moves in deadline_bw_test
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (10 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 11/43] cgroup/cpuset: Reserve the bandwidth in the root domain a task moves to Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 13/43] sched/deadline: Make a rebuild count a task in the root domain it runs in Mathieu Desnoyers
                   ` (30 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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

Add the 24 cases of deadline_bw_test that test the fixes of cpuset
attach, earlier in this series. They cover cpuset moves, and what can
happen during them:
- a rebuild of the sched domains, a policy change, an affinity change, a
  wakeup, the death of a thread, a refusal by another controller
- a task asleep, throttled, yielded, frozen or reclaiming
- moves between the housekeeping CPUs and CPUs isolated by
  isolcpus=domain
- sysrq-n during a move (move_normalized)
- a random mix of all of the above, with affinity changes (random_mix)

The comment above each case gives its scenario. random_mix also
compares the this_bw of its CPUs. Five cases need CPUs isolated by
isolcpus=domain. move_normalized fires sysrq-n, which changes the whole
system, so it needs DEADLINE_TEST_SYSRQ=1. A case skips without what it
needs.

The attach fixes are the five patches before this one, from
"sched/deadline: Move a task's bandwidth only where room was made" to
"cgroup/cpuset: Reserve the bandwidth in the root domain a task moves
to".

The message of each fix names the cases that test it. These cases are
not named there:
- move_asleep, move_asleep_setattr, move_non_contending, move_died,
  move_woken and move_woken_full test "sched/deadline: Record the root
  domain holding a task's bandwidth". They also need the attach fixes,
  so they come here.
- frozen_moved_switched, move_throttled, reclaim_moved and yield_moved
  fail with isolcpus=domain,0,1 before the attach fixes.

On v7.4-rc2, in 8 VMs of 8 CPUs, twelve of these cases fail in every VM:

  move_affinity_became_deadline       move_died
  move_affinity_changed               move_non_contending
  move_asleep                         move_vs_rebuild
  move_back_cpu_offline               move_woken
  move_became_deadline                move_woken_full
  move_became_deadline_no_room        random_mix

These cases did not run there: those that need isolcpus=domain (they
skip), move_normalized, move_asleep_setattr and
move_asleep_fair_setattr.

With the fixes up to here, every case passes wherever it runs.

Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
 .../sched/deadline/deadline_bw_test.c         | 2517 ++++++++++++++++-
 1 file changed, 2512 insertions(+), 5 deletions(-)

diff --git a/tools/testing/selftests/sched/deadline/deadline_bw_test.c b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
index ba2a18f354d4..f50d45dd5799 100644
--- a/tools/testing/selftests/sched/deadline/deadline_bw_test.c
+++ b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
@@ -5,9 +5,11 @@
  *  - priority inheritance
  *  - parameter changes
  *  - cpuset moves
+ *  - affinity changes
  *  - deaths, yields and runtime overruns
  *  - bandwidth reclaiming and fair server changes
  *  - CPU hotplug
+ *  - a random mix of most of these
  *
  * Most cases measure the free bandwidth of a root domain before and after
  * they run. probe() counts the tasks of 10ms every 100ms that the root
@@ -25,7 +27,8 @@
  * The CPUs that isolcpus="domain" isolates are in the default root
  * domain: the root domain of the isolated CPUs. The other CPUs are the
  * housekeeping CPUs, in the housekeeping root domain. The test leaves the
- * isolated CPUs out, and keeps its tasks off them.
+ * isolated CPUs out, and keeps its tasks off them. Only the cases that
+ * need them use them.
  *
  * The cases of p_cases[] run with P, a partition root of the last
  * housekeeping CPU. P is made anew for each case. Making it rebuilds the
@@ -42,7 +45,8 @@
  *
  * The test needs root, deadline admission control and 3 housekeeping
  * CPUs. Some cases need 4. Most also need the cgroup v2 cpuset
- * controller. Some need debugfs or CPU hotplug.
+ * controller. Some need debugfs or CPU hotplug. Five need
+ * isolcpus="domain" at boot.
  */
 #define _GNU_SOURCE
 #include <errno.h>
@@ -106,6 +110,7 @@ struct dl_attr {
 static char root[PATH_MAX], cg_p[PATH_MAX], cg_q[PATH_MAX];
 /* The online CPUs at the start, ascending, except the isolated ones */
 static int ncpus, *online;
+static int nisol, *isol;	/* the online CPUs that isolcpus="domain" isolates */
 static char isolated[4096];	/* the CPU list of /sys/devices/system/cpu/isolated */
 
 /* Return the @n-th highest online CPU, counting from 1. */
@@ -2539,7 +2544,7 @@ static int child_up(const char *what, int fast)
 	return 0;
 }
 
-enum mv_mode { MV_ASLEEP, MV_THROTTLED, MV_NON_CONTENDING };
+enum mv_mode { MV_ASLEEP, MV_THROTTLED, MV_YIELDED, MV_NON_CONTENDING };
 
 /*
  * Fork a process in the caller's cgroup. The process becomes a deadline
@@ -2547,6 +2552,8 @@ enum mv_mode { MV_ASLEEP, MV_THROTTLED, MV_NON_CONTENDING };
  * - MV_ASLEEP: run 1ms, set mv_state[0] to 1, then sleep.
  * - MV_THROTTLED: set mv_state[0] to 1, then spin and count in
  *   mv_state[1].
+ * - MV_YIELDED: set mv_state[0] to 1. Then spin 0.5ms, count in
+ *   mv_state[1] and yield, in a loop.
  * - MV_NON_CONTENDING: sleep a period, run a quarter of its runtime, set
  *   mv_state[0] to 1, then sleep. Its 0-lag time is still ahead.
  * If it is refused SCHED_DEADLINE, the process sets mv_state[0] to -1 and
@@ -2574,6 +2581,14 @@ static pid_t mover(enum mv_mode mode, uint64_t runtime)
 			for (;;)
 				pause();
 		}
+		if (mode == MV_YIELDED) {
+			*mv_state = 1;
+			for (;;) {
+				spin_ns(NSEC_PER_MSEC / 2);
+				mv_state[1]++;
+				sched_yield();
+			}
+		}
 		*mv_state = 1;
 		for (;;)
 			mv_state[1]++;
@@ -2581,6 +2596,69 @@ static pid_t mover(enum mv_mode mode, uint64_t runtime)
 	return pid;
 }
 
+static int wait_spinner(int moving);
+
+/*
+ * Move a deadline task into P and back, from outside P. The task is a
+ * mover() process of 30ms every 100ms, forked in the cgroup of the main
+ * process. Wait until it is in the state of @mode:
+ * - MV_ASLEEP: asleep for two periods, past its 0-lag time.
+ * - MV_NON_CONTENDING: asleep for 1ms, before its 0-lag time.
+ * - MV_THROTTLED, MV_YIELDED: its counter has stopped for 5ms.
+ * Then write its pid to cgroup.procs of P, then of the root cgroup. Both
+ * moves must succeed. A throttled or yielded task must run again within
+ * three periods. Then kill the task. P and the root cgroup must each
+ * admit as many probe tasks as before the case.
+ */
+static int moves(enum mv_mode mode, const char *name)
+{
+	int base_p, base_r, after_p, after_r, ret = KSFT_PASS;
+	pid_t pid;
+
+	base_p = probe(cg_p);
+	base_r = probe(root);
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = mover(mode, 30 * NSEC_PER_MSEC);
+	if (pid < 0 || child_up(name, mode == MV_NON_CONTENDING)) {
+		reap(pid);
+		return KSFT_FAIL;
+	}
+	if (mode == MV_NON_CONTENDING) {
+		sleep_ns(NSEC_PER_MSEC);
+	} else if (mode == MV_ASLEEP) {
+		sleep_ns(2 * PERIOD);
+	} else if (wait_spinner(0)) {
+		/* Throttled, or yielded: its counter stops. */
+		ksft_print_msg("%s: never stopped\n", name);
+		reap(pid);
+		return KSFT_FAIL;
+	}
+	if (enter(cg_p, pid) || enter(root, pid)) {
+		ksft_print_msg("%s: a move refused\n", name);
+		ret = KSFT_FAIL;
+	}
+	if (mode == MV_THROTTLED || mode == MV_YIELDED) {
+		int last = mv_state[1];
+
+		sleep_ns(3 * PERIOD);
+		if (mv_state[1] == last) {
+			ksft_print_msg("%s: moved, never ran again\n", name);
+			ret = KSFT_FAIL;
+		}
+	}
+	reap(pid);
+	sleep_ns(3 * PERIOD);
+	after_p = probe(cg_p);
+	after_r = probe(root);
+	if (ret == KSFT_PASS && (after_p != base_p || after_r != base_r)) {
+		ksft_print_msg("%s: probe tasks admitted, P %d -> %d, the other CPUs %d -> %d\n",
+			       name, base_p, after_p, base_r, after_r);
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
 /*
  * A deadline task of 60ms every 100ms sleeps in P. Move a second sleeping
  * task of 60ms every 100ms into P from outside. The move must fail with
@@ -2632,6 +2710,136 @@ static int move_refused(void)
 	return ret;
 }
 
+/*
+ * A task moved asleep into P is still on a CPU of the root domain it
+ * left. It sleeps outside P as a deadline task of 10%. The main process
+ * moves it into P, and changes it to 20%. P has room for that, so
+ * sched_setattr() must accept it. The kernel must check the request
+ * against P's root domain, which counts the task. The task then runs on
+ * P's CPU.
+ */
+static int move_asleep_setattr(void)
+{
+	int base_p, base_r, ret = KSFT_PASS, err, sfd[2];
+	pid_t pid;
+
+	base_p = probe(cg_p);
+	base_r = probe(root);
+	if (base_p < 0 || base_r < 0 || pipe(sfd))
+		return KSFT_FAIL;
+	mv_state[0] = 0;
+	pid = fork_child("a task to move into P");
+	if (!pid) {
+		char c;
+
+		close(sfd[1]);
+		mv_state[0] = 1;
+		while (read(sfd[0], &c, 1) == 1)
+			;
+		_exit(0);
+	}
+	if (pid < 0 || child_up("a task to move into P", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S')) {
+		reap(pid);
+		ret = KSFT_FAIL;
+		goto out;
+	}
+	err = set_deadline(pid, 10 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("a task of 10%% outside P refused: %s\n", strerror(-err));
+		ret = KSFT_FAIL;
+	} else if (enter(cg_p, pid)) {
+		ksft_print_msg("the move into P of a task of 10%% refused\n");
+		ret = KSFT_FAIL;
+	} else {
+		err = set_deadline(pid, 20 * NSEC_PER_MSEC, PERIOD);
+		if (err) {
+			ksft_print_msg("10%% to 20%% for a task moved asleep into P: %s\n",
+				       strerror(-err));
+			ret = KSFT_FAIL;
+		} else if (write(sfd[1], "w", 1) != 1 ||
+			   wait_for(1000, task_cpu_of(pid) == top_cpu(1))) {
+			ksft_print_msg("a task moved into P did not wake on P's CPU\n");
+			ret = KSFT_FAIL;
+		}
+	}
+	set_other(pid);
+	reap(pid);
+out:
+	close(sfd[0]);
+	close(sfd[1]);
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS && (probe(cg_p) != base_p || probe(root) != base_r)) {
+		ksft_print_msg("the free bandwidth changed after the case\n");
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
+/*
+ * The same, for a fair task: it sleeps outside P, and the main process
+ * moves it into P. Then it makes it a deadline task of 10%. P has room
+ * for that, so sched_setattr() must accept it, and P must count the task.
+ * The root domain the task left must not. The task then runs on P's CPU.
+ */
+static int move_asleep_fair_setattr(void)
+{
+	int base_p, base_r, ret = KSFT_PASS, err, sfd[2];
+	pid_t pid;
+
+	base_p = probe(cg_p);
+	base_r = probe(root);
+	if (base_p < 0 || base_r < 0 || pipe(sfd))
+		return KSFT_FAIL;
+	mv_state[0] = 0;
+	pid = fork_child("a fair task to move into P");
+	if (!pid) {
+		char c;
+
+		close(sfd[1]);
+		mv_state[0] = 1;
+		while (read(sfd[0], &c, 1) == 1)
+			;
+		_exit(0);
+	}
+	if (pid < 0 || child_up("a fair task to move into P", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S')) {
+		reap(pid);
+		ret = KSFT_FAIL;
+		goto out;
+	}
+	if (enter(cg_p, pid)) {
+		ksft_print_msg("the move into P of a fair task refused\n");
+		ret = KSFT_FAIL;
+		goto stop;
+	}
+	err = set_deadline(pid, 10 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("10%% for a fair task moved asleep into P: %s\n",
+			       strerror(-err));
+		ret = KSFT_FAIL;
+	} else if (probe(cg_p) != base_p - 1 || probe(root) != base_r) {
+		ksft_print_msg("P does not count the task, or the root domain it left does\n");
+		ret = KSFT_FAIL;
+	} else if (write(sfd[1], "w", 1) != 1 ||
+		   wait_for(1000, task_cpu_of(pid) == top_cpu(1))) {
+		ksft_print_msg("a task moved into P did not wake on P's CPU\n");
+		ret = KSFT_FAIL;
+	}
+stop:
+	set_other(pid);
+	reap(pid);
+out:
+	close(sfd[0]);
+	close(sfd[1]);
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS && (probe(cg_p) != base_p || probe(root) != base_r)) {
+		ksft_print_msg("the free bandwidth changed after the case\n");
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
 /*
  * A runtime of 1024ns every 2s gives a bandwidth of 0. A cpuset move
  * skips such a task: it has no bandwidth to move.
@@ -2722,6 +2930,44 @@ static int move_zero_bw(void)
 	return ret;
 }
 
+static int move_asleep(void)
+{
+	return moves(MV_ASLEEP, "move_asleep");
+}
+
+static int move_throttled(void)
+{
+	return moves(MV_THROTTLED, "move_throttled");
+}
+
+static int move_non_contending(void)
+{
+	return moves(MV_NON_CONTENDING, "move_non_contending");
+}
+
+/*
+ * Fork a process that reads sched_rt_runtime_us and writes the same value
+ * back @n times, 5ms apart. Then it exits. Each write rebuilds the sched
+ * domains. Return its pid, or -1.
+ */
+static pid_t rebuilder(int n)
+{
+	pid_t pid = fork_child("a sysctl writer");
+
+	if (!pid) {
+		char buf[64];
+
+		if (read_file("/proc/sys/kernel/sched_rt_runtime_us", buf, sizeof(buf)))
+			_exit(1);
+		while (n-- > 0) {
+			write_file("/proc/sys/kernel", "sched_rt_runtime_us", buf);
+			sleep_ns(5 * NSEC_PER_MSEC);
+		}
+		_exit(0);
+	}
+	return pid;
+}
+
 static void *pauser(void *arg)
 {
 	for (;;)
@@ -2729,9 +2975,200 @@ static void *pauser(void *arg)
 	return arg;
 }
 
-/* What late_setter() does, and the result. */
+/*
+ * Run as the deadline thread of wide_mover(): a deadline task of 30% that
+ * runs 1ms, sets mv_state[0] to 1 and sleeps.
+ */
+static void *dl_pauser(void *arg)
+{
+	if (set_deadline(0, 30 * NSEC_PER_MSEC, PERIOD)) {
+		mv_state[0] = -1;
+		return arg;
+	}
+	spin_ns(NSEC_PER_MSEC);
+	*mv_state = 1;
+	for (;;)
+		pause();
+	return arg;
+}
+
+/*
+ * Fork a process of @threads sleeping threads, then one deadline thread,
+ * dl_pauser(). A cgroup move of the process moves its threads one by one,
+ * between cpuset_can_attach() and cpuset_attach(). The deadline thread
+ * moves last, so that a rebuild in that window can still find it in the
+ * cgroup it leaves. Return the pid, or -1.
+ */
+static pid_t wide_mover(int threads)
+{
+	pid_t pid = fork_child("a wide deadline process");
+
+	if (!pid) {
+		pthread_attr_t a;
+		pthread_t t;
+		int i;
+
+		if (pthread_attr_init(&a) || pthread_attr_setstacksize(&a, THREAD_STACK))
+			goto no_threads;
+		for (i = 0; i < threads; i++) {
+			if (pthread_create(&t, &a, pauser, NULL))
+				goto no_threads;
+		}
+		if (pthread_create(&t, NULL, dl_pauser, NULL))
+			goto no_threads;
+		for (;;)
+			pause();
+no_threads:
+		mv_state[0] = -2;
+		_exit(1);
+	}
+	return pid;
+}
+
+/*
+ * Move a process in and out of P while rebuilder() rebuilds the sched
+ * domains. The process is wide_mover(): 2048 sleeping threads, then one
+ * sleeping deadline thread of 30%. rebuilder() writes the
+ * sched_rt_runtime_us sysctl 20 times, 5ms apart. Each write is a
+ * rebuild. Without the 5ms gaps, the rebuilds would be over before the
+ * first move reaches the window below.
+ *
+ * A rebuild between cpuset_can_attach() and cpuset_attach() would drop
+ * the bandwidth that cpuset_can_attach() reserved in the destination.
+ * cpuset_attach() would then move the bandwidth of the thread all the
+ * same. So a rebuild must wait for the end of a move in progress.
+ *
+ * A later rebuild corrects the accounting. So move until rebuilder()
+ * exits: no rebuild follows the last move. The free bandwidth of P and
+ * of the other CPUs must then be what it was with the process asleep in
+ * the root cgroup. Run six rounds.
+ */
+static int move_vs_rebuild(void)
+{
+	int base_p, base_r, with_p, with_r, after_p, after_r, round, ret = KSFT_PASS;
+	const char *name = "move_vs_rebuild";
+	pid_t pid, writer;
+
+	base_p = probe(cg_p);
+	base_r = probe(root);
+	mv_state[0] = 0;
+	pid = wide_mover(2048);
+	if (pid < 0 || child_up(name, 0)) {
+		reap(pid);
+		return mv_state[0] == -2 ? KSFT_SKIP : KSFT_FAIL;
+	}
+	/* The reference for the rounds: the task asleep in the root cgroup. */
+	sleep_ns(2 * PERIOD);
+	with_p = probe(cg_p);
+	with_r = probe(root);
+	for (round = 0; round < 6 && ret == KSFT_PASS; round++) {
+		int status, err = 0;
+
+		writer = rebuilder(20);
+		if (writer < 0) {
+			ret = KSFT_FAIL;
+			break;
+		}
+		while (!err && waitpid(writer, &status, WNOHANG) == 0) {
+			err = enter(cg_p, pid);
+			if (!err)
+				err = enter(root, pid);
+		}
+		if (err) {
+			ksft_print_msg("%s: a move refused: %s\n", name, strerror(-err));
+			reap(writer);
+			ret = KSFT_FAIL;
+			break;
+		}
+		sleep_ns(3 * PERIOD);
+		after_p = probe(cg_p);
+		after_r = probe(root);
+		if (after_p != with_p || after_r != with_r) {
+			ksft_print_msg("%s: round %d: P %d -> %d probe tasks, the rest %d -> %d\n",
+				       name, round, with_p, after_p, with_r, after_r);
+			ret = KSFT_FAIL;
+		}
+	}
+	reap(pid);
+	sleep_ns(3 * PERIOD);
+	after_p = probe(cg_p);
+	after_r = probe(root);
+	if (ret == KSFT_PASS && (after_p != base_p || after_r != base_r)) {
+		ksft_print_msg("%s: task gone: P %d -> %d probe tasks, the rest %d -> %d\n",
+			       name, base_p, after_p, base_r, after_r);
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
+/* The runtime every 100ms of the deadline threads of late_mover() */
+static uint64_t late_thread_runtime;
+
+/*
+ * Run as a deadline thread of late_mover(): a deadline task of
+ * late_thread_runtime that counts itself in mv_state[1] and sleeps.
+ */
+static void *dl_sleeper(void *arg)
+{
+	if (set_deadline(0, late_thread_runtime, PERIOD)) {
+		mv_state[0] = -1;
+		return arg;
+	}
+	mv_state[1]++;
+	for (;;)
+		pause();
+	return arg;
+}
+
+/*
+ * Fork a process of two deadline threads, dl_sleeper(), then @threads
+ * sleeping threads. Its main thread, the thread group leader, sleeps and
+ * is not a deadline task. A cgroup move of the process handles the
+ * leader first. The sleeping threads make the move long. Return the pid,
+ * or -1.
+ */
+static pid_t late_mover(int threads)
+{
+	pid_t pid = fork_child("a wide process");
+
+	if (!pid) {
+		pthread_attr_t a;
+		pthread_t t;
+		int i;
+
+		if (pthread_attr_init(&a) || pthread_attr_setstacksize(&a, THREAD_STACK))
+			goto no_threads;
+		for (i = 0; i < 2; i++) {
+			if (pthread_create(&t, &a, dl_sleeper, NULL))
+				goto no_threads;
+		}
+		for (i = 0; i < threads; i++) {
+			if (pthread_create(&t, &a, pauser, NULL))
+				goto no_threads;
+		}
+		if (wait_for_step(5000, NSEC_PER_MSEC, mv_state[1] == 2 || mv_state[0]))
+			goto no_threads;
+		if (!mv_state[0])
+			mv_state[0] = 1;
+		for (;;)
+			pause();
+no_threads:
+		mv_state[0] = -2;
+		_exit(1);
+	}
+	return pid;
+}
+
+/*
+ * What late_setter(), late_pinner() and late_killer() do, and the result.
+ * Each acts on thread @pid, @delay ns after @go is set. It stores its
+ * result in @ret and the time it returned in @done. late_setter() uses
+ * @runtime. late_killer() uses @tgid and @kill.
+ */
 static struct {
 	pid_t pid;
+	pid_t tgid;
+	int kill;
 	uint64_t runtime;
 	uint64_t delay;
 	atomic_int go;
@@ -2758,18 +3195,167 @@ static void *late_setter(void *arg)
 	return arg;
 }
 
+/*
+ * Make the main thread of a process a deadline task while the process
+ * moves from the root cgroup into P.
+ *
+ * The process is late_mover(). Its main thread sleeps and is not a
+ * deadline task. Two of its threads are sleeping deadline tasks of
+ * @thread percent each. 2048 more sleeping threads make the move long.
+ * A thread of the test, late_setter(), calls sched_setattr() on the main
+ * thread to make it a deadline task of @leader percent.
+ *
+ * cpuset_can_attach() reserves room in P for the two deadline threads.
+ * If the main thread became a deadline task after that, no room would be
+ * reserved for it. cpuset_attach() handles the main thread first.
+ *
+ * sched_setattr() waits for the end of a move in progress. So it runs
+ * before the move or after it:
+ *  - Before: the move counts three deadline tasks. With room in P for
+ *    the three, the move must succeed. P must then count the three, and
+ *    the root domain the process left must count none. Without room,
+ *    the move must be refused with EBUSY.
+ *  - After: the main thread is allowed on P's CPU only. It is still
+ *    asleep on a CPU of the root domain it left. sched_setattr() asks P
+ *    for room. Without room, it fails with EBUSY.
+ * Without room in P for the three, the case fails if the move and
+ * sched_setattr() both succeed.
+ *
+ * Try 30 delays of sched_setattr(), spread over the time a move takes.
+ */
+static int became_deadline(int thread, int leader, const char *name)
+{
+	int base_p, base_r, ret = KSFT_PASS, i, raced = 0;
+	int need = (2 * thread + leader) / 10, fits;
+	uint64_t start, len;
+	pid_t pid;
+
+	base_p = probe(cg_p);
+	base_r = probe(root);
+	fits = base_p >= need;
+	if (base_p < 2 * thread / 10) {
+		ksft_print_msg("%s: P admits %d probe tasks, %d needed\n", name, base_p,
+			       2 * thread / 10);
+		return KSFT_SKIP;
+	}
+	late_thread_runtime = thread * NSEC_PER_MSEC;
+	late.runtime = leader * NSEC_PER_MSEC;
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = late_mover(2048);
+	if (pid < 0 || child_up(name, 0)) {
+		reap(pid);
+		return mv_state[0] == -2 ? KSFT_SKIP : KSFT_FAIL;
+	}
+	/* Time one move, to spread the delays over it. */
+	start = now_ns();
+	if (enter(cg_p, pid) || enter(root, pid)) {
+		ksft_print_msg("%s: a move refused\n", name);
+		reap(pid);
+		return KSFT_FAIL;
+	}
+	len = (now_ns() - start) / 2;
+	sleep_ns(2 * PERIOD);
+
+	late.pid = pid;
+	for (i = 0; i < 30 && ret == KSFT_PASS; i++) {
+		pthread_t t;
+		int err;
+
+		late.go = 0;
+		late.delay = len * i / 30;
+		if (pthread_create(&t, NULL, late_setter, NULL)) {
+			ret = KSFT_FAIL;
+			break;
+		}
+		sleep_ns(NSEC_PER_MSEC);
+		late.go = 1;
+		err = enter(cg_p, pid);
+		join(t);
+		if (err && (fits || err != -EBUSY || late.ret)) {
+			ksft_print_msg("%s: the move refused: %s\n", name, strerror(-err));
+			ret = KSFT_FAIL;
+		} else if (!err && !late.ret && !fits) {
+			ksft_print_msg("%s: the move and the change both succeeded, with no room in P\n",
+				       name);
+			ret = KSFT_FAIL;
+		} else if (!err && !late.ret) {
+			raced++;
+			if (admits_in(cg_p, base_p - need, "P, with the three tasks") ||
+			    admits_in(root, base_r, "the root domain the tasks left"))
+				ret = KSFT_FAIL;
+		} else if (late.ret && (fits || late.ret != -EBUSY)) {
+			ksft_print_msg("%s: sched_setattr: %s\n", name, strerror(-late.ret));
+			ret = KSFT_FAIL;
+		}
+		if (ret == KSFT_FAIL)
+			ksft_print_msg("%s: try %d, the change %llu us into a move of %llu us\n",
+				       name, i, (unsigned long long)(late.delay / NSEC_PER_USEC),
+				       (unsigned long long)(len / NSEC_PER_USEC));
+		if ((!late.ret && set_other(pid)) || enter(root, pid)) {
+			ksft_print_msg("%s: the process cannot go back\n", name);
+			ret = KSFT_FAIL;
+		}
+		sleep_ns(2 * PERIOD);
+	}
+	if (ret == KSFT_PASS && fits && !raced)
+		ksft_print_msg("%s: no change succeeded with a move\n", name);
+	reap(pid);
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS && (probe(cg_p) != base_p || probe(root) != base_r)) {
+		ksft_print_msg("%s: the free bandwidth changed\n", name);
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
+/* Run it with room in P: two threads of 20% and a main thread of 30%. */
+static int move_became_deadline(void)
+{
+	return became_deadline(20, 30, "move_became_deadline");
+}
+
+/* Run it without room in P: two threads of 30% and a main thread of 40%. */
+static int move_became_deadline_no_room(void)
+{
+	return became_deadline(30, 40, "move_became_deadline_no_room");
+}
+
 static void no_op(int sig)
 {
 }
 
+/* The CPU that dl_sleeper_tid() first runs on, or -1 for any CPU */
+static int sleeper_cpu = -1;
+
 /*
  * Run as the deadline thread of pinned_mover(): a deadline task of 30%.
  * Store the tid in mv_state[3], set mv_state[0] to 1 and sleep. A signal
  * wakes the thread up. It then sleeps again. If mv_state[4] is set, this
  * thread exits instead, and the process stays.
+ *
+ * With sleeper_cpu set, first run 1ms pinned on that CPU, then restore
+ * the previous affinity. Do this before sched_setattr(): the affinity of
+ * a deadline task must include every CPU of its root domain.
  */
 static void *dl_sleeper_tid(void *arg)
 {
+	if (sleeper_cpu >= 0) {
+		cpu_set_t all, one;
+
+		CPU_ZERO(&one);
+		CPU_SET(sleeper_cpu, &one);
+		if (sched_getaffinity(0, sizeof(all), &all) ||
+		    sched_setaffinity(0, sizeof(one), &one)) {
+			mv_state[0] = -2;
+			return arg;
+		}
+		spin_ns(NSEC_PER_MSEC);
+		if (sched_setaffinity(0, sizeof(all), &all)) {
+			mv_state[0] = -2;
+			return arg;
+		}
+	}
 	if (set_deadline(0, 30 * NSEC_PER_MSEC, PERIOD)) {
 		mv_state[0] = -1;
 		return arg;
@@ -2834,6 +3420,619 @@ static pid_t pinned_mover(int threads, int fifo)
 	return pid;
 }
 
+/*
+ * Restrict late.pid to the CPU of P and the CPU in @arg, late.delay ns
+ * after late.go.
+ */
+static void *late_pinner(void *arg)
+{
+	uint64_t start;
+	cpu_set_t set;
+
+	CPU_ZERO(&set);
+	CPU_SET(top_cpu(1), &set);
+	CPU_SET((long)arg, &set);
+	while (!late.go)
+		;
+	start = now_ns();
+	while (now_ns() - start < late.delay)
+		;
+	late.ret = sched_setaffinity(late.pid, sizeof(set), &set) ? -errno : 0;
+	late.done = now_ns();
+	return NULL;
+}
+
+/*
+ * Change the affinity of a sleeping deadline thread while its process
+ * moves from P to the root cgroup.
+ *
+ * The process is pinned_mover(): 2048 sleeping threads, then a deadline
+ * thread of 30%. That thread went to sleep on a CPU of the root cgroup,
+ * and was moved into P asleep. So P counts it, and it is still on that
+ * CPU. A thread of the test, late_pinner(), calls sched_setaffinity()
+ * on it.
+ *
+ * cpuset_can_attach() reserves the bandwidth of the thread on one CPU of
+ * the root cgroup. The move records that CPU. It is the CPU the thread
+ * is on, if its affinity allows that CPU. If not, it is the first CPU of
+ * the root cgroup that its affinity allows.
+ *
+ * sched_setaffinity() restricts the thread to two CPUs: the CPU of P,
+ * and a CPU of the root cgroup that the thread is not on. The affinity
+ * of a deadline task must include every CPU of the root domain that
+ * counts it, so the mask needs the CPU of P. The move then records the
+ * second CPU.
+ *
+ * sched_setaffinity() waits for the end of a move in progress. So it
+ * runs before the move or after it:
+ *  - Before: the bandwidth is reserved on the CPU the move records. The
+ *    root domain of that CPU must count the thread once the move is
+ *    done, and P must no longer count it.
+ *  - After: the thread is counted in the root domain of the root
+ *    cgroup. The mask does not include every CPU of that root domain.
+ *    sched_setaffinity() is refused with EBUSY.
+ *
+ * Try 20 delays of sched_setaffinity(), spread over the time a move
+ * takes.
+ */
+static int move_affinity_changed(void)
+{
+	int with_p, with_r, ret = KSFT_PASS, i, raced = 0;
+	const char *name = "move_affinity_changed";
+	uint64_t start, len;
+	cpu_set_t all;
+	pid_t pid;
+
+	CPU_ZERO(&all);
+	for (i = 0; i < ncpus; i++)
+		CPU_SET(online[i], &all);
+	mv_state[0] = 0;
+	mv_state[3] = 0;
+	mv_state[4] = 0;
+	pid = pinned_mover(2048, 0);
+	if (pid < 0 || child_up(name, 0)) {
+		reap(pid);
+		return mv_state[0] == -2 ? KSFT_SKIP : KSFT_FAIL;
+	}
+	/* The reference: the thread asleep in the root cgroup. */
+	sleep_ns(2 * PERIOD);
+	with_p = probe(cg_p);
+	with_r = probe(root);
+	/* Time one move, to spread the delays over it. */
+	start = now_ns();
+	if (enter(cg_p, pid) || enter(root, pid)) {
+		ksft_print_msg("%s: a move refused\n", name);
+		reap(pid);
+		return KSFT_FAIL;
+	}
+	len = (now_ns() - start) / 2;
+
+	late.pid = mv_state[3];
+	for (i = 0; i < 20 && ret == KSFT_PASS; i++) {
+		pthread_t t;
+		long cpu;
+		int err;
+
+		if (sched_setaffinity(late.pid, sizeof(all), &all) || enter(cg_p, pid)) {
+			ksft_print_msg("%s: the process cannot go into P\n", name);
+			ret = KSFT_FAIL;
+			break;
+		}
+		/* Not the CPU the thread is on: the move would record that one. */
+		cpu = task_cpu_of(late.pid) == online[1] ? online[0] : online[1];
+		late.go = 0;
+		late.delay = len * i / 20;
+		if (pthread_create(&t, NULL, late_pinner, (void *)cpu)) {
+			ret = KSFT_FAIL;
+			break;
+		}
+		sleep_ns(NSEC_PER_MSEC);
+		late.go = 1;
+		err = enter(root, pid);
+		join(t);
+		if (err) {
+			ksft_print_msg("%s: the move refused: %s\n", name, strerror(-err));
+			ret = KSFT_FAIL;
+		} else if (!late.ret) {
+			raced++;
+			sleep_ns(2 * PERIOD);
+			if (admits_in(cg_p, with_p, "P, which the thread left") ||
+			    admits_in(root, with_r, "the root domain of the thread")) {
+				ksft_print_msg("%s: try %d, the change %llu us into a move of %llu us\n",
+					       name, i, (unsigned long long)(late.delay / NSEC_PER_USEC),
+					       (unsigned long long)(len / NSEC_PER_USEC));
+				ret = KSFT_FAIL;
+			}
+		} else if (late.ret && late.ret != -EBUSY) {
+			ksft_print_msg("%s: sched_setaffinity: %s\n", name, strerror(-late.ret));
+			ret = KSFT_FAIL;
+		}
+	}
+	if (ret == KSFT_PASS && !raced)
+		ksft_print_msg("%s: no change succeeded\n", name);
+	reap(pid);
+	return ret;
+}
+
+/*
+ * Make a thread a deadline task while sched_setaffinity() runs on it, and
+ * move its process from P to the root cgroup meanwhile.
+ *
+ * sched_setaffinity() waits for the end of a move in progress when the
+ * task is a deadline task. It tests the policy first, with no lock. Here
+ * the thread T is SCHED_OTHER at that test:
+ *
+ *   sched_setaffinity(T)         sched_setattr(T)        echo PID > cgroup.procs
+ *
+ *   T is SCHED_OTHER: no wait
+ *                                T is a deadline task
+ *                                                        cpuset_can_attach()
+ *                                                          reserves room for T
+ *   changes the affinity of T
+ *                                                        cpuset_attach()
+ *                                                          moves T
+ *
+ * The new affinity holds the CPU of P and one CPU of the root cgroup.
+ * The room was reserved on another CPU. Once the move is done, the
+ * root domain of the root cgroup must count T, and P must not.
+ *
+ * Delay injection: the window after the test of the policy is a few
+ * instructions wide. The case only reaches it on a kernel that can make
+ * sched_setaffinity() sleep there. It passes without reaching it
+ * otherwise.
+ */
+static int move_affinity_became_deadline(void)
+{
+	const char *name = "move_affinity_became_deadline";
+	int with_p, with_r, ret = KSFT_PASS, i;
+	uint64_t start, len, delay_ms;
+	cpu_set_t all;
+	pid_t pid;
+
+	CPU_ZERO(&all);
+	for (i = 0; i < ncpus; i++)
+		CPU_SET(online[i], &all);
+	mv_state[0] = 0;
+	mv_state[3] = 0;
+	mv_state[4] = 0;
+	pid = pinned_mover(2048, 0);
+	if (pid < 0 || child_up(name, 0)) {
+		reap(pid);
+		return mv_state[0] == -2 ? KSFT_SKIP : KSFT_FAIL;
+	}
+	/* The reference: the thread a deadline task, asleep in the root cgroup. */
+	sleep_ns(2 * PERIOD);
+	with_p = probe(cg_p);
+	with_r = probe(root);
+	/* Time one move, to place the change inside it. */
+	start = now_ns();
+	if (enter(cg_p, pid) || enter(root, pid)) {
+		ksft_print_msg("%s: a move refused\n", name);
+		reap(pid);
+		return KSFT_FAIL;
+	}
+	len = (now_ns() - start) / 2;
+	delay_ms = 3 * len / NSEC_PER_MSEC + 30;
+
+	late.pid = mv_state[3];
+	for (i = 0; i < 10 && ret == KSFT_PASS; i++) {
+		uint64_t t0, at;
+		pthread_t t;
+		int err;
+
+		if (sched_setaffinity(late.pid, sizeof(all), &all) || enter(cg_p, pid) ||
+		    set_other(late.pid)) {
+			ksft_print_msg("%s: the thread cannot go into P as SCHED_OTHER\n", name);
+			ret = KSFT_FAIL;
+			break;
+		}
+		/*
+		 * Wake the thread once, so that it sleeps on the CPU of P. The
+		 * move to the root cgroup then reserves room on a CPU other
+		 * than online[1], which late_pinner() adds to its affinity.
+		 */
+		if (syscall(SYS_tgkill, pid, late.pid, SIGUSR1)) {
+			ret = KSFT_FAIL;
+			break;
+		}
+		sleep_ns(5 * NSEC_PER_MSEC);
+		/*
+		 * Delay injection: sched_setaffinity() would be asked here to
+		 * sleep delay_ms after its test of the policy.
+		 */
+		late.go = 0;
+		late.delay = 0;
+		if (pthread_create(&t, NULL, late_pinner, (void *)(long)online[1])) {
+			ret = KSFT_FAIL;
+			break;
+		}
+		sleep_ns(NSEC_PER_MSEC);
+		t0 = now_ns();
+		late.go = 1;
+		/* With the delay, the change has tested the policy and sleeps. */
+		sleep_ns(5 * NSEC_PER_MSEC);
+		err = set_deadline(late.pid, 30 * NSEC_PER_MSEC, PERIOD);
+		if (err) {
+			ksft_print_msg("%s: sched_setattr: %s\n", name, strerror(-err));
+			ret = KSFT_FAIL;
+		}
+		/* Start the move so that the change wakes up inside it. */
+		at = t0 + delay_ms * NSEC_PER_MSEC - len * (i + 1) / 11;
+		while (now_ns() < at)
+			;
+		err = enter(root, pid);
+		join(t);
+		if (err) {
+			ksft_print_msg("%s: the move refused: %s\n", name, strerror(-err));
+			ret = KSFT_FAIL;
+		} else if (!late.ret) {
+			sleep_ns(2 * PERIOD);
+			if (admits_in(cg_p, with_p, "P, which the thread left") ||
+			    admits_in(root, with_r, "the root domain of the thread")) {
+				ksft_print_msg("%s: try %d, the change landed in a move of %llu us\n",
+					       name, i, (unsigned long long)(len / NSEC_PER_USEC));
+				ret = KSFT_FAIL;
+			}
+		} else if (late.ret && late.ret != -EBUSY) {
+			ksft_print_msg("%s: sched_setaffinity: %s\n", name, strerror(-late.ret));
+			ret = KSFT_FAIL;
+		}
+	}
+	reap(pid);
+	return ret;
+}
+
+/*
+ * Wake thread late.pid of process late.tgid up with a signal, late.delay
+ * ns after late.go. With late.kill, the thread then exits.
+ */
+static void *late_killer(void *arg)
+{
+	uint64_t start;
+
+	while (!late.go)
+		;
+	start = now_ns();
+	while (now_ns() - start < late.delay)
+		;
+	mv_state[4] = late.kill;
+	late.ret = syscall(SYS_tgkill, late.tgid, late.pid, SIGUSR1) ? -errno : 0;
+	late.done = now_ns();
+	return arg;
+}
+
+/*
+ * Kill a sleeping deadline thread of 30% while its process moves into
+ * P. A thread that is part of a move cannot exit before the move ends:
+ * its exit waits for it. So a thread killed during the move dies right
+ * after it, and must release its bandwidth where the move left it. Once the process
+ * is gone, the free bandwidth of P and of the root domain the process
+ * left must be what it was.
+ *
+ * Try 12 delays spread over the time a move takes, each with a new
+ * process.
+ */
+static int move_died(void)
+{
+	int base_p, base_r, ret = KSFT_PASS, i;
+	const char *name = "move_died";
+	uint64_t len = 0;
+
+	base_p = probe(cg_p);
+	base_r = probe(root);
+	for (i = 0; i < 12 && ret == KSFT_PASS; i++) {
+		pthread_t t;
+		pid_t pid;
+		int err;
+
+		mv_state[0] = 0;
+		mv_state[3] = 0;
+		mv_state[4] = 0;
+		pid = pinned_mover(2048, 0);
+		if (pid < 0 || child_up(name, 0)) {
+			reap(pid);
+			return mv_state[0] == -2 ? KSFT_SKIP : KSFT_FAIL;
+		}
+		if (!i) {
+			/* Time one move, to spread the delays over it. */
+			uint64_t start = now_ns();
+
+			if (enter(cg_p, pid) || enter(root, pid)) {
+				ksft_print_msg("%s: a move refused\n", name);
+				reap(pid);
+				return KSFT_FAIL;
+			}
+			len = (now_ns() - start) / 2;
+		}
+		late.pid = mv_state[3];
+		late.tgid = pid;
+		late.kill = 1;
+		late.go = 0;
+		late.delay = len * i / 12;
+		if (pthread_create(&t, NULL, late_killer, NULL)) {
+			reap(pid);
+			return KSFT_FAIL;
+		}
+		sleep_ns(NSEC_PER_MSEC);
+		late.go = 1;
+		err = enter(cg_p, pid);
+		join(t);
+		if (err) {
+			ksft_print_msg("%s: the move refused: %s\n", name, strerror(-err));
+			ret = KSFT_FAIL;
+		}
+		reap(pid);
+		sleep_ns(3 * PERIOD);
+		if (ret == KSFT_PASS &&
+		    (admits_in(cg_p, base_p, "P, after the thread died") ||
+		     admits_in(root, base_r, "the root domain the process left"))) {
+			ksft_print_msg("%s: try %d, the death %llu us into a move of %llu us\n",
+				       name, i, (unsigned long long)(late.delay / NSEC_PER_USEC),
+				       (unsigned long long)(len / NSEC_PER_USEC));
+			ret = KSFT_FAIL;
+		}
+	}
+	return ret;
+}
+
+static int late_sysrq_fd;
+
+/*
+ * Write 'n' to /proc/sysrq-trigger, late.delay ns after late.go. sysrq-n
+ * makes every real-time and deadline task SCHED_OTHER.
+ */
+static void *late_sysrq(void *arg)
+{
+	uint64_t start;
+
+	while (!late.go)
+		;
+	start = now_ns();
+	while (now_ns() - start < late.delay)
+		;
+	late.ret = write(late_sysrq_fd, "n", 1) == 1 ? 0 : -errno;
+	late.done = now_ns();
+	return arg;
+}
+
+/*
+ * Make sysrq-n take a sleeping deadline thread of 30% out of the class
+ * while its process moves into P. cpuset_can_attach() reserves room in P
+ * for the thread. sysrq-n does not wait for the move. If it comes after
+ * the reservation, the thread moves no bandwidth, and cpuset_attach()
+ * must give the room back. Once the process is gone, the free bandwidth of P and of
+ * the root domain the process left must be what it was.
+ *
+ * sysrq-n changes the whole system. So the case runs last of the cases
+ * with P, and only with DEADLINE_TEST_SYSRQ set.
+ *
+ * Try 12 delays spread over the time a move takes, each with a new
+ * process.
+ */
+static int move_normalized(void)
+{
+	int base_p, base_r, ret = KSFT_PASS, i;
+	const char *name = "move_normalized";
+	uint64_t len = 0;
+
+	if (!getenv("DEADLINE_TEST_SYSRQ")) {
+		ksft_print_msg("sysrq-n renices every real-time task: set DEADLINE_TEST_SYSRQ=1\n");
+		return KSFT_SKIP;
+	}
+	late_sysrq_fd = open("/proc/sysrq-trigger", O_WRONLY);
+	if (late_sysrq_fd < 0) {
+		ksft_print_msg("/proc/sysrq-trigger: %s\n", strerror(errno));
+		return KSFT_SKIP;
+	}
+	base_p = probe(cg_p);
+	base_r = probe(root);
+	for (i = 0; i < 12 && ret == KSFT_PASS; i++) {
+		pthread_t t;
+		pid_t pid;
+		int err;
+
+		mv_state[0] = 0;
+		mv_state[3] = 0;
+		mv_state[4] = 0;
+		pid = pinned_mover(2048, 0);
+		if (pid < 0 || child_up(name, 0)) {
+			reap(pid);
+			close(late_sysrq_fd);
+			return mv_state[0] == -2 ? KSFT_SKIP : KSFT_FAIL;
+		}
+		if (!i) {
+			/* Time one move, to spread the delays over it. */
+			uint64_t start = now_ns();
+
+			if (enter(cg_p, pid) || enter(root, pid)) {
+				ksft_print_msg("%s: a move refused\n", name);
+				reap(pid);
+				close(late_sysrq_fd);
+				return KSFT_FAIL;
+			}
+			len = (now_ns() - start) / 2;
+		}
+		late.go = 0;
+		late.delay = len * i / 12;
+		if (pthread_create(&t, NULL, late_sysrq, NULL)) {
+			reap(pid);
+			close(late_sysrq_fd);
+			return KSFT_FAIL;
+		}
+		sleep_ns(NSEC_PER_MSEC);
+		late.go = 1;
+		err = enter(cg_p, pid);
+		join(t);
+		if (err) {
+			ksft_print_msg("%s: the move refused: %s\n", name, strerror(-err));
+			ret = KSFT_FAIL;
+		} else if (late.ret) {
+			ksft_print_msg("%s: sysrq-n: %s\n", name, strerror(-late.ret));
+			ret = KSFT_SKIP;
+		}
+		reap(pid);
+		sleep_ns(3 * PERIOD);
+		if (ret == KSFT_PASS &&
+		    (admits_in(cg_p, base_p, "P, after sysrq-n") ||
+		     admits_in(root, base_r, "the root domain the process left"))) {
+			ksft_print_msg("%s: try %d, sysrq-n %llu us into a move of %llu us\n",
+				       name, i, (unsigned long long)(late.delay / NSEC_PER_USEC),
+				       (unsigned long long)(len / NSEC_PER_USEC));
+			ret = KSFT_FAIL;
+		}
+	}
+	close(late_sysrq_fd);
+	return ret;
+}
+
+static int hold(int n);
+static void release_held(void);
+
+/*
+ * Wake a sleeping deadline thread of 30% up while its process moves from
+ * P to the root cgroup.
+ *
+ * The process is pinned_mover(): 2048 sleeping threads, then the deadline
+ * thread. That thread first ran on the second CPU of the root cgroup,
+ * went to sleep there, and was moved into P asleep. So P counts it, and
+ * it is still on that CPU. A thread of the test, late_killer(), wakes it
+ * up with a signal.
+ *
+ * cpuset_can_attach() reserves room for the thread on the CPU that the
+ * move back records: the CPU the thread is on. If the thread wakes up
+ * after that, it runs on the CPU of P. cpuset_attach() must still move
+ * the bandwidth to the CPU recorded. Working the CPU out again would
+ * give the first CPU of the root cgroup, where nothing is reserved.
+ *
+ * Both CPUs are in the same root domain. So that root domain must count
+ * the thread once the move is done, and P must no longer count it.
+ *
+ * With @full, hold() first fills that root domain with deadline threads
+ * of the test, until 40% is free. The thread of 30% then fits once, and
+ * not twice.
+ *
+ * Try 12 delays spread over the time a move takes, each with a new
+ * process.
+ */
+static int woken(int full, const char *name)
+{
+	int base_p, base_r, free_r, ret = KSFT_PASS, i;
+	uint64_t len = 0;
+
+	base_p = probe(cg_p);
+	base_r = probe(root);
+	if (base_r < 5) {
+		ksft_print_msg("%s: no room for the thread\n", name);
+		return KSFT_SKIP;
+	}
+	free_r = base_r;
+	if (full) {
+		if (hold(base_r - 4)) {
+			release_held();
+			return KSFT_FAIL;
+		}
+		free_r = 4;
+	}
+	for (i = 0; i < 12 && ret == KSFT_PASS; i++) {
+		pid_t pid, tid;
+		pthread_t t;
+		int err;
+
+		mv_state[0] = 0;
+		mv_state[3] = 0;
+		mv_state[4] = 0;
+		/* Not the first CPU: the move falls back to that one. */
+		sleeper_cpu = online[1];
+		pid = pinned_mover(2048, 0);
+		sleeper_cpu = -1;
+		if (pid < 0 || child_up(name, 0)) {
+			reap(pid);
+			release_held();
+			return mv_state[0] == -2 ? KSFT_SKIP : KSFT_FAIL;
+		}
+		tid = mv_state[3];
+		sleep_ns(PERIOD);
+		if (!i) {
+			/*
+			 * Time the move into P, to spread the delays over
+			 * a move.
+			 */
+			uint64_t start = now_ns();
+
+			err = enter(cg_p, pid);
+			if (!err) {
+				len = now_ns() - start;
+				err = enter(root, pid);
+			}
+			if (err) {
+				ksft_print_msg("%s: a move refused\n", name);
+				reap(pid);
+				release_held();
+				return KSFT_FAIL;
+			}
+		}
+		if (enter(cg_p, pid)) {
+			ksft_print_msg("%s: the process cannot go into P\n", name);
+			reap(pid);
+			release_held();
+			return KSFT_FAIL;
+		}
+		if (task_cpu_of(tid) != online[1]) {
+			ksft_print_msg("%s: the thread is on CPU %d, not on CPU %d\n", name,
+				       task_cpu_of(tid), online[1]);
+			reap(pid);
+			release_held();
+			return KSFT_SKIP;
+		}
+		late.pid = tid;
+		late.tgid = pid;
+		late.kill = 0;
+		late.go = 0;
+		late.delay = len * i / 12;
+		if (pthread_create(&t, NULL, late_killer, NULL)) {
+			reap(pid);
+			release_held();
+			return KSFT_FAIL;
+		}
+		sleep_ns(NSEC_PER_MSEC);
+		late.go = 1;
+		err = enter(root, pid);
+		join(t);
+		if (err) {
+			ksft_print_msg("%s: the move refused: %s\n", name, strerror(-err));
+			ret = KSFT_FAIL;
+		}
+		sleep_ns(2 * PERIOD);
+		if (ret == KSFT_PASS &&
+		    (admits_in(cg_p, base_p, "P, which the thread left") ||
+		     admits_in(root, free_r - 3, "the root domain of the thread"))) {
+			ksft_print_msg("%s: try %d, the wakeup %llu us into a move of %llu us\n",
+				       name, i, (unsigned long long)(late.delay / NSEC_PER_USEC),
+				       (unsigned long long)(len / NSEC_PER_USEC));
+			ret = KSFT_FAIL;
+		}
+		reap(pid);
+		sleep_ns(3 * PERIOD);
+	}
+	release_held();
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS &&
+	    (admits_in(cg_p, base_p, "P, at the end") ||
+	     admits_in(root, base_r, "the root domain of the rest, at the end")))
+		ret = KSFT_FAIL;
+	return ret;
+}
+
+static int move_woken(void)
+{
+	return woken(0, "move_woken");
+}
+
+static int move_woken_full(void)
+{
+	return woken(1, "move_woken_full");
+}
+
 /*
  * Have the cpu controller refuse a move after cpuset_can_attach()
  * reserved room. cpuset_cancel_attach() must then give the room back.
@@ -2959,6 +4158,78 @@ static int move_cancelled(void)
 	return ret;
 }
 
+/* Return whether every task of @cg is frozen. */
+static int cg_frozen(const char *cg)
+{
+	char path[PATH_MAX + 32], buf[256];
+
+	snprintf(path, sizeof(path), "%s/cgroup.events", cg);
+	return !read_file(path, buf, sizeof(buf)) && strstr(buf, "frozen 1");
+}
+
+/*
+ * Freeze P with a running deadline task of 30% in it. Move the frozen
+ * task to the root cgroup, switch it to SCHED_OTHER, thaw P and kill the
+ * task. Do it three times. The free bandwidth of P and of the root
+ * domain of the other CPUs must then be what it was.
+ *
+ * A frozen task sleeps in its signal handling. The root cgroup is not
+ * frozen, so the move thaws the task. It is woken on P's CPU, before
+ * cpuset_attach() gives it the CPUs of the root cgroup.
+ */
+static int frozen_moved_switched(void)
+{
+	const char *what = "a deadline task to freeze";
+	int base_p, base_r, ret = KSFT_PASS, i;
+
+	base_p = probe(cg_p);
+	base_r = probe(root);
+	for (i = 0; i < 3 && ret == KSFT_PASS; i++) {
+		pid_t pid;
+
+		mv_state[0] = 0;
+		pid = fork_child(what);
+		if (!pid) {
+			if (enter(cg_p, getpid()) ||
+			    set_deadline(0, 30 * NSEC_PER_MSEC, PERIOD)) {
+				mv_state[0] = -1;
+				_exit(1);
+			}
+			mv_state[0] = 1;
+			for (;;)
+				spin_ns(NSEC_PER_MSEC);
+		}
+		if (pid < 0 || child_up(what, 0)) {
+			reap(pid);
+			return KSFT_FAIL;
+		}
+		if (write_file(cg_p, "cgroup.freeze", "1")) {
+			ksft_print_msg("P cannot be frozen\n");
+			reap(pid);
+			return KSFT_SKIP;
+		}
+		if (wait_for(2000, cg_frozen(cg_p))) {
+			ksft_print_msg("P does not freeze\n");
+			ret = KSFT_FAIL;
+		} else if (enter(root, pid)) {
+			ksft_print_msg("the frozen task cannot leave P\n");
+			ret = KSFT_FAIL;
+		} else if (set_other(pid)) {
+			ksft_print_msg("the task cannot leave SCHED_DEADLINE\n");
+			ret = KSFT_FAIL;
+		}
+		if (write_file(cg_p, "cgroup.freeze", "0"))
+			ksft_print_msg("P cannot be thawed\n");
+		reap(pid);
+	}
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS &&
+	    (admits_in(cg_p, base_p, "P, after the frozen tasks") ||
+	     admits_in(root, base_r, "the root domain of the rest")))
+		ret = KSFT_FAIL;
+	return ret;
+}
+
 /* Deaths, in P */
 
 enum die_mode { DIE_RUNNING, DIE_SWITCHED_OUT, DIE_SHRUNK };
@@ -3558,6 +4829,11 @@ static int yield_switched_out(void)
 	return ret;
 }
 
+static int yield_moved(void)
+{
+	return moves(MV_YIELDED, "yield_moved");
+}
+
 /* Kill a deadline task while sched_yield() throttles it. */
 static int yield_killed(void)
 {
@@ -3833,6 +5109,109 @@ static int reclaim_switched(void)
 	return ret;
 }
 
+/*
+ * Fork a reclaiming deadline task of 10%. It spins, and publishes in
+ * mv_state[1] the CPU time it has used, in milliseconds. It idles while
+ * mv_state[2] is set, and the moves happen then. A cpuset move waits for
+ * an RCU grace period. Where RCU runs in kthreads (PREEMPT_RT), a task
+ * that reclaims its whole CPU keeps that grace period from ending. Return
+ * the pid, or -1.
+ */
+static pid_t reclaim_mover(void)
+{
+	pid_t pid = fork_child("a reclaiming task");
+
+	if (!pid) {
+		if (set_deadline_flags(0, 10 * NSEC_PER_MSEC, PERIOD,
+				       SCHED_FLAG_RECLAIM)) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		mv_state[0] = 1;
+		for (;;) {
+			if (mv_state[2]) {
+				sleep_ns(10 * NSEC_PER_MSEC);
+				continue;
+			}
+			spin_ns(NSEC_PER_MSEC);
+			mv_state[1] = (int)(thread_time_ns() / NSEC_PER_MSEC);
+		}
+	}
+	return pid;
+}
+
+/* Idle the reclaiming task, then move it to @cg. Return 0, or -errno. */
+static int move_idle(const char *cg, pid_t pid)
+{
+	int err;
+
+	mv_state[2] = 1;
+	sleep_ns(20 * NSEC_PER_MSEC);	/* it stops spinning */
+	err = enter(cg, pid);
+	mv_state[2] = 0;
+	return err;
+}
+
+/* Return the CPU share, in percent, of the reclaiming task over @ns. */
+static int mover_share(uint64_t ns)
+{
+	uint64_t wall = now_ns();
+	int cpu = mv_state[1];
+
+	sleep_ns(ns);
+	cpu = mv_state[1] - cpu;
+	wall = now_ns() - wall;
+	return (int)(100 * (uint64_t)cpu * NSEC_PER_MSEC / wall);
+}
+
+/*
+ * Move a reclaiming task into P, back out, and into P again. It must
+ * reclaim as much of P's CPU as it did the first time. Once it is gone,
+ * the free bandwidth of both root domains must be what it was.
+ */
+static int reclaim_moved(void)
+{
+	int base_p, base_r, in_p, again = 0, ret = KSFT_PASS;
+	pid_t pid;
+
+	base_p = probe(cg_p);
+	base_r = probe(root);
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	mv_state[2] = 1;		/* idle until it is in P */
+	pid = reclaim_mover();
+	if (pid < 0)
+		return KSFT_FAIL;
+	if (child_up("a reclaiming task", 0) || move_idle(cg_p, pid)) {
+		mv_state[2] = 1;
+		reap(pid);
+		return KSFT_FAIL;
+	}
+	sleep_ns(2 * PERIOD);
+	in_p = mover_share(SHARE_NS);
+	if (move_idle(root, pid) || move_idle(cg_p, pid)) {
+		ksft_print_msg("a move of a reclaiming task refused\n");
+		ret = KSFT_FAIL;
+	} else {
+		sleep_ns(2 * PERIOD);
+		again = mover_share(SHARE_NS);
+		if (in_p < RECLAIM_MIN || again < in_p - SHARE_SLACK ||
+		    again > in_p + SHARE_SLACK) {
+			ksft_print_msg("reclaiming: %d%% of P's CPU, %d%% after a move\n",
+				       in_p, again);
+			ret = KSFT_FAIL;
+		}
+	}
+	mv_state[2] = 1;
+	reap(pid);
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS && (probe(cg_p) != base_p || probe(root) != base_r)) {
+		ksft_print_msg("a reclaiming task moved: the free bandwidth changed\n");
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
 /* Deadline servers */
 
 #define SERVER_RUNTIME	(100 * NSEC_PER_MSEC)	/* the cases start at 10% */
@@ -4557,6 +5936,281 @@ static int params_waking(void)
 	return ret;
 }
 
+/* A random mix of the transitions above */
+
+#define MIX_WORKERS	6
+#define MIX_NS		(3 * NSEC_PER_SEC)
+#define MIX_SEED	20261103	/* fixed: a rerun starts with the same draws */
+
+/*
+ * random_mix: six workers change their own state at random for 3s, and
+ * the case changes them from outside too. Q is a partition root of two
+ * CPUs, next to P. The case needs 4 housekeeping CPUs.
+ *
+ * Each worker does one of these, over and over:
+ *  - become a deadline task, with random parameters and flags
+ *  - switch to SCHED_OTHER
+ *  - sleep
+ *  - spin, at times past its runtime
+ *  - call sched_yield()
+ *  - wait up to 5ms for shm_lock and hold it 1ms. It is the mutex of the
+ *    priority inheritance cases. A deadline waiter boosts its owner.
+ *  - exit
+ *
+ * The case does one of these, over and over:
+ *  - set the deadline parameters of a random worker
+ *  - switch it to SCHED_OTHER
+ *  - change its affinity
+ *  - move it into P, into Q or into the root cgroup
+ *  - kill it
+ *  - change the fair server of P's CPU or of one CPU of Q
+ * It starts anew every worker it finds dead.
+ *
+ * The case does not check what a single transition does: the other cases
+ * do that. It checks the accounting afterwards. Once every worker is gone
+ * and its 0-lag time is past:
+ *  - P, Q and the housekeeping root domain must each admit what they
+ *    admitted before;
+ *  - this_bw of P's CPU and of the two CPUs of Q must be what it was.
+ * An over- or underflow of running_bw or this_bw also shows as a warning
+ * in the kernel log, which the test does not read.
+ */
+static atomic_int *mix_state;		/* 0: stop, 1 + i: worker i's rounds */
+
+static pid_t mix_worker(int idx, unsigned int seed)
+{
+	static const uint64_t runtime[] = { 5, 10, 20, 30 };
+	static const uint64_t period[] = { 50, 100 };
+	static const uint64_t flag[] = { 0, SCHED_FLAG_RECLAIM, SCHED_FLAG_DL_OVERRUN };
+	pid_t pid = fork_child("a worker of the mix");
+
+	if (!pid) {
+		struct sigaction sa = { .sa_handler = catch_xcpu };
+		struct timespec ts;
+		int err;
+
+		if (sigaction(SIGXCPU, &sa, NULL))
+			_exit(1);
+		seed += idx;
+		/*
+		 * Ignore the errors. Each call below is made in whatever
+		 * state the worker is in, and the kernel may refuse it.
+		 */
+		while (!mix_state[0]) {
+			unsigned int r = rand_r(&seed), v = r / 8;
+
+			switch (r % 8) {
+			case 0:
+				set_deadline_flags(0, runtime[v % 4] * NSEC_PER_MSEC,
+						   period[(v / 4) % 2] * NSEC_PER_MSEC,
+						   flag[(v / 8) % 3]);
+				break;
+			case 1:
+				set_other(0);
+				break;
+			case 2:
+				sleep_ns((v % 20 + 1) * NSEC_PER_MSEC);
+				break;
+			case 3:
+				spin_ns((v % 15 + 1) * NSEC_PER_MSEC);
+				break;
+			case 4:
+				sched_yield();
+				break;
+			case 5:
+				clock_gettime(CLOCK_REALTIME, &ts);
+				ts.tv_nsec += 5 * NSEC_PER_MSEC;
+				if (ts.tv_nsec >= NSEC_PER_SEC) {
+					ts.tv_nsec -= NSEC_PER_SEC;
+					ts.tv_sec++;
+				}
+				err = pthread_mutex_timedlock(shm_lock, &ts);
+				if (err == EOWNERDEAD)	/* its owner died */
+					err = pthread_mutex_consistent(shm_lock);
+				if (!err) {
+					spin_ns(NSEC_PER_MSEC);
+					if (pthread_mutex_unlock(shm_lock))
+						_exit(1);
+				}
+				break;
+			case 6:
+				_exit(0);	/* the case starts another */
+			default:
+				sleep_ns(NSEC_PER_MSEC / 2);
+				break;
+			}
+			mix_state[1 + idx]++;
+		}
+		_exit(0);
+	}
+	return pid;
+}
+
+static cpu_set_t mix_mask[4];
+
+static int random_mix(void)
+{
+	static const uint64_t runtime[] = { 5, 10, 20, 30 };
+	int cpu_a = top_cpu(3), cpu_b = top_cpu(2), cpu_p = top_cpu(1);
+	int base_p, base_q, base_r, i, ret = KSFT_PASS, rounds = 0, sums;
+	long ta = 0, ra, tb = 0, rb, tp = 0, rp, ta2, ra2, tb2, rb2, tp2, rp2;
+	pid_t pid[MIX_WORKERS] = { -1, -1, -1, -1, -1, -1 };
+	unsigned int seed = MIX_SEED;
+	uint64_t end;
+	char cpus[32];
+
+	if (ncpus < 4) {
+		ksft_print_msg("needs 4 non-isolated CPUs\n");
+		return KSFT_SKIP;
+	}
+	snprintf(cpus, sizeof(cpus), "%d,%d", cpu_a, cpu_b);
+	if (make_partition_cpus(cg_q, cpus)) {
+		remove_partition(cg_q);
+		ksft_print_msg("no partition root of two CPUs\n");
+		return KSFT_SKIP;
+	}
+	/*
+	 * The affinities of the mix: every CPU of the test, those of Q and
+	 * P, those of P and the rest, and all but the first.
+	 */
+	for (i = 0; i < 4; i++)
+		CPU_ZERO(&mix_mask[i]);
+	for (i = 0; i < ncpus; i++) {
+		int c = online[i];
+
+		CPU_SET(c, &mix_mask[0]);
+		if (c == cpu_a || c == cpu_b || c == cpu_p)
+			CPU_SET(c, &mix_mask[1]);
+		if (c != cpu_a && c != cpu_b)
+			CPU_SET(c, &mix_mask[2]);
+		if (i)
+			CPU_SET(c, &mix_mask[3]);
+	}
+	if (shm_lock_init()) {
+		remove_partition(cg_q);
+		return KSFT_SKIP;	/* no shared mutex for the workers */
+	}
+	/* Without this_bw in sched_debug, check the admissions only. */
+	sums = !rq_bw_of(cpu_a, &ta, &ra) && !rq_bw_of(cpu_b, &tb, &rb) &&
+	       !rq_bw_of(cpu_p, &tp, &rp);
+	base_p = probe(cg_p);
+	base_q = probe(cg_q);
+	base_r = probe(root);
+	if (base_p <= 0 || base_q <= 0 || base_r <= 0) {
+		remove_partition(cg_q);
+		ksft_print_msg("no room to probe P, Q or the rest\n");
+		return KSFT_SKIP;
+	}
+	mix_state = mv_state + 16;
+	for (i = 0; i <= MIX_WORKERS; i++)
+		mix_state[i] = 0;
+	for (i = 0; i < MIX_WORKERS; i++) {
+		pid[i] = mix_worker(i, seed);
+		if (pid[i] < 0) {
+			ret = KSFT_FAIL;
+			goto out;
+		}
+	}
+
+	end = now_ns() + MIX_NS;
+	while (now_ns() < end) {
+		unsigned int r = rand_r(&seed);
+		int w = r % MIX_WORKERS;
+
+		switch ((r / MIX_WORKERS) % 8) {
+		case 0:
+			set_deadline(pid[w], runtime[r % 4] * NSEC_PER_MSEC, PERIOD);
+			break;
+		case 7:
+			/*
+			 * Refused with EBUSY if the mask leaves out a CPU
+			 * of the root domain that counts a deadline task.
+			 */
+			sched_setaffinity(pid[w], sizeof(mix_mask[0]), &mix_mask[r % 4]);
+			break;
+		case 1:
+			set_other(pid[w]);
+			break;
+		case 2:
+			enter(cg_p, pid[w]);
+			break;
+		case 3:
+			enter(cg_q, pid[w]);
+			break;
+		case 4:
+			enter(root, pid[w]);
+			break;
+		case 5:
+			/* An exited worker is a zombie: the kill succeeds. */
+			if (kill(pid[w], SIGKILL) && errno != ESRCH)
+				ksft_print_msg("kill %d: %s\n", pid[w], strerror(errno));
+			break;
+		default:
+			server_set(r % 2 ? cpu_p : cpu_a,
+				   (r % 3 + 1) * SERVER_RUNTIME, SERVER_PERIOD);
+			break;
+		}
+		sleep_ns((r % 2000 + 100) * NSEC_PER_USEC);
+		/* Start anew each worker that exited or was killed. */
+		for (i = 0; i < MIX_WORKERS; i++) {
+			pid_t done = waitpid(pid[i], NULL, WNOHANG);
+
+			if (done < 0 && errno != EINTR) {
+				ksft_print_msg("waitpid %d: %s\n", pid[i], strerror(errno));
+				ret = KSFT_FAIL;
+				goto out;
+			}
+			if (done == pid[i]) {
+				pid[i] = mix_worker(i, seed + rounds);
+				if (pid[i] < 0) {
+					ret = KSFT_FAIL;
+					goto out;
+				}
+				rounds++;
+			}
+		}
+	}
+out:
+	mix_state[0] = 1;
+	for (i = 0; i < MIX_WORKERS; i++)
+		reap(pid[i]);
+	/*
+	 * Wait for the 0-lag times of the workers. Putting the fair servers
+	 * back needs the room they held.
+	 */
+	sleep_ns(5 * PERIOD);
+	server_restore();
+	if (ret != KSFT_PASS) {
+		remove_partition(cg_q);
+		return ret;
+	}
+	for (i = 0, rounds = 0; i < MIX_WORKERS; i++)
+		rounds += mix_state[1 + i];
+	if (!rounds) {
+		ksft_print_msg("the workers of the mix took no transition\n");
+		ret = KSFT_FAIL;
+	}
+	if (ret == KSFT_PASS && sums) {
+		if (rq_bw_of(cpu_a, &ta2, &ra2) || rq_bw_of(cpu_b, &tb2, &rb2) ||
+		    rq_bw_of(cpu_p, &tp2, &rp2)) {
+			ret = KSFT_FAIL;
+		} else if (ta2 != ta || tb2 != tb || tp2 != tp) {
+			ksft_print_msg("this_bw %ld %ld %ld, was %ld %ld %ld\n",
+				       ta2, tb2, tp2, ta, tb, tp);
+			ret = KSFT_FAIL;
+		}
+	}
+	if (ret == KSFT_PASS &&
+	    (admits_in(cg_p, base_p, "P after the mix") ||
+	     admits_in(cg_q, base_q, "Q after the mix") ||
+	     admits_in(root, base_r, "the root domain of the rest after the mix")))
+		ret = KSFT_FAIL;
+	if (ret != KSFT_PASS)
+		ksft_print_msg("seed %u, %d transitions\n", MIX_SEED, rounds);
+	remove_partition(cg_q);
+	return ret;
+}
+
 /*
  * CPU hotplug, from the main process, with no P. Two cases below run with
  * P instead: death_zombie_hotplug and pi_departed_moved.
@@ -5223,6 +6877,834 @@ static int in_cpu_list(const char *list, int cpu)
 	return 0;
 }
 
+/*
+ * Wake @pid, a task that sleeps in read() on a pipe: write a byte to @fd.
+ * The task counts its wakeups in mv_state[1]. Wait until it has run and
+ * sleeps again. Return 0, or -1.
+ */
+static int fallback_wake(int fd, pid_t pid)
+{
+	int n = mv_state[1];
+
+	if (write(fd, "w", 1) != 1) {
+		ksft_print_msg("write to the deadline task: %s\n", strerror(errno));
+		return -1;
+	}
+	if (wait_for(1000, mv_state[1] != n) ||
+	    wait_for(1000, proc_state_of(pid) == 'S')) {
+		ksft_print_msg("the deadline task did not wake up and sleep again\n");
+		return -1;
+	}
+	return 0;
+}
+
+/*
+ * The cpusets of the cases below: B and Q in the root cgroup, C in B. A
+ * case makes those it needs. cs_setup() names them and enables the cpuset
+ * controller of the root cgroup if it is off. cs_cleanup() removes them,
+ * and turns the controller off again if cs_setup() turned it on.
+ */
+static char cs_b[PATH_MAX], cs_c[PATH_MAX], cs_q[PATH_MAX];
+static int cs_added;
+
+static int cs_setup(void)
+{
+	char path[PATH_MAX + 32], buf[256];
+
+	cs_added = 0;
+	if (!root[0] ||
+	    snprintf(cs_b, sizeof(cs_b), "%s/deadline_bw_b", root) >= (int)sizeof(cs_b) ||
+	    snprintf(cs_c, sizeof(cs_c), "%s/c", cs_b) >= (int)sizeof(cs_c) ||
+	    snprintf(cs_q, sizeof(cs_q), "%s/deadline_bw_q", root) >= (int)sizeof(cs_q))
+		return -1;
+	snprintf(path, sizeof(path), "%s/cgroup.subtree_control", root);
+	if (read_file(path, buf, sizeof(buf)))
+		return -1;
+	if (!strstr(buf, "cpuset")) {
+		if (write_file(root, "cgroup.subtree_control", "+cpuset"))
+			return -1;
+		cs_added = 1;
+	}
+	return 0;
+}
+
+/* Make the cpuset @cg, and give it the CPUs of @cpus. Return 0, or -1. */
+static int cs_make(const char *cg, const char *cpus)
+{
+	int err = 0;
+
+	if (mkdir(cg, 0755) && errno != EEXIST)
+		err = -errno;
+	if (!err)
+		err = write_file(cg, "cpuset.cpus", cpus);
+	if (err)
+		ksft_print_msg("cpuset %s of CPUs %s: %s\n", cg, cpus, strerror(-err));
+	return err ? -1 : 0;
+}
+
+static void cs_cleanup(void)
+{
+	remove_partition(cs_c);
+	remove_partition(cs_b);
+	remove_partition(cs_q);
+	if (cs_added && write_file(root, "cgroup.subtree_control", "-cpuset"))
+		ksft_print_msg("the cpuset controller stays enabled\n");
+}
+
+/*
+ * Return whether the partition file of @cg holds @what. If not, and
+ * @tell, print what it holds.
+ */
+static int partition_has(const char *cg, const char *what, int tell)
+{
+	char path[PATH_MAX + 32], buf[256];
+
+	snprintf(path, sizeof(path), "%s/cpuset.cpus.partition", cg);
+	if (read_file(path, buf, sizeof(buf)))
+		return 0;
+	if (strstr(buf, what))
+		return 1;
+	if (tell)
+		ksft_print_msg("%s/cpuset.cpus.partition: %s", cg, buf);
+	return 0;
+}
+
+/*
+ * Read total_bw of the root domain of @d into @def, and of the root
+ * domain of @h into @hk. Return 0, or -1.
+ */
+static int totals_of(int d, int h, long long *def, long long *hk)
+{
+	*def = total_bw_of(d);
+	*hk = total_bw_of(h);
+	if (*def == -1 || *hk == -1) {
+		ksft_print_msg("no total_bw in /sys/kernel/debug/sched/debug\n");
+		return -1;
+	}
+	return 0;
+}
+
+/*
+ * Return KSFT_PASS if total_bw of the root domains of @d and @h is
+ * @def and @hk, else KSFT_FAIL. @what names the step in the message.
+ */
+static int totals_check(const char *what, int d, int h, long long def, long long hk)
+{
+	long long now_def, now_hk;
+
+	if (totals_of(d, h, &now_def, &now_hk))
+		return KSFT_FAIL;
+	if (now_def == def && now_hk == hk)
+		return KSFT_PASS;
+	ksft_print_msg("%s: total_bw %lld, %lld, not %lld, %lld\n",
+		       what, now_def, now_hk, def, hk);
+	return KSFT_FAIL;
+}
+
+/*
+ * Fork a task that runs on @cpu. Then it allows every CPU if @all. If
+ * not, it allows the housekeeping CPUs that were online at the start,
+ * even those offline now. It becomes a deadline task of @runtime every
+ * @period. If @fd is -1, it spins and counts in mv_state[1]. Else it
+ * sleeps in read() on @fd and counts in mv_state[1] each byte that wakes
+ * it. On the byte 'x', it spins 90ms and exits. It sets mv_state[0] as
+ * mover() does. Return its pid, or -1.
+ */
+static pid_t task_from(int cpu, int all, uint64_t runtime, uint64_t period, int fd)
+{
+	pid_t pid = fork_child("a deadline task");
+
+	if (!pid) {
+		cpu_set_t set, one;
+		int i;
+		char c;
+
+		CPU_ZERO(&one);
+		CPU_SET(cpu, &one);
+		if (sched_setaffinity(0, sizeof(one), &one))
+			_exit(1);
+		spin_ns(NSEC_PER_MSEC);
+		CPU_ZERO(&set);
+		for (i = 0; i < (all ? CPU_SETSIZE : ncpus); i++)
+			CPU_SET(all ? i : online[i], &set);
+		if (sched_setaffinity(0, sizeof(set), &set) ||
+		    set_deadline(0, runtime, period)) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		mv_state[0] = 1;
+		while (fd < 0)
+			mv_state[1]++;
+		while (read(fd, &c, 1) == 1) {
+			if (c == 'x') {
+				spin_ns(90 * NSEC_PER_MSEC);
+				_exit(0);
+			}
+			mv_state[1]++;
+		}
+		_exit(0);
+	}
+	return pid;
+}
+
+/*
+ * The default root domain spans every CPU that is offline. It also spans
+ * the CPU of an isolated partition. The steps:
+ * 1. Take hp_cpu offline. Make Q an isolated partition of Y, another
+ *    housekeeping CPU.
+ * 2. A task in the root cgroup becomes a deadline task of 10% and sleeps.
+ *    The housekeeping root domain counts it. Its affinity holds the
+ *    housekeeping CPUs, hp_cpu too.
+ * 3. Move it asleep into Q. Wake it: it runs on Y. The default root
+ *    domain counts it.
+ * 4. Move it asleep back to the root cgroup. Its mask holds hp_cpu, but
+ *    no active CPU of the default root domain.
+ * 5. Wake it. It runs on a housekeeping CPU.
+ * Check after step 4 and again after step 5. The housekeeping root
+ * domain must count the task. The default root domain must not. An
+ * offline CPU of the default root domain is no CPU where the task can
+ * stay.
+ *
+ * The references of total_bw are taken after step 1. Once the task is
+ * gone, total_bw must be back to them.
+ */
+static int move_back_cpu_offline(void)
+{
+	int y = hp_cpu == top_cpu(1) ? top_cpu(2) : top_cpu(1), h = online[0];
+	int fd[2] = { -1, -1 }, cpu, err, ret = KSFT_SKIP;
+	long long def0, hk0, def, hk, bw;
+	char buf[16];
+	pid_t pid = -1;
+
+	if (cs_setup())
+		return KSFT_SKIP;
+	if (cpu_online(hp_cpu, 0)) {
+		ksft_print_msg("CPU %d cannot go offline\n", hp_cpu);
+		goto out;
+	}
+	snprintf(buf, sizeof(buf), "%d", y);
+	if (cs_make(cs_q, buf) || write_file(cs_q, "cpuset.cpus.partition", "isolated") ||
+	    !partition_has(cs_q, "isolated", 1) || partition_has(cs_q, "invalid", 0)) {
+		ksft_print_msg("no isolated partition Q of CPU %d\n", y);
+		goto out;
+	}
+	if (totals_of(y, h, &def0, &hk0) || pipe(fd))
+		goto out;
+	ret = KSFT_FAIL;
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = task_from(h, 0, 10 * NSEC_PER_MSEC, PERIOD, fd[0]);
+	if (pid < 0 || child_up("move_back_cpu_offline", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S') || totals_of(y, h, &def, &hk))
+		goto out;
+	bw = hk - hk0;
+	if (bw <= 0 || def != def0) {
+		ksft_print_msg("the deadline task adds %lld, %lld to total_bw\n",
+			       def - def0, bw);
+		goto out;
+	}
+	err = enter(cs_q, pid);
+	if (err) {
+		ksft_print_msg("a move into Q refused: %s\n", strerror(-err));
+		goto out;
+	}
+	if (fallback_wake(fd[1], pid) ||
+	    totals_check("in Q", y, h, def0 + bw, hk0))
+		goto out;
+	cpu = task_cpu_of(pid);
+	if (cpu != y) {
+		ksft_print_msg("woken in Q on CPU %d, not %d\n", cpu, y);
+		goto out;
+	}
+	err = enter(root, pid);
+	if (err) {
+		ksft_print_msg("the move back refused: %s\n", strerror(-err));
+		goto out;
+	}
+	if (totals_check("moved back asleep", y, h, def0, hk0 + bw) ||
+	    fallback_wake(fd[1], pid) ||
+	    totals_check("woken", y, h, def0, hk0 + bw))
+		goto out;
+	cpu = task_cpu_of(pid);
+	if (cpu == y || in_cpu_list(isolated, cpu)) {
+		ksft_print_msg("woken on CPU %d\n", cpu);
+		goto out;
+	}
+	reap(pid);
+	pid = -1;
+	sleep_ns(3 * PERIOD);
+	ret = totals_check("task gone", y, h, def0, hk0);
+out:
+	reap(pid);
+	if (fd[0] >= 0) {
+		close(fd[0]);
+		close(fd[1]);
+	}
+	cs_cleanup();
+	cpu_up(hp_cpu);
+	return ret;
+}
+
+/* Moves between two root domains, from the main process, with P */
+
+/*
+ * Fork a deadline task of 30ms every 100ms, pinned to the @n CPUs of
+ * @cpus. It runs 1ms, then sleeps. If @fd is not -1, each byte read from
+ * @fd wakes it up, and it counts the wakeups in mv_state[1]. It sets
+ * mv_state[0] as mover() does. Return its pid, or -1.
+ */
+static pid_t pinned_sleeper(const int *cpus, int n, int fd)
+{
+	pid_t pid = fork_child("a pinned deadline task");
+
+	if (!pid) {
+		cpu_set_t set;
+		char c;
+		int i;
+
+		CPU_ZERO(&set);
+		for (i = 0; i < n; i++)
+			CPU_SET(cpus[i], &set);
+		if (sched_setaffinity(0, sizeof(set), &set) ||
+		    set_deadline(0, 30 * NSEC_PER_MSEC, PERIOD)) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		spin_ns(NSEC_PER_MSEC);
+		mv_state[0] = 1;
+		while (fd >= 0 && read(fd, &c, 1) == 1)
+			mv_state[1]++;
+		for (;;)
+			pause();
+	}
+	return pid;
+}
+
+/*
+ * Read total_bw of three root domains into @bw: the root domain of the
+ * isolated CPUs, the housekeeping root domain, and P. Return 0, or -1.
+ */
+static int split_totals(long long bw[3])
+{
+	bw[0] = total_bw_of(isol[0]);
+	bw[1] = total_bw_of(online[0]);
+	bw[2] = total_bw_of(top_cpu(1));
+	if (bw[0] == -1 || bw[1] == -1 || bw[2] == -1) {
+		ksft_print_msg("no total_bw in /sys/kernel/debug/sched/debug\n");
+		return -1;
+	}
+	return 0;
+}
+
+/*
+ * Return KSFT_PASS if total_bw is now @want, else KSFT_FAIL. The message
+ * gives total_bw of the root domain of the isolated CPUs, then of the
+ * housekeeping root domain, then of P.
+ */
+static int split_check(const char *what, const long long want[3])
+{
+	long long bw[3];
+
+	if (split_totals(bw))
+		return KSFT_FAIL;
+	if (bw[0] == want[0] && bw[1] == want[1] && bw[2] == want[2])
+		return KSFT_PASS;
+	ksft_print_msg("%s: total_bw %lld, %lld, %lld, not %lld, %lld, %lld\n",
+		       what, bw[0], bw[1], bw[2], want[0], want[1], want[2]);
+	return KSFT_FAIL;
+}
+
+/*
+ * Read total_bw into @base, for the cases below. Return 0, or nonzero if
+ * the case must skip. It needs CPUs isolated by isolcpus="domain".
+ */
+static int split_skip(long long base[3])
+{
+	if (!nisol) {
+		ksft_print_msg("needs CPUs isolated by isolcpus=domain\n");
+		return 1;
+	}
+	return split_totals(base);
+}
+
+/*
+ * The root cpuset holds the CPUs that isolcpus="domain" isolates, so it
+ * spans two root domains. The affinity of a task can keep it in either.
+ * A move into the root cpuset must reserve the bandwidth of the task in
+ * the root domain that the task gets.
+ *
+ * Run twice, with a deadline sleeper of 30% pinned to the isolated CPUs,
+ * then with another one pinned to the housekeeping CPUs except P's. Move
+ * the sleeper into P and back to the root cgroup, then kill it. Once it
+ * is gone, total_bw of the three root domains must be what it was.
+ */
+static int move_isolated(void)
+{
+	long long base[3];
+	int round, err;
+	pid_t pid;
+
+	if (split_skip(base))
+		return KSFT_SKIP;
+	for (round = 0; round < 2; round++) {
+		const char *what = round ? "pinned to the other CPUs" :
+				   "pinned to the isolated CPUs";
+
+		mv_state[0] = 0;
+		pid = round ? pinned_sleeper(online, ncpus - 1, -1) :
+			      pinned_sleeper(isol, nisol, -1);
+		if (pid < 0 || child_up(what, 0)) {
+			reap(pid);
+			return KSFT_FAIL;
+		}
+		err = enter(cg_p, pid);
+		if (!err)
+			err = enter(root, pid);
+		reap(pid);
+		if (err) {
+			ksft_print_msg("%s: a move refused: %s\n", what, strerror(-err));
+			return KSFT_FAIL;
+		}
+		sleep_ns(3 * PERIOD);
+		if (split_check(what, base))
+			return KSFT_FAIL;
+	}
+	return KSFT_PASS;
+}
+
+/*
+ * Fork a process pinned to the isolated CPUs. Its threads become deadline
+ * tasks of 10ms every 100ms, as in probe(), until one is refused. Then it
+ * sets mv_state[1] to 1, or to -1 on an error. The threads sleep until the
+ * process is killed.
+ */
+static pid_t fill_isolated(void)
+{
+	pid_t pid = fork_child("the tasks that fill the isolated CPUs");
+
+	if (!pid) {
+		int i, max = 16 * nisol + 16;
+		struct probe_slot *s = calloc(max, sizeof(*s));
+		pthread_attr_t a;
+		cpu_set_t set;
+
+		CPU_ZERO(&set);
+		for (i = 0; i < nisol; i++)
+			CPU_SET(isol[i], &set);
+		if (!s || sched_setaffinity(0, sizeof(set), &set) ||
+		    sem_init(&probe_done, 0, 0) || pipe(probe_hold) ||
+		    pthread_attr_init(&a) || pthread_attr_setstacksize(&a, THREAD_STACK)) {
+			mv_state[1] = -1;
+			_exit(1);
+		}
+		for (i = 0; i < max; i++) {
+			if (pthread_create(&s[i].t, &a, probe_thread, &s[i]) ||
+			    sem_wait_for(&probe_done, 10000)) {
+				mv_state[1] = -1;
+				_exit(1);
+			}
+			if (s[i].err)
+				break;
+		}
+		mv_state[1] = i < max && s[i].err == -EBUSY ? 1 : -1;
+		for (;;)
+			pause();
+	}
+	return pid;
+}
+
+/*
+ * Move a deadline sleeper pinned to the isolated CPUs into P. Fill the
+ * isolated CPUs with deadline tasks of 10%, until one is refused. Moving
+ * the sleeper back must then be refused with EBUSY.
+ */
+static int move_isolated_refused(void)
+{
+	pid_t pid, fill = -1;
+	long long base[3];
+	int err, ret = KSFT_FAIL;
+
+	if (split_skip(base))
+		return KSFT_SKIP;
+	mv_state[0] = 0;
+	pid = pinned_sleeper(isol, nisol, -1);
+	if (pid < 0 || child_up("a sleeper pinned to the isolated CPUs", 0))
+		goto out;
+	err = enter(cg_p, pid);
+	if (err) {
+		ksft_print_msg("a move into P refused: %s\n", strerror(-err));
+		goto out;
+	}
+	mv_state[1] = 0;
+	fill = fill_isolated();
+	if (fill < 0 || wait_for(10000, mv_state[1]) || mv_state[1] != 1) {
+		ksft_print_msg("the isolated CPUs cannot be filled\n");
+		goto out;
+	}
+	err = enter(root, pid);
+	if (err == -EBUSY) {
+		ret = KSFT_PASS;
+	} else {
+		ksft_print_msg("a move back to the full isolated CPUs: %s, not EBUSY\n",
+			       err ? strerror(-err) : "accepted");
+	}
+out:
+	reap(fill);
+	reap(pid);
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS)
+		ret = split_check("the isolated CPUs filled", base);
+	return ret;
+}
+
+/*
+ * A deadline sleeper is pinned to the isolated CPUs. The case allows it
+ * all CPUs, then moves it into P and back, without waking it. So it stays
+ * on an isolated CPU, which its mask holds again. The root domain of the
+ * isolated CPUs must still count its bandwidth. Then wake it: it must run
+ * on an isolated CPU, and that root domain must still count it.
+ */
+static int move_isolated_asleep(void)
+{
+	long long base[3], want[3];
+	int fd[2], err, cpu, i, ret = KSFT_FAIL;
+	cpu_set_t set;
+	pid_t pid;
+
+	if (split_skip(base))
+		return KSFT_SKIP;
+	if (pipe(fd)) {
+		ksft_print_msg("pipe: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = pinned_sleeper(isol, nisol, fd[0]);
+	if (pid < 0 || child_up("a sleeper pinned to the isolated CPUs", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S') || split_totals(want))
+		goto out;
+	CPU_ZERO(&set);
+	for (i = 0; i < CPU_SETSIZE; i++)
+		CPU_SET(i, &set);
+	err = sched_setaffinity(pid, sizeof(set), &set) ? -errno : 0;
+	if (!err)
+		err = enter(cg_p, pid);
+	if (!err)
+		err = enter(root, pid);
+	if (err) {
+		ksft_print_msg("the affinity of all CPUs, or a move: %s\n", strerror(-err));
+		goto out;
+	}
+	for (i = 0; i < 2; i++) {
+		const char *what = i ? "woken" : "moved back asleep";
+
+		cpu = task_cpu_of(pid);
+		if (!in_cpu_list(isolated, cpu)) {
+			ksft_print_msg("%s on CPU %d, not an isolated one\n", what, cpu);
+			goto out;
+		}
+		if (split_check(what, want))
+			goto out;
+		if (!i && fallback_wake(fd[1], pid))
+			goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	reap(pid);
+	close(fd[0]);
+	close(fd[1]);
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS)
+		ret = split_check("task gone", base);
+	return ret;
+}
+
+/* The CPUs of move_spanning(): two root domains, an isolated CPU first */
+static cpu_set_t span_set;
+
+/*
+ * Fork a task that pins itself to the isolated CPUs, becomes a deadline
+ * task of 30ms every 100ms, then takes the CPUs of span_set. If @fd is
+ * -1, it spins and counts in mv_state[1]. Else it sleeps, each byte read
+ * from @fd wakes it up, and it counts the wakeups there. It sets
+ * mv_state[0] as mover() does. Return its pid, or -1.
+ */
+static pid_t spanning_task(int fd)
+{
+	pid_t pid = fork_child("a deadline task on two root domains");
+
+	if (!pid) {
+		cpu_set_t set;
+		char c;
+		int i;
+
+		CPU_ZERO(&set);
+		for (i = 0; i < nisol; i++)
+			CPU_SET(isol[i], &set);
+		if (sched_setaffinity(0, sizeof(set), &set) ||
+		    set_deadline(0, 30 * NSEC_PER_MSEC, PERIOD) ||
+		    sched_setaffinity(0, sizeof(span_set), &span_set)) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		mv_state[0] = 1;
+		while (fd < 0)
+			mv_state[1]++;
+		while (read(fd, &c, 1) == 1)
+			mv_state[1]++;
+		for (;;)
+			pause();
+	}
+	return pid;
+}
+
+/*
+ * A task becomes a deadline task on the isolated CPUs, where it is
+ * counted. Then it takes a wider affinity: the isolated CPUs, and the
+ * housekeeping CPUs above the first isolated one except P's. In the root
+ * cpuset, its CPUs span two root domains, and the lowest one is isolated.
+ * The case moves it into P, where it runs, and back to the root cgroup.
+ * The task must then run on a housekeeping CPU, and the housekeeping root
+ * domain must count its bandwidth. The root domain of the isolated CPUs
+ * must count it no more. Run twice: with a running task, then with a
+ * sleeper woken in P and again after the move back.
+ *
+ * The kernel counts a task that has a housekeeping CPU in the
+ * housekeeping root domain. The move reserves there, and a rebuild of the
+ * accounting makes the same choice. The lowest CPU of the task is
+ * isolated, so a move that takes the first CPU of the mask reserves in
+ * the wrong root domain.
+ */
+static int move_spanning(void)
+{
+	int fd[2] = { -1, -1 }, round, cpu, err, i, n = 0, ret = KSFT_PASS;
+	long long base[3], want[3];
+	pid_t pid;
+
+	if (split_skip(base))
+		return KSFT_SKIP;
+	CPU_ZERO(&span_set);
+	for (i = 0; i < nisol; i++)
+		CPU_SET(isol[i], &span_set);
+	for (i = 0; i < ncpus - 1; i++) {
+		if (online[i] > isol[0]) {
+			CPU_SET(online[i], &span_set);
+			n++;
+		}
+	}
+	if (!n) {
+		ksft_print_msg("needs a CPU above the first isolated one, besides P\n");
+		return KSFT_SKIP;
+	}
+	for (round = 0; round < 2 && ret == KSFT_PASS; round++) {
+		const char *what = round ? "a sleeper" : "a running task";
+
+		ret = KSFT_FAIL;
+		if (round && pipe(fd)) {
+			ksft_print_msg("pipe: %s\n", strerror(errno));
+			break;
+		}
+		mv_state[0] = 0;
+		mv_state[1] = 0;
+		pid = spanning_task(fd[0]);
+		if (pid < 0 || child_up(what, 0) || split_totals(want))
+			goto next;
+		/*
+		 * Moved back, its bandwidth goes to the housekeeping root
+		 * domain, not to the root domain of the isolated CPUs.
+		 */
+		want[1] += want[0] - base[0];
+		want[0] = base[0];
+		err = enter(cg_p, pid);
+		if (err) {
+			ksft_print_msg("%s: a move into P refused: %s\n", what, strerror(-err));
+			goto next;
+		}
+		if ((round && fallback_wake(fd[1], pid)) ||
+		    wait_for(1000, task_cpu_of(pid) == top_cpu(1))) {
+			ksft_print_msg("%s: not on P's CPU\n", what);
+			goto next;
+		}
+		err = enter(root, pid);
+		if (err) {
+			ksft_print_msg("%s: the move back refused: %s\n", what, strerror(-err));
+			goto next;
+		}
+		if (round ? fallback_wake(fd[1], pid) :
+			    wait_for(1000, task_cpu_of(pid) != top_cpu(1)))
+			goto next;
+		sleep_ns(PERIOD);
+		cpu = task_cpu_of(pid);
+		if (in_cpu_list(isolated, cpu)) {
+			ksft_print_msg("%s: moved back to isolated CPU %d\n", what, cpu);
+			goto next;
+		}
+		ret = split_check(what, want);
+next:
+		reap(pid);
+		if (round) {
+			close(fd[0]);
+			close(fd[1]);
+		}
+		sleep_ns(3 * PERIOD);
+		if (ret == KSFT_PASS)
+			ret = split_check("task gone", base);
+	}
+	return ret;
+}
+
+/*
+ * A deadline task moved asleep into another cpuset still sleeps on a CPU
+ * of the root domain it left. The root domain it moved to counts its
+ * bandwidth. sched_setaffinity() must check a new mask against the root
+ * domain that counts the task, not the one it sleeps in.
+ *
+ * H is a cpuset here, not the CPU of fallback_case(). It holds the
+ * housekeeping CPUs except P's. The steps:
+ * 1. Pin a fair task to the isolated CPUs.
+ * 2. Move it into H. Its affinity has no CPU of H, so it gets all the
+ *    CPUs of H.
+ * 3. Make it a deadline task there, and let it sleep.
+ * 4. Move it asleep into the root cgroup. Its affinity gives it the
+ *    isolated CPUs again, and their root domain counts it.
+ * 5. Set its affinity to the CPUs of H. That would take it out of the
+ *    root domain that counts it, so it must fail with EBUSY.
+ *
+ * If the change is accepted, wake the task and report where it runs.
+ */
+static int affinity_moved_asleep(void)
+{
+	char cg_h[PATH_MAX], cpus[4096], what[64];
+	int fd[2], i, n = 0, cpu, err, made = 0, ret = KSFT_SKIP;
+	long long base[3], want[3], bw;
+	cpu_set_t set;
+	pid_t pid = -1;
+
+	if (split_skip(base))
+		return KSFT_SKIP;
+	if (pipe(fd)) {
+		ksft_print_msg("pipe: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	/*
+	 * H holds the housekeeping CPUs except P's. A task there can become
+	 * a deadline task: its mask holds its whole root domain.
+	 */
+	CPU_ZERO(&set);
+	for (i = 0; i < ncpus - 1 && n < (int)sizeof(cpus); i++) {
+		n += snprintf(cpus + n, sizeof(cpus) - n, "%s%d", i ? "," : "", online[i]);
+		CPU_SET(online[i], &set);
+	}
+	if (snprintf(cg_h, sizeof(cg_h), "%s/deadline_bw_h", root) >= (int)sizeof(cg_h))
+		goto out;
+	if (mkdir(cg_h, 0755) && errno != EEXIST) {
+		ksft_print_msg("mkdir %s: %s\n", cg_h, strerror(errno));
+		goto out;
+	}
+	made = 1;
+	if (n >= (int)sizeof(cpus) || write_file(cg_h, "cpuset.cpus", cpus)) {
+		ksft_print_msg("cpuset H cannot be made\n");
+		goto out;
+	}
+	ret = KSFT_FAIL;
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = fork_child("a task moved asleep");
+	if (!pid) {
+		cpu_set_t iso;
+		char c;
+
+		CPU_ZERO(&iso);
+		for (i = 0; i < nisol; i++)
+			CPU_SET(isol[i], &iso);
+		if (sched_setaffinity(0, sizeof(iso), &iso)) {
+			mv_state[1] = -1;
+			_exit(1);
+		}
+		mv_state[1] = 1;
+		/* Wait for the move into H. Become a deadline task there. */
+		if (read(fd[0], &c, 1) != 1 || set_deadline(0, 30 * NSEC_PER_MSEC, PERIOD)) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		spin_ns(NSEC_PER_MSEC);
+		mv_state[0] = 1;
+		while (read(fd[0], &c, 1) == 1)
+			mv_state[1]++;
+		for (;;)
+			pause();
+	}
+	if (pid < 0)
+		goto out;
+	if (wait_for(1000, mv_state[1]) || mv_state[1] != 1) {
+		ksft_print_msg("the task cannot take the isolated CPUs\n");
+		goto out;
+	}
+	err = enter(cg_h, pid);
+	if (err) {
+		ksft_print_msg("a move into H refused: %s\n", strerror(-err));
+		goto out;
+	}
+	if (write(fd[1], "d", 1) != 1) {
+		ksft_print_msg("write to the task: %s\n", strerror(errno));
+		goto out;
+	}
+	if (child_up("a task moved into H", 0) || wait_for(1000, proc_state_of(pid) == 'S'))
+		goto out;
+	bw = (30 * NSEC_PER_MSEC << 20) / PERIOD;	/* as to_ratio() */
+	memcpy(want, base, sizeof(want));
+	want[1] += bw;
+	if (split_check("a deadline task in H", want))
+		goto out;
+
+	/*
+	 * Moved asleep, it stays on its CPU. The root domain of the
+	 * isolated CPUs counts it.
+	 */
+	err = enter(root, pid);
+	if (err) {
+		ksft_print_msg("the move into the root cgroup refused: %s\n", strerror(-err));
+		goto out;
+	}
+	cpu = task_cpu_of(pid);
+	if (in_cpu_list(isolated, cpu)) {
+		ksft_print_msg("moved asleep on CPU %d, an isolated one\n", cpu);
+		goto out;
+	}
+	want[0] += bw;
+	want[1] -= bw;
+	if (split_check("moved asleep", want))
+		goto out;
+
+	/* The CPUs of H leave out the root domain that counts the task. */
+	err = sched_setaffinity(pid, sizeof(set), &set) ? -errno : 0;
+	if (err == -EBUSY) {
+		ret = KSFT_PASS;
+		goto out;
+	}
+	ksft_print_msg("the affinity of the CPUs of H: %s, not EBUSY\n",
+		       err ? strerror(-err) : "accepted");
+	if (err || fallback_wake(fd[1], pid))
+		goto out;
+	/* Report its CPU, and whether the root domain of that CPU counts it. */
+	cpu = task_cpu_of(pid);
+	memcpy(want, base, sizeof(want));
+	want[in_cpu_list(isolated, cpu) ? 0 : 1] += bw;
+	snprintf(what, sizeof(what), "woken on CPU %d", cpu);
+	if (split_check(what, want) == KSFT_PASS)
+		ksft_print_msg("%s: its root domain counts it\n", what);
+out:
+	reap(pid);
+	close(fd[0]);
+	close(fd[1]);
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS)
+		ret = split_check("task gone", base);
+	if (made && wait_for(1000, !rmdir(cg_h) || errno == ENOENT))
+		ksft_print_msg("rmdir %s: %s\n", cg_h, strerror(errno));
+	return ret;
+}
+
 /* Setup */
 
 static int find_cgroup2(void)
@@ -5413,9 +7895,28 @@ static const struct p_case {
 	{ "return_asleep_new_params", return_asleep_new_params, MEASURED_IN_P },
 	{ "deboost_blocked_keeps_order", deboost_blocked_keeps_order, MEASURED_IN_P },
 	{ "pi_chain_donor_leaves", pi_chain_donor_leaves, MEASURED_IN_P },
+	{ "move_asleep", move_asleep, FROM_OUTSIDE },
+	{ "move_throttled", move_throttled, FROM_OUTSIDE },
+	{ "move_non_contending", move_non_contending, FROM_OUTSIDE },
 	{ "move_refused", move_refused, FROM_OUTSIDE },
 	{ "move_zero_bw", move_zero_bw, FROM_OUTSIDE },
+	{ "move_asleep_setattr", move_asleep_setattr, FROM_OUTSIDE },
+	{ "move_asleep_fair_setattr", move_asleep_fair_setattr, FROM_OUTSIDE },
+	{ "move_vs_rebuild", move_vs_rebuild, FROM_OUTSIDE },
+	{ "move_became_deadline", move_became_deadline, FROM_OUTSIDE },
+	{ "move_became_deadline_no_room", move_became_deadline_no_room, FROM_OUTSIDE },
+	{ "move_affinity_changed", move_affinity_changed, FROM_OUTSIDE },
+	{ "move_affinity_became_deadline", move_affinity_became_deadline, FROM_OUTSIDE },
+	{ "move_died", move_died, FROM_OUTSIDE },
+	{ "move_woken", move_woken, FROM_OUTSIDE },
+	{ "move_woken_full", move_woken_full, FROM_OUTSIDE },
 	{ "move_cancelled", move_cancelled, FROM_OUTSIDE },
+	{ "frozen_moved_switched", frozen_moved_switched, FROM_OUTSIDE },
+	{ "move_isolated", move_isolated, FROM_OUTSIDE },
+	{ "move_isolated_refused", move_isolated_refused, FROM_OUTSIDE },
+	{ "move_isolated_asleep", move_isolated_asleep, FROM_OUTSIDE },
+	{ "move_spanning", move_spanning, FROM_OUTSIDE },
+	{ "affinity_moved_asleep", affinity_moved_asleep, FROM_OUTSIDE },
 	{ "death_running", death_running, MEASURED_IN_P },
 	{ "death_switched_out", death_switched_out, MEASURED_IN_P },
 	{ "death_shrunk", death_shrunk, MEASURED_IN_P },
@@ -5431,16 +7932,20 @@ static const struct p_case {
 	{ "death_zombie_switched", death_zombie_switched, FROM_OUTSIDE },
 	{ "death_zombie_hotplug", death_zombie_hotplug, FROM_OUTSIDE },
 	{ "yield_switched_out", yield_switched_out, IN_P },
+	{ "yield_moved", yield_moved, FROM_OUTSIDE },
 	{ "yield_killed", yield_killed, MEASURED_IN_P },
 	{ "overrun_caught", overrun_caught, IN_P },
 	{ "overrun_group_death", overrun_group_death, MEASURED_IN_P },
 	{ "reclaim_runs", reclaim_runs, MEASURED_IN_P },
 	{ "reclaim_switched", reclaim_switched, MEASURED_IN_P },
+	{ "reclaim_moved", reclaim_moved, FROM_OUTSIDE },
 	{ "server_params", server_params, IN_P },
 	{ "server_rebuilds", server_rebuilds, FROM_OUTSIDE },
 	{ "server_states", server_states, FROM_OUTSIDE },
 	{ "server_reclaim", server_reclaim, MEASURED_IN_P },
 	{ "params_waking", params_waking, FROM_OUTSIDE },
+	{ "random_mix", random_mix, FROM_OUTSIDE },
+	{ "move_normalized", move_normalized, FROM_OUTSIDE },
 };
 
 #define N_P_CASES	((int)ARRAY_SIZE(p_cases))
@@ -5457,6 +7962,7 @@ static const struct hp_case {
 	{ "hotplug_departed", hotplug_departed },
 	{ "hotplug_server", hotplug_server },
 	{ "affinity_vs_setattr", affinity_vs_setattr, 1 },
+	{ "move_back_cpu_offline", move_back_cpu_offline },
 };
 
 #define N_HP_CASES	((int)ARRAY_SIZE(hp_cases))
@@ -5560,7 +8066,8 @@ int main(void)
 	if (read_file("/sys/devices/system/cpu/isolated", isolated, sizeof(isolated)))
 		isolated[0] = 0;
 	ncpus = read_online(&online, 0);
-	if (ncpus < 0)
+	nisol = read_online(&isol, 1);
+	if (ncpus < 0 || nisol < 0)
 		ksft_exit_fail_msg("the online CPUs cannot be read\n");
 	if (ncpus < 3)
 		ksft_exit_skip("needs 3 CPUs not isolated by isolcpus=domain\n");
-- 
2.47.3


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

* [PATCH v11 13/43] sched/deadline: Make a rebuild count a task in the root domain it runs in
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (11 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 12/43] selftests/sched: Test cpuset moves in deadline_bw_test Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 14/43] sched/deadline: Move a task's bandwidth to " Mathieu Desnoyers
                   ` (29 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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] 59+ messages in thread

* [PATCH v11 14/43] sched/deadline: Move a task's bandwidth to the root domain it runs in
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (12 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 13/43] sched/deadline: Make a rebuild count a task in the root domain it runs in Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 15/43] sched/deadline: Keep a task in the root domain that counts its bandwidth Mathieu Desnoyers
                   ` (28 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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] 59+ messages in thread

* [PATCH v11 15/43] sched/deadline: Keep a task in the root domain that counts its bandwidth
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (13 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 14/43] sched/deadline: Move a task's bandwidth to " Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:38   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 16/43] sched/deadline: Keep the last CPU a task has in its root domain Mathieu Desnoyers
                   ` (27 subsequent siblings)
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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     |  70 +++++++++++
 kernel/sched/deadline.c | 271 ++++++++++++++++++++++++++++++++++------
 kernel/sched/sched.h    |   3 +
 4 files changed, 314 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..3dd42581cc17 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -3264,6 +3264,27 @@ 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. 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))
+				p->wake_cpu = dest_cpu;
+		}
 	}
 
 	do_set_cpus_allowed(p, ctx);
@@ -3668,8 +3689,22 @@ 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) {
+		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 +3721,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 +3768,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] 59+ messages in thread

* [PATCH v11 16/43] sched/deadline: Keep the last CPU a task has in its root domain
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (14 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 15/43] sched/deadline: Keep a task in the root domain that counts its bandwidth Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:35   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 17/43] cgroup/cpuset: Refuse to take a deadline task out of " Mathieu Desnoyers
                   ` (26 subsequent siblings)
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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..37d04b08996e 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_intersects(pmask, possible))
+				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] 59+ messages in thread

* [PATCH v11 17/43] cgroup/cpuset: Refuse to take a deadline task out of its root domain
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (15 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 16/43] sched/deadline: Keep the last CPU a task has in its root domain Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:41   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 18/43] selftests/sched: Test the root domain of a task in deadline_bw_test Mathieu Desnoyers
                   ` (25 subsequent siblings)
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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").

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

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

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

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.

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 check of that
span alone would refuse a valid child partition. It would stay invalid
until the next change. So for a root partition, the CPUs it has after
the change count too: the rebuild gives them to its 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  |   3 +
 kernel/cgroup/cpuset-internal.h |   1 +
 kernel/cgroup/cpuset.c          | 213 +++++++++++++++++++++++++++++++-
 kernel/sched/deadline.c         |  39 ++++++
 4 files changed, 253 insertions(+), 3 deletions(-)

diff --git a/include/linux/sched/deadline.h b/include/linux/sched/deadline.h
index 8eb5cd13b9dd..fa66e75cbdd8 100644
--- a/include/linux/sched/deadline.h
+++ b/include/linux/sched/deadline.h
@@ -63,6 +63,9 @@ 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);
 
 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 37d04b08996e..67b2429c0e22 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 (!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,91 @@ 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.
+	 */
+	if (root->partition_root_state == PRS_ROOT) {
+		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, NULL);
+			if (!keep)
+				break;
+		}
+	}
+	rcu_read_unlock();
+	return keep;
+}
+
 /*
  * tasks_nocpu_error - Return true if tasks will have no effective_cpus
  */
@@ -1698,6 +1816,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 +1921,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 +2072,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 +2162,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 +2247,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 +2662,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 +2750,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 +4188,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..aa35933c0550 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -5296,6 +5296,45 @@ 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);
+}
+
 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] 59+ messages in thread

* [PATCH v11 18/43] selftests/sched: Test the root domain of a task in deadline_bw_test
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (16 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 17/43] cgroup/cpuset: Refuse to take a deadline task out of " Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 19/43] sched/deadline: Count only active CPUs when spreading extra_bw Mathieu Desnoyers
                   ` (24 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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

Earlier in this series, fixes keep a deadline task in the root domain
that counts its bandwidth. Add the 32 cases of deadline_bw_test that
test them. They cover CPU hotplug and cpuset changes with partition
roots, and with CPUs isolated by isolcpus=domain:
- the CPU a task falls back to when its CPU goes offline
- a task that runs, sleeps or wakes while its CPU goes offline
- the refusals of a CPU offline or a cpuset change that would leave a
  deadline task no CPU in its root domain
- a rebuild that counts a task in the root domain it runs in
- a CPU offline that would take more bandwidth than the root domain has
  free, with the CPU's fair server (hotplug_server_refused)

The comment above each case gives its scenario. Twenty-one of these cases
need CPUs isolated by isolcpus=domain, and skip without them.

The message of each fix names the cases that test it.
hotplug_server_refused is not named there. It fails with
isolcpus=domain,0,1 before these fixes.

On v7.4-rc2, in 8 VMs of 8 CPUs, hotplug_partition_invalid_refused fails
in every VM. hotplug_child_partition_kept fails in 2 of 8. The cases
that need isolcpus=domain skip there. With the first series alone,
rebuild_record_taken fails with isolcpus=domain,0,1 in a guest of 7
CPUs.

These cases did not run on v7.4-rc2:
- hotplug_sibling_partition_refused fails if cpuset_offline_moves_dl()
  ignores a partition left with tasks and no CPU.
- hotplug_top_last_refused tests the offline of the last CPU of the
  top cpuset.
- partition_grows_child_valid fails without the check of the CPUs a
  partition root just got, in "cgroup/cpuset: Refuse to take a
  deadline task out of its root domain".
- hotplug_asleep_setattr fails if sched_setattr() admits a task asleep
  on an offline CPU in the root domain of that CPU. Without
  isolcpus=domain, that root domain has no active CPU, so
  sched_setattr() returns EBUSY. "sched/deadline: Record the root
  domain holding a task's bandwidth" admits the task in the root domain
  of an active CPU of its mask instead.
- hotplug_first_sibling_refused, hotplug_nested_partition_refused and
  hotplug_isolated_child_refused take the last CPU of a child partition.
  Its parent partition has no CPU of its own, so cpuset can then give
  it the CPUs of another child partition. A deadline task under that
  parent would change root domain. "sched/deadline: Keep the last CPU
  a task has in its root domain" refuses that offline with EBUSY.

With the fixes up to here, every case passes wherever it runs.

Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
 .../sched/deadline/deadline_bw_test.c         | 2615 ++++++++++++++++-
 1 file changed, 2612 insertions(+), 3 deletions(-)

diff --git a/tools/testing/selftests/sched/deadline/deadline_bw_test.c b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
index f50d45dd5799..87fa1a7d420f 100644
--- a/tools/testing/selftests/sched/deadline/deadline_bw_test.c
+++ b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
@@ -35,8 +35,13 @@
  * accounting, which clears what an earlier case left.
  *
  * The cases of hp_cases[] run after them, without P. These are the
- * hotplug cases, and affinity_vs_setattr. The test skips the hotplug
- * cases if no CPU can go offline. It still runs affinity_vs_setattr.
+ * hotplug cases, and ten other cases: mask_out_refused,
+ * partition_takes_refused, no_admission_affinity_moves,
+ * affinity_vs_setattr, rebuild_waking_keeps,
+ * partition_takes_fallback_refused, mask_grows_refused,
+ * partition_swap_refused, partition_refused_no_warn and
+ * partition_grows_child_valid. The test skips the hotplug cases if no
+ * CPU can go offline. It still runs these ten.
  * death_zombie_hotplug takes CPUs offline too, but it is in p_cases[]: it
  * needs the cpuset setup of those cases.
  *
@@ -45,7 +50,7 @@
  *
  * The test needs root, deadline admission control and 3 housekeeping
  * CPUs. Some cases need 4. Most also need the cgroup v2 cpuset
- * controller. Some need debugfs or CPU hotplug. Five need
+ * controller. Some need debugfs or CPU hotplug. Twenty-six need
  * isolcpus="domain" at boot.
  */
 #define _GNU_SOURCE
@@ -6859,6 +6864,73 @@ static int hotplug_server(void)
 	return KSFT_PASS;
 }
 
+/*
+ * A CPU that goes offline takes its capacity and the bandwidth of its
+ * fair server out of the root domain. Set the server of hp_cpu to the
+ * admission limit less 10%. The offline then costs the root domain the
+ * room of one probe task. Hold every probe task that the root domain
+ * admits but one: the CPU can still go offline. Hold one more: the
+ * offline must fail with EBUSY.
+ */
+static int hotplug_server_refused(void)
+{
+	uint64_t rt_runtime, rt_period, runtime;
+	int n, err, ret = KSFT_PASS;
+	char buf[32];
+
+	if (ext_switched_all()) {
+		ksft_print_msg("a hotplug can end the sched_ext scheduler\n");
+		return KSFT_SKIP;
+	}
+	if (read_file("/proc/sys/kernel/sched_rt_runtime_us", buf, sizeof(buf)) ||
+	    read_file("/proc/sys/kernel/sched_rt_period_us", buf, sizeof(buf))) {
+		ksft_print_msg("no sched_rt_runtime_us or sched_rt_period_us\n");
+		return KSFT_SKIP;
+	}
+	read_file("/proc/sys/kernel/sched_rt_runtime_us", buf, sizeof(buf));
+	rt_runtime = atoll(buf);
+	read_file("/proc/sys/kernel/sched_rt_period_us", buf, sizeof(buf));
+	rt_period = atoll(buf);
+	if (!rt_period || 5 * rt_runtime < rt_period) {
+		ksft_print_msg("the admission limit is below a fifth of a CPU\n");
+		return KSFT_SKIP;
+	}
+	runtime = SERVER_PERIOD * rt_runtime / rt_period - SERVER_PERIOD / 10;
+	if (server_set(hp_cpu, runtime, SERVER_PERIOD)) {
+		ksft_print_msg("the fair server of CPU %d cannot be set\n", hp_cpu);
+		return KSFT_SKIP;
+	}
+	n = probe(NULL);
+	if (n < 2) {
+		ksft_print_msg("no room for two probe tasks\n");
+		return KSFT_SKIP;
+	}
+	if (hold(n - 1)) {
+		release_held();
+		return KSFT_FAIL;
+	}
+	err = cpu_online(hp_cpu, 0);
+	if (err) {
+		ksft_print_msg("CPU %d, room for one probe task left: offline refused (%s)\n",
+			       hp_cpu, strerror(-err));
+		ret = KSFT_FAIL;
+	} else if (cpu_online(hp_cpu, 1) || hold(1)) {
+		cpu_up(hp_cpu);
+		ret = KSFT_FAIL;
+	} else {
+		err = cpu_online(hp_cpu, 0);
+		if (err != -EBUSY) {
+			ksft_print_msg("CPU %d, no room left: offline %s, not EBUSY\n",
+				       hp_cpu, err ? strerror(-err) : "accepted");
+			if (!err)
+				cpu_up(hp_cpu);
+			ret = KSFT_FAIL;
+		}
+	}
+	release_held();
+	return ret;
+}
+
 /* Return whether @cpu is in @list, a CPU list as sysfs prints it. */
 static int in_cpu_list(const char *list, int cpu)
 {
@@ -6898,6 +6970,485 @@ static int fallback_wake(int fd, pid_t pid)
 	return 0;
 }
 
+/*
+ * The CPUs of fallback_case() and no_admission_affinity_moves(). I1 and I2
+ * are isolated by isolcpus="domain". H and K are housekeeping CPUs: CPUs
+ * that isolcpus does not isolate. H has a higher number than I2. K is
+ * another one.
+ *
+ * H has a higher number than I2 because of select_fallback_rq(). It
+ * gives a task that
+ * must leave its CPU the first CPU of its mask. A task allowed on I2 and
+ * H then goes to I2, unless the kernel keeps it in its root domain.
+ *
+ * fb_i1_hp says whether I1 can go offline.
+ */
+static int fb_i1 = -1, fb_i2 = -1, fb_h = -1, fb_k = -1, fb_i1_hp;
+
+/*
+ * Read total_bw of the root domain of the isolated CPUs into @def, and of
+ * the housekeeping root domain into @hk. Return 0, or -1.
+ */
+static int fallback_totals(long long *def, long long *hk)
+{
+	*def = total_bw_of(fb_i2);
+	*hk = total_bw_of(fb_h);
+	if (*def == -1 || *hk == -1) {
+		ksft_print_msg("no total_bw in /sys/kernel/debug/sched/debug\n");
+		return -1;
+	}
+	return 0;
+}
+
+/*
+ * Find I1, I2, H and K. Take a hotpluggable CPU as I1 if there is one.
+ * With @offline, I1 must be hotpluggable. Return 0, or -1 if the CPUs do
+ * not allow the case. fb_k is set only once all four are found.
+ */
+static int fallback_cpus(int offline)
+{
+	int i;
+
+	if (fb_k >= 0)
+		return offline && !fb_i1_hp ? -1 : 0;
+	/* A failed scan can leave I1, I2 or H set. Scan from scratch. */
+	fb_i1 = -1;
+	fb_i2 = -1;
+	fb_h = -1;
+	for (i = 0; i < nisol; i++) {
+		if (fb_i1 < 0 && cpu_hotpluggable(isol[i]))
+			fb_i1 = isol[i];
+		else if (fb_i2 < 0)
+			fb_i2 = isol[i];
+	}
+	fb_i1_hp = fb_i1 >= 0;
+	if (fb_i1 < 0 && nisol >= 2) {
+		fb_i1 = isol[0];
+		fb_i2 = isol[1];
+	}
+	for (i = 0; fb_i2 >= 0 && i < ncpus && fb_h < 0; i++) {
+		if (online[i] > fb_i2)
+			fb_h = online[i];
+	}
+	for (i = 0; fb_h >= 0 && i < ncpus && fb_k < 0; i++) {
+		if (online[i] != fb_h)
+			fb_k = online[i];
+	}
+	if (fb_i1 >= 0 && fb_i2 >= 0 && fb_k >= 0)
+		return offline && !fb_i1_hp ? -1 : 0;
+	fb_k = -1;
+	return -1;
+}
+
+enum fb_mode { FB_RUN_I1, FB_ON_I1, FB_ON_K, FB_ON_H, FB_MASK_H, FB_LAST_H, FB_PART_H, FB_STAY_K };
+
+/*
+ * B is a cpuset of I1, I2 and H. C is a cpuset of I1, in B. Neither is a
+ * partition. A deadline task of 10% is allowed on all CPUs. It sleeps on
+ * K or on H, and the housekeeping root domain counts it. The case moves
+ * it, asleep, into C or into B.
+ *
+ * In C, the task has I1 only. The move asks the root domain of the
+ * isolated CPUs for room, and that root domain counts the task. In B, the
+ * task still has H, a CPU of the housekeeping root domain. That root
+ * domain goes on counting it.
+ *
+ * The case then does one thing, and wakes the task. The table gives the
+ * cpuset the task is in, the CPU it sleeps on, what the case does, and
+ * the CPU the task must wake up on:
+ *
+ *   case                       in  asleep on  then                  wakes on
+ *   hotplug_fallback           C   I1         I1 goes offline       I2
+ *   hotplug_fallback_running   C   I1, runs   I1 goes offline       I2
+ *   hotplug_fallback_moved     C   K          I1 goes offline       I2
+ *   hotplug_fallback_in_mask   C   H          I1 goes offline       I2
+ *   mask_out_refused           C   H          C is given H only:    I1
+ *                                             EBUSY
+ *   hotplug_last_refused       B   H          H offline: EBUSY      H
+ *   hotplug_keeps_root_domain  B   H          H goes offline        K
+ *   partition_takes_refused    B   H          Q takes H: invalid    H
+ *
+ * hotplug_fallback wakes the task once after the move, so that it sleeps
+ * on I1. In hotplug_fallback_running, the task then spins on I1 with a
+ * period of 2ms. It is moved off I1 before the cpuset update of the
+ * offline, by select_fallback_rq(). The case checks where it runs after
+ * the offline. hotplug_keeps_root_domain gives B the CPU K as well. In
+ * partition_takes_refused, Q is a cpuset of H next to B. The case makes
+ * it a partition root, which must be invalid.
+ *
+ * With I1 offline, C has no CPU left, and the task gets the CPUs of B:
+ * I2 and H. It must wake up on I2, in the root domain that counts it. On
+ * H, it would run in a root domain that did not admit it. The three
+ * refusals have one reason: each change would leave the task no CPU in
+ * the root domain that counts it.
+ *
+ * In every case, the root domain of the CPU the task wakes on must count
+ * it, and the other one must not. The case checks the root domain of that
+ * CPU, not its number. The reference values of total_bw are taken with no
+ * task. If the case takes a CPU offline, they are taken with that CPU
+ * offline. Once the task is gone, total_bw must be
+ * back to them. The messages give total_bw of the root domain of the
+ * isolated CPUs first, then of the housekeeping one.
+ */
+static int fallback_case(enum fb_mode mode)
+{
+	int in_b = mode == FB_LAST_H || mode == FB_PART_H || mode == FB_STAY_K;
+	int off_cpu;
+	int on_h = mode == FB_ON_H || mode == FB_MASK_H || in_b;
+	int no_offline = mode == FB_MASK_H || mode == FB_LAST_H || mode == FB_PART_H;
+	char cg_q[PATH_MAX];
+	int running = mode == FB_RUN_I1;
+	int on_i1 = mode == FB_ON_I1 || running;
+	char cg_b[PATH_MAX], cg_c[PATH_MAX], path[PATH_MAX + 32], buf[256], one[16];
+	long long def0, hk0, def_off = 0, hk_off = 0, def_ref, hk_ref, def, hk, bw;
+	int fd[2], ret = KSFT_SKIP, added = 0, made = 0, w, at, err;
+	pid_t pid = -1;
+
+	/* hotplug_keeps_root_domain takes H offline, not I1. */
+	if (!root[0] || fallback_cpus(!no_offline && mode != FB_STAY_K)) {
+		ksft_print_msg("needs isolcpus=domain: 2 isolated, 2 housekeeping CPUs%s\n",
+			       no_offline ? "" : ", CPU hotplug");
+		return KSFT_SKIP;
+	}
+	off_cpu = mode == FB_STAY_K ? fb_h : fb_i1;
+	if ((mode == FB_LAST_H || mode == FB_STAY_K) && !cpu_hotpluggable(fb_h)) {
+		ksft_print_msg("CPU %d cannot go offline\n", fb_h);
+		return KSFT_SKIP;
+	}
+	snprintf(path, sizeof(path), "%s/cgroup.subtree_control", root);
+	if (read_file(path, buf, sizeof(buf)))
+		return KSFT_SKIP;
+	if (!strstr(buf, "cpuset")) {
+		if (write_file(root, "cgroup.subtree_control", "+cpuset"))
+			return KSFT_SKIP;
+		added = 1;
+	}
+	if (snprintf(cg_q, sizeof(cg_q), "%s/deadline_bw_q", root) >= (int)sizeof(cg_q) ||
+	    snprintf(cg_b, sizeof(cg_b), "%s/deadline_bw_b", root) >= (int)sizeof(cg_b) ||
+	    snprintf(cg_c, sizeof(cg_c), "%s/c", cg_b) >= (int)sizeof(cg_c))
+		goto out;
+	if (mkdir(cg_b, 0755) && errno != EEXIST) {
+		ksft_print_msg("mkdir %s: %s\n", cg_b, strerror(errno));
+		goto out;
+	}
+	made = 1;
+	if (mode == FB_STAY_K)
+		snprintf(buf, sizeof(buf), "%d,%d,%d,%d", fb_i1, fb_i2, fb_h, fb_k);
+	else
+		snprintf(buf, sizeof(buf), "%d,%d,%d", fb_i1, fb_i2, fb_h);
+	snprintf(one, sizeof(one), "%d", fb_i1);
+	if (write_file(cg_b, "cpuset.cpus", buf) ||
+	    write_file(cg_b, "cgroup.subtree_control", "+cpuset") ||
+	    (mkdir(cg_c, 0755) && errno != EEXIST) ||
+	    write_file(cg_c, "cpuset.cpus", one)) {
+		ksft_print_msg("cpusets B and C cannot be made\n");
+		goto out;
+	}
+	if (fallback_totals(&def0, &hk0))
+		goto out;
+	ret = KSFT_FAIL;
+	if (!no_offline) {
+		if (cpu_online(off_cpu, 0)) {
+			ksft_print_msg("offline of CPU %d refused\n", off_cpu);
+			goto out;
+		}
+		/* H may be the offline CPU: read the housekeeping total_bw on K. */
+		def_off = total_bw_of(fb_i2);
+		hk_off = total_bw_of(fb_k);
+		if (def_off == -1 || hk_off == -1)
+			ret = KSFT_SKIP;
+		cpu_up(off_cpu);
+		if (ret == KSFT_SKIP)
+			goto out;
+	}
+
+	if (pipe(fd)) {
+		ksft_print_msg("pipe: %s\n", strerror(errno));
+		goto out;
+	}
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = fork_child("a deadline task");
+	if (!pid) {
+		cpu_set_t set;
+		int i, err;
+		char c;
+
+		/* Run on K or H, then allow every CPU again, and stay there. */
+		close(fd[1]);
+		CPU_ZERO(&set);
+		CPU_SET(on_h ? fb_h : fb_k, &set);
+		err = sched_setaffinity(0, sizeof(set), &set);
+		for (i = 0; i < CPU_SETSIZE; i++)
+			CPU_SET(i, &set);
+		if (err || sched_setaffinity(0, sizeof(set), &set) ||
+		    (running ? set_deadline(0, 1 * NSEC_PER_MSEC, 2 * NSEC_PER_MSEC) :
+			       set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD))) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		mv_state[0] = 1;
+		/* hotplug_fallback_running: spin from the first wakeup on. */
+		if (running) {
+			if (read(fd[0], &c, 1) == 1)
+				mv_state[1]++;
+			for (;;)
+				;
+		}
+		while (read(fd[0], &c, 1) == 1)
+			mv_state[1]++;
+		_exit(0);
+	}
+	close(fd[0]);
+	if (pid < 0 || child_up("hotplug_fallback", 0))
+		goto out_fd;
+	if (wait_for(1000, proc_state_of(pid) == 'S') || fallback_totals(&def, &hk))
+		goto out_fd;
+	bw = def + hk - def0 - hk0;
+	if (bw <= 0) {
+		ksft_print_msg("the deadline task adds %lld to total_bw\n", bw);
+		goto out_fd;
+	}
+
+	/*
+	 * Move it asleep into C, or into B. For hotplug_fallback, wake it
+	 * once so that it runs on I1.
+	 */
+	if (enter(in_b ? cg_b : cg_c, pid) ||
+	    (on_i1 && !running && fallback_wake(fd[1], pid)))
+		goto out_fd;
+	if (running) {
+		int n = mv_state[1];
+
+		if (write(fd[1], "w", 1) != 1 || wait_for(1000, mv_state[1] != n) ||
+		    wait_for(1000, task_cpu_of(pid) == fb_i1)) {
+			ksft_print_msg("the deadline task does not run on CPU %d\n", fb_i1);
+			goto out_fd;
+		}
+	}
+	at = task_cpu_of(pid);
+	if (on_i1 ? at != fb_i1 : on_h ? at != fb_h : at == fb_i1) {
+		ksft_print_msg("the deadline task sleeps on CPU %d\n", at);
+		ret = on_h ? KSFT_SKIP : KSFT_FAIL;
+		goto out_fd;
+	}
+	/* With no CPU offline, the reference is total_bw with no task. */
+	def_ref = no_offline ? def0 : def_off;
+	hk_ref = no_offline ? hk0 : hk_off;
+	if (mode == FB_MASK_H) {
+		snprintf(one, sizeof(one), "%d", fb_h);
+		err = write_file(cg_c, "cpuset.cpus", one);
+		if (err != -EBUSY) {
+			ksft_print_msg("C given CPU %d only: %s, not EBUSY\n", fb_h,
+				       err ? strerror(-err) : "accepted");
+			goto out_fd;
+		}
+	} else if (mode == FB_LAST_H) {
+		err = cpu_online(fb_h, 0);
+		if (err != -EBUSY) {
+			ksft_print_msg("offline of CPU %d: %s, not EBUSY\n", fb_h,
+				       err ? strerror(-err) : "accepted");
+			cpu_up(fb_h);
+			goto out_fd;
+		}
+	} else if (mode == FB_PART_H) {
+		snprintf(one, sizeof(one), "%d", fb_h);
+		if ((mkdir(cg_q, 0755) && errno != EEXIST) ||
+		    write_file(cg_q, "cpuset.cpus", one) ||
+		    write_file(cg_q, "cpuset.cpus.partition", "root")) {
+			ksft_print_msg("cpuset Q cannot be made\n");
+			goto out_fd;
+		}
+		snprintf(path, sizeof(path), "%s/cpuset.cpus.partition", cg_q);
+		if (read_file(path, buf, sizeof(buf)) || !strstr(buf, "Deadline task")) {
+			ksft_print_msg("Q takes CPU %d from B: %s", fb_h, buf);
+			goto out_fd;
+		}
+	} else if (cpu_online(off_cpu, 0)) {
+		ksft_print_msg("offline of CPU %d with the task asleep refused\n", off_cpu);
+		goto out_fd;
+	}
+	if (running)
+		sleep_ns(PERIOD);
+	else if (fallback_wake(fd[1], pid))
+		goto out_up;
+	def = total_bw_of(fb_i2);
+	hk = total_bw_of(fb_k);
+	if (def == -1 || hk == -1)
+		goto out_up;
+	w = task_cpu_of(pid);
+	ret = KSFT_PASS;
+	if (in_cpu_list(isolated, w) ? def != def_ref + bw || hk != hk_ref :
+				     hk != hk_ref + bw || def != def_ref) {
+		ksft_print_msg("woken on CPU %d: total_bw %lld, %lld, not %lld, %lld\n",
+			       w, def, hk,
+			       in_cpu_list(isolated, w) ? def_ref + bw : def_ref,
+			       in_cpu_list(isolated, w) ? hk_ref : hk_ref + bw);
+		ret = KSFT_FAIL;
+	} else if (in_cpu_list(isolated, w) == in_b) {
+		ksft_print_msg("woken on CPU %d: out of the root domain that counted it\n",
+			       w);
+		ret = KSFT_FAIL;
+	}
+	reap(pid);
+	pid = -1;
+	sleep_ns(3 * PERIOD);
+	def = total_bw_of(fb_i2);
+	hk = total_bw_of(fb_k);
+	if (def != def_ref || hk != hk_ref) {
+		ksft_print_msg("task gone: total_bw %lld, %lld, not %lld, %lld\n",
+			       def, hk, def_ref, hk_ref);
+		ret = KSFT_FAIL;
+	}
+out_up:
+	reap(pid);
+	if (!no_offline)
+		cpu_up(off_cpu);
+	pid = -1;
+out_fd:
+	reap(pid);
+	close(fd[1]);
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS && (fallback_totals(&def, &hk) || def != def0 || hk != hk0)) {
+		ksft_print_msg("task gone, CPU %d online: total_bw %lld, %lld, not %lld, %lld\n",
+			       off_cpu, def, hk, def0, hk0);
+		ret = KSFT_FAIL;
+	}
+out:
+	if (made) {
+		if (rmdir(cg_q) && errno != ENOENT)
+			ksft_print_msg("rmdir %s: %s\n", cg_q, strerror(errno));
+		if (wait_for(1000, !rmdir(cg_c) || errno == ENOENT) ||
+		    wait_for(1000, !rmdir(cg_b) || errno == ENOENT))
+			ksft_print_msg("rmdir %s: %s\n", cg_b, strerror(errno));
+	}
+	if (added && write_file(root, "cgroup.subtree_control", "-cpuset"))
+		ksft_print_msg("the cpuset controller stays enabled\n");
+	return ret;
+}
+
+static int hotplug_fallback_running(void)
+{
+	return fallback_case(FB_RUN_I1);
+}
+
+static int hotplug_fallback(void)
+{
+	return fallback_case(FB_ON_I1);
+}
+
+static int hotplug_fallback_moved(void)
+{
+	return fallback_case(FB_ON_K);
+}
+
+static int hotplug_fallback_in_mask(void)
+{
+	return fallback_case(FB_ON_H);
+}
+
+static int mask_out_refused(void)
+{
+	return fallback_case(FB_MASK_H);
+}
+
+static int hotplug_last_refused(void)
+{
+	return fallback_case(FB_LAST_H);
+}
+
+static int hotplug_keeps_root_domain(void)
+{
+	return fallback_case(FB_STAY_K);
+}
+
+static int partition_takes_refused(void)
+{
+	return fallback_case(FB_PART_H);
+}
+
+/*
+ * Turn admission control off. A task pins itself to H, becomes a deadline
+ * task of 10% and spins. The housekeeping root domain counts it. The case
+ * then sets its affinity to I2 with sched_setaffinity(). Nothing reserves
+ * room for it: its bandwidth must follow it to the root domain of the
+ * isolated CPUs. Once the task is gone and admission control is on again,
+ * total_bw must be what it was.
+ */
+static int no_admission_affinity_moves(void)
+{
+	long long def0, hk0, def, hk, bw;
+	int ret = KSFT_FAIL, at;
+	char saved[64];
+	cpu_set_t set;
+	pid_t pid;
+
+	if (fallback_cpus(0)) {
+		ksft_print_msg("needs isolcpus=domain: 2 isolated, 2 housekeeping CPUs\n");
+		return KSFT_SKIP;
+	}
+	if (fallback_totals(&def0, &hk0))
+		return KSFT_SKIP;
+	if (read_file("/proc/sys/kernel/sched_rt_runtime_us", saved, sizeof(saved)) ||
+	    write_file("/proc/sys/kernel", "sched_rt_runtime_us", "-1")) {
+		ksft_print_msg("admission control cannot be turned off\n");
+		return KSFT_SKIP;
+	}
+	mv_state[0] = 0;
+	pid = fork_child("a deadline task");
+	if (!pid) {
+		CPU_ZERO(&set);
+		CPU_SET(fb_h, &set);
+		if (sched_setaffinity(0, sizeof(set), &set) ||
+		    set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD)) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		mv_state[0] = 1;
+		for (;;)
+			spin_ns(NSEC_PER_MSEC);
+	}
+	if (pid < 0 || child_up("no_admission_affinity_moves", 0))
+		goto out;
+	sleep_ns(PERIOD);
+	if (fallback_totals(&def, &hk))
+		goto out;
+	bw = hk - hk0;
+	if (bw <= 0 || def != def0) {
+		ksft_print_msg("the deadline task adds %lld to total_bw of its root domain\n", bw);
+		goto out;
+	}
+	CPU_ZERO(&set);
+	CPU_SET(fb_i2, &set);
+	if (sched_setaffinity(pid, sizeof(set), &set)) {
+		ksft_print_msg("sched_setaffinity to CPU %d: %s\n", fb_i2, strerror(errno));
+		goto out;
+	}
+	sleep_ns(2 * PERIOD);
+	at = task_cpu_of(pid);
+	if (at != fb_i2 || fallback_totals(&def, &hk))
+		goto out;
+	ret = KSFT_PASS;
+	if (def != def0 + bw || hk != hk0) {
+		ksft_print_msg("on CPU %d: total_bw %lld, %lld, not %lld, %lld\n",
+			       at, def, hk, def0 + bw, hk0);
+		ret = KSFT_FAIL;
+	}
+out:
+	reap(pid);
+	if (write_file("/proc/sys/kernel", "sched_rt_runtime_us", saved)) {
+		ksft_print_msg("admission control cannot be turned on again\n");
+		return KSFT_FAIL;
+	}
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS && (fallback_totals(&def, &hk) || def != def0 || hk != hk0)) {
+		ksft_print_msg("task gone: total_bw %lld, %lld, not %lld, %lld\n",
+			       def, hk, def0, hk0);
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
 /*
  * The cpusets of the cases below: B and Q in the root cgroup, C in B. A
  * case makes those it needs. cs_setup() names them and enables the cpuset
@@ -7145,6 +7696,1779 @@ static int move_back_cpu_offline(void)
 	return ret;
 }
 
+enum sp_mode { SP_HK_10, SP_HK_WAKING, SP_ISO_WAKING };
+
+/*
+ * Return a CPU other than @not: an isolated one if @side, else a
+ * housekeeping one. Return -1 if there is none.
+ */
+static int other_cpu(int side, int not)
+{
+	int n = side ? nisol : ncpus, *cpus = side ? isol : online, i;
+
+	for (i = n - 1; i >= 0; i--) {
+		if (cpus[i] != not)
+			return cpus[i];
+	}
+	return -1;
+}
+
+/*
+ * A deadline task loses its CPU to an offline. It is in the root cgroup,
+ * and allowed on every CPU: its mask holds CPUs of the two root domains.
+ * It must stay in the root domain that counts it. The steps:
+ * 1. A task runs on the last housekeeping CPU that can go offline. Then
+ *    it allows every CPU and becomes a deadline task, of 10% for
+ *    SP_HK_10, of 90% for SP_HK_WAKING. The housekeeping root domain
+ *    counts it.
+ *    For SP_ISO_WAKING, the task runs on the last isolated CPU that can
+ *    go offline. Then it allows the isolated CPUs only, and becomes a
+ *    deadline task of 90%. The root domain of the isolated CPUs counts
+ *    it. Then it allows every CPU.
+ *    The task of SP_HK_10 spins. The others spin 50us and sleep 50us, in
+ *    a loop.
+ * 2. Wait a period. X is the CPU the task runs on.
+ * 3. Take X offline.
+ * 4. Wait two periods. The task must run on a CPU of its root domain.
+ *    That root domain must still count it.
+ * The task of SP_HK_10 is throttled most of the time. Its replenishment
+ * timer then finds its CPU offline, and picks a CPU for it. The other
+ * tasks wake up while the offline goes on, and the wakeup picks a CPU
+ * for them.
+ *
+ * A kernel that does not prefer the root domain of the task at a wakeup
+ * gives it the first CPU of its mask. The waking cases fail on such a
+ * kernel only if that CPU is of the other kind. SP_HK_WAKING needs an
+ * isolated CPU first, SP_ISO_WAKING a housekeeping CPU first.
+ *
+ * The kernel records with the task the CPU where it became a deadline
+ * task. The waking cases need X to be that CPU: a wakeup in the offline
+ * looks at the root domain of that CPU. SP_HK_10 takes any housekeeping
+ * CPU as X.
+ *
+ * Do it in rounds, each with a new task. Stop once 3 rounds check
+ * something, or after 10 rounds. A round checks nothing if X cannot go
+ * offline, or for a waking case, if X is not the CPU recorded.
+ *
+ * The references of total_bw are taken with no task: with X offline
+ * after the task is gone, and with every CPU online. The messages give
+ * total_bw of the root domain of the isolated CPUs first, then of the
+ * housekeeping one.
+ */
+static int spin_offline(enum sp_mode mode)
+{
+	uint64_t runtime = (mode == SP_HK_10 ? 10 : 90) * NSEC_PER_MSEC;
+	int iso = mode == SP_ISO_WAKING, start = -1, rounds = 0, round;
+	long long def0, hk0, def, hk, ref_def, ref_hk, bw;
+	int x, d, h, cpu, i, down, ret = KSFT_SKIP;
+	pid_t pid;
+
+	for (i = 0; i < (iso ? nisol : ncpus); i++) {
+		if (cpu_hotpluggable(iso ? isol[i] : online[i]))
+			start = iso ? isol[i] : online[i];
+	}
+	if (!nisol || (iso && nisol < 2) || start < 0) {
+		ksft_print_msg("needs isolcpus=domain: %d isolated CPUs, one hotpluggable\n",
+			       iso ? 2 : 1);
+		return KSFT_SKIP;
+	}
+	if (totals_of(isol[0], online[0], &def0, &hk0))
+		return KSFT_SKIP;
+	ret = KSFT_PASS;
+	for (round = 0; round < 10 && rounds < 3 && ret == KSFT_PASS; round++) {
+		mv_state[0] = 0;
+		mv_state[1] = 0;
+		pid = fork_child("a spinning deadline task");
+		if (!pid) {
+			cpu_set_t set;
+
+			CPU_ZERO(&set);
+			CPU_SET(start, &set);
+			if (sched_setaffinity(0, sizeof(set), &set))
+				_exit(1);
+			spin_ns(NSEC_PER_MSEC);
+			for (i = 0; i < (iso ? nisol : CPU_SETSIZE); i++)
+				CPU_SET(iso ? isol[i] : i, &set);
+			if (sched_setaffinity(0, sizeof(set), &set) ||
+			    set_deadline(0, runtime, PERIOD)) {
+				mv_state[0] = -1;
+				_exit(1);
+			}
+			for (i = 0; i < CPU_SETSIZE; i++)
+				CPU_SET(i, &set);
+			if (sched_setaffinity(0, sizeof(set), &set)) {
+				mv_state[0] = -1;
+				_exit(1);
+			}
+			mv_state[0] = 1;
+			for (;;) {
+				mv_state[1]++;
+				if (mode == SP_HK_10)
+					continue;
+				spin_ns(50 * NSEC_PER_USEC);
+				sleep_ns(50 * NSEC_PER_USEC);
+			}
+		}
+		ret = KSFT_FAIL;
+		down = 0;
+		if (pid < 0 || child_up("spin_offline", 0))
+			goto next;
+		sleep_ns(PERIOD);
+		x = task_cpu_of(pid);
+		if (mode == SP_HK_10 ? in_cpu_list(isolated, x) || !cpu_hotpluggable(x) :
+				       x != start) {
+			ret = KSFT_PASS;	/* check nothing */
+			goto next;
+		}
+		d = other_cpu(1, x);
+		h = other_cpu(0, x);
+		if (totals_of(d, h, &def, &hk))
+			goto next;
+		bw = iso ? def - def0 : hk - hk0;
+		if (bw <= 0 || (iso ? hk != hk0 : def != def0)) {
+			ksft_print_msg("on CPU %d, the deadline task adds %lld, %lld to total_bw\n",
+				       task_cpu_of(pid), def - def0, hk - hk0);
+			goto next;
+		}
+		if (task_cpu_of(pid) != x) {
+			ret = KSFT_PASS;	/* moved off X: check nothing */
+			goto next;
+		}
+		rounds++;
+		if (cpu_online(x, 0)) {
+			ksft_print_msg("offline of CPU %d with the task on it refused\n", x);
+			goto next;
+		}
+		down = 1;
+		sleep_ns(2 * PERIOD);
+		cpu = task_cpu_of(pid);
+		if (totals_of(d, h, &def, &hk))
+			goto next;
+		reap(pid);
+		pid = -1;
+		sleep_ns(3 * PERIOD);
+		if (totals_of(d, h, &ref_def, &ref_hk))
+			goto next;
+		if (in_cpu_list(isolated, cpu) != iso) {
+			ksft_print_msg("round %d: CPU %d offline, the task runs on CPU %d\n",
+				       round, x, cpu);
+			goto next;
+		}
+		if (iso ? def != ref_def + bw || hk != ref_hk :
+			  hk != ref_hk + bw || def != ref_def) {
+			ksft_print_msg("round %d: on CPU %d: total_bw %lld, %lld, not %lld, %lld\n",
+				       round, cpu, def, hk, iso ? ref_def + bw : ref_def,
+				       iso ? ref_hk : ref_hk + bw);
+			goto next;
+		}
+		ret = KSFT_PASS;
+next:
+		reap(pid);
+		if (down)
+			cpu_up(x);
+		sleep_ns(3 * PERIOD);
+		if (ret == KSFT_PASS)
+			ret = totals_check("task gone", isol[0], online[0], def0, hk0);
+	}
+	if (ret == KSFT_PASS && !rounds) {
+		ksft_print_msg("the task never ran on a CPU that can go offline\n");
+		ret = KSFT_SKIP;
+	}
+	return ret;
+}
+
+static int hotplug_spinner_keeps(void)
+{
+	return spin_offline(SP_HK_10);
+}
+
+static int hotplug_waking_keeps(void)
+{
+	return spin_offline(SP_HK_WAKING);
+}
+
+static int hotplug_isolated_keeps(void)
+{
+	return spin_offline(SP_ISO_WAKING);
+}
+
+/*
+ * A rebuild of the sched domains must keep a deadline task in the root
+ * domain that counts it. The task wakes up often, so that a wakeup can
+ * land inside a rebuild. The steps:
+ * 1. A task runs on H, the highest housekeeping CPU. Then it allows every
+ *    CPU and becomes a deadline task of 90%. The housekeeping root domain
+ *    counts it. It spins 50us and sleeps 50us, in a loop.
+ * 2. Wait a period. The task must run on a housekeeping CPU.
+ * 3. Make Q a partition root of another housekeeping CPU, and remove it.
+ *    Each of the two steps rebuilds the sched domains.
+ * 4. The task must run on a housekeeping CPU. The housekeeping root
+ *    domain must still count it, and the other one must not.
+ * A kernel that gets this wrong gives the task the first CPU of the root
+ * domain of the isolated CPUs. That root domain then counts it, with no
+ * admission test. This shows only if that first CPU is isolated, as with
+ * isolcpus=domain,0,1. The case skips otherwise.
+ *
+ * Do it in 20 rounds, each with a new task. The first rebuild of a new
+ * task is the one most likely to go wrong. The case is not deterministic.
+ * The messages give total_bw of the root domain of the isolated CPUs
+ * first, then of the housekeeping one.
+ */
+static int rebuild_waking_keeps(void)
+{
+	int h = top_cpu(1), q = other_cpu(0, top_cpu(1)), d = nisol ? isol[0] : -1;
+	long long def0, hk0, def, hk;
+	int round, cpu, ret;
+	pid_t pid;
+
+	if (d < 0 || d > online[0] || q < 0) {
+		ksft_print_msg("needs isolcpus=domain with the first CPU isolated, as with 0,1\n");
+		return KSFT_SKIP;
+	}
+	if (cs_setup())
+		return KSFT_SKIP;
+	ret = KSFT_SKIP;
+	if (totals_of(d, h, &def0, &hk0))
+		goto out;
+	ret = KSFT_PASS;
+	for (round = 0; round < 20 && ret == KSFT_PASS; round++) {
+		mv_state[0] = 0;
+		pid = fork_child("a waking deadline task");
+		if (!pid) {
+			cpu_set_t set;
+			int i;
+
+			CPU_ZERO(&set);
+			CPU_SET(h, &set);
+			if (sched_setaffinity(0, sizeof(set), &set))
+				_exit(1);
+			spin_ns(NSEC_PER_MSEC);
+			for (i = 0; i < CPU_SETSIZE; i++)
+				CPU_SET(i, &set);
+			if (sched_setaffinity(0, sizeof(set), &set) ||
+			    set_deadline(0, 90 * NSEC_PER_MSEC, PERIOD)) {
+				mv_state[0] = -1;
+				_exit(1);
+			}
+			mv_state[0] = 1;
+			for (;;) {
+				spin_ns(50 * NSEC_PER_USEC);
+				sleep_ns(50 * NSEC_PER_USEC);
+			}
+		}
+		ret = KSFT_FAIL;
+		if (pid < 0 || child_up("rebuild_waking_keeps", 0))
+			goto next;
+		sleep_ns(PERIOD);
+		cpu = task_cpu_of(pid);
+		if (totals_of(d, h, &def, &hk))
+			goto next;
+		if (in_cpu_list(isolated, cpu) || def != def0 || hk <= hk0) {
+			ksft_print_msg("round %d: on CPU %d before the rebuild: total_bw %lld, %lld\n",
+				       round, cpu, def, hk);
+			goto next;
+		}
+		if (make_partition(cs_q, q)) {
+			ksft_print_msg("no partition root Q of CPU %d\n", q);
+			goto next;
+		}
+		remove_partition(cs_q);
+		cpu = task_cpu_of(pid);
+		if (totals_check("after the rebuild", d, h, def, hk) != KSFT_PASS)
+			ksft_print_msg("round %d: the task runs on CPU %d\n", round, cpu);
+		else if (in_cpu_list(isolated, cpu))
+			ksft_print_msg("round %d: after the rebuild, the task runs on CPU %d\n",
+				       round, cpu);
+		else
+			ret = KSFT_PASS;
+next:
+		remove_partition(cs_q);
+		reap(pid);
+		sleep_ns(3 * PERIOD);
+		if (ret == KSFT_PASS)
+			ret = totals_check("task gone", d, h, def0, hk0);
+	}
+out:
+	cs_cleanup();
+	return ret;
+}
+
+/*
+ * A user affinity can keep a task out of the root domain that counts
+ * it. The CPUs are those of fallback_case(). B is a cpuset of I1, I2, H
+ * and K. C, in B, is a cpuset of H. Neither is a partition. The steps:
+ * 1. A task in the root cgroup allows I1 and I2 only. It becomes a
+ *    deadline task of 10%. The root domain of the isolated CPUs counts
+ *    it.
+ * 2. It sets its affinity to I1, I2 and H. That holds the root domain
+ *    that counts it, so it is accepted. It sleeps.
+ * 3. Move it asleep into C. It has H only. The housekeeping root domain
+ *    counts it now. Wake it: it runs on H.
+ * 4. Take H offline. C has no CPU left, and the task would get the CPUs
+ *    of B: I1, I2 and K. Its affinity keeps I1 and I2 of them. That holds
+ *    no CPU of the root domain that counts it.
+ * The offline must fail with EBUSY. The task must still sleep on H, and
+ * total_bw must not change. Wake it: it must run on H.
+ */
+static int hotplug_user_mask_refused(void)
+{
+	int fd[2] = { -1, -1 }, err, cpu, ret = KSFT_SKIP;
+	long long def0, hk0, def, hk, bw;
+	char buf[64];
+	pid_t pid = -1;
+
+	if (fallback_cpus(0) || !cpu_hotpluggable(fb_h)) {
+		ksft_print_msg("needs isolcpus=domain: 2 isolated, 2 housekeeping CPUs, hotplug\n");
+		return KSFT_SKIP;
+	}
+	if (cs_setup())
+		return KSFT_SKIP;
+	snprintf(buf, sizeof(buf), "%d,%d,%d,%d", fb_i1, fb_i2, fb_h, fb_k);
+	if (cs_make(cs_b, buf) || write_file(cs_b, "cgroup.subtree_control", "+cpuset"))
+		goto out;
+	snprintf(buf, sizeof(buf), "%d", fb_h);
+	if (cs_make(cs_c, buf) || fallback_totals(&def0, &hk0) || pipe(fd))
+		goto out;
+	ret = KSFT_FAIL;
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = fork_child("a deadline task");
+	if (!pid) {
+		cpu_set_t set;
+		char c;
+
+		CPU_ZERO(&set);
+		CPU_SET(fb_i1, &set);
+		CPU_SET(fb_i2, &set);
+		if (sched_setaffinity(0, sizeof(set), &set) ||
+		    set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD)) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		CPU_SET(fb_h, &set);
+		if (sched_setaffinity(0, sizeof(set), &set)) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		mv_state[0] = 1;
+		while (read(fd[0], &c, 1) == 1)
+			mv_state[1]++;
+		_exit(0);
+	}
+	if (pid < 0 || child_up("hotplug_user_mask_refused", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S') || fallback_totals(&def, &hk))
+		goto out;
+	bw = def - def0;
+	if (bw <= 0 || hk != hk0) {
+		ksft_print_msg("the deadline task adds %lld, %lld to total_bw\n", bw, hk - hk0);
+		goto out;
+	}
+	err = enter(cs_c, pid);
+	if (err) {
+		ksft_print_msg("a move into C refused: %s\n", strerror(-err));
+		goto out;
+	}
+	if (fallback_wake(fd[1], pid) ||
+	    totals_check("in C", fb_i2, fb_h, def0, hk0 + bw))
+		goto out;
+	cpu = task_cpu_of(pid);
+	if (cpu != fb_h) {
+		ksft_print_msg("woken in C on CPU %d, not %d\n", cpu, fb_h);
+		goto out;
+	}
+	err = cpu_online(fb_h, 0);
+	if (err != -EBUSY) {
+		ksft_print_msg("offline of CPU %d: %s, not EBUSY\n", fb_h,
+			       err ? strerror(-err) : "accepted");
+		if (!err) {
+			if (!fallback_wake(fd[1], pid))
+				ksft_print_msg("woken on CPU %d\n", task_cpu_of(pid));
+			cpu_up(fb_h);
+		}
+		goto out;
+	}
+	cpu = task_cpu_of(pid);
+	if (cpu != fb_h || proc_state_of(pid) != 'S') {
+		ksft_print_msg("offline refused: the task is on CPU %d, state %c\n",
+			       cpu, proc_state_of(pid));
+		goto out;
+	}
+	if (totals_check("offline refused", fb_i2, fb_h, def0, hk0 + bw) ||
+	    fallback_wake(fd[1], pid))
+		goto out;
+	cpu = task_cpu_of(pid);
+	if (cpu != fb_h) {
+		ksft_print_msg("woken on CPU %d, not %d\n", cpu, fb_h);
+		goto out;
+	}
+	ret = totals_check("woken", fb_i2, fb_h, def0, hk0 + bw);
+out:
+	reap(pid);
+	if (fd[0] >= 0) {
+		close(fd[0]);
+		close(fd[1]);
+	}
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS)
+		ret = totals_check("task gone", fb_i2, fb_h, def0, hk0);
+	cs_cleanup();
+	return ret;
+}
+
+/*
+ * cgroup v2 works out the CPUs of each cpuset from the top down, at an
+ * offline too. A cpuset left with no CPU takes all those of its parent.
+ * Its child then keeps those that its own cpuset.cpus holds. The CPUs are
+ * those of fallback_case(). B, in the root cgroup, has cpuset.cpus H. C,
+ * in B, has cpuset.cpus I1, I2 and H. Neither is a partition. C gets H.
+ * The steps:
+ * 1. A task in the root cgroup runs on H. Then it allows every CPU and
+ *    becomes a deadline task of 10%. It sleeps. The housekeeping root
+ *    domain counts it.
+ * 2. Move it asleep into C. It keeps H.
+ * 3. Take H offline. B has no CPU left, and gets all the CPUs of the root
+ *    cgroup. C keeps I1 and I2 of them: no CPU of the root domain that
+ *    counts the task. The root cgroup itself still has K. The kernel must
+ *    work out the CPUs of C from those of B, not from those of the root
+ *    cgroup.
+ * The offline must fail with EBUSY. The task must still sleep on H, and
+ * total_bw must not change. Wake it: it must run on H.
+ */
+static int hotplug_nested_refused(void)
+{
+	int fd[2] = { -1, -1 }, err, cpu, ret = KSFT_SKIP;
+	long long def0, hk0, def, hk, bw;
+	char buf[64];
+	pid_t pid = -1;
+
+	if (fallback_cpus(0) || !cpu_hotpluggable(fb_h)) {
+		ksft_print_msg("needs isolcpus=domain: 2 isolated, 2 housekeeping CPUs, hotplug\n");
+		return KSFT_SKIP;
+	}
+	if (cs_setup())
+		return KSFT_SKIP;
+	snprintf(buf, sizeof(buf), "%d", fb_h);
+	if (cs_make(cs_b, buf) ||
+	    write_file(cs_b, "cgroup.subtree_control", "+cpuset"))
+		goto out;
+	snprintf(buf, sizeof(buf), "%d,%d,%d", fb_i1, fb_i2, fb_h);
+	if (cs_make(cs_c, buf) || fallback_totals(&def0, &hk0) || pipe(fd))
+		goto out;
+	ret = KSFT_FAIL;
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = task_from(fb_h, 1, 10 * NSEC_PER_MSEC, PERIOD, fd[0]);
+	if (pid < 0 || child_up("hotplug_nested_refused", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S') ||
+	    fallback_totals(&def, &hk))
+		goto out;
+	bw = hk - hk0;
+	err = enter(cs_c, pid);
+	cpu = task_cpu_of(pid);
+	if (bw <= 0 || def != def0 || err || cpu != fb_h) {
+		ksft_print_msg("a deadline task adds %lld, %lld to total_bw, in C: %s, on CPU %d\n",
+			       def - def0, bw, strerror(-err), cpu);
+		goto out;
+	}
+	if (totals_check("in C", fb_i2, fb_h, def0, hk0 + bw))
+		goto out;
+	err = cpu_online(fb_h, 0);
+	if (err != -EBUSY) {
+		ksft_print_msg("offline of CPU %d: %s, not EBUSY\n", fb_h,
+			       err ? strerror(-err) : "accepted");
+		if (!err) {
+			if (!fallback_wake(fd[1], pid))
+				ksft_print_msg("woken on CPU %d\n",
+					       task_cpu_of(pid));
+			cpu_up(fb_h);
+		}
+		goto out;
+	}
+	cpu = task_cpu_of(pid);
+	if (cpu != fb_h || proc_state_of(pid) != 'S') {
+		ksft_print_msg("offline refused: the task is on CPU %d, state %c\n",
+			       cpu, proc_state_of(pid));
+		goto out;
+	}
+	if (totals_check("offline refused", fb_i2, fb_h, def0, hk0 + bw) ||
+	    fallback_wake(fd[1], pid))
+		goto out;
+	cpu = task_cpu_of(pid);
+	if (cpu != fb_h) {
+		ksft_print_msg("woken on CPU %d, not %d\n", cpu, fb_h);
+		goto out;
+	}
+	ret = totals_check("woken", fb_i2, fb_h, def0, hk0 + bw);
+out:
+	reap(pid);
+	if (fd[0] >= 0) {
+		close(fd[0]);
+		close(fd[1]);
+	}
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS)
+		ret = totals_check("task gone", fb_i2, fb_h, def0, hk0);
+	cs_cleanup();
+	return ret;
+}
+
+/*
+ * The CPUs of the partition cases and of cascade_case(). X, Y and Z are
+ * the three highest online CPUs: CPUs that isolcpus="domain" does not
+ * isolate. W, the lowest one, stays with the root cgroup. Return 0, or -1
+ * if they are missing or X cannot go offline.
+ */
+static int pc_x, pc_y, pc_z, pc_w;
+
+static int partition_cpus(void)
+{
+	if (ncpus < 4 || !cpu_hotpluggable(top_cpu(3))) {
+		ksft_print_msg("needs 4 CPUs, CPU hotplug\n");
+		return -1;
+	}
+	pc_x = top_cpu(3);
+	pc_y = top_cpu(2);
+	pc_z = top_cpu(1);
+	pc_w = online[0];
+	return 0;
+}
+
+/*
+ * A partition root left with no CPU of its own takes the CPUs of a child
+ * partition, if it holds a task. The child partition becomes invalid. B
+ * is an isolated partition of X, Y and Z. C, in B, is an isolated
+ * partition of Y and Z. So B keeps X only. The steps:
+ * 1. Take X offline and back with no task, to read the total_bw of each
+ *    root domain without X.
+ * 2. A task in the root cgroup runs on W. Then it allows every CPU and
+ *    becomes a deadline task of 10%. It sleeps. The housekeeping root
+ *    domain counts it.
+ * 3. Move it asleep into B. It has X only. The default root domain, which
+ *    spans the CPUs of isolated partitions, counts it.
+ * 4. Take X offline. B takes Y and Z, and C becomes invalid. The task gets
+ *    Y and Z: CPUs of the same root domain.
+ * The offline must be accepted. The default root domain must still count
+ * the task. Wake it: it must run on Y or Z.
+ */
+static int hotplug_child_partition_kept(void)
+{
+	int fd[2] = { -1, -1 }, err, cpu, ret = KSFT_SKIP, x_off = 0;
+	long long def0, hk0, def_off, hk_off, def, hk, bw;
+	char buf[64];
+	pid_t pid = -1;
+
+	if (partition_cpus() || cs_setup())
+		return KSFT_SKIP;
+	snprintf(buf, sizeof(buf), "%d,%d,%d", pc_x, pc_y, pc_z);
+	if (cs_make(cs_b, buf) ||
+	    write_file(cs_b, "cpuset.cpus.partition", "isolated") ||
+	    write_file(cs_b, "cgroup.subtree_control", "+cpuset"))
+		goto out;
+	snprintf(buf, sizeof(buf), "%d,%d", pc_y, pc_z);
+	if (cs_make(cs_c, buf) ||
+	    write_file(cs_c, "cpuset.cpus.partition", "isolated") ||
+	    !partition_has(cs_b, "isolated", 1) || partition_has(cs_b, "invalid", 0) ||
+	    !partition_has(cs_c, "isolated", 1) || partition_has(cs_c, "invalid", 0))
+		goto out;
+	if (totals_of(pc_y, pc_w, &def0, &hk0))
+		goto out;
+	err = cpu_online(pc_x, 0);
+	if (err) {
+		ksft_print_msg("offline of CPU %d with no task: %s\n", pc_x, strerror(-err));
+		goto out;
+	}
+	err = totals_of(pc_y, pc_w, &def_off, &hk_off);
+	cpu_up(pc_x);
+	if (err || pipe(fd))
+		goto out;
+	ret = KSFT_FAIL;
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = task_from(pc_w, 1, 10 * NSEC_PER_MSEC, PERIOD, fd[0]);
+	if (pid < 0 || child_up("hotplug_child_partition_kept", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S') || totals_of(pc_y, pc_w, &def, &hk))
+		goto out;
+	bw = hk - hk0;
+	err = enter(cs_b, pid);
+	if (bw <= 0 || def != def0 || err) {
+		ksft_print_msg("a deadline task adds %lld, %lld to total_bw, in B: %s\n",
+			       def - def0, bw, strerror(-err));
+		goto out;
+	}
+	if (totals_check("in B", pc_y, pc_w, def0 + bw, hk0) || fallback_wake(fd[1], pid))
+		goto out;
+	cpu = task_cpu_of(pid);
+	if (cpu != pc_x) {
+		ksft_print_msg("woken in B on CPU %d, not %d\n", cpu, pc_x);
+		goto out;
+	}
+	err = cpu_online(pc_x, 0);
+	if (err) {
+		ksft_print_msg("offline of CPU %d: %s, not accepted\n", pc_x, strerror(-err));
+		goto out;
+	}
+	x_off = 1;
+	if (!partition_has(cs_c, "invalid", 1) ||
+	    totals_check("X offline", pc_y, pc_w, def_off + bw, hk_off) ||
+	    fallback_wake(fd[1], pid))
+		goto out;
+	cpu = task_cpu_of(pid);
+	if (cpu != pc_y && cpu != pc_z) {
+		ksft_print_msg("woken on CPU %d, not %d or %d\n", cpu, pc_y, pc_z);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	reap(pid);
+	if (fd[0] >= 0) {
+		close(fd[0]);
+		close(fd[1]);
+	}
+	if (x_off)
+		cpu_up(pc_x);
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS)
+		ret = totals_check("task gone", pc_y, pc_w, def0, hk0);
+	cs_cleanup();
+	return ret;
+}
+
+/*
+ * The same rule, with a child partition of another kind. B is a root
+ * partition of X and Y. C, in B, is an isolated partition of Y. So B keeps
+ * X only, in a root domain of its own. N, in B, is a cpuset that is not a
+ * partition. The steps:
+ * 1. A task that is not a deadline task sleeps in N.
+ * 2. A task in the root cgroup runs on W. Then it allows every CPU and
+ *    becomes a deadline task of 10%. It sleeps. The housekeeping root
+ *    domain counts it.
+ * 3. Move it asleep into C. The default root domain counts it.
+ * 4. Take X offline. B would take Y, and C would become invalid. Y would
+ *    leave the default root domain for that of B, with the deadline task.
+ *    That root domain did not admit it.
+ * The offline must fail with EBUSY. C must stay valid, and total_bw must
+ * not change. Wake the task: it must run on Y. Once the task is gone, the
+ * offline must be accepted.
+ */
+static int hotplug_partition_invalid_refused(void)
+{
+	int fd[2] = { -1, -1 }, err, cpu, ret = KSFT_SKIP, x_off = 0;
+	long long def0, hk0, def, hk, bw;
+	char buf[64], cs_n[PATH_MAX];
+	pid_t pid = -1, other = -1;
+
+	if (partition_cpus() || cs_setup())
+		return KSFT_SKIP;
+	if (snprintf(cs_n, sizeof(cs_n), "%s/n", cs_b) >= (int)sizeof(cs_n))
+		goto out;
+	snprintf(buf, sizeof(buf), "%d,%d", pc_x, pc_y);
+	if (cs_make(cs_b, buf) ||
+	    write_file(cs_b, "cpuset.cpus.partition", "root") ||
+	    write_file(cs_b, "cgroup.subtree_control", "+cpuset"))
+		goto out;
+	snprintf(buf, sizeof(buf), "%d", pc_y);
+	if (cs_make(cs_c, buf) ||
+	    write_file(cs_c, "cpuset.cpus.partition", "isolated") ||
+	    !partition_has(cs_b, "root", 1) || partition_has(cs_b, "invalid", 0) ||
+	    !partition_has(cs_c, "isolated", 1) || partition_has(cs_c, "invalid", 0))
+		goto out;
+	if (mkdir(cs_n, 0755) && errno != EEXIST) {
+		ksft_print_msg("mkdir %s: %s\n", cs_n, strerror(errno));
+		goto out;
+	}
+	other = fork_child("a task in N");
+	if (!other) {
+		for (;;)
+			pause();
+	}
+	if (other < 0 || enter(cs_n, other) || totals_of(pc_y, pc_w, &def0, &hk0) ||
+	    pipe(fd))
+		goto out;
+	ret = KSFT_FAIL;
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = task_from(pc_w, 1, 10 * NSEC_PER_MSEC, PERIOD, fd[0]);
+	if (pid < 0 || child_up("hotplug_partition_invalid_refused", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S') || totals_of(pc_y, pc_w, &def, &hk))
+		goto out;
+	bw = hk - hk0;
+	err = enter(cs_c, pid);
+	if (bw <= 0 || def != def0 || err) {
+		ksft_print_msg("a deadline task adds %lld, %lld to total_bw, in C: %s\n",
+			       def - def0, bw, strerror(-err));
+		goto out;
+	}
+	if (totals_check("in C", pc_y, pc_w, def0 + bw, hk0))
+		goto out;
+	err = cpu_online(pc_x, 0);
+	if (err != -EBUSY) {
+		ksft_print_msg("offline of CPU %d: %s, not EBUSY\n", pc_x,
+			       err ? strerror(-err) : "accepted");
+		x_off = !err;
+		goto out;
+	}
+	if (partition_has(cs_c, "invalid", 0) ||
+	    totals_check("offline refused", pc_y, pc_w, def0 + bw, hk0) ||
+	    fallback_wake(fd[1], pid))
+		goto out;
+	cpu = task_cpu_of(pid);
+	if (cpu != pc_y) {
+		ksft_print_msg("woken on CPU %d, not %d\n", cpu, pc_y);
+		goto out;
+	}
+	reap(pid);
+	pid = -1;
+	sleep_ns(3 * PERIOD);
+	err = cpu_online(pc_x, 0);
+	if (err) {
+		ksft_print_msg("offline of CPU %d with the task gone: %s\n", pc_x,
+			       strerror(-err));
+		goto out;
+	}
+	x_off = 1;
+	ret = KSFT_PASS;
+out:
+	reap(pid);
+	reap(other);
+	if (fd[0] >= 0) {
+		close(fd[0]);
+		close(fd[1]);
+	}
+	if (x_off)
+		cpu_up(pc_x);
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS)
+		ret = totals_check("task gone", pc_y, pc_w, def0, hk0);
+	if (cs_n[0] && wait_for(1000, !rmdir(cs_n) || errno == ENOENT))
+		ksft_print_msg("rmdir %s: %s\n", cs_n, strerror(errno));
+	cs_cleanup();
+	return ret;
+}
+
+/*
+ * A partition root that gets more CPUs makes a child partition valid. A
+ * is the highest housekeeping CPU, B the next one:
+ * 1. B is a root partition of A. A deadline task of 10% sleeps in B.
+ * 2. C, in B, becomes a root partition of A. B would have no CPU left
+ *    for its task: C is invalid.
+ * 3. B gets A and B.
+ * C must become valid. The check runs before the rebuild of the sched
+ * domains: the root domain that counts the task still spans A alone.
+ * Its task then gets B.
+ */
+static int partition_grows_child_valid(void)
+{
+	int go[2] = { -1, -1 }, ack[2] = { -1, -1 }, i, err, ret = KSFT_SKIP;
+	int a = top_cpu(1), b = top_cpu(2);
+	char buf[64], path[PATH_MAX + 32];
+	pid_t pid = -1;
+	cpu_set_t all;
+	char c;
+
+	if (ncpus < 3 || cs_setup())
+		return KSFT_SKIP;
+	snprintf(buf, sizeof(buf), "%d", a);
+	if (cs_make(cs_b, buf) ||
+	    write_file(cs_b, "cpuset.cpus.partition", "root") ||
+	    write_file(cs_b, "cgroup.subtree_control", "+cpuset") ||
+	    !partition_has(cs_b, "root", 1) || partition_has(cs_b, "invalid", 0))
+		goto out;
+	if (pipe(go) || pipe(ack))
+		goto out;
+	pid = fork_child("a deadline task in B");
+	if (!pid) {
+		/* Run once in B, so that the task sleeps on a CPU of B. */
+		if (read(go[0], &c, 1) == 1 && write(ack[1], &c, 1) == 1)
+			for (;;)
+				pause();
+		_exit(1);
+	}
+	ret = KSFT_FAIL;
+	if (pid < 0)
+		goto out;
+	CPU_ZERO(&all);
+	for (i = 0; i < CPU_SETSIZE; i++)
+		CPU_SET(i, &all);
+	if (sched_setaffinity(pid, sizeof(all), &all)) {
+		ksft_print_msg("sched_setaffinity: %s\n", strerror(errno));
+		goto out;
+	}
+	c = 'x';
+	if (enter(cs_b, pid) || write(go[1], &c, 1) != 1 || read(ack[0], &c, 1) != 1) {
+		ksft_print_msg("the task never ran in B\n");
+		goto out;
+	}
+	err = set_deadline(pid, 10 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("a deadline task refused in B: %s\n", strerror(-err));
+		goto out;
+	}
+	snprintf(buf, sizeof(buf), "%d", a);
+	if (cs_make(cs_c, buf))
+		goto out;
+	write_file(cs_c, "cpuset.cpus.partition", "root");
+	if (!partition_has(cs_c, "invalid", 1)) {
+		ksft_print_msg("C took the last CPU of B\n");
+		goto out;
+	}
+	snprintf(buf, sizeof(buf), "%d,%d", a, b);
+	err = write_file(cs_b, "cpuset.cpus", buf);
+	if (err) {
+		ksft_print_msg("B cannot get CPUs %s: %s\n", buf, strerror(-err));
+		goto out;
+	}
+	if (!partition_has(cs_c, "root", 1) || partition_has(cs_c, "invalid", 0))
+		goto out;
+	snprintf(path, sizeof(path), "%s/cpuset.cpus.effective", cs_b);
+	if (read_file(path, buf, sizeof(buf)))
+		goto out;
+	buf[strcspn(buf, "\n")] = 0;
+	snprintf(path, sizeof(path), "%d", b);
+	if (strcmp(buf, path)) {
+		ksft_print_msg("B has CPUs %s, not %d\n", buf, b);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	reap(pid);
+	for (i = 0; i < 2; i++) {
+		if (go[i] >= 0)
+			close(go[i]);
+		if (ack[i] >= 0)
+			close(ack[i]);
+	}
+	sleep_ns(3 * PERIOD);
+	cs_cleanup();
+	return ret;
+}
+
+/*
+ * Take offline the last CPU of the top cpuset. B is a root partition of
+ * every housekeeping CPU but X, the highest one. A deadline task of 10%
+ * sleeps in B. With X offline, the top cpuset would have no CPU left, so
+ * cpuset would make every partition invalid. B's CPUs would join a new
+ * root domain, with the deadline task. That root domain did not admit it.
+ * The offline must fail with EBUSY, and B must stay valid. Once the task
+ * is gone, the offline must be accepted. The case skips if the top
+ * cpuset keeps other CPUs, such as isolated ones.
+ */
+static int hotplug_top_last_refused(void)
+{
+	int i, n = 0, err, ret = KSFT_SKIP, x = top_cpu(1), x_off = 0;
+	char buf[256], cpus[1024], path[PATH_MAX + 32];
+	int go[2] = { -1, -1 }, ack[2] = { -1, -1 };
+	pid_t pid = -1;
+	cpu_set_t all;
+	char c;
+
+	if (ncpus < 3 || !cpu_hotpluggable(x) || cs_setup())
+		return KSFT_SKIP;
+	for (i = 0; i < ncpus - 1 && n < (int)sizeof(cpus) - 16; i++)
+		n += snprintf(cpus + n, sizeof(cpus) - n, "%s%d", i ? "," : "", online[i]);
+	if (cs_make(cs_b, cpus) ||
+	    write_file(cs_b, "cpuset.cpus.partition", "root") ||
+	    !partition_has(cs_b, "root", 1) || partition_has(cs_b, "invalid", 0))
+		goto out;
+	snprintf(path, sizeof(path), "%s/cpuset.cpus.effective", root);
+	if (read_file(path, buf, sizeof(buf)))
+		goto out;
+	buf[strcspn(buf, "\n")] = 0;
+	snprintf(cpus, sizeof(cpus), "%d", x);
+	if (strcmp(buf, cpus)) {
+		ksft_print_msg("the top cpuset keeps CPUs %s, not only %d\n", buf, x);
+		goto out;
+	}
+	if (pipe(go) || pipe(ack))
+		goto out;
+	pid = fork_child("a deadline task in B");
+	if (!pid) {
+		/* Run once in B, so that the task sleeps on a CPU of B. */
+		if (read(go[0], &c, 1) == 1 && write(ack[1], &c, 1) == 1)
+			for (;;)
+				pause();
+		_exit(1);
+	}
+	ret = KSFT_FAIL;
+	if (pid < 0)
+		goto out;
+	/* It inherits our affinity: let it have every CPU of B. */
+	CPU_ZERO(&all);
+	for (i = 0; i < CPU_SETSIZE; i++)
+		CPU_SET(i, &all);
+	if (sched_setaffinity(pid, sizeof(all), &all)) {
+		ksft_print_msg("sched_setaffinity: %s\n", strerror(errno));
+		goto out;
+	}
+	if (enter(cs_b, pid))
+		goto out;
+	c = 'x';
+	if (write(go[1], &c, 1) != 1 || read(ack[0], &c, 1) != 1) {
+		ksft_print_msg("the task never ran in B\n");
+		goto out;
+	}
+	err = set_deadline(pid, 10 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("a deadline task refused in B: %s\n", strerror(-err));
+		goto out;
+	}
+	err = cpu_online(x, 0);
+	if (err != -EBUSY) {
+		ksft_print_msg("offline of CPU %d: %s, not EBUSY\n", x,
+			       err ? strerror(-err) : "accepted");
+		x_off = !err;
+		goto out;
+	}
+	if (partition_has(cs_b, "invalid", 0)) {
+		ksft_print_msg("B became invalid\n");
+		goto out;
+	}
+	reap(pid);
+	pid = -1;
+	sleep_ns(3 * PERIOD);
+	err = cpu_online(x, 0);
+	if (err) {
+		ksft_print_msg("offline of CPU %d with the task gone: %s\n", x,
+			       strerror(-err));
+		goto out;
+	}
+	x_off = 1;
+	ret = KSFT_PASS;
+out:
+	reap(pid);
+	for (i = 0; i < 2; i++) {
+		if (go[i] >= 0)
+			close(go[i]);
+		if (ack[i] >= 0)
+			close(ack[i]);
+	}
+	if (x_off)
+		cpu_up(x);
+	sleep_ns(3 * PERIOD);
+	cs_cleanup();
+	return ret;
+}
+
+/*
+ * The same rule, when the offline makes invalid a partition that does not
+ * hold the CPU. B is a root partition of X and Y, with no task. D, in B,
+ * is a root partition of X. C, in B, is an isolated partition of Y, made
+ * after D. So B keeps no CPU of its own. The steps:
+ * 1. A task that is not a deadline task sleeps in D.
+ * 2. A task in the root cgroup runs on W. Then it allows every CPU and
+ *    becomes a deadline task of 10%. It sleeps. The housekeeping root
+ *    domain counts it.
+ * 3. Move it asleep into C. The default root domain counts it.
+ * 4. Take X offline. D would have no CPU left, and become invalid. Its
+ *    task would then count in B, which would take Y from C. C would
+ *    become invalid. Y would leave the default root domain for that of B,
+ *    with the deadline task. That root domain did not admit it.
+ * The offline must fail with EBUSY. C must stay valid, and total_bw must
+ * not change. Once the task is gone, the offline must be accepted, and C
+ * must become invalid.
+ */
+static int hotplug_sibling_partition_refused(void)
+{
+	int fd[2] = { -1, -1 }, err, ret = KSFT_SKIP, x_off = 0;
+	long long def0, hk0, def, hk, bw;
+	char buf[64], cs_d[PATH_MAX];
+	pid_t pid = -1, other = -1;
+
+	cs_d[0] = 0;
+	if (partition_cpus() || cs_setup())
+		return KSFT_SKIP;
+	snprintf(buf, sizeof(buf), "%d,%d", pc_x, pc_y);
+	if (cs_make(cs_b, buf) ||
+	    write_file(cs_b, "cpuset.cpus.partition", "root") ||
+	    write_file(cs_b, "cgroup.subtree_control", "+cpuset"))
+		goto out;
+	if (snprintf(cs_d, sizeof(cs_d), "%s/d", cs_b) >= (int)sizeof(cs_d)) {
+		cs_d[0] = 0;
+		goto out;
+	}
+	snprintf(buf, sizeof(buf), "%d", pc_x);
+	if (cs_make(cs_d, buf) ||
+	    write_file(cs_d, "cpuset.cpus.partition", "root"))
+		goto out;
+	snprintf(buf, sizeof(buf), "%d", pc_y);
+	if (cs_make(cs_c, buf) ||
+	    write_file(cs_c, "cpuset.cpus.partition", "isolated") ||
+	    !partition_has(cs_d, "root", 1) || partition_has(cs_d, "invalid", 0) ||
+	    !partition_has(cs_c, "isolated", 1) || partition_has(cs_c, "invalid", 0))
+		goto out;
+	other = fork_child("a task in D");
+	if (!other) {
+		for (;;)
+			pause();
+	}
+	if (other < 0 || enter(cs_d, other) || totals_of(pc_y, pc_w, &def0, &hk0) ||
+	    pipe(fd))
+		goto out;
+	ret = KSFT_FAIL;
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = task_from(pc_w, 1, 10 * NSEC_PER_MSEC, PERIOD, fd[0]);
+	if (pid < 0 || child_up("hotplug_sibling_partition_refused", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S') || totals_of(pc_y, pc_w, &def, &hk))
+		goto out;
+	bw = hk - hk0;
+	err = enter(cs_c, pid);
+	if (bw <= 0 || def != def0 || err) {
+		ksft_print_msg("a deadline task adds %lld, %lld to total_bw, in C: %s\n",
+			       def - def0, bw, strerror(-err));
+		goto out;
+	}
+	if (totals_check("in C", pc_y, pc_w, def0 + bw, hk0))
+		goto out;
+	err = cpu_online(pc_x, 0);
+	if (err != -EBUSY) {
+		ksft_print_msg("offline of CPU %d: %s, not EBUSY\n", pc_x,
+			       err ? strerror(-err) : "accepted");
+		x_off = !err;
+		goto out;
+	}
+	if (partition_has(cs_c, "invalid", 0) ||
+	    totals_check("offline refused", pc_y, pc_w, def0 + bw, hk0))
+		goto out;
+	reap(pid);
+	pid = -1;
+	sleep_ns(3 * PERIOD);
+	err = cpu_online(pc_x, 0);
+	if (err) {
+		ksft_print_msg("offline of CPU %d with the task gone: %s\n", pc_x,
+			       strerror(-err));
+		goto out;
+	}
+	x_off = 1;
+	/* The offline did make C invalid: the refusal was not too strict. */
+	if (!partition_has(cs_c, "invalid", 1)) {
+		ksft_print_msg("C stays valid with CPU %d offline\n", pc_x);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	reap(pid);
+	reap(other);
+	if (fd[0] >= 0) {
+		close(fd[0]);
+		close(fd[1]);
+	}
+	if (x_off)
+		cpu_up(pc_x);
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS)
+		ret = totals_check("task gone", pc_y, pc_w, def0, hk0);
+	if (cs_d[0] && wait_for(1000, !rmdir(cs_d) || errno == ENOENT))
+		ksft_print_msg("rmdir %s: %s\n", cs_d, strerror(errno));
+	cs_cleanup();
+	return ret;
+}
+
+/*
+ * A CPU of an isolated partition is in the default root domain, like the
+ * CPUs that isolcpus="domain" isolates. X and K are housekeeping CPUs: X
+ * the highest, K the lowest. I is an isolated CPU. Q is an isolated
+ * partition of X. The steps:
+ * 1. A task in the root cgroup runs on K. Then it allows every CPU and
+ *    becomes a deadline task of 10%. It sleeps. The housekeeping root
+ *    domain counts it.
+ * 2. Move it asleep into Q. The default root domain counts it.
+ * 3. Take X offline. Q has no CPU left and becomes invalid. The task
+ *    falls back to the CPUs of the root cgroup. The isolated CPUs are
+ *    still in the default root domain.
+ * The offline must be accepted. The default root domain must go on
+ * counting the task, and the housekeeping root domain must not. Woken,
+ * the task must run on an isolated CPU.
+ */
+static int hotplug_isolated_partition_falls_back(void)
+{
+	int fd[2] = { -1, -1 }, err, cpu, i, ret = KSFT_SKIP, x_off = 0;
+	int x = ncpus >= 2 ? top_cpu(1) : -1, k = online[0], ic = nisol ? isol[0] : -1;
+	long long def0, hk0, def, hk, bw, srv;
+	uint64_t runtime, period;
+	char buf[64];
+	pid_t pid = -1;
+
+	if (ic < 0 || x < 0 || !cpu_hotpluggable(x) || !server_found || cs_setup()) {
+		ksft_print_msg("needs isolcpus=\"domain\", 2 housekeeping CPUs, CPU hotplug, fair server files\n");
+		return KSFT_SKIP;
+	}
+	snprintf(buf, sizeof(buf), "%d", x);
+	if (cs_make(cs_q, buf) || write_file(cs_q, "cpuset.cpus.partition", "isolated") ||
+	    !partition_has(cs_q, "isolated", 1) || partition_has(cs_q, "invalid", 0) ||
+	    totals_of(ic, k, &def0, &hk0) || pipe(fd))
+		goto out;
+	ret = KSFT_FAIL;
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = task_from(k, 1, 10 * NSEC_PER_MSEC, PERIOD, fd[0]);
+	if (pid < 0 || child_up("hotplug_isolated_partition_falls_back", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S') || totals_of(ic, k, &def, &hk))
+		goto out;
+	bw = hk - hk0;
+	err = enter(cs_q, pid);
+	if (bw <= 0 || def != def0 || err) {
+		ksft_print_msg("a deadline task adds %lld, %lld to total_bw, in Q: %s\n",
+			       def - def0, bw, strerror(-err));
+		goto out;
+	}
+	if (totals_check("in Q", ic, k, def0 + bw, hk0))
+		goto out;
+	/* The fair server of X leaves the default root domain with X. */
+	if (server_get(x, "runtime", &runtime) || server_get(x, "period", &period) || !period) {
+		ksft_print_msg("no fair server parameters for CPU %d\n", x);
+		goto out;
+	}
+	srv = (long long)((runtime << 20) / period);	/* as to_ratio() */
+	err = cpu_online(x, 0);
+	if (err) {
+		ksft_print_msg("offline of CPU %d: %s\n", x, strerror(-err));
+		goto out;
+	}
+	x_off = 1;
+	if (totals_check("X offline", ic, k, def0 + bw - srv, hk0) || fallback_wake(fd[1], pid))
+		goto out;
+	cpu = task_cpu_of(pid);
+	for (i = 0; i < nisol && isol[i] != cpu; i++)
+		;
+	if (i == nisol) {
+		ksft_print_msg("woken on CPU %d, not an isolated CPU\n", cpu);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	reap(pid);
+	if (fd[0] >= 0) {
+		close(fd[0]);
+		close(fd[1]);
+	}
+	if (x_off)
+		cpu_up(x);
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS)
+		ret = totals_check("task gone", ic, k, def0, hk0);
+	cs_cleanup();
+	return ret;
+}
+
+/*
+ * A dead task runs no more, so it cannot leave its root domain. The CPUs
+ * are those of fallback_case(). B is a cpuset of I1, I2 and H, not a
+ * partition. The steps:
+ * 1. A task in the root cgroup runs on H. Then it allows every CPU and
+ *    becomes a deadline task of 100ms every 1s. It sleeps.
+ * 2. Move it asleep into B. It keeps H. The housekeeping root domain
+ *    counts it.
+ * 3. Wake it. It spins 90ms and exits. The case does not reap it. Its
+ *    0-lag time is about 800ms ahead.
+ * 4. Take H offline. Once H is offline, the dead task would have no CPU
+ *    in the root domain that counts it. That does not matter: it never
+ *    runs again.
+ * The offline must be accepted. The case then reaps the task and brings
+ * H back. Past the 0-lag time, total_bw must be what it was.
+ *
+ * The case depends on time: it skips if the task takes more than 500ms
+ * to show as a zombie.
+ */
+static int hotplug_dead_accepted(void)
+{
+	int fd[2] = { -1, -1 }, err, cpu, ret = KSFT_SKIP, ran = 0;
+	long long def0, hk0, def, hk;
+	uint64_t t;
+	char buf[64];
+	pid_t pid = -1;
+
+	if (fallback_cpus(0) || !cpu_hotpluggable(fb_h)) {
+		ksft_print_msg("needs isolcpus=domain: 2 isolated, 2 housekeeping CPUs, hotplug\n");
+		return KSFT_SKIP;
+	}
+	if (cs_setup())
+		return KSFT_SKIP;
+	snprintf(buf, sizeof(buf), "%d,%d,%d", fb_i1, fb_i2, fb_h);
+	if (cs_make(cs_b, buf) || fallback_totals(&def0, &hk0) || pipe(fd))
+		goto out;
+	ret = KSFT_FAIL;
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = task_from(fb_h, 1, 100 * NSEC_PER_MSEC, NSEC_PER_SEC, fd[0]);
+	ran = pid >= 0;
+	if (pid < 0 || child_up("hotplug_dead_accepted", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S'))
+		goto out;
+	err = enter(cs_b, pid);
+	if (err) {
+		ksft_print_msg("a move into B refused: %s\n", strerror(-err));
+		goto out;
+	}
+	if (fallback_totals(&def, &hk))
+		goto out;
+	cpu = task_cpu_of(pid);
+	if (cpu != fb_h || def != def0 || hk <= hk0) {
+		ksft_print_msg("in B on CPU %d: total_bw %lld, %lld\n", cpu, def, hk);
+		goto out;
+	}
+	if (write(fd[1], "x", 1) != 1) {
+		ksft_print_msg("write to the deadline task: %s\n", strerror(errno));
+		goto out;
+	}
+	t = now_ns();
+	if (wait_for(1000, proc_state_of(pid) == 'Z'))
+		goto out;
+	if (now_ns() - t > 500 * NSEC_PER_MSEC) {
+		ksft_print_msg("the task took over 500ms to exit\n");
+		ret = KSFT_SKIP;
+		goto out;
+	}
+	sleep_ns(10 * NSEC_PER_MSEC);		/* past do_task_dead() */
+	err = cpu_online(fb_h, 0);
+	if (err) {
+		ksft_print_msg("offline of CPU %d under a dead task: %s\n", fb_h,
+			       strerror(-err));
+		goto out;
+	}
+	reap(pid);
+	pid = -1;
+	cpu_up(fb_h);
+	sleep_ns(NSEC_PER_SEC);			/* past the 0-lag time */
+	ran = 0;
+	ret = totals_check("task gone", fb_i2, fb_h, def0, hk0);
+out:
+	reap(pid);
+	cpu_up(fb_h);
+	/* Let the next case start after the 0-lag time of the task. */
+	if (ran)
+		sleep_ns(NSEC_PER_SEC);
+	if (fd[0] >= 0) {
+		close(fd[0]);
+		close(fd[1]);
+	}
+	cs_cleanup();
+	return ret;
+}
+
+/*
+ * A cpuset that loses all its CPUs takes them from its parent, through
+ * its own cpuset.cpus. The CPUs are those of fallback_case(). The steps:
+ * 1. B, in the root cgroup, has cpuset.cpus H. C, in B, has cpuset.cpus
+ *    I2. I2 is not in B, so C gets H.
+ * 2. A task in the root cgroup runs on H. Then it allows every CPU and
+ *    becomes a deadline task of 10%. It sleeps. The housekeeping root
+ *    domain counts it.
+ * 3. Move it asleep into C. It keeps H.
+ * 4. Q, in the root cgroup, has cpuset.cpus H. Make it a partition root.
+ *    B would then get the CPUs of the root cgroup, and C would get I2
+ *    of them. The task would have no CPU in the root domain that counts
+ *    it.
+ * Q must be an invalid partition root, for the deadline task. Wake the
+ * task: it must run on H, and the housekeeping root domain must count it.
+ */
+static int partition_takes_fallback_refused(void)
+{
+	int fd[2] = { -1, -1 }, cpu, err, ret = KSFT_SKIP;
+	long long def0, hk0, def, hk, bw;
+	char buf[64];
+	pid_t pid = -1;
+
+	if (fallback_cpus(0)) {
+		ksft_print_msg("needs isolcpus=domain: 2 isolated, 2 housekeeping CPUs\n");
+		return KSFT_SKIP;
+	}
+	if (cs_setup())
+		return KSFT_SKIP;
+	snprintf(buf, sizeof(buf), "%d", fb_h);
+	if (cs_make(cs_b, buf) || write_file(cs_b, "cgroup.subtree_control", "+cpuset"))
+		goto out;
+	snprintf(buf, sizeof(buf), "%d", fb_i2);
+	if (cs_make(cs_c, buf) || fallback_totals(&def0, &hk0) || pipe(fd))
+		goto out;
+	ret = KSFT_FAIL;
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = task_from(fb_h, 1, 10 * NSEC_PER_MSEC, PERIOD, fd[0]);
+	if (pid < 0 || child_up("partition_takes_fallback_refused", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S') || fallback_totals(&def, &hk))
+		goto out;
+	bw = hk - hk0;
+	err = enter(cs_c, pid);
+	cpu = task_cpu_of(pid);
+	if (bw <= 0 || def != def0 || err || cpu != fb_h) {
+		ksft_print_msg("a deadline task adds %lld, %lld to total_bw, in C: %s, on CPU %d\n",
+			       def - def0, bw, strerror(-err), cpu);
+		goto out;
+	}
+	snprintf(buf, sizeof(buf), "%d", fb_h);
+	if (cs_make(cs_q, buf))
+		goto out;
+	write_file(cs_q, "cpuset.cpus.partition", "root");
+	if (!partition_has(cs_q, "Deadline task", 1) ||
+	    fallback_wake(fd[1], pid))
+		goto out;
+	cpu = task_cpu_of(pid);
+	if (cpu != fb_h) {
+		ksft_print_msg("woken on CPU %d, not %d\n", cpu, fb_h);
+		goto out;
+	}
+	ret = totals_check("woken", fb_i2, fb_h, def0, hk0 + bw);
+out:
+	reap(pid);
+	if (fd[0] >= 0) {
+		close(fd[0]);
+		close(fd[1]);
+	}
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS)
+		ret = totals_check("task gone", fb_i2, fb_h, def0, hk0);
+	cs_cleanup();
+	return ret;
+}
+
+/*
+ * A mask that grows can still take a task out of its root domain. That
+ * happens if the user affinity of the task holds only the new CPUs.
+ * The CPUs: I1 is isolated by isolcpus="domain", H is the first
+ * housekeeping CPU. The steps:
+ * 1. Q is a partition root of the other housekeeping CPUs. The
+ *    housekeeping root domain of the root cgroup then has H only.
+ * 2. B, in the root cgroup, is a cpuset of H and I1. A task enters B. It
+ *    sets its affinity to I1, and runs there. It is not a deadline task.
+ * 3. Give B the CPU H only. The task gets H: its affinity holds no CPU of
+ *    B. Wake it: it runs on H.
+ * 4. The task becomes a deadline task of 10%. Its mask holds the whole
+ *    housekeeping root domain of the root cgroup, H. That root domain
+ *    counts it. It sleeps.
+ * 5. Give B the CPUs H and I1 again. The task would then get I1 only, its
+ *    affinity, in another root domain.
+ * The write of step 5 must fail with EBUSY. Wake the task: it must run on
+ * H, and the housekeeping root domain must count it.
+ */
+static int mask_grows_refused(void)
+{
+	int h = online[0], i1 = nisol ? isol[0] : -1, fd[2] = { -1, -1 };
+	int i, n = 0, err, cpu, ret = KSFT_SKIP;
+	long long def0, hk0, def, hk, bw;
+	char buf[4096];
+	pid_t pid = -1;
+
+	if (i1 < 0) {
+		ksft_print_msg("needs CPUs isolated by isolcpus=domain\n");
+		return KSFT_SKIP;
+	}
+	if (cs_setup())
+		return KSFT_SKIP;
+	for (i = 1; i < ncpus && n < (int)sizeof(buf); i++)
+		n += snprintf(buf + n, sizeof(buf) - n, "%s%d", i > 1 ? "," : "", online[i]);
+	if (n >= (int)sizeof(buf) || make_partition_cpus(cs_q, buf)) {
+		ksft_print_msg("no partition root Q of CPUs %s\n", buf);
+		goto out;
+	}
+	snprintf(buf, sizeof(buf), "%d,%d", h, i1);
+	if (cs_make(cs_b, buf) || totals_of(i1, h, &def0, &hk0) || pipe(fd))
+		goto out;
+	ret = KSFT_FAIL;
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = fork_child("a task with an affinity");
+	if (!pid) {
+		cpu_set_t set;
+		char c;
+
+		CPU_ZERO(&set);
+		CPU_SET(i1, &set);
+		if (enter(cs_b, getpid()) || sched_setaffinity(0, sizeof(set), &set)) {
+			mv_state[1] = -1;
+			_exit(1);
+		}
+		spin_ns(NSEC_PER_MSEC);
+		mv_state[1] = 1;
+		/* Wait for B of H only. Run there, and become a deadline task. */
+		if (read(fd[0], &c, 1) != 1)
+			_exit(1);
+		spin_ns(NSEC_PER_MSEC);
+		if (set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD)) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		mv_state[0] = 1;
+		while (read(fd[0], &c, 1) == 1)
+			mv_state[1]++;
+		_exit(0);
+	}
+	if (pid < 0 || wait_for(1000, mv_state[1]) || mv_state[1] != 1 ||
+	    wait_for(1000, proc_state_of(pid) == 'S')) {
+		ksft_print_msg("the task cannot take CPU %d\n", i1);
+		goto out;
+	}
+	snprintf(buf, sizeof(buf), "%d", h);
+	err = write_file(cs_b, "cpuset.cpus", buf);
+	if (err) {
+		ksft_print_msg("B given CPU %d only: %s\n", h, strerror(-err));
+		goto out;
+	}
+	mv_state[1] = 0;
+	if (write(fd[1], "d", 1) != 1 || child_up("mask_grows_refused", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S') || totals_of(i1, h, &def, &hk))
+		goto out;
+	bw = hk - hk0;
+	cpu = task_cpu_of(pid);
+	if (bw <= 0 || def != def0 || cpu != h) {
+		ksft_print_msg("a deadline task on CPU %d adds %lld, %lld to total_bw\n",
+			       cpu, def - def0, bw);
+		goto out;
+	}
+	snprintf(buf, sizeof(buf), "%d,%d", h, i1);
+	err = write_file(cs_b, "cpuset.cpus", buf);
+	if (err != -EBUSY) {
+		ksft_print_msg("B given CPUs %s: %s, not EBUSY\n", buf,
+			       err ? strerror(-err) : "accepted");
+		if (!err && !fallback_wake(fd[1], pid))
+			ksft_print_msg("woken on CPU %d\n", task_cpu_of(pid));
+		goto out;
+	}
+	if (fallback_wake(fd[1], pid))
+		goto out;
+	cpu = task_cpu_of(pid);
+	if (cpu != h) {
+		ksft_print_msg("woken on CPU %d, not %d\n", cpu, h);
+		goto out;
+	}
+	ret = totals_check("woken", i1, h, def0, hk0 + bw);
+out:
+	reap(pid);
+	if (fd[0] >= 0) {
+		close(fd[0]);
+		close(fd[1]);
+	}
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS)
+		ret = totals_check("task gone", i1, h, def0, hk0);
+	cs_cleanup();
+	return ret;
+}
+
+/*
+ * One write to cpuset.cpus can make a partition root take CPUs and give
+ * others back. The CPUs: I1 is isolated by isolcpus="domain". H is a
+ * housekeeping CPU. The steps:
+ * 1. Q is an isolated partition root of I1.
+ * 2. B, in the root cgroup, has cpuset.cpus H and I1. Q holds I1, so B
+ *    gets H.
+ * 3. A task in the root cgroup runs on H. Then it allows every CPU and
+ *    becomes a deadline task of 10%. It sleeps. The housekeeping root
+ *    domain counts it.
+ * 4. Move it asleep into B. It keeps H.
+ * 5. Write H to the cpuset.cpus of Q. Q would take H and give I1 back. B
+ *    would then get I1 only, in another root domain.
+ * Q must become an invalid partition root, for the deadline task. Wake
+ * the task: it must run on H, and the housekeeping root domain must count
+ * it.
+ */
+static int partition_swap_refused(void)
+{
+	int h = online[ncpus - 1], i1 = nisol ? isol[0] : -1, fd[2] = { -1, -1 };
+	int cpu, err, ret = KSFT_SKIP;
+	long long def0, hk0, def, hk, bw;
+	char buf[64];
+	pid_t pid = -1;
+
+	if (i1 < 0) {
+		ksft_print_msg("needs CPUs isolated by isolcpus=domain\n");
+		return KSFT_SKIP;
+	}
+	if (cs_setup())
+		return KSFT_SKIP;
+	snprintf(buf, sizeof(buf), "%d", i1);
+	if (cs_make(cs_q, buf) || write_file(cs_q, "cpuset.cpus.partition", "isolated") ||
+	    !partition_has(cs_q, "isolated", 1) || partition_has(cs_q, "invalid", 0)) {
+		ksft_print_msg("no isolated partition Q of CPU %d\n", i1);
+		goto out;
+	}
+	snprintf(buf, sizeof(buf), "%d,%d", h, i1);
+	if (cs_make(cs_b, buf) || totals_of(i1, h, &def0, &hk0) || pipe(fd))
+		goto out;
+	ret = KSFT_FAIL;
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = task_from(h, 1, 10 * NSEC_PER_MSEC, PERIOD, fd[0]);
+	if (pid < 0 || child_up("partition_swap_refused", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S') || totals_of(i1, h, &def, &hk))
+		goto out;
+	bw = hk - hk0;
+	err = enter(cs_b, pid);
+	cpu = task_cpu_of(pid);
+	if (bw <= 0 || def != def0 || err || cpu != h) {
+		ksft_print_msg("a deadline task adds %lld, %lld to total_bw, in B: %s, on CPU %d\n",
+			       def - def0, bw, strerror(-err), cpu);
+		goto out;
+	}
+	snprintf(buf, sizeof(buf), "%d", h);
+	write_file(cs_q, "cpuset.cpus", buf);
+	if (!partition_has(cs_q, "Deadline task", 1) || fallback_wake(fd[1], pid))
+		goto out;
+	cpu = task_cpu_of(pid);
+	if (cpu != h) {
+		ksft_print_msg("woken on CPU %d, not %d\n", cpu, h);
+		goto out;
+	}
+	ret = totals_check("woken", i1, h, def0, hk0 + bw);
+out:
+	reap(pid);
+	if (fd[0] >= 0) {
+		close(fd[0]);
+		close(fd[1]);
+	}
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS)
+		ret = totals_check("task gone", i1, h, def0, hk0);
+	cs_cleanup();
+	return ret;
+}
+
+/* Return the taint flags of the kernel, or -1. */
+static long taint_flags(void)
+{
+	char buf[64];
+
+	if (read_file("/proc/sys/kernel/tainted", buf, sizeof(buf)))
+		return -1;
+	return atol(buf);
+}
+
+#define TAINT_WARN	(1L << 9)
+
+/*
+ * An invalid partition root holds no CPU of its parent. A refusal must
+ * not give any back. The CPUs are those of fallback_case(). B is a cpuset
+ * of I1, I2 and H, not a partition. The steps:
+ * 1. A task in the root cgroup runs on H. Then it allows every CPU and
+ *    becomes a deadline task of 10%. It sleeps. The housekeeping root
+ *    domain counts it.
+ * 2. Move it asleep into B. It keeps H.
+ * 3. Q, in the root cgroup, has cpuset.cpus H and K. Its
+ *    cpuset.cpus.exclusive is H. Make it a partition root. It would take H,
+ *    the only housekeeping CPU of B. Q must be invalid, for the deadline
+ *    task.
+ * 4. Write H to the cpuset.cpus of Q. The same check refuses again.
+ * The kernel must not warn: the taint flag W must stay clear. Q must
+ * still be invalid for the deadline task. The case skips if the flag
+ * was set before.
+ */
+static int partition_refused_no_warn(void)
+{
+	int fd[2] = { -1, -1 }, cpu, err, ret = KSFT_SKIP;
+	long long def0, hk0, def, hk, bw;
+	char buf[64];
+	pid_t pid = -1;
+
+	if (fallback_cpus(0)) {
+		ksft_print_msg("needs isolcpus=domain: 2 isolated, 2 housekeeping CPUs\n");
+		return KSFT_SKIP;
+	}
+	if (taint_flags() < 0 || (taint_flags() & TAINT_WARN)) {
+		ksft_print_msg("the kernel has warned already\n");
+		return KSFT_SKIP;
+	}
+	if (cs_setup())
+		return KSFT_SKIP;
+	snprintf(buf, sizeof(buf), "%d,%d,%d", fb_i1, fb_i2, fb_h);
+	if (cs_make(cs_b, buf) || fallback_totals(&def0, &hk0) || pipe(fd))
+		goto out;
+	ret = KSFT_FAIL;
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = task_from(fb_h, 1, 10 * NSEC_PER_MSEC, PERIOD, fd[0]);
+	if (pid < 0 || child_up("partition_refused_no_warn", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S') || fallback_totals(&def, &hk))
+		goto out;
+	bw = hk - hk0;
+	err = enter(cs_b, pid);
+	cpu = task_cpu_of(pid);
+	if (bw <= 0 || def != def0 || err || cpu != fb_h) {
+		ksft_print_msg("a deadline task adds %lld, %lld to total_bw, in B: %s, on CPU %d\n",
+			       def - def0, bw, strerror(-err), cpu);
+		goto out;
+	}
+	snprintf(buf, sizeof(buf), "%d,%d", fb_h, fb_k);
+	if (cs_make(cs_q, buf))
+		goto out;
+	snprintf(buf, sizeof(buf), "%d", fb_h);
+	if (write_file(cs_q, "cpuset.cpus.exclusive", buf)) {
+		ksft_print_msg("Q cannot have CPU %d exclusive\n", fb_h);
+		goto out;
+	}
+	write_file(cs_q, "cpuset.cpus.partition", "root");
+	if (!partition_has(cs_q, "Deadline task", 1))
+		goto out;
+	write_file(cs_q, "cpuset.cpus", buf);
+	if (taint_flags() & TAINT_WARN) {
+		ksft_print_msg("Q given CPU %d: the kernel warned\n", fb_h);
+		goto out;
+	}
+	if (!partition_has(cs_q, "Deadline task", 1) || fallback_wake(fd[1], pid))
+		goto out;
+	cpu = task_cpu_of(pid);
+	if (cpu != fb_h) {
+		ksft_print_msg("woken on CPU %d, not %d\n", cpu, fb_h);
+		goto out;
+	}
+	ret = totals_check("woken", fb_i2, fb_h, def0, hk0 + bw);
+out:
+	reap(pid);
+	if (fd[0] >= 0) {
+		close(fd[0]);
+		close(fd[1]);
+	}
+	sleep_ns(3 * PERIOD);
+	if (ret == KSFT_PASS)
+		ret = totals_check("task gone", fb_i2, fb_h, def0, hk0);
+	cs_cleanup();
+	return ret;
+}
+
+/*
+ * A rebuild must count a task where its cpuset lets it run. The kernel
+ * records, with the bandwidth of a task, a CPU of the root domain that
+ * counts it. A partition root can take that CPU later. A, B and D are the
+ * three highest housekeeping CPUs. C is the first one. Q is a partition
+ * root of the other housekeeping CPUs, C among them. The steps:
+ * 1. Take D offline. The housekeeping root domain then has A and B only.
+ * 2. A task in the root cgroup sets its affinity to A and B. It becomes a
+ *    deadline task of 10% and sleeps. Bring D back online. The task keeps
+ *    its affinity.
+ * 3. Take A and B offline. No CPU of the task's mask is active. Its
+ *    cpuset gives it D, so the rebuild counts it on D. D is recorded.
+ * 4. Make Q a member, then a partition root of D instead of C. The
+ *    cpuset of the task now gives it C. Its mask is still A and B.
+ * Q must not count the task. The root domain of C must count it. Wake
+ * the task: it must run on C, and total_bw must not change.
+ *
+ * The references of total_bw are taken once the task is gone, with the
+ * CPUs as in step 4.
+ */
+static int rebuild_record_taken(void)
+{
+	int a = top_cpu(3), b = top_cpu(2), c = online[0], d = top_cpu(1);
+	int fd[2] = { -1, -1 }, i, n, err, cpu, ret = KSFT_SKIP;
+	long long q, h, q0, h0, bw;
+	char buf[4096];
+	pid_t pid = -1;
+
+	if (ncpus < 4 || !cpu_hotpluggable(a) || !cpu_hotpluggable(b) ||
+	    !cpu_hotpluggable(d)) {
+		ksft_print_msg("needs 4 CPUs, 3 of them hotpluggable\n");
+		return KSFT_SKIP;
+	}
+	if (cs_setup())
+		return KSFT_SKIP;
+	/* Q has every housekeeping CPU but A, B and D. */
+	for (i = n = 0; i < ncpus - 3; i++)
+		n += snprintf(buf + n, sizeof(buf) - n, "%s%d", n ? "," : "",
+			      online[i]);
+	if (make_partition_cpus(cs_q, buf)) {
+		ksft_print_msg("Q cannot be a partition root of CPUs %s\n", buf);
+		goto out;
+	}
+	ret = KSFT_FAIL;
+	err = cpu_online(d, 0);
+	if (err) {
+		ksft_print_msg("offline of CPU %d: %s\n", d, strerror(-err));
+		goto out;
+	}
+	bw = total_bw_of(a);
+	if (bw == -1) {
+		ksft_print_msg("no total_bw in /sys/kernel/debug/sched/debug\n");
+		ret = KSFT_SKIP;
+		goto out;
+	}
+	if (pipe(fd)) {
+		ksft_print_msg("pipe: %s\n", strerror(errno));
+		goto out;
+	}
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = fork_child("a deadline task");
+	if (!pid) {
+		cpu_set_t set;
+		char ch;
+
+		CPU_ZERO(&set);
+		CPU_SET(a, &set);
+		CPU_SET(b, &set);
+		if (sched_setaffinity(0, sizeof(set), &set) ||
+		    set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD)) {
+			mv_state[0] = -1;
+			_exit(1);
+		}
+		mv_state[0] = 1;
+		while (read(fd[0], &ch, 1) == 1)
+			mv_state[1]++;
+		_exit(0);
+	}
+	if (pid < 0 || child_up("rebuild_record_taken", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S'))
+		goto out;
+	bw = total_bw_of(a) - bw;
+	if (bw <= 0) {
+		ksft_print_msg("the deadline task adds %lld to total_bw\n", bw);
+		goto out;
+	}
+	err = cpu_online(d, 1);
+	if (!err)
+		err = cpu_online(a, 0);
+	if (!err)
+		err = cpu_online(b, 0);
+	if (err) {
+		ksft_print_msg("hotplug of CPUs %d, %d, %d: %s\n", d, a, b,
+			       strerror(-err));
+		goto out;
+	}
+	/*
+	 * Q has D and every CPU it had but C. One write of cpuset.cpus
+	 * would make Q an invalid partition root: the check sees the root
+	 * cgroup lose D, and get C back too late.
+	 */
+	for (i = 1, n = 0; i < ncpus - 3; i++)
+		n += snprintf(buf + n, sizeof(buf) - n, "%d,", online[i]);
+	snprintf(buf + n, sizeof(buf) - n, "%d", d);
+	err = write_file(cs_q, "cpuset.cpus.partition", "member");
+	if (err || make_partition_cpus(cs_q, buf)) {
+		ksft_print_msg("Q cannot be a partition root of CPUs %s\n", buf);
+		partition_has(cs_q, "root\n", 1);
+		goto out;
+	}
+	q = total_bw_of(d);
+	h = total_bw_of(c);
+	if (fallback_wake(fd[1], pid))
+		goto out;
+	/* Go on after a failure: the totals tell more. */
+	cpu = task_cpu_of(pid);
+	if (cpu != c)
+		ksft_print_msg("woken on CPU %d, not %d\n", cpu, c);
+	else if (!totals_check("woken", d, c, q, h))
+		ret = KSFT_PASS;
+	reap(pid);
+	pid = -1;
+	sleep_ns(3 * PERIOD);
+	if (totals_of(d, c, &q0, &h0)) {
+		ret = KSFT_FAIL;
+		goto out;
+	}
+	if (q != q0 || h != h0 + bw) {
+		ksft_print_msg("Q counts %lld of %lld, the root cgroup %lld\n",
+			       q - q0, bw, h - h0);
+		ret = KSFT_FAIL;
+	}
+out:
+	reap(pid);
+	if (fd[0] >= 0) {
+		close(fd[0]);
+		close(fd[1]);
+	}
+	cpu_up(a);
+	cpu_up(b);
+	cpu_up(d);
+	cs_cleanup();
+	return ret;
+}
+
 /* Moves between two root domains, from the main process, with P */
 
 /*
@@ -7950,6 +10274,259 @@ static const struct p_case {
 
 #define N_P_CASES	((int)ARRAY_SIZE(p_cases))
 
+/*
+ * A fair task asleep on a CPU that goes offline is still on that CPU. In
+ * the root cgroup, its mask still holds that CPU. sched_setattr() must admit
+ * the task in the root domain of an active CPU of its mask. The steps:
+ * 1. A task in the root cgroup runs on hp_cpu, then allows every CPU and
+ *    sleeps.
+ * 2. Take hp_cpu offline.
+ * 3. Make the task a deadline task of 10ms every 100ms.
+ * The change must be accepted. Without isolcpus=domain, the root domain
+ * of the offline CPU has no active CPU, and would refuse it with EBUSY.
+ */
+static int hotplug_asleep_setattr(void)
+{
+	int fd[2], err, ret = KSFT_FAIL, off = 0;
+	pid_t pid;
+
+	if (hp_cpu < 0)
+		return KSFT_SKIP;
+	if (pipe(fd)) {
+		ksft_print_msg("pipe: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	pid = fork_child("a task asleep on a CPU going offline");
+	if (!pid) {
+		cpu_set_t one, all;
+		char c;
+
+		CPU_ZERO(&one);
+		CPU_SET(hp_cpu, &one);
+		if (sched_getaffinity(0, sizeof(all), &all) ||
+		    sched_setaffinity(0, sizeof(one), &one))
+			_exit(1);
+		spin_ns(NSEC_PER_MSEC);
+		if (sched_setaffinity(0, sizeof(all), &all))
+			_exit(1);
+		if (read(fd[0], &c, 1) != 1)
+			_exit(1);
+		_exit(0);
+	}
+	if (pid < 0)
+		goto out;
+	if (wait_for(1000, proc_state_of(pid) == 'S' && task_cpu_of(pid) == hp_cpu)) {
+		ksft_print_msg("the task is not asleep on CPU %d\n", hp_cpu);
+		goto out;
+	}
+	err = cpu_online(hp_cpu, 0);
+	if (err) {
+		ksft_print_msg("offline of CPU %d: %s\n", hp_cpu, strerror(-err));
+		goto out;
+	}
+	off = 1;
+	err = set_deadline(pid, 10 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("sched_setattr() of the task asleep on offline CPU %d: %s\n",
+			       hp_cpu, strerror(-err));
+		goto out;
+	}
+	ret = KSFT_PASS;
+	if (set_other(pid))
+		ksft_print_msg("the task cannot leave SCHED_DEADLINE\n");
+out:
+	reap(pid);
+	close(fd[0]);
+	close(fd[1]);
+	if (off)
+		cpu_up(hp_cpu);
+	return ret;
+}
+
+/* The child cpusets that a cascade case made, the deepest last. */
+static char cc_sub[4][PATH_MAX];
+static int cc_n;
+
+/*
+ * Make the child cpuset @name of @parent, with cpuset.cpus @cpus, and make
+ * it a partition of type @prs. Return its path, or NULL.
+ */
+static const char *cc_make(const char *parent, const char *name, const char *cpus,
+			   const char *prs)
+{
+	char *cg = cc_sub[cc_n];
+
+	if (cc_n >= 4 ||
+	    snprintf(cg, PATH_MAX, "%s/%s", parent, name) >= PATH_MAX)
+		return NULL;
+	cc_n++;
+	if (cs_make(cg, cpus))
+		return NULL;
+	if (write_file(cg, "cpuset.cpus.partition", prs) ||
+	    !partition_has(cg, prs, 1) || partition_has(cg, "invalid", 0))
+		return NULL;
+	return cg;
+}
+
+/* Remove the child cpusets of a cascade case, the deepest first. */
+static void cc_cleanup(void)
+{
+	while (cc_n > 0)
+		remove_partition(cc_sub[--cc_n]);
+}
+
+/*
+ * Start a deadline task of 10% in the root cgroup on W, asleep, and move
+ * it into @cg. Return its pid, or -1.
+ */
+static pid_t cc_dl_task(const char *cg, int fd)
+{
+	pid_t pid;
+	int err;
+
+	mv_state[0] = 0;
+	mv_state[1] = 0;
+	pid = task_from(pc_w, 1, 10 * NSEC_PER_MSEC, PERIOD, fd);
+	if (pid < 0 || child_up("a cascade case", 0) ||
+	    wait_for(1000, proc_state_of(pid) == 'S'))
+		return pid < 0 ? -1 : (reap(pid), -1);
+	err = enter(cg, pid);
+	if (err) {
+		ksft_print_msg("a move into %s refused: %s\n", cg, strerror(-err));
+		reap(pid);
+		return -1;
+	}
+	return pid;
+}
+
+/* Start a task that is not a deadline task, asleep in @cg. Return its pid, or -1. */
+static pid_t cc_fair_task(const char *cg)
+{
+	pid_t pid = fork_child("a task that is not a deadline task");
+
+	if (!pid) {
+		for (;;)
+			pause();
+	}
+	if (pid > 0 && enter(cg, pid)) {
+		reap(pid);
+		return -1;
+	}
+	return pid;
+}
+
+enum { CC_FIRST, CC_NESTED, CC_ISOLATED };
+
+/*
+ * Run a cascade case of @kind: the offline of X makes a partition
+ * invalid, and cpuset then takes the CPUs of another partition. B is a
+ * root partition with no task, whose CPUs all go to child partitions.
+ * Its child G, made first, holds X. The offline of X leaves the
+ * partition that holds X with tasks and no CPU: G, or the child of G
+ * with CC_NESTED. cpuset makes that partition invalid. Its tasks then
+ * count in its parent. What the hotplug walk then does depends on the
+ * order of the children:
+ * - CC_FIRST: G is a root partition with a task that is not a deadline
+ *   task. S1, an isolated partition of Y, holds a deadline task. S2 is an
+ *   isolated partition of Z. B now holds the task of G and has no CPU. It
+ *   takes Y from S1, the first child after G. The deadline task of S1
+ *   would leave the default root domain.
+ * - CC_NESTED: G is a root partition of X with a child root partition of
+ *   X, which holds a task that is not a deadline task. S, an isolated
+ *   partition of Y and Z, holds a deadline task. The child of G becomes
+ *   invalid. G is visited before it, so G stays valid, with tasks and no
+ *   CPU. The next hotplug event makes G invalid, then S: the deadline
+ *   task of S would leave the default root domain.
+ * - CC_ISOLATED: B has X and Y. G is an isolated partition of X with a
+ *   deadline task and a task that is not one. S2 is an isolated partition
+ *   of Y. B takes Y from S2. The deadline task of G would leave the
+ *   default root domain.
+ * The offline must fail with EBUSY.
+ */
+static int cascade_case(int kind)
+{
+	const char *g, *s = NULL, *s2 = NULL, *gc = NULL;
+	int fd[2] = { -1, -1 }, err, ret = KSFT_SKIP, x_off = 0;
+	pid_t dl = -1, fair = -1;
+	char buf[64];
+
+	cc_n = 0;
+	if (partition_cpus() || cs_setup())
+		return KSFT_SKIP;
+	if (kind == CC_ISOLATED)
+		snprintf(buf, sizeof(buf), "%d,%d", pc_x, pc_y);
+	else
+		snprintf(buf, sizeof(buf), "%d,%d,%d", pc_x, pc_y, pc_z);
+	if (cs_make(cs_b, buf) ||
+	    write_file(cs_b, "cpuset.cpus.partition", "root") ||
+	    write_file(cs_b, "cgroup.subtree_control", "+cpuset") || pipe(fd))
+		goto out;
+	snprintf(buf, sizeof(buf), "%d", pc_x);
+	g = cc_make(cs_b, "g", buf, kind == CC_ISOLATED ? "isolated" : "root");
+	if (!g)
+		goto out;
+	if (kind == CC_NESTED) {
+		if (write_file(g, "cgroup.subtree_control", "+cpuset"))
+			goto out;
+		gc = cc_make(g, "gc", buf, "root");
+		snprintf(buf, sizeof(buf), "%d,%d", pc_y, pc_z);
+		s = gc ? cc_make(cs_b, "s", buf, "isolated") : NULL;
+	} else {
+		snprintf(buf, sizeof(buf), "%d", pc_y);
+		s = cc_make(cs_b, kind == CC_FIRST ? "s1" : "s2", buf, "isolated");
+		if (s && kind == CC_FIRST) {
+			snprintf(buf, sizeof(buf), "%d", pc_z);
+			s2 = cc_make(cs_b, "s2", buf, "isolated");
+		}
+	}
+	if (!s || (kind == CC_FIRST && !s2))
+		goto out;
+	ret = KSFT_FAIL;
+	fair = cc_fair_task(kind == CC_NESTED ? gc : g);
+	dl = fair < 0 ? -1 : cc_dl_task(kind == CC_ISOLATED ? g : s, fd[0]);
+	if (dl < 0)
+		goto out;
+	err = cpu_online(pc_x, 0);
+	if (err != -EBUSY) {
+		ksft_print_msg("offline of CPU %d: %s, not EBUSY\n", pc_x,
+			       err ? strerror(-err) : "accepted");
+		x_off = !err;
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	reap(dl);
+	reap(fair);
+	if (fd[0] >= 0) {
+		close(fd[0]);
+		close(fd[1]);
+	}
+	if (x_off)
+		cpu_up(pc_x);
+	sleep_ns(3 * PERIOD);
+	cc_cleanup();
+	cs_cleanup();
+	return ret;
+}
+
+/* The CC_FIRST kind of cascade_case() */
+static int hotplug_first_sibling_refused(void)
+{
+	return cascade_case(CC_FIRST);
+}
+
+/* The CC_NESTED kind of cascade_case() */
+static int hotplug_nested_partition_refused(void)
+{
+	return cascade_case(CC_NESTED);
+}
+
+/* The CC_ISOLATED kind of cascade_case() */
+static int hotplug_isolated_child_refused(void)
+{
+	return cascade_case(CC_ISOLATED);
+}
+
 static const struct hp_case {
 	const char *name;
 	int (*fn)(void);
@@ -7961,8 +10538,40 @@ static const struct hp_case {
 	{ "hotplug_refused", hotplug_refused },
 	{ "hotplug_departed", hotplug_departed },
 	{ "hotplug_server", hotplug_server },
+	{ "hotplug_server_refused", hotplug_server_refused },
+	{ "hotplug_fallback", hotplug_fallback },
+	{ "hotplug_fallback_running", hotplug_fallback_running },
+	{ "hotplug_fallback_moved", hotplug_fallback_moved },
+	{ "hotplug_fallback_in_mask", hotplug_fallback_in_mask },
+	{ "mask_out_refused", mask_out_refused, 1 },
+	{ "hotplug_last_refused", hotplug_last_refused },
+	{ "hotplug_keeps_root_domain", hotplug_keeps_root_domain },
+	{ "partition_takes_refused", partition_takes_refused, 1 },
+	{ "no_admission_affinity_moves", no_admission_affinity_moves, 1 },
 	{ "affinity_vs_setattr", affinity_vs_setattr, 1 },
 	{ "move_back_cpu_offline", move_back_cpu_offline },
+	{ "hotplug_spinner_keeps", hotplug_spinner_keeps },
+	{ "hotplug_waking_keeps", hotplug_waking_keeps },
+	{ "hotplug_isolated_keeps", hotplug_isolated_keeps },
+	{ "rebuild_waking_keeps", rebuild_waking_keeps, 1 },
+	{ "hotplug_user_mask_refused", hotplug_user_mask_refused },
+	{ "hotplug_nested_refused", hotplug_nested_refused },
+	{ "hotplug_dead_accepted", hotplug_dead_accepted },
+	{ "hotplug_child_partition_kept", hotplug_child_partition_kept },
+	{ "hotplug_partition_invalid_refused", hotplug_partition_invalid_refused },
+	{ "hotplug_sibling_partition_refused", hotplug_sibling_partition_refused },
+	{ "hotplug_top_last_refused", hotplug_top_last_refused },
+	{ "partition_grows_child_valid", partition_grows_child_valid, 1 },
+	{ "hotplug_asleep_setattr", hotplug_asleep_setattr },
+	{ "hotplug_first_sibling_refused", hotplug_first_sibling_refused },
+	{ "hotplug_nested_partition_refused", hotplug_nested_partition_refused },
+	{ "hotplug_isolated_child_refused", hotplug_isolated_child_refused },
+	{ "hotplug_isolated_partition_falls_back", hotplug_isolated_partition_falls_back },
+	{ "partition_takes_fallback_refused", partition_takes_fallback_refused, 1 },
+	{ "mask_grows_refused", mask_grows_refused, 1 },
+	{ "partition_swap_refused", partition_swap_refused, 1 },
+	{ "partition_refused_no_warn", partition_refused_no_warn, 1 },
+	{ "rebuild_record_taken", rebuild_record_taken },
 };
 
 #define N_HP_CASES	((int)ARRAY_SIZE(hp_cases))
-- 
2.47.3


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

* [PATCH v11 19/43] sched/deadline: Count only active CPUs when spreading extra_bw
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (17 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 18/43] selftests/sched: Test the root domain of a task in deadline_bw_test Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 20/43] sched/deadline: Do not truncate a bandwidth to 32 bits in __dl_add/sub() Mathieu Desnoyers
                   ` (23 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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 aa35933c0550..347db90e9e9b 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] 59+ messages in thread

* [PATCH v11 20/43] sched/deadline: Do not truncate a bandwidth to 32 bits in __dl_add/sub()
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (18 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 19/43] sched/deadline: Count only active CPUs when spreading extra_bw Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 21/43] rtmutex: Continue the chain walk when a waiter's deadline donor changes Mathieu Desnoyers
                   ` (22 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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 347db90e9e9b..ffe381f9eb99 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] 59+ messages in thread

* [PATCH v11 21/43] rtmutex: Continue the chain walk when a waiter's deadline donor changes
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (19 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 20/43] sched/deadline: Do not truncate a bandwidth to 32 bits in __dl_add/sub() Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:32   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 22/43] rtmutex: Do not stop the chain walk at an owner whose top waiter changed Mathieu Desnoyers
                   ` (21 subsequent siblings)
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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. Two walks can overlap on a chain of three locks
or more. The owners further down then keep the old donor until the
first walk reaches them.

The case pi_chain_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] 59+ messages in thread

* [PATCH v11 22/43] rtmutex: Do not stop the chain walk at an owner whose top waiter changed
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (20 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 21/43] rtmutex: Continue the chain walk when a waiter's deadline donor changes Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 23/43] sched/deadline: Hold a reference on the deadline donor of a boosted task Mathieu Desnoyers
                   ` (20 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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] 59+ messages in thread

* [PATCH v11 23/43] sched/deadline: Hold a reference on the deadline donor of a boosted task
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (21 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 22/43] rtmutex: Do not stop the chain walk at an owner whose top waiter changed Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 24/43] selftests/sched: Test the rtmutex chain walk in deadline_bw_test Mathieu Desnoyers
                   ` (19 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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 3dd42581cc17..9831b4aa5235 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -7969,19 +7969,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 ffe381f9eb99..74b3c6b967ee 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] 59+ messages in thread

* [PATCH v11 24/43] selftests/sched: Test the rtmutex chain walk in deadline_bw_test
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (22 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 23/43] sched/deadline: Hold a reference on the deadline donor of a boosted task Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 25/43] sched/deadline: Count the 0-lag time from the next period Mathieu Desnoyers
                   ` (18 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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

Add pi_chain_top_moves and pi_chain_top_moves_rt to deadline_bw_test.
They test the two rtmutex fixes earlier in this series. In both, a
chain walk changes the top waiter of an owner to a waiter of another
lock it holds. The walk must go on to the next owner. That owner must
then get the new donor, or the new priority. The first case uses
deadline tasks, the second RT tasks. The comment above each
case gives its scenario.

On v7.4-rc2, in 8 VMs of 8 CPUs, pi_chain_top_moves_rt fails in every
VM.
pi_chain_top_moves passes there. It fails with the first series, until
"rtmutex: Continue the chain walk when a waiter's deadline donor
changes" and "rtmutex: Do not stop the chain walk at an owner whose top
waiter changed". It needs both.

The cases run in P, a cpuset partition root. With CONFIG_RT_GROUP_SCHED,
P can have no RT runtime. sched_setscheduler() then refuses SCHED_FIFO
with EPERM, and pi_chain_top_moves_rt skips.

With the fixes up to here, both cases pass wherever they run.

Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
 .../sched/deadline/deadline_bw_test.c         | 297 ++++++++++++++++++
 1 file changed, 297 insertions(+)

diff --git a/tools/testing/selftests/sched/deadline/deadline_bw_test.c b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
index 87fa1a7d420f..a403122191b8 100644
--- a/tools/testing/selftests/sched/deadline/deadline_bw_test.c
+++ b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
@@ -2522,6 +2522,301 @@ static int pi_chain_donor_leaves(void)
 	return ret;
 }
 
+/*
+ * The threads of top_moves(): O, M, W, Z and Y. top_tid[] holds their
+ * tids. top_lock is L1'. top_y_ns is the CPU time Y gets in O's window,
+ * or -1.
+ */
+enum { TM_O, TM_M, TM_W, TM_Z, TM_Y, TM_N };
+static _Atomic pid_t top_tid[TM_N];
+static pthread_mutex_t top_lock;
+static atomic_int top_err, top_rt, top_m_locking, top_w_locking, top_y_stop;
+static _Atomic long long top_y_ns;
+static sem_t top_o_go, top_m_go;
+
+/* The priority /proc shows for a SCHED_FIFO task of priority @p. */
+#define FIFO_TASK_PRIO(p)	(-1 - (p))
+
+/*
+ * O: take pi_lock2 (L2), and sleep until top_o_go. With Y (@arg), spin
+ * 200ms and measure the CPU time Y gets meanwhile. Then unlock L2.
+ */
+static void *top_o(void *arg)
+{
+	uint64_t t0, y0;
+
+	if (pthread_mutex_lock(&pi_lock2)) {
+		top_err = 1;
+		return arg;
+	}
+	top_tid[TM_O] = gettid_();	/* O holds L2 */
+	sem_wait_sig(&top_o_go);
+	if (arg) {
+		y0 = cpu_time_of(*(pthread_t *)arg);
+		t0 = now_ns();
+		while (now_ns() - t0 < 2 * PERIOD)
+			;
+		top_y_ns = cpu_time_of(*(pthread_t *)arg) - y0;
+	}
+	pthread_mutex_unlock(&pi_lock2);
+	return NULL;
+}
+
+/*
+ * M: take pi_lock (L1) and top_lock (L1'). At top_m_go, block on L2,
+ * which O holds. Unlock L2, L1 and L1' once it gets L2.
+ */
+static void *top_m(void *arg)
+{
+	if (pthread_mutex_lock(&pi_lock)) {
+		top_err = 1;
+		return arg;
+	}
+	if (pthread_mutex_lock(&top_lock)) {
+		pthread_mutex_unlock(&pi_lock);
+		top_err = 1;
+		return arg;
+	}
+	top_tid[TM_M] = gettid_();	/* M holds L1 and L1' */
+	sem_wait_sig(&top_m_go);
+	top_m_locking = 1;
+	if (pthread_mutex_lock(&pi_lock2))
+		top_err = 1;
+	else
+		pthread_mutex_unlock(&pi_lock2);
+	pthread_mutex_unlock(&pi_lock);
+	pthread_mutex_unlock(&top_lock);
+	return arg;
+}
+
+/*
+ * W and Z: W blocks on L1', Z on L1. @arg is 1 for W. With top_rt, W
+ * becomes SCHED_FIFO 50 and Z SCHED_FIFO 20. Otherwise W becomes a
+ * deadline task of 2ms every 80ms and Z one of 5ms every 200ms. The main
+ * thread switches W to SCHED_OTHER while it waits.
+ */
+static void *top_waiter(void *arg)
+{
+	int w = (long)arg;
+	struct sched_param sp = { .sched_priority = w ? 50 : 20 };
+	uint64_t runtime = (w ? 2 : 5) * NSEC_PER_MSEC;
+	pthread_mutex_t *l = w ? &top_lock : &pi_lock;
+
+	if (top_rt ? sched_setscheduler(0, SCHED_FIFO, &sp) :
+		     set_deadline(0, runtime, 40 * runtime)) {
+		/* With RT group scheduling, P can have no RT runtime. */
+		top_err = top_rt && errno == EPERM ? 2 : 1;
+		return arg;
+	}
+	top_tid[w ? TM_W : TM_Z] = gettid_();
+	if (w)
+		top_w_locking = 1;
+	if (pthread_mutex_lock(l))
+		top_err = 1;
+	else
+		pthread_mutex_unlock(l);
+	if (set_other(0))
+		top_err = 1;
+	return arg;
+}
+
+/* Y: become a deadline task of 30ms every 100ms, and spin. */
+static void *top_y(void *arg)
+{
+	if (set_deadline(0, 30 * NSEC_PER_MSEC, PERIOD)) {
+		top_err = 1;
+		return arg;
+	}
+	top_tid[TM_Y] = gettid_();
+	while (!top_y_stop)
+		;
+	return arg;
+}
+
+/*
+ * A chain walk must go on past a task whose top waiter moves to another
+ * lock. The priority of that task changes, and the next owner must
+ * follow.
+ *
+ * L1 is pi_lock, L1' is top_lock and L2 is pi_lock2. All threads run on
+ * the CPU of P. W and Z set their own policy when they start. With @rt,
+ * W is SCHED_FIFO 50 and Z SCHED_FIFO 20. Without @rt, W is a deadline
+ * task of 2ms every 80ms and Z one of 5ms every 200ms. W has the earlier
+ * deadline. O and M are SCHED_OTHER. Without @rt, Y is a deadline task
+ * of 30ms every 100ms. It spins all along.
+ *
+ * 1. O takes L2, and sleeps.
+ * 2. M takes L1 and L1', and sleeps.
+ * 3. W blocks on L1'. W boosts M.
+ * 4. M blocks on L2. M passes W on to O.
+ * 5. Z blocks on L1. W stays the top waiter of M.
+ * 6. The main thread switches W to SCHED_OTHER. The chain walk requeues
+ *    W on L1'. Z on L1 becomes the top waiter of M, and Z boosts M. The
+ *    walk must go on to O. Z must boost O too.
+ *
+ * With @rt, the case reads O's priority. It must be the one of Z. With
+ * the walk stopped at M, O keeps the priority of W.
+ *
+ * Without @rt, W sleeps and has run almost nothing. So its parameters
+ * are cleared at once. 250ms later, the main thread wakes O up. O
+ * measures the CPU time Y gets over the next 200ms, and unlocks L2.
+ *
+ * With Z as its donor, O gets 5ms every 200ms. Y runs at the start of
+ * each of its periods, and gets its 60ms. With W as its donor, O runs on
+ * cleared parameters. Each refill gives it no runtime and a deadline of
+ * about now. O then runs before Y until Y's deadline is past. Y runs
+ * only then, one period late, and gets about 30ms. The case fails if Y
+ * gets less than 45ms.
+ *
+ * W does not exit before O unlocks L2. It waits for L1', which M
+ * releases after it gets L2.
+ */
+static int top_moves(int rt)
+{
+	int ret = KSFT_FAIL, i, have[TM_N] = { 0 };
+	int boost = rt ? FIFO_TASK_PRIO(50) : DL_TASK_PRIO;
+	pthread_mutexattr_t a;
+	pthread_t t[TM_N];
+	long long y_ns;
+	int err, o_prio = 0;
+
+	if (pi_init())
+		return KSFT_SKIP;
+	if (pi_init_lock2()) {
+		pi_fini();
+		return KSFT_SKIP;
+	}
+	err = pthread_mutexattr_init(&a);
+	if (!err) {
+		err = pthread_mutexattr_setprotocol(&a, PTHREAD_PRIO_INHERIT);
+		if (!err)
+			err = pthread_mutex_init(&top_lock, &a);
+		pthread_mutexattr_destroy(&a);
+	}
+	if (err) {
+		ksft_print_msg("no third priority inheritance mutex: %s\n",
+			       strerror(err));
+		ret = KSFT_SKIP;
+		goto out_lock2;
+	}
+	if (sem_init(&top_o_go, 0, 0) || sem_init(&top_m_go, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		goto out_lock3;
+	}
+	for (i = 0; i < TM_N; i++)
+		top_tid[i] = 0;
+	top_err = 0;
+	top_rt = rt;
+	top_m_locking = 0;
+	top_w_locking = 0;
+	top_y_stop = 0;
+	top_y_ns = -1;
+	if (!rt) {
+		have[TM_Y] = !pthread_create(&t[TM_Y], NULL, top_y, NULL);
+		if (!have[TM_Y] || wait_for(1000, top_tid[TM_Y] || top_err)) {
+			ksft_print_msg("Y never became a deadline task\n");
+			goto out;
+		}
+	}
+	have[TM_O] = !pthread_create(&t[TM_O], NULL, top_o,
+				     rt ? NULL : &t[TM_Y]);
+	if (!have[TM_O] || wait_for(1000, top_tid[TM_O] || top_err)) {
+		ksft_print_msg("O never took L2\n");
+		goto out;
+	}
+	have[TM_M] = !pthread_create(&t[TM_M], NULL, top_m, NULL);
+	if (!have[TM_M] || wait_for(1000, top_tid[TM_M] || top_err)) {
+		ksft_print_msg("M never took L1 and L1'\n");
+		goto out;
+	}
+	have[TM_W] = !pthread_create(&t[TM_W], NULL, top_waiter, (void *)1L);
+	if (!have[TM_W] ||
+	    wait_for(1000, (top_w_locking &&
+			    proc_state_of(top_tid[TM_W]) == 'S') || top_err)) {
+		ksft_print_msg("W never blocked on L1'\n");
+		goto out;
+	}
+	sem_post(&top_m_go);
+	if (wait_for(1000, (top_m_locking && prio_of(top_tid[TM_O]) == boost) ||
+			   top_err)) {
+		ksft_print_msg("O was not boosted through M\n");
+		goto out;
+	}
+	have[TM_Z] = !pthread_create(&t[TM_Z], NULL, top_waiter, (void *)0L);
+	if (!have[TM_Z] ||
+	    wait_for(1000, (top_tid[TM_Z] &&
+			    proc_state_of(top_tid[TM_Z]) == 'S') || top_err)) {
+		ksft_print_msg("Z never blocked on L1\n");
+		goto out;
+	}
+	sleep_ns(10 * NSEC_PER_MSEC);	/* the chain walk of Z is done */
+	err = top_err ? -EINVAL : set_other(top_tid[TM_W]);
+	if (err) {
+		ksft_print_msg("W cannot leave its class: %s\n",
+			       strerror(-err));
+		goto out;
+	}
+	if (rt) {
+		sleep_ns(10 * NSEC_PER_MSEC);
+		if (prio_of(top_tid[TM_M]) != FIFO_TASK_PRIO(20)) {
+			ksft_print_msg("Z does not boost M\n");
+			goto out;
+		}
+		o_prio = prio_of(top_tid[TM_O]);
+	} else {
+		sleep_ns(250 * NSEC_PER_MSEC);
+	}
+	ret = KSFT_PASS;
+out:
+	/* Let every thread end: O unlocks L2, then M unlocks L1 and L1'. */
+	sem_post(&top_m_go);
+	sem_post(&top_o_go);
+	for (i = TM_O; i < TM_Y; i++)
+		if (have[i])
+			join(t[i]);
+	top_y_stop = 1;
+	if (have[TM_Y])
+		join(t[TM_Y]);
+	y_ns = top_y_ns;
+	if (top_err == 2) {
+		ksft_print_msg("SCHED_FIFO refused in P\n");
+		ret = KSFT_SKIP;
+	} else if (top_err) {
+		ksft_print_msg("a thread of the chain failed\n");
+		ret = KSFT_FAIL;
+	} else if (ret == KSFT_PASS && rt && o_prio != FIFO_TASK_PRIO(20)) {
+		ksft_print_msg("O runs at priority %d, not %d: W still boosts it\n",
+			       o_prio, FIFO_TASK_PRIO(20));
+		ret = KSFT_FAIL;
+	} else if (ret == KSFT_PASS && !rt &&
+		   y_ns < 45 * (long long)NSEC_PER_MSEC) {
+		ksft_print_msg("Y ran %lld ms of 200: W is still the donor of O\n",
+			       y_ns / (long long)NSEC_PER_MSEC);
+		ret = KSFT_FAIL;
+	}
+	sem_destroy(&top_o_go);
+	sem_destroy(&top_m_go);
+out_lock3:
+	pthread_mutex_destroy(&top_lock);
+out_lock2:
+	pthread_mutex_destroy(&pi_lock2);
+	sem_destroy(&holder_go);
+	pi_fini();
+	return ret;
+}
+
+/* W and Z are deadline tasks. */
+static int pi_chain_top_moves(void)
+{
+	return top_moves(0);
+}
+
+/* W and Z are SCHED_FIFO tasks. */
+static int pi_chain_top_moves_rt(void)
+{
+	return top_moves(1);
+}
+
 /* cpuset moves, from the main process, outside P */
 
 /* Shared with the processes of a case: atomic in shared memory. */
@@ -10219,6 +10514,8 @@ static const struct p_case {
 	{ "return_asleep_new_params", return_asleep_new_params, MEASURED_IN_P },
 	{ "deboost_blocked_keeps_order", deboost_blocked_keeps_order, MEASURED_IN_P },
 	{ "pi_chain_donor_leaves", pi_chain_donor_leaves, MEASURED_IN_P },
+	{ "pi_chain_top_moves", pi_chain_top_moves, MEASURED_IN_P },
+	{ "pi_chain_top_moves_rt", pi_chain_top_moves_rt, MEASURED_IN_P },
 	{ "move_asleep", move_asleep, FROM_OUTSIDE },
 	{ "move_throttled", move_throttled, FROM_OUTSIDE },
 	{ "move_non_contending", move_non_contending, FROM_OUTSIDE },
-- 
2.47.3


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

* [PATCH v11 25/43] sched/deadline: Count the 0-lag time from the next period
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (23 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 24/43] selftests/sched: Test the rtmutex chain walk in deadline_bw_test Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:35   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 26/43] sched/deadline: Keep a departing constrained task until its " Mathieu Desnoyers
                   ` (17 subsequent siblings)
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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                    | 26 +++++++++++++---------
 2 files changed, 22 insertions(+), 16 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 74b3c6b967ee..1d2dcf478f95 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,12 @@ 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);
 
 	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 +663,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 +672,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)) {
-- 
2.47.3


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

* [PATCH v11 26/43] sched/deadline: Keep a departing constrained task until its next period
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (24 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 25/43] sched/deadline: Count the 0-lag time from the next period Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:44   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 27/43] sched/deadline: Replenish a throttled task boosted while asleep Mathieu Desnoyers
                   ` (16 subsequent siblings)
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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.

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 | 38 +++++++++++++++++++++++++++++++++++++-
 1 file changed, 37 insertions(+), 1 deletion(-)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 1d2dcf478f95..11774b3b9fe9 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -759,6 +759,22 @@ static void task_non_contending(struct sched_dl_entity *dl_se, bool dl_task)
 
 	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) &&
+	    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
@@ -2598,6 +2614,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));
@@ -4572,7 +4607,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] 59+ messages in thread

* [PATCH v11 27/43] sched/deadline: Replenish a throttled task boosted while asleep
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (25 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 26/43] sched/deadline: Keep a departing constrained task until its " Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 28/43] sched/deadline: Restore the owner's period at a deboost in the class Mathieu Desnoyers
                   ` (15 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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 11774b3b9fe9..172fb2811d4a 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -1675,10 +1675,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] 59+ messages in thread

* [PATCH v11 28/43] sched/deadline: Restore the owner's period at a deboost in the class
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (26 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 27/43] sched/deadline: Replenish a throttled task boosted while asleep Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:57   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 29/43] sched/deadline: Count the bandwidth a boosted task is given Mathieu Desnoyers
                   ` (14 subsequent siblings)
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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 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 | 185 +++++++++++++++++++++++++++++++++++++++-
 kernel/sched/sched.h    |  14 +++
 kernel/sched/syscalls.c |   2 +-
 5 files changed, 225 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 9831b4aa5235..40bfa1364b90 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -7972,16 +7972,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 172fb2811d4a..100cb4b5fdb6 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -83,6 +83,53 @@ 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.
+ */
+static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se)
+{
+	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 {
+		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 +140,104 @@ 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 has no period to save. 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->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.
+ *  - 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 held = dl_end_held_boost(dl_se);
+	bool own = held;
+
+	if (dl_se->dl_donor_refill) {
+		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.
+	 */
+	if (held && dl_se->runtime <= 0) {
+		struct rq *rq = task_rq(p);
+
+		dl_se->dl_throttled = 1;
+		if (!start_dl_timer(dl_se)) {
+			dl_se->dl_throttled = 0;
+			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;
@@ -776,10 +915,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 {
@@ -1129,6 +1270,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;
@@ -1231,8 +1373,10 @@ static void replenish_dl_entity(struct sched_dl_entity *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;
@@ -1250,6 +1394,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;
 	}
@@ -1257,6 +1402,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
@@ -4998,6 +5146,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.
@@ -5127,6 +5302,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] 59+ messages in thread

* [PATCH v11 29/43] sched/deadline: Count the bandwidth a boosted task is given
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (27 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 28/43] sched/deadline: Restore the owner's period at a deboost in the class Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 30/43] sched/deadline: Start a period for a task that enters the class blocked Mathieu Desnoyers
                   ` (13 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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 100cb4b5fdb6..5ec1c5eaf764 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -728,22 +728,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);
@@ -5060,10 +5075,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
@@ -5078,6 +5089,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);
 
@@ -5107,7 +5128,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)) {
 		/*
@@ -5184,8 +5204,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] 59+ messages in thread

* [PATCH v11 30/43] sched/deadline: Start a period for a task that enters the class blocked
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (28 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 29/43] sched/deadline: Count the bandwidth a boosted task is given Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:53   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 31/43] sched/deadline: Restore the owner's period at a deboost out of the class Mathieu Desnoyers
                   ` (12 subsequent siblings)
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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 40bfa1364b90..5b2ac1b3f6f6 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -7969,8 +7969,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 5ec1c5eaf764..4d46d1c9c698 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -228,6 +228,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)
 {
@@ -242,6 +248,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)
@@ -1301,6 +1312,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:
@@ -4866,6 +4901,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] 59+ messages in thread

* [PATCH v11 31/43] sched/deadline: Restore the owner's period at a deboost out of the class
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (29 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 30/43] sched/deadline: Start a period for a task that enters the class blocked Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:50   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 32/43] sched/deadline: Start a period for a task requeued onto an rt_mutex Mathieu Desnoyers
                   ` (11 subsequent siblings)
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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.

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 | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 4d46d1c9c698..5d1d4ea28878 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -4802,6 +4802,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);
+	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
@@ -4834,6 +4850,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] 59+ messages in thread

* [PATCH v11 32/43] sched/deadline: Start a period for a task requeued onto an rt_mutex
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (30 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 31/43] sched/deadline: Restore the owner's period at a deboost out of the class Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:57   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 33/43] selftests/sched: Test deadline boosts in deadline_bw_test Mathieu Desnoyers
                   ` (10 subsequent siblings)
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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.

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, or one that has passed, gets a new period. 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 new period
  would start before its next period, which the constrained gap
  forbids. So its waiter still sorts first.
- 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_api.c   | 12 +++++++
 kernel/sched/deadline.c        | 59 ++++++++++++++++++++++++++++++++--
 3 files changed, 69 insertions(+), 3 deletions(-)

diff --git a/include/linux/sched/deadline.h b/include/linux/sched/deadline.h
index fa66e75cbdd8..5c53b12948a7 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_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 5d1d4ea28878..c59953e80b1a 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -1682,6 +1682,59 @@ 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. 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)))
+			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
@@ -4939,9 +4992,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] 59+ messages in thread

* [PATCH v11 33/43] selftests/sched: Test deadline boosts in deadline_bw_test
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (31 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 32/43] sched/deadline: Start a period for a task requeued onto an rt_mutex Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 34/43] sched/deadline: Cancel the replenishment timer with the parameters Mathieu Desnoyers
                   ` (9 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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

Add ten cases to deadline_bw_test for the fixes of priority inheritance
boosts and deboosts. The comment above each case gives its scenario.

Eight of these cases fail on v7.4-rc2, in each of two VMs of 8 CPUs.
Each one fails without the fix named:
- deboost_after_donor_refill and deboost_in_class_resets_period:
  "sched/deadline: Restore the owner's period at a deboost in the
  class".
- deboost_out_asleep_after_refill: "sched/deadline: Restore the owner's
  period at a deboost out of the class".
- setattr_blocked_keeps_order and boost_blocked_keeps_order:
  "sched/deadline: Start a period for a task that enters the class
  blocked".
- requeue_pi_new_period: "sched/deadline: Start a period for a task
  requeued onto an rt_mutex".
- deboost_released_resets_period and pi_former_owner_asleep: the first
  series. Its fixes do not name them. They test deboosts, so they come
  here.

On v7.4-rc2, deboost_out_after_donor_refill and
deboost_in_asleep_after_refill pass. They check that an owner refilled
from its donor stays counted in total_bw after its deboost, until the
end of its own period.

pi_other_owner_asleep, deboost_resets_period and
deboost_keeps_own_runtime now run through the helpers of the new cases.
They test the same as before.

With the fixes up to this patch, every case passes in 12 VMs of 4 to 8
CPUs: with proxy execution on and off, with PREEMPT_RT, without
CONFIG_CPUSETS, with CONFIG_RT_GROUP_SCHED, and with isolcpus=domain.

Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
 .../sched/deadline/deadline_bw_test.c         | 1019 ++++++++++++++++-
 1 file changed, 982 insertions(+), 37 deletions(-)

diff --git a/tools/testing/selftests/sched/deadline/deadline_bw_test.c b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
index a403122191b8..1e3881199e4c 100644
--- a/tools/testing/selftests/sched/deadline/deadline_bw_test.c
+++ b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
@@ -881,12 +881,31 @@ static int pi_chain_two_owners(void)
 }
 
 /*
- * Run as the owner thread: take pi_lock, and sleep 400ms while holding
- * it. Return NULL, or 1 on an error.
+ * Run as the owner thread. With @arg (was_dl) set, first become a
+ * deadline task of 30ms every 100ms, run 1ms, and sleep on owner_go. The
+ * main thread switches the owner to SCHED_OTHER during that sleep. Then
+ * take pi_lock, and sleep 400ms while holding it. Return NULL, or 1 on an
+ * error.
  */
 static void *sleeping_owner(void *arg)
 {
+	int was_dl = (long)arg;
+
 	owner_tid = gettid_();
+	if (was_dl) {
+		if (set_deadline(0, 30 * NSEC_PER_MSEC, PERIOD)) {
+			owner_holds = -1;
+			sem_post(&owner_ready);
+			return (void *)1;
+		}
+		spin_ns(NSEC_PER_MSEC);
+		/*
+		 * Sleep. The main thread switches this thread to SCHED_OTHER
+		 * 200ms later, past its 0-lag time.
+		 */
+		sem_post(&owner_ready);
+		sem_wait_sig(&owner_go);
+	}
 	if (take_pi_lock())
 		return (void *)1;
 	owner_holds = 2;
@@ -897,30 +916,50 @@ static void *sleeping_owner(void *arg)
 
 /*
  * A SCHED_OTHER owner takes pi_lock and sleeps 400ms while holding it.
- * The main thread then waits 20ms for the lock, 5 times. For each wait it
- * becomes a deadline task of 5ms every 50ms. Each wait boosts the
+ * The main thread then waits 20ms for the lock, @rounds times. For each
+ * wait it becomes a deadline task of 5ms every 50ms. Each wait boosts the
  * sleeping owner, and its timeout deboosts it. Every wait must time out.
+ *
+ * With @was_dl, the owner was a deadline task of 30ms every 100ms before.
+ * It ran 1ms and slept. The main thread switched it to SCHED_OTHER 200ms
+ * later, past its 0-lag time.
  */
-static int pi_other_owner_asleep(void)
+static int pi_asleep(int was_dl, int rounds)
 {
 	pthread_t o;
 	int r, ret = KSFT_PASS;
 
 	if (pi_init())
 		return KSFT_SKIP;
-	if (pthread_create(&o, NULL, sleeping_owner, NULL)) {
+	if (pthread_create(&o, NULL, sleeping_owner, (void *)(long)was_dl)) {
 		ksft_print_msg("the owner thread could not start\n");
 		return KSFT_FAIL;
 	}
-	if (wait_for(5000, owner_holds) || owner_holds != 2) {
+	if (was_dl) {
+		if (sem_wait_for(&owner_ready, 5000) || owner_holds < 0) {
+			ksft_print_msg("the owner did not become a deadline task\n");
+			ret = KSFT_FAIL;
+		} else {
+			sleep_ns(200 * NSEC_PER_MSEC);
+			if (proc_state_of(owner_tid) != 'S') {
+				ksft_print_msg("the owner is not asleep at 200ms\n");
+				ret = KSFT_FAIL;
+			} else if (set_other(owner_tid)) {
+				ksft_print_msg("the owner cannot leave SCHED_DEADLINE\n");
+				ret = KSFT_FAIL;
+			}
+		}
+		sem_post(&owner_go);
+	}
+	if (ret == KSFT_PASS && (wait_for(5000, owner_holds) || owner_holds != 2)) {
 		ksft_print_msg("the owner never took the lock\n");
 		ret = KSFT_FAIL;
 	}
 	if (ret == KSFT_PASS)
 		sleep_ns(20 * NSEC_PER_MSEC);
-	for (r = 0; r < 5 && ret == KSFT_PASS; r++) {
+	for (r = 0; r < rounds && ret == KSFT_PASS; r++) {
 		if (wait_lock_for(20, 1)) {
-			ksft_print_msg("round %d of 5 failed\n", r + 1);
+			ksft_print_msg("round %d of %d failed\n", r + 1, rounds);
 			ret = KSFT_FAIL;
 		}
 	}
@@ -928,6 +967,16 @@ static int pi_other_owner_asleep(void)
 	return ret;
 }
 
+static int pi_other_owner_asleep(void)
+{
+	return pi_asleep(0, 5);
+}
+
+static int pi_former_owner_asleep(void)
+{
+	return pi_asleep(1, 5);
+}
+
 /*
  * Run as the owner thread. Become a deadline task of 30ms every 100ms,
  * and take pi_lock. Hold it for 300ms, spinning 2ms and sleeping 5ms in
@@ -1636,9 +1685,9 @@ static atomic_int owner_first_period_ms;
 static _Atomic pid_t donor_tid;
 
 /*
- * Run as the owner O of deboost_resets_period(). Store the CPU time of
- * step 4, in ms, in owner_first_period_ms. Return NULL, 1 on an error, or
- * 2 if no waiter boosted it within 1s.
+ * Run as the owner O of deboost_case(). @arg is its @mode. Store the CPU
+ * time of step 4, in ms, in owner_first_period_ms. Return NULL, 1 on an
+ * error, or 2 if no waiter boosted it within 1s.
  */
 static void *deboosted_owner(void *arg)
 {
@@ -1646,6 +1695,17 @@ static void *deboosted_owner(void *arg)
 	int err;
 
 	owner_tid = gettid_();
+	if (arg == (void *)1L) {
+		err = set_deadline(0, 60 * NSEC_PER_MSEC, PERIOD);
+		if (err) {
+			ksft_print_msg("the owner refused as a deadline task: %s\n",
+				       strerror(-err));
+			return (void *)1;
+		}
+		spin_ns(NSEC_PER_MSEC);
+		sem_post(&owner_ready);
+		sem_wait_sig(&owner_go);
+	}
 	if (take_pi_lock())
 		return (void *)1;
 	owner_holds = 2;
@@ -1656,9 +1716,18 @@ static void *deboosted_owner(void *arg)
 			return (void *)2;	/* never boosted */
 		}
 	}
+	if (arg == (void *)2L) {
+		err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+		if (err) {
+			ksft_print_msg("the boosted owner refused as a deadline task: %s\n",
+				       strerror(-err));
+			drop_pi_lock();
+			return (void *)1;
+		}
+	}
 	spin_ns(5 * NSEC_PER_MSEC);
 	drop_pi_lock();
-	err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	err = arg == (void *)2L ? 0 : set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
 	if (err) {
 		ksft_print_msg("the owner refused as a deadline task: %s\n", strerror(-err));
 		return (void *)1;
@@ -1695,8 +1764,8 @@ static void *donor_waiter(void *arg)
 }
 
 /*
- * The owner O starts as SCHED_OTHER. The donor D is the waiter that
- * boosts it: a deadline task of 40ms every 100ms.
+ * Run a deboost case. The owner O starts as SCHED_OTHER. The donor D is
+ * the waiter that boosts it: a deadline task of 40ms every 100ms.
  * 1. O takes pi_lock and spins.
  * 2. D blocks on pi_lock. This boosts O, which then runs on D's runtime.
  * 3. O spins 5ms more and unlocks. The unlock deboosts O.
@@ -1705,8 +1774,16 @@ static void *donor_waiter(void *arg)
  *
  * O must get about 10ms in step 4. The case fails above 20ms: O then
  * still runs on the runtime that the boost left.
+ *
+ * @mode changes one step:
+ * - 0: nothing.
+ * - 1: before step 1, O runs 1ms as a deadline task of 60ms every 100ms,
+ *   and sleeps. The main thread switches it to SCHED_OTHER 300ms later,
+ *   past its 0-lag time.
+ * - 2: in step 3, before the 5ms, O becomes the deadline task of 10ms
+ *   every 100ms of step 4. So O stays in the class at the deboost.
  */
-static int deboost_resets_period(void)
+static int deboost_case(long mode)
 {
 	int err, ret = KSFT_PASS;
 	void *o_ret, *w_ret;
@@ -1715,10 +1792,27 @@ static int deboost_resets_period(void)
 	if (pi_init())
 		return KSFT_SKIP;
 	owner_first_period_ms = -1;
-	if (pthread_create(&o, NULL, deboosted_owner, NULL)) {
+	if (pthread_create(&o, NULL, deboosted_owner, (void *)mode)) {
 		ksft_print_msg("the owner thread could not start\n");
 		return KSFT_FAIL;
 	}
+	if (mode == 1) {
+		if (sem_wait_for(&owner_ready, 5000)) {
+			/* The owner may get there late. Let it end. */
+			sem_post(&owner_go);
+			join(o);
+			return KSFT_FAIL;	/* the owner said why */
+		}
+		sleep_ns(3 * PERIOD);
+		err = proc_state_of(owner_tid) == 'S' ? set_other(owner_tid) : -EAGAIN;
+		sem_post(&owner_go);
+		if (err) {
+			ksft_print_msg("the owner could not leave the class asleep: %s\n",
+				       strerror(-err));
+			join(o);
+			return KSFT_FAIL;
+		}
+	}
 	if (wait_for(5000, owner_holds) || owner_holds != 2) {
 		ksft_print_msg("the owner never took the lock\n");
 		join(o);
@@ -1753,6 +1847,27 @@ static int deboost_resets_period(void)
 	return ret;
 }
 
+/* Run deboost_case() with a plain SCHED_OTHER owner. */
+static int deboost_resets_period(void)
+{
+	return deboost_case(0);
+}
+
+/*
+ * Run deboost_case() with an owner that left the deadline class asleep.
+ * Its bandwidth was released then.
+ */
+static int deboost_released_resets_period(void)
+{
+	return deboost_case(1);
+}
+
+/* Run deboost_case() with an owner that enters the class while boosted. */
+static int deboost_in_class_resets_period(void)
+{
+	return deboost_case(2);
+}
+
 /*
  * Return the runtime that the deadline task @tid has left, in ns, from
  * dl.runtime in /proc/<tid>/sched. Return -1 if it cannot be read.
@@ -1783,14 +1898,16 @@ static long long dl_runtime_left(pid_t tid)
 #define REFILL_DONOR_RUNTIME	(2 * NSEC_PER_MSEC)
 #define REFILL_DONOR_PERIOD	(10 * NSEC_PER_MSEC)
 
-static sem_t refill_donor_ready;
-static atomic_int refill_donor_locking;
-static _Atomic long long refill_owner_left;
+static sem_t refill_donor_ready, refill_measured;
+static atomic_int refill_donor_locking, refill_hold_donor;
+static _Atomic long long refill_owner_left, refill_owner_read_ms;
 
 /*
- * Run as the donor D of deboost_keeps_own_runtime(). Become a deadline
- * task of 2ms every 10ms and sleep until the owner holds pi_lock. Then
- * block on pi_lock. Return NULL once it got the lock, or 1 on an error.
+ * Run as the donor D of refill_case(). Become a deadline task of 2ms
+ * every 10ms and sleep until the owner holds pi_lock. Then block on
+ * pi_lock. With refill_hold_donor, stay a deadline task after the unlock
+ * until refill_measured is posted. Return NULL once it got the lock, or 1
+ * on an error.
  */
 static void *refill_donor(void *arg)
 {
@@ -1810,24 +1927,28 @@ static void *refill_donor(void *arg)
 	err = take_pi_lock();
 	if (!err)
 		drop_pi_lock();
+	if (refill_hold_donor)
+		sem_wait_sig(&refill_measured);
 	if (set_other(0))
 		ksft_print_msg("the donor cannot leave SCHED_DEADLINE\n");
 	return (void *)(long)err;
 }
 
 /*
- * Run as the owner O of deboost_keeps_own_runtime(). @arg is the CPU
- * time, in ms, that O spins with the lock once it is boosted. Store the
- * runtime O has left after the unlock in refill_owner_left. Return NULL,
- * 1 on an error, or 2 if the donor did not block on the lock within 1s.
+ * Run as the owner O of refill_case(). @arg is the CPU time, in ms, that
+ * O spins with the lock once it is boosted. Store in refill_owner_left
+ * the runtime O has left after the unlock. Store in refill_owner_read_ms
+ * when O read it, in ms since O became a deadline task. Return NULL, 1
+ * on an error, or 2 if the donor did not block on the lock within 1s.
  */
 static void *refill_owner(void *arg)
 {
-	uint64_t t0;
+	uint64_t t0, start;
 	int err;
 
 	owner_tid = gettid_();
 	err = set_deadline(0, REFILL_OWN_RUNTIME, PERIOD);
+	start = now_ns();
 	if (err) {
 		ksft_print_msg("the owner refused as a deadline task: %s\n", strerror(-err));
 		return (void *)1;
@@ -1848,6 +1969,7 @@ static void *refill_owner(void *arg)
 	spin_ns((long)arg * NSEC_PER_MSEC);
 	drop_pi_lock();
 	refill_owner_left = dl_runtime_left(owner_tid);
+	refill_owner_read_ms = (now_ns() - start) / NSEC_PER_MSEC;
 	if (set_other(0))
 		ksft_print_msg("the owner cannot leave SCHED_DEADLINE\n");
 	return NULL;
@@ -1866,18 +1988,29 @@ static void *refill_owner(void *arg)
  *                                        preempts O: its deadline is
  *                                          earlier
  *                                        blocks on pi_lock, boosts O
- *   runs 1ms more
+ *   runs @spin_ms more
  *   unlocks: the boost ends
  *                                        takes pi_lock, unlocks
+ *   with @spin_ms 8: waits for its next
+ *     period, at 100ms
  *   reads its dl.runtime
  *
  * A boosted task that runs out of runtime is not throttled. Its runtime
- * is refilled from the parameters of its donor. Here O has used about 3ms
- * of its own 5ms at the unlock, and was never refilled. It must keep what
- * it has left. A new period would hand it a full runtime at every
- * contended unlock. The case fails if O has 4ms or more.
+ * is refilled from the parameters of its donor: 2ms here.
+ *
+ * - @spin_ms is 8: O runs out of its own 5ms, and is refilled from D at
+ *   least once. At the unlock it holds what the last refill left, 2ms at
+ *   most. That is not the runtime of its own reservation. O must go back
+ *   to its own period, whose 5ms it used up, and wait for its next one.
+ *   O reads its runtime when it runs again. The case fails if O reads it
+ *   less than 90ms after it became a deadline task, or if O then has
+ *   3.5ms or less.
+ * - @spin_ms is 1: O has used about 3ms of its own 5ms at the unlock, and
+ *   was never refilled. It must keep what it has left. A new period would
+ *   hand it a full runtime at every contended unlock. The case fails if O
+ *   has 4ms or more.
  */
-static int deboost_keeps_own_runtime(void)
+static int refill_case(long spin_ms)
 {
 	void *o_ret = NULL, *d_ret = NULL;
 	int err, ret = KSFT_PASS;
@@ -1904,7 +2037,7 @@ static int deboost_keeps_own_runtime(void)
 		join(d);
 		return KSFT_FAIL;
 	}
-	if (pthread_create(&o, NULL, refill_owner, (void *)1L)) {
+	if (pthread_create(&o, NULL, refill_owner, (void *)spin_ms)) {
 		ksft_print_msg("the owner thread could not start\n");
 		sem_post(&owner_go);
 		join(d);
@@ -1931,7 +2064,15 @@ static int deboost_keeps_own_runtime(void)
 	} else if (left < 0) {
 		ksft_print_msg("the runtime of the owner cannot be read\n");
 		ret = KSFT_SKIP;
-	} else if (left >= 4 * NSEC_PER_MSEC) {
+	} else if (spin_ms == 8 && left <= 3500 * NSEC_PER_USEC) {
+		ksft_print_msg("the owner has %lld us after the unlock: what the donor's refill left\n",
+			       left / NSEC_PER_USEC);
+		ret = KSFT_FAIL;
+	} else if (spin_ms == 8 && refill_owner_read_ms < 90) {
+		ksft_print_msg("the owner ran again at %lld ms, before its next period at 100\n",
+			       (long long)refill_owner_read_ms);
+		ret = KSFT_FAIL;
+	} else if (spin_ms == 1 && left >= 4 * NSEC_PER_MSEC) {
 		ksft_print_msg("the owner has %lld us after the unlock: a new runtime, with no refill from the donor\n",
 			       left / NSEC_PER_USEC);
 		ret = KSFT_FAIL;
@@ -1939,6 +2080,675 @@ static int deboost_keeps_own_runtime(void)
 	return ret;
 }
 
+/* Run refill_case() with an owner that is refilled from its donor. */
+static int deboost_after_donor_refill(void)
+{
+	return refill_case(8);
+}
+
+/* Run refill_case() with an owner that stays on its own runtime. */
+static int deboost_keeps_own_runtime(void)
+{
+	return refill_case(1);
+}
+
+/*
+ * Run as the owner O of deboost_out_after_donor_refill(). Store total_bw
+ * of O's root domain right after the unlock in refill_owner_left. Return
+ * NULL, 1 on an error, or 2 if the donor did not block on the lock within
+ * 1s.
+ */
+static void *former_owner(void *arg)
+{
+	uint64_t t0;
+	int err;
+
+	owner_tid = gettid_();
+	err = set_deadline(0, REFILL_OWN_RUNTIME, PERIOD);
+	if (err) {
+		ksft_print_msg("the owner refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	spin_ns(2 * NSEC_PER_MSEC);
+	if (take_pi_lock())
+		return (void *)1;
+	if (set_other(0)) {
+		ksft_print_msg("the owner cannot leave SCHED_DEADLINE\n");
+		drop_pi_lock();
+		return (void *)1;
+	}
+	owner_holds = 2;
+	sem_post(&owner_go);
+	t0 = now_ns();
+	while (!refill_donor_locking || proc_state_of(donor_tid) != 'S') {
+		if (now_ns() - t0 > NSEC_PER_SEC) {
+			drop_pi_lock();
+			return (void *)2;
+		}
+	}
+	spin_ns(8 * NSEC_PER_MSEC);
+	drop_pi_lock();
+	refill_owner_left = total_bw_of(top_cpu(1));
+	sem_post(&refill_measured);
+	return NULL;
+}
+
+/*
+ * As refill_case() with @spin_ms 8, but O leaves SCHED_DEADLINE once it
+ * holds pi_lock. O and D share the CPU of P.
+ *
+ *   owner O: 5ms every 100ms             donor D: 2ms every 10ms
+ *
+ *                                        sleeps
+ *   starts its period, runs 2ms
+ *   takes pi_lock
+ *   switches to SCHED_OTHER: its 0-lag
+ *     time is about 40ms ahead
+ *   wakes D up
+ *                                        preempts O
+ *                                        blocks on pi_lock, boosts O
+ *   runs 8ms: runs out of its own
+ *     runtime, is refilled from D
+ *   unlocks: leaves the class
+ *                                        takes pi_lock, unlocks, waits
+ *   reads total_bw
+ *
+ * At the unlock, O's runtime and deadline come from D's refills. O must
+ * go back to its own period there, whose 5ms it used up. Its 0-lag time
+ * is then the end of that period, at 100ms. Its bandwidth must still be
+ * in total_bw right after the unlock. A new period of its own would
+ * release it at once, although O used its runtime in this period.
+ */
+static int deboost_out_after_donor_refill(void)
+{
+	void *o_ret = NULL, *d_ret = NULL;
+	int err, ret = KSFT_PASS;
+	long long base;
+	pthread_t o, d;
+
+	if (total_bw_of(top_cpu(1)) < 0) {
+		ksft_print_msg("sched_debug tells of no total_bw\n");
+		return KSFT_SKIP;
+	}
+	if (pi_init())
+		return KSFT_SKIP;
+	if (sem_init(&refill_donor_ready, 0, 0) || sem_init(&refill_measured, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		pi_fini();
+		return KSFT_SKIP;
+	}
+	refill_donor_locking = 0;
+	refill_hold_donor = 1;
+	refill_owner_left = -1;
+	donor_tid = 0;
+	if (pthread_create(&d, NULL, refill_donor, NULL)) {
+		ksft_print_msg("the donor thread could not start\n");
+		refill_hold_donor = 0;
+		return KSFT_FAIL;
+	}
+	if (sem_wait_for(&refill_donor_ready, 5000) || donor_tid <= 0) {
+		ksft_print_msg("the donor is not ready\n");
+		sem_post(&owner_go);
+		sem_post(&refill_measured);
+		join(d);
+		refill_hold_donor = 0;
+		return KSFT_FAIL;
+	}
+	base = total_bw_of(top_cpu(1));	/* with D, without O */
+	if (pthread_create(&o, NULL, former_owner, NULL)) {
+		ksft_print_msg("the owner thread could not start\n");
+		sem_post(&owner_go);
+		sem_post(&refill_measured);
+		join(d);
+		refill_hold_donor = 0;
+		return KSFT_FAIL;
+	}
+	err = pthread_join(o, &o_ret);
+	if (err) {
+		ksft_print_msg("pthread_join: %s\n", strerror(err));
+		ret = KSFT_FAIL;
+	}
+	if (o_ret == (void *)1)
+		sem_post(&owner_go);	/* the owner never woke the donor up */
+	if (o_ret)
+		sem_post(&refill_measured);
+	err = pthread_join(d, &d_ret);
+	if (err) {
+		ksft_print_msg("pthread_join: %s\n", strerror(err));
+		ret = KSFT_FAIL;
+	}
+	refill_hold_donor = 0;
+	if (o_ret == (void *)2) {
+		ksft_print_msg("the donor never blocked on the lock\n");
+		ret = KSFT_FAIL;
+	} else if (o_ret || d_ret) {
+		ret = KSFT_FAIL;	/* the thread said why */
+	} else if (refill_owner_left != base + bw_of(REFILL_OWN_RUNTIME, PERIOD)) {
+		ksft_print_msg("total_bw %lld right after the unlock, %lld expected\n",
+			       (long long)refill_owner_left,
+			       base + bw_of(REFILL_OWN_RUNTIME, PERIOD));
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
+static sem_t aslp_donor_ready, aslp_owner_locked, aslp_owner_wake;
+static sem_t aslp_donor_out, aslp_read_done;
+static atomic_int aslp_donor_tid, aslp_donor_locking;
+static _Atomic long long aslp_total_bw;
+
+/*
+ * Run as the donor D of deboost_out_asleep_after_refill(). Post
+ * aslp_donor_out right after the timeout, then wait for aslp_read_done.
+ * On an error before the timeout, post aslp_donor_out and return. Return
+ * NULL, or 1 on an error.
+ *
+ * The timeout starts a new period for D. Each microsecond of CPU time
+ * that D then uses moves its 0-lag time 1ms ahead. A read of sched_debug
+ * can take more than 300us. Done by D, it would move D's 0-lag time past
+ * the 300ms that measured() waits before its second probe. So the main
+ * thread reads total_bw, not D.
+ */
+static void *asleep_donor(void *arg)
+{
+	struct timespec ts;
+	int err;
+
+	aslp_donor_tid = gettid_();
+	err = set_deadline(0, NSEC_PER_MSEC, NSEC_PER_SEC);
+	sem_post(&aslp_donor_ready);
+	if (err) {
+		ksft_print_msg("the donor refused as a deadline task: %s\n", strerror(-err));
+		sem_post(&aslp_donor_out);
+		return (void *)1;
+	}
+	if (sem_wait_for(&aslp_owner_locked, 5000)) {
+		ksft_print_msg("the owner did not take the lock\n");
+		sem_post(&aslp_donor_out);
+		return (void *)1;
+	}
+	clock_gettime(CLOCK_REALTIME, &ts);
+	ts.tv_nsec += 200 * 1000000L;
+	ts.tv_sec += ts.tv_nsec / 1000000000L;
+	ts.tv_nsec %= 1000000000L;
+	aslp_donor_locking = 1;
+	err = pthread_mutex_timedlock(&pi_lock, &ts);
+	sem_post(&aslp_donor_out);
+	sem_wait_sig(&aslp_read_done);
+	if (!err) {
+		ksft_print_msg("the donor got the lock, not a timeout\n");
+		pthread_mutex_unlock(&pi_lock);
+		return (void *)1;
+	}
+	if (err != ETIMEDOUT) {
+		ksft_print_msg("the donor's wait: %s\n", strerror(err));
+		return (void *)1;
+	}
+	return NULL;
+}
+
+/*
+ * Run as the owner O of deboost_out_asleep_after_refill(). Return NULL,
+ * 1 on an error, or 2 if the donor did not block on the lock within 1s.
+ */
+static void *asleep_owner(void *arg)
+{
+	uint64_t t0;
+	int err;
+
+	err = set_deadline(0, REFILL_OWN_RUNTIME, PERIOD);
+	if (err) {
+		ksft_print_msg("the owner refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	spin_ns(2 * NSEC_PER_MSEC);
+	if (take_pi_lock())
+		return (void *)1;
+	if (set_other(0)) {
+		ksft_print_msg("the owner cannot leave SCHED_DEADLINE\n");
+		drop_pi_lock();
+		return (void *)1;
+	}
+	sem_post(&aslp_owner_locked);
+	t0 = now_ns();
+	while (!aslp_donor_locking || proc_state_of(aslp_donor_tid) != 'S') {
+		if (now_ns() - t0 > NSEC_PER_SEC) {
+			drop_pi_lock();
+			return (void *)2;
+		}
+	}
+	spin_ns(8 * NSEC_PER_MSEC);
+	while (sem_wait(&aslp_owner_wake) && errno == EINTR)
+		;
+	drop_pi_lock();
+	return NULL;
+}
+
+/*
+ * As deboost_out_after_donor_refill(), but O sleeps when the boost ends.
+ * D has a lower bandwidth than O. O and D share the CPU of P.
+ *
+ *   owner O: 5ms every 100ms             donor D: 1ms every 1s
+ *
+ *                                        waits for O
+ *   starts its period, runs 2ms
+ *   takes pi_lock
+ *   switches to SCHED_OTHER
+ *   wakes D up
+ *                                        blocks on pi_lock for 200ms,
+ *                                          boosts O
+ *   runs 8ms: runs out of its own
+ *     runtime, is refilled from D
+ *   sleeps, boosted
+ *                                        times out: O leaves the class
+ *                                        sleeps; the main thread reads
+ *                                          total_bw
+ *
+ * O blocked with the runtime and the deadline of D's refills. Mixed with
+ * O's own parameters, they put its 0-lag time seconds ahead. At the end
+ * of the boost, 200ms after it started, O's own period has ended. O must
+ * start its next one. Its 0-lag time is then now, and its bandwidth must
+ * be gone from total_bw at once.
+ */
+static int deboost_out_asleep_after_refill(void)
+{
+	void *o_ret = NULL, *d_ret = NULL;
+	int err, ret = KSFT_PASS;
+	long long base;
+	pthread_t o, d;
+
+	if (total_bw_of(top_cpu(1)) < 0) {
+		ksft_print_msg("sched_debug tells of no total_bw\n");
+		return KSFT_SKIP;
+	}
+	if (pi_init())
+		return KSFT_SKIP;
+	if (sem_init(&aslp_donor_ready, 0, 0) || sem_init(&aslp_owner_locked, 0, 0) ||
+	    sem_init(&aslp_owner_wake, 0, 0) || sem_init(&aslp_donor_out, 0, 0) ||
+	    sem_init(&aslp_read_done, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		pi_fini();
+		return KSFT_SKIP;
+	}
+	aslp_donor_tid = 0;
+	aslp_donor_locking = 0;
+	aslp_total_bw = -1;
+	if (pthread_create(&d, NULL, asleep_donor, NULL)) {
+		ksft_print_msg("the donor thread could not start\n");
+		return KSFT_FAIL;
+	}
+	if (sem_wait_for(&aslp_donor_ready, 5000)) {
+		ksft_print_msg("the donor is not ready\n");
+		sem_post(&aslp_owner_locked);
+		sem_post(&aslp_read_done);
+		join(d);
+		return KSFT_FAIL;
+	}
+	base = total_bw_of(top_cpu(1));	/* with D, without O */
+	if (pthread_create(&o, NULL, asleep_owner, NULL)) {
+		ksft_print_msg("the owner thread could not start\n");
+		sem_post(&aslp_owner_locked);
+		sem_post(&aslp_read_done);
+		join(d);
+		return KSFT_FAIL;
+	}
+	if (sem_wait_for(&aslp_donor_out, 5000)) {
+		ksft_print_msg("the donor did not time out\n");
+		ret = KSFT_FAIL;
+	} else {
+		aslp_total_bw = total_bw_of(top_cpu(1));
+	}
+	sem_post(&aslp_read_done);
+	err = pthread_join(d, &d_ret);
+	if (err) {
+		ksft_print_msg("pthread_join: %s\n", strerror(err));
+		ret = KSFT_FAIL;
+	}
+	sem_post(&aslp_owner_wake);
+	err = pthread_join(o, &o_ret);
+	if (err) {
+		ksft_print_msg("pthread_join: %s\n", strerror(err));
+		ret = KSFT_FAIL;
+	}
+	if (o_ret == (void *)2) {
+		ksft_print_msg("the donor never blocked on the lock\n");
+		ret = KSFT_FAIL;
+	} else if (o_ret || d_ret) {
+		ret = KSFT_FAIL;	/* the thread said why */
+	} else if (aslp_total_bw != base) {
+		ksft_print_msg("total_bw %lld right after the timeout, %lld expected\n",
+			       (long long)aslp_total_bw, base);
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
+static sem_t inas_ready, inas_locked, inas_out, inas_read, inas_wake;
+static atomic_int inas_locking;
+static _Atomic pid_t inas_d_tid, inas_o_tid;
+
+/*
+ * Run as the donor D of deboost_in_asleep_after_refill(). Become a
+ * deadline task of 2ms every 50ms. Once O holds pi_lock, wait 30ms for
+ * it. Then post inas_out, and wait for inas_read. Return NULL if the wait
+ * timed out, or 1 otherwise.
+ */
+static void *inas_donor(void *arg)
+{
+	struct timespec ts;
+	int err;
+
+	inas_d_tid = gettid_();
+	err = set_deadline(0, 2 * NSEC_PER_MSEC, PERIOD / 2);
+	sem_post(&inas_ready);
+	if (err) {
+		ksft_print_msg("the donor refused as a deadline task: %s\n", strerror(-err));
+		sem_post(&inas_out);
+		return (void *)1;
+	}
+	if (sem_wait_for(&inas_locked, 5000)) {
+		ksft_print_msg("the owner did not take the lock\n");
+		sem_post(&inas_out);
+		set_other(0);
+		return (void *)1;
+	}
+	clock_gettime(CLOCK_REALTIME, &ts);
+	ts.tv_nsec += 30 * 1000000L;
+	ts.tv_sec += ts.tv_nsec / 1000000000L;
+	ts.tv_nsec %= 1000000000L;
+	inas_locking = 1;
+	err = pthread_mutex_timedlock(&pi_lock, &ts);
+	sem_post(&inas_out);
+	sem_wait_sig(&inas_read);
+	if (!err)
+		pthread_mutex_unlock(&pi_lock);
+	if (set_other(0))
+		ksft_print_msg("the donor cannot leave SCHED_DEADLINE\n");
+	if (err != ETIMEDOUT) {
+		ksft_print_msg("the donor: %s, not a timeout\n",
+			       err ? strerror(err) : "got pi_lock");
+		return (void *)1;
+	}
+	return NULL;
+}
+
+/*
+ * Run as the owner O of deboost_in_asleep_after_refill(). The comment of
+ * that function has the steps. Return NULL, or 1 on an error.
+ */
+static void *inas_owner(void *arg)
+{
+	uint64_t t0;
+	int err;
+
+	inas_o_tid = gettid_();
+	err = set_deadline(0, 5 * NSEC_PER_MSEC, PERIOD);
+	if (err || take_pi_lock()) {
+		if (err)
+			ksft_print_msg("the owner refused as a deadline task: %s\n",
+				       strerror(-err));
+		sem_post(&inas_locked);
+		set_other(0);
+		return (void *)1;
+	}
+	sem_post(&inas_locked);
+	t0 = now_ns();
+	while (!inas_locking || proc_state_of(inas_d_tid) != 'S') {
+		if (now_ns() - t0 > NSEC_PER_SEC) {
+			ksft_print_msg("the donor did not block on the lock\n");
+			drop_pi_lock();
+			set_other(0);
+			return (void *)1;
+		}
+	}
+	spin_ns(8 * NSEC_PER_MSEC);
+	sem_wait_sig(&inas_wake);
+	drop_pi_lock();
+	set_other(0);
+	return NULL;
+}
+
+/*
+ * Like deboost_out_asleep_after_refill(), O sleeps boosted after a
+ * refill. Here O stays in the class at the deboost, and the boost ends
+ * within O's own period. O and D share the CPU of P:
+ * 1. D becomes a deadline task of 2ms every 50ms, and waits.
+ * 2. O becomes a deadline task of 5ms every 100ms. It takes pi_lock.
+ * 3. D waits 30ms for pi_lock. Its deadline is the earlier one: it boosts
+ *    O.
+ * 4. O runs 8ms. It runs out of its own 5ms, and is refilled from D. It
+ *    sleeps, boosted.
+ * 5. D times out, and the boost ends. O goes back to its own period,
+ *    whose 5ms it used up. Its 0-lag time is the end of that period, at
+ *    100ms.
+ * 6. The main thread switches O to SCHED_OTHER, and reads total_bw.
+ *
+ * O went to sleep with the runtime and the deadline of D's refills, which
+ * are not those of its own reservation. O's bandwidth must still be in
+ * total_bw at step 6, until the end of its own period.
+ */
+static int deboost_in_asleep_after_refill(void)
+{
+	void *o_ret = NULL, *d_ret = NULL;
+	long long base, bw = -1;
+	int err, ret = KSFT_FAIL;
+	pthread_t o, d;
+
+	if (total_bw_of(top_cpu(1)) < 0) {
+		ksft_print_msg("sched_debug tells of no total_bw\n");
+		return KSFT_SKIP;
+	}
+	if (pi_init())
+		return KSFT_SKIP;
+	if (sem_init(&inas_ready, 0, 0) || sem_init(&inas_locked, 0, 0) ||
+	    sem_init(&inas_out, 0, 0) || sem_init(&inas_read, 0, 0) ||
+	    sem_init(&inas_wake, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		pi_fini();
+		return KSFT_SKIP;
+	}
+	inas_locking = 0;
+	inas_d_tid = 0;
+	inas_o_tid = 0;
+	if (pthread_create(&d, NULL, inas_donor, NULL)) {
+		ksft_print_msg("the donor thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&inas_ready, 5000)) {
+		sem_post(&inas_locked);
+		sem_post(&inas_read);
+		join(d);
+		goto out;
+	}
+	base = total_bw_of(top_cpu(1));	/* with D, without O */
+	if (pthread_create(&o, NULL, inas_owner, NULL)) {
+		ksft_print_msg("the owner thread could not start\n");
+		sem_post(&inas_locked);
+		sem_post(&inas_read);
+		join(d);
+		goto out;
+	}
+	if (sem_wait_for(&inas_out, 5000)) {
+		ksft_print_msg("the donor did not time out\n");
+	} else if (wait_for(1000, proc_state_of(inas_o_tid) == 'S')) {
+		ksft_print_msg("the owner is not asleep\n");
+	} else {
+		err = set_other(inas_o_tid);
+		if (err)
+			ksft_print_msg("the owner cannot leave SCHED_DEADLINE: %s\n",
+				       strerror(-err));
+		else
+			bw = total_bw_of(top_cpu(1));
+	}
+	sem_post(&inas_read);
+	pthread_join(d, &d_ret);
+	sem_post(&inas_wake);
+	pthread_join(o, &o_ret);
+	if (o_ret || d_ret || bw < 0)
+		goto out;	/* a thread said why */
+	if (bw != base + bw_of(5 * NSEC_PER_MSEC, PERIOD)) {
+		ksft_print_msg("total_bw %lld after O left the class asleep, %lld expected\n",
+			       bw, base + bw_of(5 * NSEC_PER_MSEC, PERIOD));
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&inas_ready);
+	sem_destroy(&inas_locked);
+	sem_destroy(&inas_out);
+	sem_destroy(&inas_read);
+	sem_destroy(&inas_wake);
+	pi_fini();
+	return ret;
+}
+
+static _Atomic uint32_t rq_cond, rq_pi;
+static atomic_int rq_order, rq_w_rank, rq_x_rank, rq_x_locking;
+static _Atomic pid_t rq_w_tid, rq_x_tid;
+
+/* Unlock the PI futex rq_pi, held by the caller. */
+static void rq_pi_unlock(void)
+{
+	uint32_t tid = gettid_();
+
+	if (!atomic_compare_exchange_strong(&rq_pi, &tid, 0))
+		syscall(SYS_futex, &rq_pi, FUTEX_UNLOCK_PI | FUTEX_PRIVATE_FLAG,
+			0, NULL, NULL, 0);
+}
+
+/*
+ * Run as W of requeue_pi_new_period(). Wait on rq_cond with
+ * FUTEX_WAIT_REQUEUE_PI, to be requeued onto rq_pi. Once W holds rq_pi,
+ * store its rank in rq_w_rank and unlock. Return NULL, or 1 on an error.
+ */
+static void *rq_w(void *arg)
+{
+	long ret;
+
+	rq_w_tid = gettid_();
+	ret = syscall(SYS_futex, &rq_cond, FUTEX_WAIT_REQUEUE_PI | FUTEX_PRIVATE_FLAG,
+		      0, NULL, &rq_pi, 0);
+	if (ret) {
+		ksft_print_msg("FUTEX_WAIT_REQUEUE_PI: %s\n", strerror(errno));
+		return (void *)1;
+	}
+	rq_w_rank = rq_order++;
+	rq_pi_unlock();
+	if (set_other(0))
+		ksft_print_msg("W cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run as X of requeue_pi_new_period(). Become a deadline task of 5ms
+ * every 50ms, and take rq_pi with FUTEX_LOCK_PI. Store its rank in
+ * rq_x_rank and unlock. Return NULL, or 1 on an error.
+ */
+static void *rq_x(void *arg)
+{
+	int err;
+
+	rq_x_tid = gettid_();
+	err = set_deadline(0, 5 * NSEC_PER_MSEC, PERIOD / 2);
+	if (err) {
+		ksft_print_msg("X refused as a deadline task: %s\n", strerror(-err));
+		rq_x_locking = -1;
+		return (void *)1;
+	}
+	rq_x_locking = 1;
+	if (syscall(SYS_futex, &rq_pi, FUTEX_LOCK_PI | FUTEX_PRIVATE_FLAG,
+		    0, NULL, NULL, 0)) {
+		ksft_print_msg("FUTEX_LOCK_PI: %s\n", strerror(errno));
+		set_other(0);
+		return (void *)1;
+	}
+	rq_x_rank = rq_order++;
+	rq_pi_unlock();
+	if (set_other(0))
+		ksft_print_msg("X cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * FUTEX_CMP_REQUEUE_PI makes a sleeping task wait on a PI futex. The main
+ * thread holds the PI futex rq_pi:
+ * 1. W, a fair task, sleeps in FUTEX_WAIT_REQUEUE_PI.
+ * 2. The main thread makes W a deadline task of 5ms every 100ms. W sleeps,
+ *    so it gets no deadline yet: its deadline is 0.
+ * 3. X, a deadline task of 5ms every 50ms, blocks on rq_pi.
+ * 4. The main thread requeues W onto rq_pi, then unlocks it.
+ *
+ * X has the earlier deadline. It must get rq_pi first. With W's deadline
+ * of 0 in its waiter node, W would get it first.
+ */
+static int requeue_pi_new_period(void)
+{
+	void *w_ret = NULL, *x_ret = NULL;
+	int ret = KSFT_FAIL, have_x = 0, err;
+	pthread_t w, x;
+	long n;
+
+	rq_cond = 0;
+	rq_pi = gettid_();
+	rq_order = 0;
+	rq_w_rank = -1;
+	rq_x_rank = -1;
+	rq_x_locking = 0;
+	rq_w_tid = 0;
+	if (pthread_create(&w, NULL, rq_w, NULL)) {
+		ksft_print_msg("the W thread could not start\n");
+		return KSFT_FAIL;
+	}
+	if (wait_for(1000, rq_w_tid && proc_state_of(rq_w_tid) == 'S')) {
+		ksft_print_msg("W never slept\n");
+		goto out;
+	}
+	err = set_deadline(rq_w_tid, 5 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("W refused as a deadline task: %s\n", strerror(-err));
+		goto out;
+	}
+	have_x = !pthread_create(&x, NULL, rq_x, NULL);
+	if (!have_x || wait_for(1000, rq_x_locking &&
+				   (rq_x_locking < 0 || proc_state_of(rq_x_tid) == 'S')) ||
+	    rq_x_locking < 0) {
+		ksft_print_msg("X never waited on rq_pi\n");
+		goto out;
+	}
+	n = syscall(SYS_futex, &rq_cond, FUTEX_CMP_REQUEUE_PI | FUTEX_PRIVATE_FLAG,
+		    1, (void *)1L, &rq_pi, 0);
+	if (n < 0) {
+		ksft_print_msg("FUTEX_CMP_REQUEUE_PI: %s\n", strerror(errno));
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	rq_pi_unlock();
+	if (ret != KSFT_PASS) {
+		/*
+		 * Let W go if it was not requeued. FUTEX_WAKE cannot wake a
+		 * waiter of FUTEX_WAIT_REQUEUE_PI, so requeue W onto rq_pi. W
+		 * takes rq_pi at once if it is free, or after X unlocks it. If
+		 * W has not started its wait, the new value of rq_cond makes
+		 * the wait return at once. Set it first.
+		 */
+		rq_cond = 1;
+		syscall(SYS_futex, &rq_cond, FUTEX_CMP_REQUEUE_PI | FUTEX_PRIVATE_FLAG,
+			1, (void *)1L, &rq_pi, 1);
+	}
+	if (have_x && pthread_join(x, &x_ret))
+		ret = KSFT_FAIL;
+	if (pthread_join(w, &w_ret))
+		ret = KSFT_FAIL;
+	if (ret == KSFT_PASS && (w_ret || x_ret)) {
+		ret = KSFT_FAIL;	/* the thread said why */
+	} else if (ret == KSFT_PASS && rq_w_rank < rq_x_rank) {
+		ksft_print_msg("W got rq_pi before X\n");
+		ret = KSFT_FAIL;
+	}
+	return ret;
+}
+
 static sem_t ret_ready, ret_go;
 static _Atomic pid_t ret_tid;
 static atomic_int ret_first_period_ms;
@@ -2033,7 +2843,7 @@ static pthread_mutex_t pi_lock2;
 static sem_t holder_go;
 static atomic_int holder_holds, chain_waits, donor_done, x_waits, l2_takes;
 static atomic_int chain_rank, x_rank;
-static _Atomic pid_t x_tid;
+static _Atomic pid_t x_tid, fair_tid;
 
 /* The holder thread: take pi_lock2, and hold it until holder_go. */
 static void *l2_holder(void *arg)
@@ -2191,6 +3001,7 @@ static int pi_init_lock2(void)
 	x_rank = -1;
 	donor_tid = 0;
 	x_tid = 0;
+	fair_tid = 0;
 	return 0;
 }
 
@@ -2289,6 +3100,130 @@ static int deboost_blocked_keeps_order(void)
 	return ret;
 }
 
+/*
+ * The fair waiter: wait on pi_lock2 as a fair task. With @arg set, hold
+ * pi_lock meanwhile, for a donor to boost it. Otherwise the main thread
+ * makes it a deadline task while it waits. It leaves the class at the end.
+ */
+static void *fair_waiter(void *arg)
+{
+	int err;
+
+	fair_tid = gettid_();
+	if (arg && take_pi_lock())
+		return (void *)1;
+	chain_waits = 1;
+	err = take_l2_ranked(&chain_rank);
+	if (arg)
+		drop_pi_lock();
+	else if (set_other(0))
+		ksft_print_msg("a waiter cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+/*
+ * Check the order of the waiters of pi_lock2 when one of them enters the
+ * class while it waits. The holder has pi_lock2:
+ * 1. The fair waiter waits on pi_lock2. With @boost, it holds pi_lock.
+ * 2. The other waiter, a deadline task of 5ms every 50ms, waits on
+ *    pi_lock2.
+ * 3. The fair waiter enters the class:
+ *    - Without @boost, the main thread makes it a deadline task of 10ms
+ *      every 200ms.
+ *    - With @boost, a donor of 40ms every 100ms waits on pi_lock, and
+ *      boosts it.
+ * 4. The holder drops pi_lock2.
+ *
+ * The other waiter must take pi_lock2 first: it started its period
+ * earlier, with a shorter deadline. At step 3 the fair waiter is not
+ * queued, and the chain walk copies its deadline into its waiter node on
+ * pi_lock2. A deadline of 0 in the node would put the fair waiter first.
+ */
+static int blocked_keeps_order(long boost)
+{
+	void *f_ret = NULL, *x_ret = NULL, *w_ret = NULL;
+	int ret = KSFT_FAIL, have_f = 0, have_x = 0, have_w = 0, err;
+	pthread_t h, f, x, w;
+
+	if (pi_init())
+		return KSFT_SKIP;
+	if (pi_init_lock2()) {
+		pi_fini();
+		return KSFT_SKIP;
+	}
+	if (pthread_create(&h, NULL, l2_holder, NULL)) {
+		ksft_print_msg("the holder thread could not start\n");
+		goto out_fini;
+	}
+	if (wait_for(5000, holder_holds) || holder_holds != 1) {
+		ksft_print_msg("the holder never took pi_lock2\n");
+		goto out;
+	}
+	have_f = !pthread_create(&f, NULL, fair_waiter, (void *)boost);
+	if (!have_f || wait_for(1000, chain_waits && proc_state_of(fair_tid) == 'S')) {
+		ksft_print_msg("the fair waiter never waited on pi_lock2\n");
+		goto out;
+	}
+	have_x = !pthread_create(&x, NULL, early_waiter, NULL);
+	if (!have_x || wait_for(1000, x_waits && proc_state_of(x_tid) == 'S')) {
+		ksft_print_msg("the other waiter never waited on pi_lock2\n");
+		goto out;
+	}
+	if (boost) {
+		have_w = !pthread_create(&w, NULL, donor_waiter, NULL);
+		if (!have_w || wait_for(1000, donor_tid && proc_state_of(donor_tid) == 'S')) {
+			ksft_print_msg("the donor never waited on pi_lock\n");
+			goto out;
+		}
+		if (prio_of(fair_tid) != DL_TASK_PRIO) {
+			ksft_print_msg("the donor never boosted the fair waiter\n");
+			goto out;
+		}
+	} else {
+		err = set_deadline(fair_tid, 10 * NSEC_PER_MSEC, 2 * PERIOD);
+		if (err) {
+			ksft_print_msg("the fair waiter refused as a deadline task: %s\n",
+				       strerror(-err));
+			if (err == -EBUSY)
+				ret = KSFT_SKIP;	/* no room in P */
+			goto out;
+		}
+	}
+	ret = KSFT_PASS;
+out:
+	sem_post(&holder_go);	/* pi_lock2 goes to its top waiter */
+	if (have_w && pthread_join(w, &w_ret))
+		ret = KSFT_FAIL;
+	if (have_x && pthread_join(x, &x_ret))
+		ret = KSFT_FAIL;
+	if (have_f && pthread_join(f, &f_ret))
+		ret = KSFT_FAIL;
+	join(h);
+	if (f_ret || x_ret || w_ret) {
+		ret = KSFT_FAIL;	/* the thread said why */
+	} else if (ret == KSFT_PASS && chain_rank < x_rank) {
+		ksft_print_msg("the fair waiter took pi_lock2 before the earlier waiter\n");
+		ret = KSFT_FAIL;
+	}
+out_fini:
+	pthread_mutex_destroy(&pi_lock2);
+	sem_destroy(&holder_go);
+	pi_fini();
+	return ret;
+}
+
+/* sched_setattr() puts the fair waiter in the class. */
+static int setattr_blocked_keeps_order(void)
+{
+	return blocked_keeps_order(0);
+}
+
+/* A boost puts the fair waiter in the class. */
+static int boost_blocked_keeps_order(void)
+{
+	return blocked_keeps_order(1);
+}
+
 /*
  * The threads of pi_chain_donor_leaves(): O, M, W, Z and Y. leave_tid[]
  * holds their tids. leave_y_ns is the CPU time Y gets in O's window, or
@@ -10497,6 +11432,7 @@ static const struct p_case {
 } p_cases[] = {
 	{ "pi_deadline_owner", pi_deadline_owner, MEASURED_IN_P },
 	{ "pi_other_owner_asleep", pi_other_owner_asleep, MEASURED_IN_P },
+	{ "pi_former_owner_asleep", pi_former_owner_asleep, MEASURED_IN_P },
 	{ "pi_unlock_running", pi_unlock_running, MEASURED_IN_P },
 	{ "pi_chain_two_owners", pi_chain_two_owners, MEASURED_IN_P },
 	{ "pi_departed_moved", pi_departed_moved, FROM_OUTSIDE },
@@ -10510,9 +11446,18 @@ static const struct p_case {
 	{ "params_keep_boosted", params_keep_boosted, MEASURED_IN_P },
 	{ "boosted_owner_policy", boosted_owner_policy, MEASURED_IN_P },
 	{ "deboost_resets_period", deboost_resets_period, MEASURED_IN_P },
+	{ "deboost_released_resets_period", deboost_released_resets_period, MEASURED_IN_P },
+	{ "deboost_in_class_resets_period", deboost_in_class_resets_period, MEASURED_IN_P },
+	{ "deboost_after_donor_refill", deboost_after_donor_refill, MEASURED_IN_P },
+	{ "deboost_out_after_donor_refill", deboost_out_after_donor_refill, MEASURED_IN_P },
+	{ "deboost_out_asleep_after_refill", deboost_out_asleep_after_refill, MEASURED_IN_P },
+	{ "deboost_in_asleep_after_refill", deboost_in_asleep_after_refill, MEASURED_IN_P },
+	{ "requeue_pi_new_period", requeue_pi_new_period, MEASURED_IN_P },
 	{ "deboost_keeps_own_runtime", deboost_keeps_own_runtime, MEASURED_IN_P },
 	{ "return_asleep_new_params", return_asleep_new_params, MEASURED_IN_P },
 	{ "deboost_blocked_keeps_order", deboost_blocked_keeps_order, MEASURED_IN_P },
+	{ "setattr_blocked_keeps_order", setattr_blocked_keeps_order, MEASURED_IN_P },
+	{ "boost_blocked_keeps_order", boost_blocked_keeps_order, MEASURED_IN_P },
 	{ "pi_chain_donor_leaves", pi_chain_donor_leaves, MEASURED_IN_P },
 	{ "pi_chain_top_moves", pi_chain_top_moves, MEASURED_IN_P },
 	{ "pi_chain_top_moves_rt", pi_chain_top_moves_rt, MEASURED_IN_P },
-- 
2.47.3


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

* [PATCH v11 34/43] sched/deadline: Cancel the replenishment timer with the parameters
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (32 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 33/43] selftests/sched: Test deadline boosts in deadline_bw_test Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:45   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 35/43] sched/deadline: Cap the runtime left of a constrained task at dl_runtime Mathieu Desnoyers
                   ` (8 subsequent siblings)
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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 c59953e80b1a..828923a77107 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -959,6 +959,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);
 			}
 		}
@@ -2895,6 +2896,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] 59+ messages in thread

* [PATCH v11 35/43] sched/deadline: Cap the runtime left of a constrained task at dl_runtime
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (33 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 34/43] sched/deadline: Cancel the replenishment timer with the parameters Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 36/43] sched/deadline: Check the runtime of a task that comes back runnable Mathieu Desnoyers
                   ` (7 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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 828923a77107..6e4edadddf24 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -1648,6 +1648,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] 59+ messages in thread

* [PATCH v11 36/43] sched/deadline: Check the runtime of a task that comes back runnable
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (34 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 35/43] sched/deadline: Cap the runtime left of a constrained task at dl_runtime Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 37/43] sched/deadline: Keep the debt of a task across a change of parameters Mathieu Desnoyers
                   ` (6 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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 6e4edadddf24..23186eb9968e 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -3159,6 +3159,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] 59+ messages in thread

* [PATCH v11 37/43] sched/deadline: Keep the debt of a task across a change of parameters
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (35 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 36/43] sched/deadline: Check the runtime of a task that comes back runnable Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  2:16   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 38/43] sched/deadline: Boost an owner that cannot run on its own reservation Mathieu Desnoyers
                   ` (5 subsequent siblings)
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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                       | 573 ++++++++++++++++--
 kernel/sched/sched.h                          |   3 +
 kernel/sched/syscalls.c                       |  25 +-
 .../sched/deadline/deadline_bw_test.c         |  28 +-
 6 files changed, 607 insertions(+), 79 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 5b2ac1b3f6f6..fa032d6dc873 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -7966,8 +7966,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;
 
@@ -7990,12 +7997,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 23186eb9968e..1ec7789e81b8 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -89,26 +89,28 @@ 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.
  */
 static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se)
 {
 	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
@@ -130,6 +132,19 @@ 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 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_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)
 {
@@ -144,12 +159,12 @@ 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 has no period to save. 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 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)
 {
@@ -166,6 +181,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:
@@ -175,11 +201,29 @@ static int start_dl_timer(struct sched_dl_entity *dl_se);
  *    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.
- *  - 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.
+ *    refill, start a new period now. 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.
@@ -187,6 +231,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 held = dl_end_held_boost(dl_se);
 	bool own = held;
 
@@ -227,12 +272,80 @@ 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)
+/*
+ * 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. dl_deboost() does the same. switched_from_dl() has already
+ * worked out the 0-lag time, before this fit: see dl_time_to_zerolag().
+ *
+ * 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_setattr_period(dl_se, dl_se->setattr_runtime,
+				  dl_se->setattr_deadline, dl_se->setattr_period);
+}
+
+/*
+ * 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)
@@ -773,6 +886,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);
 
@@ -799,18 +941,27 @@ 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);
 
-	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);
 
 		/*
@@ -839,13 +990,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);
 }
 
@@ -934,7 +1085,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) &&
 	    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;
@@ -1299,7 +1451,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;
 
 	/*
@@ -1402,6 +1555,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
@@ -1422,6 +1576,7 @@ static void replenish_dl_entity(struct sched_dl_entity *dl_se)
 		WARN_ON_ONCE(!is_dl_boosted(dl_se));
 		if (!dl_se->dl_deadline) {
 			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) {
@@ -1446,7 +1601,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;
 	}
 
@@ -1464,8 +1620,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
@@ -1655,7 +1822,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)
@@ -1691,9 +1859,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
@@ -1743,6 +1916,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);
@@ -1784,7 +1958,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));
 	}
 
@@ -1934,6 +2108,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;
@@ -1959,6 +2137,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:
 	 *
@@ -2652,6 +2842,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);
@@ -3110,7 +3301,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);
 
@@ -3159,12 +3361,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) &&
@@ -4913,6 +5116,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;
 	}
 
@@ -5012,8 +5216,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
@@ -5021,8 +5226,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;
@@ -5325,47 +5529,298 @@ 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_period_start = dl_se->period_start;
 	dl_se->dl_boost_held = 1;
+	dl_se->dl_setattr_saved = 0;
+	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);
 }
 #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
@@ -5388,6 +5843,15 @@ 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;
 }
 
 void __getparam_dl(struct task_struct *p, struct sched_attr *attr, unsigned int flags)
@@ -5487,6 +5951,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;
@@ -5500,6 +5965,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] 59+ messages in thread

* [PATCH v11 38/43] sched/deadline: Boost an owner that cannot run on its own reservation
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (36 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 37/43] sched/deadline: Keep the debt of a task across a change of parameters Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  2:17   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 39/43] sched/deadline: Boost an owner throttled after its waiter blocked Mathieu Desnoyers
                   ` (4 subsequent siblings)
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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(): a throttled owner, or one in
its constrained gap, is always boosted. 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 resumed runtime is capped 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.

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     |  36 +++++---
 kernel/sched/deadline.c | 183 +++++++++++++++++++++++++++++++++++-----
 kernel/sched/sched.h    |  17 +++-
 kernel/sched/syscalls.c |   4 +-
 5 files changed, 218 insertions(+), 40 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 fa032d6dc873..c1e043d27b67 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -7961,9 +7961,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)) {
 			/*
@@ -7975,13 +7975,27 @@ 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) &&
 			     !(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);
+				if (!dl_set_donor(&p->dl, pi_task)) {
+					/*
+					 * The donor of the top waiter is @p: @p waits
+					 * on a lock that it owns. End the boost of a
+					 * deadline task, as a deboost does. Another
+					 * task keeps its donor: a deboost would leave
+					 * it in the class with no parameters.
+					 */
+					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);
 				/*
@@ -7990,8 +8004,10 @@ void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
 				 * 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);
+				    dl_waiter_boosts(p, pi_task) &&
+				    dl_set_donor(&p->dl, pi_task)) {
+					if (p->dl.pi_se != &p->dl)
+						dl_boost_start(&p->dl);
 					scope->flags |= ENQUEUE_REPLENISH;
 				}
 			}
diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 1ec7789e81b8..a526497c099c 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.
  */
 static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se)
 {
@@ -107,6 +107,14 @@ 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;
@@ -126,7 +134,15 @@ static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se)
 					       (dl_se->dl_density *
 						(dl_se->deadline - now)) >> BW_SHIFT);
 	} else {
+		/*
+		 * A new period lifts the throttle. A task asleep since
+		 * before the boost still has its replenishment timer armed
+		 * for its old next period: cancel it.
+		 */
 		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;
@@ -179,9 +195,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)
@@ -196,10 +215,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. dl_hold_refilled_boost() holds the
  *    boost of a task that had them.
@@ -264,6 +283,13 @@ void dl_deboost(struct sched_dl_entity *dl_se)
 	if (held && dl_se->runtime <= 0) {
 		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;
@@ -347,6 +373,114 @@ 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) {
+		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))
+			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);
+
+	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->boost_deadline;
+		dl_se->runtime = dl_se->boost_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)
 {
@@ -1644,7 +1778,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);
 	}
 
@@ -5548,10 +5688,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.
@@ -5692,12 +5832,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
@@ -5966,6 +6108,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..f5a4e033f335 100644
--- a/kernel/sched/sched.h
+++ b/kernel/sched/sched.h
@@ -386,24 +386,31 @@ static inline void dl_replace_donor(struct sched_dl_entity *dl_se,
  * put_task_struct() frees it through call_rcu(), and the rq lock holds
  * off the grace period.
  *
+ * The donor of @pi_task can be @dl_se itself: the task of @dl_se then
+ * waits, through @pi_task, on a lock that it owns, while a chain walk is
+ * in progress. Return false then, and leave the donor as it is. Return
+ * true if @dl_se has the donor of @pi_task.
+ *
  * 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,
+static inline bool 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)
+			return false;
 		if (pi_se == dl_se->pi_se)
-			return;
-		if (pi_se == dl_se ||
-		    tryget_task_struct(container_of(pi_se, struct task_struct, dl)))
+			return true;
+		if (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);
+	return true;
 }
 
 /* Make @dl_se its own donor. The caller holds the rq lock of its task. */
@@ -416,6 +423,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
diff --git a/kernel/sched/syscalls.c b/kernel/sched/syscalls.c
index 4f26601f0530..165f407f45b3 100644
--- a/kernel/sched/syscalls.c
+++ b/kernel/sched/syscalls.c
@@ -315,10 +315,8 @@ static inline void __setscheduler_dl_pi(int newprio, int policy,
 	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);
+		if (pi_task && dl_set_donor(&p->dl, pi_task))
 			scope->flags |= ENQUEUE_REPLENISH;
-		}
 	}
 
 	/*
-- 
2.47.3


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

* [PATCH v11 39/43] sched/deadline: Boost an owner throttled after its waiter blocked
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (37 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 38/43] sched/deadline: Boost an owner that cannot run on its own reservation Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 40/43] sched/deadline: Reschedule a running task throttled at its enqueue Mathieu Desnoyers
                   ` (3 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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      | 92 ++++++++++++++++++++++++++++++++++++
 7 files changed, 166 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 b09816977d4e..4088c253a611 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:
@@ -1270,6 +1291,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;
 		}
@@ -1574,6 +1596,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 c1e043d27b67..d0113caa5826 100644
--- a/kernel/sched/core.c
+++ b/kernel/sched/core.c
@@ -8626,6 +8626,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 a526497c099c..7a1beec2d95e 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -481,6 +481,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)
 {
@@ -491,6 +567,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;
@@ -2382,6 +2462,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));
 	}
 }
 
@@ -2554,6 +2637,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))) {
@@ -5899,6 +5988,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;
 }
 
@@ -6131,6 +6222,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] 59+ messages in thread

* [PATCH v11 40/43] sched/deadline: Reschedule a running task throttled at its enqueue
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (38 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 39/43] sched/deadline: Boost an owner throttled after its waiter blocked Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 41/43] sched/deadline: Run a boost held at its first refill on a donor period Mathieu Desnoyers
                   ` (2 subsequent siblings)
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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 7a1beec2d95e..52095e24638c 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -2465,6 +2465,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] 59+ messages in thread

* [PATCH v11 41/43] sched/deadline: Run a boost held at its first refill on a donor period
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (39 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 40/43] sched/deadline: Reschedule a running task throttled at its enqueue Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  2:02   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 42/43] selftests/sched: Test parameter changes in deadline_bw_test Mathieu Desnoyers
  2026-11-26  1:08 ` [PATCH v11 43/43] selftests/sched: Share the helpers of the deadline tests Mathieu Desnoyers
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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 | 70 +++++++++++++++++++++++++++--------------
 1 file changed, 46 insertions(+), 24 deletions(-)

diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
index 52095e24638c..3d573bf812ee 100644
--- a/kernel/sched/deadline.c
+++ b/kernel/sched/deadline.c
@@ -172,26 +172,30 @@ 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 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 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->dl_boost_held)
-		dl_hold_refilled_boost(dl_se);
+	if (!first || !dl_se->dl_runtime || 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);
@@ -563,8 +567,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)
@@ -1663,11 +1668,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
@@ -6002,11 +6009,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
@@ -6016,11 +6026,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;
@@ -6037,6 +6051,14 @@ static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se)
 		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);
+	/*
+	 * 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] 59+ messages in thread

* [PATCH v11 42/43] selftests/sched: Test parameter changes in deadline_bw_test
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (40 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 41/43] sched/deadline: Run a boost held at its first refill on a donor period Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  2026-11-26  2:01   ` sashiko-bot
  2026-11-26  1:08 ` [PATCH v11 43/43] selftests/sched: Share the helpers of the deadline tests Mathieu Desnoyers
  42 siblings, 1 reply; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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

Add 39 cases to deadline_bw_test, for the fixes earlier in this series.
The comment above each case gives its scenario:
- In 24 cases, a task with runtime left changes its parameters, or
  comes back to the class with new ones. In params_swap_overload, two
  tasks pass a large runtime back and forth. This is Example 1 of Tang,
  Anderson and Abeni (RTNS 2021).
- In 11 cases, a lock owner cannot run on its own reservation, so a
  deadline waiter must boost it. In pi_owner_runs_out_later,
  pi_owner_wakes_in_gap_later and pi_owner_handed_off, the owner loses
  its reservation after the waiter blocked. In pi_owner_reboost_loop
  and pi_owners_reboost_loop, a waiter boosts a throttled owner over and
  over. Another deadline task must still get its runtime.
- In 4 cases, a constrained task leaves the class in its gap and comes
  back. The gap is the time between its deadline and its next period.

These cases fail on v7.4-rc2, in each of two VMs of 8 CPUs. In the
series, each one fails at the patch before the fix named, and passes
from that fix on:
- "sched/deadline: Cap the runtime left of a constrained task at
  dl_runtime": wake_constrained_new_params.
- "sched/deadline: Check the runtime of a task that comes back
  runnable": return_running_new_params.
- "sched/deadline: Keep the debt of a task across a change of
  parameters": change_running_new_params, change_boosted_new_params,
  constrained_gap_change_running, change_constrained_new_params,
  setattr_blocked_new_period, period_grown_untouched,
  deadline_widened_asleep, period_shrunk_throttled,
  period_shrunk_throttled_started, runtime_raised_waited,
  deboost_out_new_params and params_swap_overload.
- "sched/deadline: Boost an owner that cannot run on its own
  reservation": pi_owner_asleep_in_gap, pi_owner_throttled,
  pi_owner_throttled_asleep and pi_owner_held_new_params.
- "sched/deadline: Boost an owner throttled after its waiter blocked":
  pi_owner_runs_out_later, pi_owner_wakes_in_gap_later and
  pi_owner_handed_off.

These cases pass on v7.4-rc2 and with the whole series. A wrong
version of the fix named would fail them:
- "sched/deadline: Keep the debt of a task across a change of
  parameters": deboost_asleep_new_params, setattr_blocked_reenter,
  deadline_grows_running, period_shrunk_running, period_grown_running,
  params_flip_no_gain, period_shrunk_no_burst,
  wake_after_deadline_shrunk and constrained_after_job.
- "sched/deadline: Boost an owner that cannot run on its own
  reservation": pi_owner_throttled_rival, pi_owner_held_long,
  pi_owner_reboost_loop and pi_owners_reboost_loop. In the series
  before that fix, pi_owner_throttled_rival failed in some runs. The
  last two failed on an earlier version of the fix, in which each boost
  started a new period of the waiter.

deboost_new_params_reboost passes on v7.4-rc2, and at each patch of
this series. On v7.4-rc2, a task made SCHED_DEADLINE while it waits on a
PI mutex keeps a deadline of 0. So it boosts the owner in any case.
From "sched/deadline: Start a period for a task that enters the class
blocked" on, that task gets a real deadline. The case then checks the
deboost of "sched/deadline: Keep the debt of a task across a change of
parameters". The debt moves the owner's deadline after the waiter's.
The deboost must then boost the owner again.

The four reenter_*_in_gap cases pass on v7.4-rc2. On the first
series, they fail from these patches on:
- "sched/deadline: Reset the deadline and the runtime with the
  parameters": reenter_runnable_in_gap.
- "sched/deadline: Release the bandwidth of a task that leaves the class
  asleep": reenter_asleep_in_gap, reenter_asleep_late_in_gap and
  reenter_pi_blocked_in_gap.
Three of them pass from "sched/deadline: Count the 0-lag time from the
next period" on. reenter_asleep_late_in_gap passes from
"sched/deadline: Keep a departing constrained task until its next
period" on.

The cases run in P, a one-CPU partition root. The harness now waits
after each case, for up to 10s. It waits until the total_bw of P's CPU
comes back down to its value before the case. A task of a case can keep
its bandwidth counted after it exits, until its 0-lag time.
params_swap_overload leaves a debt that takes seconds to repay.
random_mix runs right after it. Without the wait, random_mix failed in
most runs: the this_bw it read dropped when that debt was repaid.

With the whole series, every case passes, PREEMPT_RT included. No
kernel warning is logged.

Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
 .../sched/deadline/deadline_bw_test.c         | 3645 ++++++++++++++++-
 1 file changed, 3608 insertions(+), 37 deletions(-)

diff --git a/tools/testing/selftests/sched/deadline/deadline_bw_test.c b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
index 83dd8b4e79a3..78b58888e9d5 100644
--- a/tools/testing/selftests/sched/deadline/deadline_bw_test.c
+++ b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
@@ -32,7 +32,9 @@
  *
  * The cases of p_cases[] run with P, a partition root of the last
  * housekeeping CPU. P is made anew for each case. Making it rebuilds the
- * accounting, which clears what an earlier case left.
+ * accounting, which clears what an earlier case leaked. A task that exits
+ * stays counted until its 0-lag time: run_p_cases() waits for that after
+ * each case.
  *
  * The cases of hp_cases[] run after them, without P. These are the
  * hotplug cases, and ten other cases: mask_out_refused,
@@ -58,6 +60,7 @@
 #include <fcntl.h>
 #include <limits.h>
 #include <pthread.h>
+#include <sys/klog.h>
 #include <sched.h>
 #include <semaphore.h>
 #include <signal.h>
@@ -284,6 +287,20 @@ static int set_deadline(pid_t tid, uint64_t runtime, uint64_t period)
 	return set_deadline_flags(tid, runtime, period, 0);
 }
 
+/* Make @tid a deadline task with a relative deadline shorter than @period. */
+static int set_constrained(pid_t tid, uint64_t runtime, uint64_t deadline, uint64_t period)
+{
+	struct dl_attr attr = {
+		.size = sizeof(attr),
+		.sched_policy = SCHED_DEADLINE,
+		.sched_runtime = runtime,
+		.sched_deadline = deadline,
+		.sched_period = period,
+	};
+
+	return syscall(SYS_sched_setattr, tid, &attr, 0) ? -errno : 0;
+}
+
 static int set_other(pid_t tid)
 {
 	struct dl_attr attr = { .size = sizeof(attr), .sched_policy = SCHED_OTHER };
@@ -2602,6 +2619,163 @@ static int deboost_in_asleep_after_refill(void)
 	return ret;
 }
 
+static sem_t nps_wake;
+static _Atomic pid_t nps_o_tid;
+static _Atomic uint64_t nps_t0;
+
+/*
+ * Run as the owner O of deboost_out_new_params(). Its comment has the
+ * steps. Return NULL, or 1 on an error.
+ */
+static void *nps_owner(void *arg)
+{
+	uint64_t t0;
+	int err;
+
+	nps_o_tid = gettid_();
+	err = set_deadline(0, 5 * NSEC_PER_MSEC, PERIOD);
+	nps_t0 = now_ns();
+	if (err || take_pi_lock()) {
+		if (err)
+			ksft_print_msg("the owner refused as a deadline task: %s\n",
+				       strerror(-err));
+		sem_post(&inas_locked);
+		set_other(0);
+		return (void *)1;
+	}
+	sem_post(&inas_locked);
+	t0 = now_ns();
+	while (!inas_locking || proc_state_of(inas_d_tid) != 'S') {
+		if (now_ns() - t0 > NSEC_PER_SEC) {
+			ksft_print_msg("the donor did not block on the lock\n");
+			drop_pi_lock();
+			set_other(0);
+			return (void *)1;
+		}
+	}
+	spin_ns(4 * NSEC_PER_MSEC);
+	sem_wait_sig(&nps_wake);
+	drop_pi_lock();
+	set_other(0);
+	return NULL;
+}
+
+/*
+ * A boosted task changes its parameters before any refill, then leaves
+ * the class at its deboost. O and D share the CPU of P:
+ * 1. D becomes a deadline task of 2ms every 50ms, and waits.
+ * 2. O becomes a deadline task of 5ms every 100ms, at 0ms. It takes
+ *    pi_lock.
+ * 3. D waits 30ms for pi_lock. Its deadline is the earlier one: it boosts
+ *    O.
+ * 4. O runs 4ms, within its own runtime, and sleeps, boosted. Its 0-lag
+ *    time is at 100 - 1 * 100 / 5 = 80ms.
+ * 5. The main thread changes O to 5ms every 200ms, then switches O to
+ *    SCHED_OTHER. The boost keeps O in the class.
+ * 6. D times out at about 30ms. O leaves the class at its deboost.
+ *
+ * At the deboost, at 30ms, O has used 4ms. Its old bandwidth of 5% gave
+ * it 1.5ms by then. So O has a debt of 2.5ms. The new bandwidth of 2.5%
+ * repays that at 130ms. O's bandwidth must stay in total_bw until then.
+ * Mixing the runtime and the deadline of the old parameters with the new
+ * ones would put its 0-lag time at 200 - 1 * 200 / 5 = 160ms. The case
+ * reads total_bw at 115ms and at 145ms.
+ */
+static int deboost_out_new_params(void)
+{
+	long long base, with_o = -1, early = -1, late = -1;
+	void *o_ret = NULL, *d_ret = NULL;
+	int err, out = 0, ret = KSFT_FAIL;
+	pthread_t o, d;
+
+	if (total_bw_of(top_cpu(1)) < 0) {
+		ksft_print_msg("sched_debug tells of no total_bw\n");
+		return KSFT_SKIP;
+	}
+	if (pi_init())
+		return KSFT_SKIP;
+	if (sem_init(&inas_ready, 0, 0) || sem_init(&inas_locked, 0, 0) ||
+	    sem_init(&inas_out, 0, 0) || sem_init(&inas_read, 0, 0) ||
+	    sem_init(&nps_wake, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		pi_fini();
+		return KSFT_SKIP;
+	}
+	inas_locking = 0;
+	inas_d_tid = 0;
+	nps_o_tid = 0;
+	if (pthread_create(&d, NULL, inas_donor, NULL)) {
+		ksft_print_msg("the donor thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&inas_ready, 5000)) {
+		sem_post(&inas_locked);
+		sem_post(&inas_read);
+		join(d);
+		goto out;
+	}
+	base = total_bw_of(top_cpu(1));	/* with D, without O */
+	if (pthread_create(&o, NULL, nps_owner, NULL)) {
+		ksft_print_msg("the owner thread could not start\n");
+		sem_post(&inas_locked);
+		sem_post(&inas_read);
+		join(d);
+		goto out;
+	}
+	if (wait_for(1000, inas_locking && proc_state_of(inas_d_tid) == 'S' &&
+		     nps_o_tid && proc_state_of(nps_o_tid) == 'S')) {
+		ksft_print_msg("the owner did not sleep boosted\n");
+	} else {
+		err = set_deadline(nps_o_tid, 5 * NSEC_PER_MSEC, 2 * PERIOD);
+		if (!err)
+			with_o = total_bw_of(top_cpu(1));
+		if (!err)
+			err = set_other(nps_o_tid);
+		if (!err && sem_getvalue(&inas_out, &out))
+			out = -1;
+		if (err)
+			ksft_print_msg("the owner cannot change its parameters: %s\n",
+				       strerror(-err));
+		else if (out)
+			ksft_print_msg("the donor timed out before the change\n");
+		else if (sem_wait_for(&inas_out, 5000))
+			ksft_print_msg("the donor did not time out\n");
+		else {
+			while (now_ns() - nps_t0 < 115 * NSEC_PER_MSEC)
+				sleep_ns(NSEC_PER_MSEC);
+			early = total_bw_of(top_cpu(1));
+			while (now_ns() - nps_t0 < 145 * NSEC_PER_MSEC)
+				sleep_ns(NSEC_PER_MSEC);
+			late = total_bw_of(top_cpu(1));
+		}
+	}
+	sem_post(&inas_read);
+	pthread_join(d, &d_ret);
+	sem_post(&nps_wake);
+	pthread_join(o, &o_ret);
+	if (o_ret || d_ret || late < 0)
+		goto out;	/* a thread said why */
+	if (early != with_o) {
+		ksft_print_msg("total_bw %lld at 115 ms, %lld expected: %s\n", early,
+			       with_o, "O left before it repaid its debt");
+		goto out;
+	}
+	if (late != base) {
+		ksft_print_msg("total_bw %lld at 145 ms, %lld expected: %s\n", late,
+			       base, "O stayed after it repaid its debt");
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&inas_ready);
+	sem_destroy(&inas_locked);
+	sem_destroy(&inas_out);
+	sem_destroy(&inas_read);
+	sem_destroy(&nps_wake);
+	pi_fini();
+	return ret;
+}
+
 static _Atomic uint32_t rq_cond, rq_pi;
 static atomic_int rq_order, rq_w_rank, rq_x_rank, rq_x_locking;
 static _Atomic pid_t rq_w_tid, rq_x_tid;
@@ -2754,17 +2928,30 @@ static _Atomic pid_t ret_tid;
 static atomic_int ret_first_period_ms;
 
 /*
- * Run as the thread of return_asleep_new_params(). Become a deadline task
- * of 50ms every 100ms and run 20ms. 30ms of runtime are left, and the
- * 0-lag time is about 20ms ahead. Then sleep. The main thread switches
- * the thread to SCHED_OTHER and back, with 10ms every 100ms. Then spin
- * for 100ms, and store the CPU time used, in ms, in ret_first_period_ms.
- * Return NULL, or 1 on an error.
+ * Run as the thread of the return cases. Become a deadline task of 50ms
+ * every 100ms and run 20ms. 30ms of runtime are left, and the 0-lag time
+ * is about 20ms ahead. Then change to new parameters, as @arg says:
+ * - 0: the thread switches itself to SCHED_OTHER and back to
+ *   SCHED_DEADLINE, while it runs.
+ * - 1: the thread sleeps. The main thread switches it to SCHED_OTHER and
+ *   back.
+ * - 2: the thread changes its own parameters while it runs. It stays in
+ *   SCHED_DEADLINE.
+ * - 3: as 2, while a donor boosts the thread. The thread takes pi_lock and
+ *   wakes the donor up. The donor blocks on pi_lock. The thread then
+ *   changes its parameters, and unlocks.
+ * - 4: as 2, to a constrained deadline: 8ms in 20ms, every 100ms.
+ * - 5: the thread sleeps. The main thread changes it to 8ms in 20ms,
+ *   every 100ms.
+ * The new parameters are 10ms every 100ms, except in modes 4 and 5.
+ * Then spin for 100ms, and store the CPU time used, in ms, in
+ * ret_first_period_ms. Return NULL, or 1 on an error.
  */
 static void *returner(void *arg)
 {
+	long mode = (long)arg;
 	uint64_t t0, cpu0;
-	int err;
+	int err = 0;
 
 	ret_tid = gettid_();
 	err = set_deadline(0, 50 * NSEC_PER_MSEC, PERIOD);
@@ -2773,8 +2960,34 @@ static void *returner(void *arg)
 		return (void *)1;
 	}
 	spin_ns(20 * NSEC_PER_MSEC);
-	sem_post(&ret_ready);
-	sem_wait_sig(&ret_go);
+	if (mode == 1 || mode == 5) {
+		sem_post(&ret_ready);
+		sem_wait_sig(&ret_go);
+	} else if (mode == 4) {
+		err = set_constrained(0, 8 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, PERIOD);
+	} else if (mode == 3) {
+		if (take_pi_lock())
+			return (void *)1;
+		sem_post(&owner_go);
+		t0 = now_ns();
+		while (!refill_donor_locking || proc_state_of(donor_tid) != 'S') {
+			if (now_ns() - t0 > NSEC_PER_SEC) {
+				ksft_print_msg("the donor did not block on the lock\n");
+				drop_pi_lock();
+				return (void *)1;
+			}
+		}
+		err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+		drop_pi_lock();
+	} else {
+		err = mode ? 0 : set_other(0);
+		if (!err)
+			err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	}
+	if (err) {
+		ksft_print_msg("the task could not change: %s\n", strerror(-err));
+		return (void *)1;
+	}
 	t0 = now_ns();
 	cpu0 = thread_time_ns();
 	while (now_ns() - t0 < PERIOD)
@@ -2784,46 +2997,80 @@ static void *returner(void *arg)
 }
 
 /*
- * A task leaves SCHED_DEADLINE while it sleeps, and comes back at once
- * with a smaller runtime. Its 0-lag time is ahead, so it keeps its
- * deadline and the runtime it has left. returner() runs the task. It must
- * get about 10ms of CPU time in the 100ms after the change: its new
- * runtime, not the 30ms left from the old one. The case fails above 20ms.
+ * Run a return case: returner() with @mode as its argument. The thread
+ * must get about 10ms of CPU time in the 100ms after the change, 8ms in
+ * modes 4 and 5. That is its new runtime, not the 30ms left from the old
+ * one. The case fails above 20ms.
  */
-static int return_asleep_new_params(void)
+static int return_case(long mode)
 {
-	void *t_ret;
+	void *t_ret = NULL, *d_ret = NULL;
 	int err, ret = KSFT_PASS;
-	pthread_t t;
+	pthread_t t, d;
 
 	if (sem_init(&ret_ready, 0, 0) || sem_init(&ret_go, 0, 0)) {
 		ksft_print_msg("sem_init: %s\n", strerror(errno));
 		return KSFT_FAIL;
 	}
 	ret_first_period_ms = -1;
-	if (pthread_create(&t, NULL, returner, NULL)) {
+	if (mode == 3) {
+		/* The donor: a deadline task of 2ms every 10ms */
+		if (pi_init() || sem_init(&refill_donor_ready, 0, 0))
+			return KSFT_SKIP;
+		refill_donor_locking = 0;
+		donor_tid = 0;
+		if (pthread_create(&d, NULL, refill_donor, NULL)) {
+			ksft_print_msg("the donor thread could not start\n");
+			return KSFT_FAIL;
+		}
+		if (sem_wait_for(&refill_donor_ready, 5000) || donor_tid <= 0) {
+			ksft_print_msg("the donor is not ready\n");
+			sem_post(&owner_go);
+			join(d);
+			return KSFT_FAIL;
+		}
+	}
+	if (pthread_create(&t, NULL, returner, (void *)mode)) {
 		ksft_print_msg("the task thread could not start\n");
+		if (mode == 3) {
+			sem_post(&owner_go);
+			join(d);
+		}
 		return KSFT_FAIL;
 	}
-	if (sem_wait_for(&ret_ready, 5000)) {
-		/* The thread may get there late. Let it end. */
+	if (mode == 1 || mode == 5) {
+		if (sem_wait_for(&ret_ready, 5000)) {
+			/* The thread may get there late. Let it end. */
+			sem_post(&ret_go);
+			join(t);
+			return KSFT_FAIL;	/* the task said why */
+		}
+		/* Before its 0-lag time, about 20ms ahead */
+		err = wait_for(10, proc_state_of(ret_tid) == 'S') ? -EAGAIN : 0;
+		if (!err && mode == 1)
+			err = set_other(ret_tid);
+		if (!err && mode == 1)
+			err = set_deadline(ret_tid, 10 * NSEC_PER_MSEC, PERIOD);
+		if (!err && mode == 5)
+			err = set_constrained(ret_tid, 8 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC,
+					      PERIOD);
 		sem_post(&ret_go);
-		join(t);
-		return KSFT_FAIL;	/* the task said why */
-	}
-	/* Before its 0-lag time, about 20ms ahead */
-	err = wait_for(10, proc_state_of(ret_tid) == 'S') ? -EAGAIN : 0;
-	if (!err)
-		err = set_other(ret_tid);
-	if (!err)
-		err = set_deadline(ret_tid, 10 * NSEC_PER_MSEC, PERIOD);
-	sem_post(&ret_go);
-	if (err) {
-		ksft_print_msg("the task could not change asleep: %s\n", strerror(-err));
-		join(t);
-		return KSFT_FAIL;
+		if (err) {
+			ksft_print_msg("the task could not change asleep: %s\n",
+				       strerror(-err));
+			join(t);
+			return KSFT_FAIL;
+		}
 	}
 	err = pthread_join(t, &t_ret);
+	if (mode == 3) {
+		if (t_ret)
+			sem_post(&owner_go);	/* the task never woke the donor up */
+		if (pthread_join(d, &d_ret) || d_ret)
+			ret = KSFT_FAIL;
+		pi_fini();
+		sem_destroy(&refill_donor_ready);
+	}
 	if (err) {
 		ksft_print_msg("pthread_join: %s\n", strerror(err));
 		ret = KSFT_FAIL;
@@ -2839,6 +3086,3008 @@ static int return_asleep_new_params(void)
 	return ret;
 }
 
+/*
+ * A running task leaves SCHED_DEADLINE and comes back at once with a
+ * smaller runtime. Its 0-lag time is ahead, so it keeps its deadline and
+ * the runtime it has left. It must not run on more than the new runtime.
+ */
+static int return_running_new_params(void)
+{
+	return return_case(0);
+}
+
+/* The same, for a task that leaves and comes back while it sleeps. */
+static int return_asleep_new_params(void)
+{
+	return return_case(1);
+}
+
+/* The same, for a task that changes its parameters within the class. */
+static int change_running_new_params(void)
+{
+	return return_case(2);
+}
+
+/*
+ * The same, for a task that changes its parameters while a donor boosts
+ * it. The donor is a deadline task of 2ms every 10ms. Its deadline is the
+ * earlier one, so the task runs on its own runtime while boosted. The
+ * unlock ends the boost. The runtime left must then be checked against
+ * the new parameters.
+ */
+static int change_boosted_new_params(void)
+{
+	return return_case(3);
+}
+
+/*
+ * A running task of 50ms every 100ms has 30ms left. It changes itself to
+ * 8ms in 20ms, every 100ms. Its deadline stays 80ms ahead, further than
+ * the new 20ms. The check of the runtime left uses the new density over
+ * those 80ms. That allows 32ms, so the check keeps the 30ms. The task
+ * must keep no more than its new 8ms.
+ */
+static int change_constrained_new_params(void)
+{
+	return return_case(4);
+}
+
+/*
+ * The same, for a task that the main thread changes while it sleeps. The
+ * check is at its wakeup.
+ */
+static int wake_constrained_new_params(void)
+{
+	return return_case(5);
+}
+
+static sem_t shrink_ready;
+static _Atomic pid_t shrink_tid;
+static _Atomic unsigned long long shrink_t0;
+static _Atomic long long shrink_back_ms;
+
+/*
+ * Run as T of wake_after_deadline_shrunk(). Its comment has the steps.
+ * Store in shrink_back_ms the time at which T runs after its sleep.
+ * Return NULL, or 1 on an error.
+ */
+static void *shrink_t(void *arg)
+{
+	struct timespec ts;
+	uint64_t t0, end;
+	int err;
+
+	shrink_tid = gettid_();
+	err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	t0 = now_ns();
+	shrink_t0 = t0;
+	sem_post(&shrink_ready);
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	spin_ns(NSEC_PER_MSEC);
+	end = t0 + 110 * NSEC_PER_MSEC;
+	ts.tv_sec = end / NSEC_PER_SEC;
+	ts.tv_nsec = end % NSEC_PER_SEC;
+	while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR)
+		;
+	shrink_back_ms = (now_ns() - t0) / NSEC_PER_MSEC;
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Shorten the relative deadline of a task asleep past its deadline:
+ * 1. T makes itself a deadline task of 10ms every 100ms, at 0ms. Its
+ *    deadline is 100ms. It runs 1ms, and sleeps until 110ms.
+ * 2. At 105ms, the main thread changes T to 10ms in 20ms, every 100ms.
+ * 3. T wakes up at 110ms.
+ *
+ * T's job ran. It counts as a job of the new parameters with the same
+ * deadline, released at 100 - 20 = 80ms. So T's next period starts at
+ * 80 + 100 = 180ms, and T runs then. A new period at the wakeup would
+ * start only 30ms after the release of the job that ran. That is less
+ * than a period of the new parameters. The case fails if T runs before
+ * 170ms or at 200ms or later.
+ */
+static int wake_after_deadline_shrunk(void)
+{
+	void *t_ret = NULL;
+	int err, ret = KSFT_FAIL;
+	uint64_t at;
+	pthread_t t;
+
+	if (sem_init(&shrink_ready, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	shrink_back_ms = -1;
+	if (pthread_create(&t, NULL, shrink_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&shrink_ready, 5000)) {
+		join(t);
+		goto out;
+	}
+	at = shrink_t0 + 105 * NSEC_PER_MSEC;
+	while (now_ns() < at)
+		sleep_ns(NSEC_PER_MSEC);
+	if (proc_state_of(shrink_tid) != 'S') {
+		ksft_print_msg("T is not asleep at 105ms\n");
+		join(t);
+		goto out;
+	}
+	err = set_constrained(shrink_tid, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC,
+			      PERIOD);
+	if (err) {
+		ksft_print_msg("T could not change asleep: %s\n", strerror(-err));
+		join(t);
+		goto out;
+	}
+	pthread_join(t, &t_ret);
+	if (t_ret || shrink_back_ms < 0)
+		goto out;	/* T said why */
+	if (shrink_back_ms < 170 || shrink_back_ms >= 200) {
+		ksft_print_msg("T ran again at %lld ms, not at 180\n",
+			       (long long)shrink_back_ms);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&shrink_ready);
+	return ret;
+}
+
+static sem_t widen_ready;
+static _Atomic pid_t widen_tid;
+static _Atomic unsigned long long widen_t0;
+static _Atomic long long widen_used_us;
+
+/*
+ * Run as T of deadline_widened_asleep(). Its comment has the steps.
+ * Store in widen_used_us the CPU time that T gets from 30ms to 95ms.
+ * Return NULL, or 1 on an error.
+ */
+static void *widen_t(void *arg)
+{
+	struct timespec ts;
+	uint64_t t0, end, cpu0;
+	int err;
+
+	widen_tid = gettid_();
+	err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, PERIOD);
+	t0 = now_ns();
+	widen_t0 = t0;
+	sem_post(&widen_ready);
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	spin_ns(8 * NSEC_PER_MSEC);
+	end = t0 + 30 * NSEC_PER_MSEC;
+	ts.tv_sec = end / NSEC_PER_SEC;
+	ts.tv_nsec = end % NSEC_PER_SEC;
+	while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR)
+		;
+	cpu0 = thread_time_ns();
+	while (now_ns() < t0 + 95 * NSEC_PER_MSEC)
+		;
+	widen_used_us = (thread_time_ns() - cpu0) / NSEC_PER_USEC;
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Widen the relative deadline of a task asleep in its period:
+ * 1. T becomes a deadline task of 10ms in 20ms, every 100ms, at 0ms. It
+ *    spins 8ms and sleeps until 30ms.
+ * 2. At 25ms, the main thread changes T to 10ms every 100ms. T's deadline
+ *    is now 100ms. It has 2ms of runtime left.
+ * 3. T wakes up at 30ms and spins until 95ms.
+ *
+ * T must get about its 2ms left before 100ms. If its deadline stayed at
+ * 20ms, it would have passed at the wakeup. T would then get a new period
+ * of 10ms. The case fails if T gets 5ms of CPU time or more.
+ */
+static int deadline_widened_asleep(void)
+{
+	void *t_ret = NULL;
+	int err, ret = KSFT_FAIL;
+	uint64_t at;
+	pthread_t t;
+
+	if (sem_init(&widen_ready, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	widen_used_us = -1;
+	if (pthread_create(&t, NULL, widen_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&widen_ready, 5000)) {
+		join(t);
+		goto out;
+	}
+	at = widen_t0 + 25 * NSEC_PER_MSEC;
+	while (now_ns() < at)
+		sleep_ns(NSEC_PER_MSEC);
+	if (proc_state_of(widen_tid) != 'S') {
+		ksft_print_msg("T is not asleep at 25ms\n");
+		join(t);
+		goto out;
+	}
+	err = set_deadline(widen_tid, 10 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("T could not change asleep: %s\n", strerror(-err));
+		join(t);
+		goto out;
+	}
+	pthread_join(t, &t_ret);
+	if (t_ret || widen_used_us < 0)
+		goto out;	/* T said why */
+	if (widen_used_us >= 5000) {
+		ksft_print_msg("T got %lld us before its deadline, with 2ms left\n",
+			       (long long)widen_used_us);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&widen_ready);
+	return ret;
+}
+
+/*
+ * The kernel prints this when a refill finds a deadline long passed. It
+ * prints it once per boot, so a case can see it only if no earlier test
+ * caused it.
+ */
+#define DL_LAG_MSG	"sched: DL replenish lagged too much"
+
+/*
+ * Return 1 if the kernel log holds @s, 0 if it does not, or -1 if it
+ * cannot be read.
+ */
+static int klog_has(const char *s)
+{
+	int len = klogctl(10, NULL, 0);		/* SYSLOG_ACTION_SIZE_BUFFER */
+	char *buf;
+	int n, ret;
+
+	if (len <= 0)
+		return -1;
+	buf = malloc(len + 1);
+	if (!buf)
+		return -1;
+	n = klogctl(3, buf, len);		/* SYSLOG_ACTION_READ_ALL */
+	ret = -1;
+	if (n >= 0) {
+		buf[n] = '\0';
+		ret = !!strstr(buf, s);
+	}
+	free(buf);
+	return ret;
+}
+
+static sem_t shorten_ready;
+static _Atomic pid_t shorten_tid;
+static _Atomic unsigned long long shorten_t0;
+static _Atomic long long shorten_back_ms;
+
+/*
+ * Run as T of period_shrunk_throttled(). Its comment has the steps. Store
+ * in shorten_back_ms the time at which T runs after its yield. Return
+ * NULL, or 1 on an error.
+ */
+static void *shorten_t(void *arg)
+{
+	uint64_t t0;
+	int err;
+
+	shorten_tid = gettid_();
+	err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	t0 = now_ns();
+	shorten_t0 = t0;
+	sem_post(&shorten_ready);
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	spin_ns(8 * NSEC_PER_MSEC);
+	sched_yield();
+	shorten_back_ms = (now_ns() - t0) / NSEC_PER_MSEC;
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Shorten the period of a task throttled until its next period:
+ * 1. T becomes a deadline task of 10ms every 100ms, at 0ms. It runs 8ms
+ *    and yields. Its replenishment timer is armed at 100ms.
+ * 2. At @at_ms, the main thread changes T to 10ms every @period_ms.
+ *
+ * T ran ahead of its share: its 0-lag time is at 80ms. The change keeps
+ * that debt, and repays it at the new bandwidth. T's next period starts
+ * once it is repaid. The timer must be armed again there. T must run
+ * again at @back_ms: the case fails 5ms before it, or 30ms after it. A
+ * refill at 100ms would also find a period that ended before, and print
+ * "sched: DL replenish lagged too much". The case fails if that message
+ * is logged. It skips if the message was logged before: the kernel prints
+ * it once.
+ */
+static int shorten_case(int at_ms, int period_ms, int back_ms)
+{
+	void *t_ret = NULL;
+	int err, had, ret = KSFT_FAIL;
+	uint64_t at;
+	pthread_t t;
+
+	had = klog_has(DL_LAG_MSG);
+	if (had) {
+		ksft_print_msg(had < 0 ? "the kernel log cannot be read\n" :
+			       "the lag message was logged before this case\n");
+		return KSFT_SKIP;
+	}
+	if (sem_init(&shorten_ready, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	shorten_back_ms = -1;
+	if (pthread_create(&t, NULL, shorten_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&shorten_ready, 5000)) {
+		join(t);
+		goto out;
+	}
+	at = shorten_t0 + at_ms * NSEC_PER_MSEC;
+	while (now_ns() < at)
+		sleep_ns(NSEC_PER_MSEC);
+	err = set_deadline(shorten_tid, 10 * NSEC_PER_MSEC, period_ms * NSEC_PER_MSEC);
+	if (err) {
+		ksft_print_msg("T could not change throttled: %s\n", strerror(-err));
+		join(t);
+		goto out;
+	}
+	pthread_join(t, &t_ret);
+	if (t_ret || shorten_back_ms < 0)
+		goto out;	/* T said why */
+	if (shorten_back_ms < back_ms - 5 || shorten_back_ms >= back_ms + 30) {
+		ksft_print_msg("T ran again at %lld ms, not at its next period at %d\n",
+			       (long long)shorten_back_ms, back_ms);
+		goto out;
+	}
+	if (klog_has(DL_LAG_MSG) == 1) {
+		ksft_print_msg("the refill logged \"%s\"\n", DL_LAG_MSG);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&shorten_ready);
+	return ret;
+}
+
+/*
+ * Shorten the period of a throttled task: shorten_case() with a change at
+ * 30ms to a period of 50ms. T then owes 5ms, repaid at 20% in 25ms. T
+ * must run again at 55ms.
+ */
+static int period_shrunk_throttled(void)
+{
+	return shorten_case(30, 50, 55);
+}
+
+/*
+ * Shorten the period of a throttled task, later in its period:
+ * shorten_case() with a change at 60ms to a period of 20ms. T then owes
+ * 2ms, repaid at 50% in 4ms. T must run again at 64ms.
+ */
+static int period_shrunk_throttled_started(void)
+{
+	return shorten_case(60, 20, 64);
+}
+
+/* The kinds of period_rule_case() */
+enum { PR_SHRUNK, PR_GROWN, PR_UNTOUCHED, PR_RAISED };
+
+static sem_t pr_h_ready, pr_h_go;
+static atomic_int pr_h_err;
+static int pr_kind;
+static _Atomic long long pr_pre_cpu_ms, pr_mark_ms, pr_done_ms;
+
+/*
+ * Run as H of period_rule_case(). Become a deadline task with a deadline
+ * earlier than T's, and wait for pr_h_go. Then keep the CPU: 5ms with
+ * PR_UNTOUCHED, 60ms with PR_RAISED. Return NULL, or 1 on an error.
+ */
+static void *pr_h(void *arg)
+{
+	int err;
+
+	if (pr_kind == PR_UNTOUCHED)
+		err = set_constrained(0, 6 * NSEC_PER_MSEC, 10 * NSEC_PER_MSEC, PERIOD);
+	else
+		err = set_constrained(0, 62 * NSEC_PER_MSEC, 65 * NSEC_PER_MSEC, PERIOD);
+	pr_h_err = err;
+	sem_post(&pr_h_ready);
+	if (err) {
+		ksft_print_msg("H refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	sem_wait_sig(&pr_h_go);
+	spin_ns((pr_kind == PR_UNTOUCHED ? 5 : 60) * NSEC_PER_MSEC);
+	if (set_other(0))
+		ksft_print_msg("H cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run as T of period_rule_case(). The comments of the cases have the
+ * steps. Store the times of T's marks in pr_mark_ms and pr_done_ms, and
+ * the CPU time T used before its change in pr_pre_cpu_ms. Return NULL, or
+ * 1 on an error.
+ */
+static void *pr_t(void *arg)
+{
+	uint64_t ms = NSEC_PER_MSEC, t0, c0;
+	int err;
+
+	if (pr_kind == PR_RAISED)
+		err = set_deadline(0, 10 * ms, PERIOD);
+	else
+		err = set_constrained(0, 10 * ms, 20 * ms,
+				      pr_kind == PR_SHRUNK ? PERIOD : PERIOD / 2);
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		sem_post(&pr_h_go);
+		return (void *)1;
+	}
+	t0 = now_ns();
+	c0 = thread_time_ns();
+	switch (pr_kind) {
+	case PR_SHRUNK:
+	case PR_GROWN:
+		spin_ns(3 * ms);
+		break;
+	case PR_UNTOUCHED:
+		/* H preempts T here, for 5ms. */
+		sem_post(&pr_h_go);
+		while (now_ns() - t0 < 4 * ms)
+			;
+		break;
+	case PR_RAISED:
+		spin_ns(2 * ms);
+		/* H preempts T here, for 60ms. */
+		sem_post(&pr_h_go);
+		while (now_ns() - t0 < 55 * ms)
+			;
+		break;
+	}
+	pr_pre_cpu_ms = (thread_time_ns() - c0) / ms;
+	if (pr_kind == PR_RAISED)
+		err = set_deadline(0, 15 * ms, PERIOD);
+	else
+		err = set_constrained(0, 10 * ms, 20 * ms,
+				      pr_kind == PR_SHRUNK ? PERIOD / 2 : PERIOD);
+	if (err) {
+		ksft_print_msg("T could not change: %s\n", strerror(-err));
+		set_other(0);
+		return (void *)1;
+	}
+	switch (pr_kind) {
+	case PR_SHRUNK:
+		spin_ns(9 * ms);
+		break;
+	case PR_GROWN:
+		spin_ns(4 * ms);
+		pr_mark_ms = (now_ns() - t0) / ms;
+		spin_ns(5 * ms);
+		break;
+	case PR_UNTOUCHED:
+		spin_ns(9 * ms);
+		break;
+	case PR_RAISED:
+		spin_ns(12 * ms);
+		break;
+	}
+	pr_done_ms = (now_ns() - t0) / ms;
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run a case where T changes its own parameters while it runs. P has one
+ * CPU. With PR_UNTOUCHED and PR_RAISED, a deadline task H first keeps T
+ * off the CPU: H has the earlier deadline. So T has more runtime left than
+ * a wakeup at that time would give it. H sleeps more than its period
+ * before T wakes it: its wakeup then starts a new period.
+ */
+static int period_rule_case(int kind)
+{
+	int with_h = kind == PR_UNTOUCHED || kind == PR_RAISED;
+	void *h_ret = NULL, *t_ret = NULL;
+	int ret = KSFT_FAIL;
+	pthread_t h, t;
+
+	if (sem_init(&pr_h_ready, 0, 0) || sem_init(&pr_h_go, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	pr_kind = kind;
+	pr_pre_cpu_ms = -1;
+	pr_mark_ms = -1;
+	pr_done_ms = -1;
+	if (with_h) {
+		if (pthread_create(&h, NULL, pr_h, NULL)) {
+			ksft_print_msg("the H thread could not start\n");
+			goto out;
+		}
+		if (sem_wait_for(&pr_h_ready, 5000) || pr_h_err) {
+			sem_post(&pr_h_go);
+			join(h);
+			goto out;	/* H said why */
+		}
+		sleep_ns(PERIOD + 10 * NSEC_PER_MSEC);
+	}
+	if (pthread_create(&t, NULL, pr_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		t_ret = (void *)1;
+	} else {
+		pthread_join(t, &t_ret);
+	}
+	if (with_h) {
+		sem_post(&pr_h_go);	/* if T never woke H */
+		pthread_join(h, &h_ret);
+	}
+	if (t_ret || h_ret || pr_done_ms < 0)
+		goto out;	/* the thread said why */
+	switch (kind) {
+	case PR_SHRUNK:
+		if (pr_done_ms < 45 || pr_done_ms >= 80) {
+			ksft_print_msg("T ended at %lld ms: its next period is at 50\n",
+				       (long long)pr_done_ms);
+			goto out;
+		}
+		break;
+	case PR_GROWN:
+		if (pr_mark_ms >= 30) {
+			ksft_print_msg("T used 7ms of its runtime by %lld ms\n",
+				       (long long)pr_mark_ms);
+			goto out;
+		}
+		if (pr_done_ms < 95 || pr_done_ms >= 130) {
+			ksft_print_msg("T ended at %lld ms: its next period is at 100\n",
+				       (long long)pr_done_ms);
+			goto out;
+		}
+		break;
+	case PR_UNTOUCHED:
+		if (pr_pre_cpu_ms > 2) {
+			ksft_print_msg("T used %lld ms before its change: H did not delay it\n",
+				       (long long)pr_pre_cpu_ms);
+			goto out;
+		}
+		if (pr_done_ms < 95 || pr_done_ms >= 130) {
+			ksft_print_msg("T ended at %lld ms: its next period is at 100\n",
+				       (long long)pr_done_ms);
+			goto out;
+		}
+		break;
+	case PR_RAISED:
+		if (pr_pre_cpu_ms > 6) {
+			ksft_print_msg("T used %lld ms before its change: H did not delay it\n",
+				       (long long)pr_pre_cpu_ms);
+			goto out;
+		}
+		if (pr_done_ms < 110 || pr_done_ms >= 140) {
+			ksft_print_msg("T ended at %lld ms: its next period is at about 115\n",
+				       (long long)pr_done_ms);
+			goto out;
+		}
+		break;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&pr_h_ready);
+	sem_destroy(&pr_h_go);
+	return ret;
+}
+
+/*
+ * Shorten the period of a running task:
+ * 1. T becomes a deadline task of 10ms in 20ms, every 100ms, at 0ms. It
+ *    spins 3ms.
+ * 2. T changes its period to 50ms, and spins 9ms more. It runs out of
+ *    runtime at about 10ms.
+ *
+ * The period in progress keeps its start. So T's next period starts at
+ * 50ms, and T ends its spin at about 52ms. The case fails if T ends
+ * before 45ms, or at 80ms or later.
+ */
+static int period_shrunk_running(void)
+{
+	return period_rule_case(PR_SHRUNK);
+}
+
+/*
+ * Lengthen the period of a running task:
+ * 1. T becomes a deadline task of 10ms in 20ms, every 50ms, at 0ms. It
+ *    spins 3ms.
+ * 2. T changes its period to 100ms, and spins 4ms more. It then spins
+ *    5ms more, and runs out of runtime at about 10ms.
+ *
+ * The job in progress keeps its deadline, at 20ms: T must end its first
+ * 7ms at once. T's next period starts at 100ms, and T ends at about
+ * 102ms. The case fails if T ends its first 7ms at 30ms or later, or if
+ * it ends before 95ms, or at 130ms or later.
+ */
+static int period_grown_running(void)
+{
+	return period_rule_case(PR_GROWN);
+}
+
+/*
+ * Lengthen the period of a task that has not run yet in its period:
+ * 1. H, a deadline task of 6ms in 10ms, every 100ms, sleeps.
+ * 2. T becomes a deadline task of 10ms in 20ms, every 50ms, at 0ms, and
+ *    wakes H. H has the earlier deadline. It runs for 5ms.
+ * 3. T runs from 5ms, with its 10ms of runtime and 15ms to its deadline.
+ *    It changes its period to 100ms, and spins 9ms.
+ *
+ * T keeps its job, with the runtime that the new density allows before
+ * its deadline: 10ms in 20ms over the 15ms left, 7.5ms. Its next period
+ * is its release plus the new period, at 100ms. T runs 7.5ms, waits, and
+ * ends at about 101ms. The case fails if T ends before 95ms, or at 130ms
+ * or later.
+ */
+static int period_grown_untouched(void)
+{
+	return period_rule_case(PR_UNTOUCHED);
+}
+
+/*
+ * Raise the runtime of a task late in its period:
+ * 1. H, a deadline task of 62ms in 65ms, every 100ms, sleeps.
+ * 2. T becomes a deadline task of 10ms every 100ms, at 0ms. It spins 2ms,
+ *    and wakes H. H has the earlier deadline. It runs for 60ms.
+ * 3. T runs from about 62ms, with 8ms left. It raises its runtime to
+ *    15ms, and spins 12ms.
+ *
+ * T used 2ms by 62ms, less than its share: it has no debt. It keeps its
+ * job and its 8ms. Its next period starts once those 8ms are paid at the
+ * new bandwidth, at about 115ms. T runs its 8ms, waits, and ends at about
+ * 119ms. The case fails if T ends before 110ms, or at 140ms or later.
+ */
+static int runtime_raised_waited(void)
+{
+	return period_rule_case(PR_RAISED);
+}
+
+static atomic_int flip_stop;
+static _Atomic pid_t flip_tid;
+static _Atomic long long flip_cpu_ms;
+static sem_t flip_ready;
+
+/*
+ * Run as T of params_flip_no_gain(). Become a deadline task of 10ms
+ * every 100ms, and spin until flip_stop. Store the CPU time used in
+ * flip_cpu_ms. Return NULL, or 1 on an error.
+ */
+static void *flip_t(void *arg)
+{
+	uint64_t c0;
+	int err;
+
+	flip_tid = gettid_();
+	err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	sem_post(&flip_ready);
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	c0 = thread_time_ns();
+	while (!flip_stop)
+		;
+	flip_cpu_ms = (thread_time_ns() - c0) / NSEC_PER_MSEC;
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Flip the parameters of a task that never sleeps:
+ * 1. T becomes a deadline task of 10ms every 100ms, and spins.
+ * 2. For 500ms, the main thread changes T every 3ms: to 2ms every 20ms,
+ *    then back to 10ms every 100ms. Both are 10% of a CPU. P has one
+ *    CPU, so the main thread mostly runs while T is throttled.
+ *
+ * No change may give T runtime. T must get about 10% of the 500ms, plus
+ * its first 10ms. The case fails if T gets 90ms of CPU time or more, or
+ * if the kernel logs "sched: DL replenish lagged too much". It skips if
+ * that message was logged before: the kernel prints it once.
+ */
+static int params_flip_no_gain(void)
+{
+	void *t_ret = NULL;
+	int err = 0, had, i, ret = KSFT_FAIL;
+	uint64_t end;
+	pthread_t t;
+
+	had = klog_has(DL_LAG_MSG);
+	if (had) {
+		ksft_print_msg(had < 0 ? "the kernel log cannot be read\n" :
+			       "the lag message was logged before this case\n");
+		return KSFT_SKIP;
+	}
+	if (sem_init(&flip_ready, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	flip_stop = 0;
+	flip_cpu_ms = -1;
+	if (pthread_create(&t, NULL, flip_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&flip_ready, 5000)) {
+		flip_stop = 1;
+		join(t);
+		goto out;
+	}
+	end = now_ns() + 500 * NSEC_PER_MSEC;
+	for (i = 0; !err && now_ns() < end; i++) {
+		sleep_ns(3 * NSEC_PER_MSEC);
+		if (i & 1)
+			err = set_deadline(flip_tid, 10 * NSEC_PER_MSEC, PERIOD);
+		else
+			err = set_deadline(flip_tid, 2 * NSEC_PER_MSEC, PERIOD / 5);
+	}
+	flip_stop = 1;
+	pthread_join(t, &t_ret);
+	if (err) {
+		ksft_print_msg("T could not change: %s\n", strerror(-err));
+		goto out;
+	}
+	if (t_ret || flip_cpu_ms < 0)
+		goto out;	/* T said why */
+	if (flip_cpu_ms >= 90) {
+		ksft_print_msg("T got %lld ms of CPU time in 500ms, with 10%% of a CPU\n",
+			       (long long)flip_cpu_ms);
+		goto out;
+	}
+	if (klog_has(DL_LAG_MSG) == 1) {
+		ksft_print_msg("a refill logged \"%s\"\n", DL_LAG_MSG);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&flip_ready);
+	return ret;
+}
+
+static sem_t vic_b_ready, vic_go;
+static atomic_int vic_stop, vic_b_err;
+static _Atomic unsigned long long vic_t0;
+static _Atomic long long vic_b_done_ms;
+
+/*
+ * Run as B of period_shrunk_no_burst(). Become a deadline task of 40ms
+ * every 100ms, and wait for vic_go. Then spin 39ms, and store in
+ * vic_b_done_ms the time at which the spin ends. Return NULL, or 1 on an
+ * error.
+ */
+static void *vic_b(void *arg)
+{
+	int err = set_deadline(0, 40 * NSEC_PER_MSEC, PERIOD);
+
+	vic_b_err = err;
+	sem_post(&vic_b_ready);
+	if (err) {
+		ksft_print_msg("B refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	sem_wait_sig(&vic_go);
+	if (!vic_stop) {
+		spin_ns(39 * NSEC_PER_MSEC);
+		vic_b_done_ms = (now_ns() - vic_t0) / NSEC_PER_MSEC;
+	}
+	if (set_other(0))
+		ksft_print_msg("B cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run as A of period_shrunk_no_burst(). Its comment has the steps. Return
+ * NULL, or 1 on an error.
+ */
+static void *vic_a(void *arg)
+{
+	int err = set_deadline(0, 40 * NSEC_PER_MSEC, PERIOD);
+
+	if (err) {
+		ksft_print_msg("A refused as a deadline task: %s\n", strerror(-err));
+		vic_stop = 1;
+		sem_post(&vic_go);
+		return (void *)1;
+	}
+	vic_t0 = now_ns();
+	sem_post(&vic_go);
+	spin_ns(39 * NSEC_PER_MSEC + NSEC_PER_MSEC / 2);
+	err = set_deadline(0, 400 * NSEC_PER_USEC, NSEC_PER_MSEC);
+	if (err)
+		ksft_print_msg("A could not change: %s\n", strerror(-err));
+	while (!vic_stop)
+		;
+	if (set_other(0))
+		ksft_print_msg("A cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+/*
+ * A task that used its runtime shortens its period, at the same
+ * bandwidth. P has one CPU:
+ * 1. B, a deadline task of 40ms every 100ms, sleeps for more than its
+ *    period.
+ * 2. A becomes a deadline task of 40ms every 100ms, at 0ms, and wakes B.
+ *    B's wakeup starts a period, with a deadline just after A's.
+ * 3. A spins 39.5ms. It then changes to 0.4ms every 1ms, and spins on.
+ * 4. B runs when A is throttled, and spins 39ms.
+ *
+ * A ran about 24ms ahead of its share. Repaid at its new bandwidth, that
+ * debt puts A's next period at about 99ms, and B ends at about 79ms. If the change gave A a
+ * period at once, A would run 0.4ms of every 1ms from 40ms, with
+ * deadlines before B's. B would end at about 105ms, after its deadline.
+ * The case fails if B ends at 95ms or later.
+ */
+static int period_shrunk_no_burst(void)
+{
+	void *a_ret = NULL, *b_ret = NULL;
+	int ret = KSFT_FAIL;
+	pthread_t a, b;
+
+	if (sem_init(&vic_b_ready, 0, 0) || sem_init(&vic_go, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	vic_stop = 0;
+	vic_b_done_ms = -1;
+	if (pthread_create(&b, NULL, vic_b, NULL)) {
+		ksft_print_msg("the B thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&vic_b_ready, 5000) || vic_b_err) {
+		vic_stop = 1;
+		sem_post(&vic_go);
+		join(b);
+		goto out;	/* B said why */
+	}
+	sleep_ns(PERIOD + 10 * NSEC_PER_MSEC);
+	if (pthread_create(&a, NULL, vic_a, NULL)) {
+		ksft_print_msg("the A thread could not start\n");
+		vic_stop = 1;
+		sem_post(&vic_go);
+		join(b);
+		goto out;
+	}
+	pthread_join(b, &b_ret);
+	vic_stop = 1;
+	pthread_join(a, &a_ret);
+	if (a_ret || b_ret || vic_b_done_ms < 0)
+		goto out;	/* the thread said why */
+	if (vic_b_done_ms >= 95) {
+		ksft_print_msg("B ended at %lld ms: A ran in new periods before 99ms\n",
+			       (long long)vic_b_done_ms);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&vic_b_ready);
+	sem_destroy(&vic_go);
+	return ret;
+}
+
+static sem_t cmix_b_ready, cmix_go;
+static atomic_int cmix_stop, cmix_b_err;
+static _Atomic unsigned long long cmix_t0;
+static _Atomic long long cmix_b_done_ms;
+
+/*
+ * Run as B of constrained_after_job(). Become a deadline task of 150ms
+ * every 200ms, and wait for cmix_go. Then spin 148ms, and store in
+ * cmix_b_done_ms the time at which the spin ends. Return NULL, or 1 on an
+ * error.
+ */
+static void *cmix_b(void *arg)
+{
+	int err = set_deadline(0, 150 * NSEC_PER_MSEC, 200 * NSEC_PER_MSEC);
+
+	cmix_b_err = err;
+	sem_post(&cmix_b_ready);
+	if (err) {
+		ksft_print_msg("B refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	sem_wait_sig(&cmix_go);
+	if (!cmix_stop) {
+		spin_ns(148 * NSEC_PER_MSEC);
+		cmix_b_done_ms = (now_ns() - cmix_t0) / NSEC_PER_MSEC;
+	}
+	if (set_other(0))
+		ksft_print_msg("B cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run as A of constrained_after_job(). Its comment has the steps. Return
+ * NULL, or 1 on an error.
+ */
+static void *cmix_a(void *arg)
+{
+	int err = set_deadline(0, 15 * NSEC_PER_MSEC, PERIOD);
+
+	if (err) {
+		ksft_print_msg("A refused as a deadline task: %s\n", strerror(-err));
+		cmix_stop = 1;
+		sem_post(&cmix_go);
+		return (void *)1;
+	}
+	cmix_t0 = now_ns();
+	sem_post(&cmix_go);
+	spin_ns(14 * NSEC_PER_MSEC + NSEC_PER_MSEC / 2);
+	err = set_constrained(0, 18 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC,
+			      120 * NSEC_PER_MSEC);
+	if (err)
+		ksft_print_msg("A could not change: %s\n", strerror(-err));
+	while (!cmix_stop)
+		;
+	if (set_other(0))
+		ksft_print_msg("A cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+/*
+ * A task that used most of its runtime moves to a constrained deadline,
+ * at the same bandwidth. P has one CPU:
+ * 1. B makes itself a deadline task of 150ms every 200ms. It sleeps for
+ *    more than its period.
+ * 2. A makes itself a deadline task of 15ms every 100ms, at 0ms, and
+ *    wakes B. A's deadline is 100ms. B's wakeup starts a period, with a
+ *    deadline at 200ms.
+ * 3. A spins 14.5ms. It then changes itself to 18ms in 20ms, every
+ *    120ms, and spins on.
+ * 4. A is throttled at 15ms, when its runtime runs out. B then runs, and
+ *    spins 148ms.
+ *
+ * A's job of the old parameters counts as a whole job of the new ones.
+ * It keeps its deadline of 100ms, so it counts as released at
+ * 100 - 20 = 80ms. A's next job then starts at 80 + 120 = 200ms, and B
+ * ends at about 163ms. If A's next job started at 120ms, its deadline at
+ * 140ms would come before B's. A would preempt B for 18ms, and B would
+ * end at about 181ms. The case fails if B ends at 172ms or later.
+ */
+static int constrained_after_job(void)
+{
+	void *a_ret = NULL, *b_ret = NULL;
+	int ret = KSFT_FAIL;
+	pthread_t a, b;
+
+	if (sem_init(&cmix_b_ready, 0, 0) || sem_init(&cmix_go, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	cmix_stop = 0;
+	cmix_b_done_ms = -1;
+	if (pthread_create(&b, NULL, cmix_b, NULL)) {
+		ksft_print_msg("the B thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&cmix_b_ready, 5000) || cmix_b_err) {
+		cmix_stop = 1;
+		sem_post(&cmix_go);
+		join(b);
+		goto out;	/* B said why */
+	}
+	sleep_ns(210 * NSEC_PER_MSEC);
+	if (pthread_create(&a, NULL, cmix_a, NULL)) {
+		ksft_print_msg("the A thread could not start\n");
+		cmix_stop = 1;
+		sem_post(&cmix_go);
+		join(b);
+		goto out;
+	}
+	pthread_join(b, &b_ret);
+	cmix_stop = 1;
+	pthread_join(a, &a_ret);
+	if (a_ret || b_ret || cmix_b_done_ms < 0)
+		goto out;	/* the thread said why */
+	if (cmix_b_done_ms >= 172) {
+		ksft_print_msg("B ended at %lld ms: A's next job came before 200ms\n",
+			       (long long)cmix_b_done_ms);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&cmix_b_ready);
+	sem_destroy(&cmix_go);
+	return ret;
+}
+
+static _Atomic long long grow_back_ms;
+
+/*
+ * Run as T of deadline_grows_running(). Its comment has the steps. Store
+ * in grow_back_ms how late T runs after its sleep. Return NULL, or 1 on
+ * an error.
+ */
+static void *grow_t(void *arg)
+{
+	struct timespec ts;
+	uint64_t end;
+	int err;
+
+	err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, PERIOD);
+	if (!err) {
+		sched_yield();
+		err = set_constrained(0, 10 * NSEC_PER_MSEC, 50 * NSEC_PER_MSEC,
+				      PERIOD);
+	}
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		set_other(0);
+		return (void *)1;
+	}
+	sched_yield();
+	end = now_ns() + 30 * NSEC_PER_MSEC;
+	ts.tv_sec = end / NSEC_PER_SEC;
+	ts.tv_nsec = end % NSEC_PER_SEC;
+	while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR)
+		;
+	grow_back_ms = (now_ns() - end) / NSEC_PER_MSEC;
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Lengthen the relative deadline of a task that its replenishment timer
+ * refills:
+ * 1. T becomes a deadline task of 10ms in 20ms, every 100ms, and yields.
+ *    The timer refills it at the start of its next period.
+ * 2. T changes itself to 10ms in 50ms, every 100ms, and yields again.
+ * 3. The timer refills T at the start of its next period. T then sleeps
+ *    30ms. It wakes up before its new deadline, 50ms into the period.
+ *
+ * T must run at once. With the old relative deadline, its deadline would
+ * be 20ms into the period, and the wakeup would throttle T until the next
+ * period. The case fails if T runs 20ms or more after its wakeup.
+ */
+static int deadline_grows_running(void)
+{
+	void *t_ret = NULL;
+	pthread_t t;
+
+	grow_back_ms = -1;
+	if (pthread_create(&t, NULL, grow_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		return KSFT_FAIL;
+	}
+	pthread_join(t, &t_ret);
+	if (t_ret || grow_back_ms < 0)
+		return KSFT_FAIL;	/* T said why */
+	if (grow_back_ms >= 20) {
+		ksft_print_msg("T ran %lld ms after its wakeup\n",
+			       (long long)grow_back_ms);
+		return KSFT_FAIL;
+	}
+	return KSFT_PASS;
+}
+
+static sem_t gap_h_ready, gap_h_go, gap_h_end;
+static atomic_int gap_h_err;
+static _Atomic long long gap_used_ms, gap_back_ms;
+
+/*
+ * Run as H of constrained_gap_change_running(). Become a deadline task of
+ * 40ms in 45ms, every 100ms, and wait for gap_h_go. Then spin for 35ms of
+ * CPU time, and wait for gap_h_end. Return NULL, or 1 on an error.
+ */
+static void *gap_h(void *arg)
+{
+	int err = set_constrained(0, 40 * NSEC_PER_MSEC, 45 * NSEC_PER_MSEC, PERIOD);
+
+	gap_h_err = err;
+	sem_post(&gap_h_ready);
+	if (err) {
+		ksft_print_msg("H refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	sem_wait_sig(&gap_h_go);
+	spin_ns(35 * NSEC_PER_MSEC);
+	sem_wait_sig(&gap_h_end);
+	if (set_other(0))
+		ksft_print_msg("H cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run as T of constrained_gap_change_running(). Its comment has the
+ * steps. Store in gap_used_ms the CPU time T used until 55ms, and in
+ * gap_back_ms the time at which T runs again after its change. Return
+ * NULL, or 1 on an error.
+ */
+static void *gap_t(void *arg)
+{
+	uint64_t t0, c0;
+	int err;
+
+	err = set_constrained(0, 40 * NSEC_PER_MSEC, 50 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	t0 = now_ns();
+	c0 = thread_time_ns();
+	sem_post(&gap_h_go);
+	while (now_ns() - t0 < 55 * NSEC_PER_MSEC)
+		;
+	gap_used_ms = (thread_time_ns() - c0) / NSEC_PER_MSEC;
+	err = set_constrained(0, 39 * NSEC_PER_MSEC, 50 * NSEC_PER_MSEC, PERIOD);
+	gap_back_ms = (now_ns() - t0) / NSEC_PER_MSEC;
+	if (err)
+		ksft_print_msg("T could not change: %s\n", strerror(-err));
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+/*
+ * Change the parameters of a running task past its deadline, before its
+ * next period. P has one CPU:
+ * 1. H, a deadline task of 40ms in 45ms, every 100ms, waits.
+ * 2. T becomes a deadline task of 40ms in 50ms, every 100ms, and wakes H.
+ *    H has the earlier deadline. It runs for 35ms.
+ * 3. T runs from 35ms. At 50ms it is past its deadline, with runtime
+ *    left.
+ * 4. At 55ms, T changes its runtime to 39ms. The enqueue of the change
+ *    throttles it until its next period, at 100ms.
+ *
+ * T must then leave the CPU until 100ms. Its CPU time does not show it:
+ * a throttled task that keeps running is not charged. So T reads the time
+ * when its change returns. The case fails before 90ms.
+ */
+static int constrained_gap_change_running(void)
+{
+	void *h_ret = NULL, *t_ret = NULL;
+	int ret = KSFT_FAIL;
+	pthread_t h, t;
+
+	if (sem_init(&gap_h_ready, 0, 0) || sem_init(&gap_h_go, 0, 0) ||
+	    sem_init(&gap_h_end, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	gap_used_ms = -1;
+	gap_back_ms = -1;
+	if (pthread_create(&h, NULL, gap_h, NULL)) {
+		ksft_print_msg("the H thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&gap_h_ready, 5000) || gap_h_err) {
+		sem_post(&gap_h_go);
+		sem_post(&gap_h_end);
+		join(h);
+		goto out;	/* H said why */
+	}
+	if (pthread_create(&t, NULL, gap_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		sem_post(&gap_h_go);
+		sem_post(&gap_h_end);
+		join(h);
+		goto out;
+	}
+	pthread_join(t, &t_ret);
+	sem_post(&gap_h_go);	/* if T never woke H */
+	sem_post(&gap_h_end);
+	pthread_join(h, &h_ret);
+	if (t_ret || h_ret || gap_back_ms < 0)
+		goto out;	/* the thread said why */
+	if (gap_used_ms > 30) {
+		ksft_print_msg("T used %lld ms of its first 55: H did not delay it\n",
+			       (long long)gap_used_ms);
+		goto out;
+	}
+	if (gap_back_ms < 90) {
+		ksft_print_msg("T ran again at %lld ms, throttled until 100\n",
+			       (long long)gap_back_ms);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&gap_h_ready);
+	sem_destroy(&gap_h_go);
+	sem_destroy(&gap_h_end);
+	return ret;
+}
+
+/*
+ * Return the absolute deadline of the deadline task @tid, in ns of the rq
+ * clock, from dl.deadline in /proc/<tid>/sched. Return -1 if it cannot be
+ * read.
+ */
+static long long dl_deadline_of(pid_t tid)
+{
+	char path[64], line[256];
+	long long d = -1;
+	FILE *f;
+
+	snprintf(path, sizeof(path), "/proc/%d/sched", tid);
+	f = fopen(path, "r");
+	if (!f)
+		return -1;
+	while (fgets(line, sizeof(line), f)) {
+		char *val = strchr(line, ':');
+
+		if (!strncmp(line, "dl.deadline", 11) && val) {
+			d = atoll(val + 1);
+			break;
+		}
+	}
+	fclose(f);
+	return d;
+}
+
+/* Milliseconds from @from to @to, both from now_ns(). */
+#define MS_FROM(from, to)	((long long)((int64_t)((to) - (from)) / (int64_t)NSEC_PER_MSEC))
+
+static _Atomic uint32_t rb2_pi;
+static atomic_int rb2_t_locking;
+static _Atomic pid_t rb2_t_tid;
+static _Atomic uint64_t rb2_t_start, rb2_t_got;
+
+/*
+ * Run as T of reenter_pi_blocked_in_gap(). Become a deadline task of 10ms
+ * in 20ms, every 500ms. Spin 2ms of CPU time, then take rb2_pi with
+ * FUTEX_LOCK_PI. Once T holds it, store the time and unlock. Return NULL,
+ * or 1 on an error.
+ */
+static void *rb2_t(void *arg)
+{
+	uint32_t tid = gettid_();
+	int err;
+
+	rb2_t_tid = tid;
+	err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);
+	rb2_t_start = now_ns();
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		rb2_t_locking = -1;
+		return (void *)1;
+	}
+	spin_ns(2 * NSEC_PER_MSEC);
+	rb2_t_locking = 1;
+	if (syscall(SYS_futex, &rb2_pi, FUTEX_LOCK_PI | FUTEX_PRIVATE_FLAG,
+		    0, NULL, NULL, 0)) {
+		ksft_print_msg("FUTEX_LOCK_PI: %s\n", strerror(errno));
+		set_other(0);
+		return (void *)1;
+	}
+	rb2_t_got = now_ns();
+	if (!atomic_compare_exchange_strong(&rb2_pi, &tid, 0))
+		syscall(SYS_futex, &rb2_pi, FUTEX_UNLOCK_PI | FUTEX_PRIVATE_FLAG,
+			0, NULL, NULL, 0);
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * A task blocked on an rt_mutex leaves the deadline class in its
+ * constrained gap and comes back. The main thread holds the PI futex
+ * rb2_pi. P has one CPU:
+ * 1. T becomes a deadline task of 10ms in 20ms, every 500ms, at 0ms. It
+ *    spins 2ms and blocks on rb2_pi. Its deadline is 20ms.
+ * 2. At 40ms, T is past its deadline and before its next period, at
+ *    500ms. The main thread switches T to SCHED_OTHER, then back to
+ *    SCHED_DEADLINE with the same parameters. T still waits on rb2_pi.
+ * 3. At about 45ms, the main thread unlocks rb2_pi.
+ *
+ * T used 2ms of its 10ms. Past its deadline, it gets no more runtime in
+ * that period: a wakeup would throttle it until 500ms. Leaving the class
+ * and coming back must not give it a new period before then. The case
+ * fails if T gets rb2_pi before 490ms.
+ */
+static int reenter_pi_blocked_in_gap(void)
+{
+	long long dl_gap = -1, dl_back = -1;
+	uint64_t back_at = 0, unlock_at;
+	int ret = KSFT_FAIL, err;
+	void *t_ret = NULL;
+	pthread_t t;
+
+	rb2_pi = gettid_();
+	rb2_t_locking = 0;
+	rb2_t_tid = 0;
+	rb2_t_start = 0;
+	rb2_t_got = 0;
+	if (pthread_create(&t, NULL, rb2_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		return KSFT_FAIL;
+	}
+	if (wait_for(1000, rb2_t_locking &&
+		     (rb2_t_locking < 0 || (proc_state_of(rb2_t_tid) == 'S' &&
+					    (rb2_pi & FUTEX_WAITERS)))) ||
+	    rb2_t_locking < 0) {
+		ksft_print_msg("T never blocked on rb2_pi\n");
+		goto out;
+	}
+	while (now_ns() - rb2_t_start < 40 * NSEC_PER_MSEC)
+		sleep_ns(NSEC_PER_MSEC);
+	dl_gap = dl_deadline_of(rb2_t_tid);
+	err = set_other(rb2_t_tid);
+	if (err) {
+		ksft_print_msg("T cannot leave SCHED_DEADLINE: %s\n", strerror(-err));
+		goto out;
+	}
+	err = set_constrained(rb2_t_tid, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);
+	back_at = now_ns();
+	if (err) {
+		ksft_print_msg("T refused back as a deadline task: %s\n", strerror(-err));
+		goto out;
+	}
+	dl_back = dl_deadline_of(rb2_t_tid);
+	if (proc_state_of(rb2_t_tid) != 'S' || !(rb2_pi & FUTEX_WAITERS)) {
+		ksft_print_msg("T no longer waits on rb2_pi\n");
+		goto out;
+	}
+	sleep_ns(5 * NSEC_PER_MSEC);
+	ret = KSFT_PASS;
+out:
+	unlock_at = now_ns();
+	{
+		uint32_t tid = gettid_();
+
+		if (!atomic_compare_exchange_strong(&rb2_pi, &tid, 0))
+			syscall(SYS_futex, &rb2_pi, FUTEX_UNLOCK_PI | FUTEX_PRIVATE_FLAG,
+				0, NULL, NULL, 0);
+	}
+	if (pthread_join(t, &t_ret) || t_ret || ret != KSFT_PASS)
+		return KSFT_FAIL;	/* the thread said why */
+	ksft_print_msg("T back at %lld ms, deadline moved by %lld ms; next period at 500 ms\n",
+		       MS_FROM(rb2_t_start, back_at),
+		       dl_back < 0 || dl_gap < 0 ? -1LL :
+		       (dl_back - dl_gap) / (long long)NSEC_PER_MSEC);
+	ksft_print_msg("(0: kept, %lld: new period); unlock %lld ms; T got the lock %lld ms\n",
+		       MS_FROM(rb2_t_start, back_at),
+		       MS_FROM(rb2_t_start, unlock_at), MS_FROM(rb2_t_start, rb2_t_got));
+	if (MS_FROM(rb2_t_start, rb2_t_got) < 490) {
+		ksft_print_msg("T ran before its next period\n");
+		return KSFT_FAIL;
+	}
+	return KSFT_PASS;
+}
+
+static int ra_fd[2];
+static atomic_int ra_t_asleep;
+static _Atomic pid_t ra_t_tid;
+static _Atomic uint64_t ra_t_start, ra_t_run;
+
+/*
+ * Run as T of reenter_asleep_case(). Become a deadline task of 10ms in
+ * 20ms, every 500ms. Spin 2ms of CPU time, then sleep in a read of
+ * ra_fd[0]. Once woken, store the time and leave SCHED_DEADLINE. Return
+ * NULL, or 1 on an error.
+ */
+static void *ra_t(void *arg)
+{
+	char c;
+	int err;
+
+	ra_t_tid = gettid_();
+	err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);
+	ra_t_start = now_ns();
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		ra_t_asleep = -1;
+		return (void *)1;
+	}
+	spin_ns(2 * NSEC_PER_MSEC);
+	ra_t_asleep = 1;
+	if (read(ra_fd[0], &c, 1) != 1) {
+		ksft_print_msg("T: read: %s\n", strerror(errno));
+		set_other(0);
+		return (void *)1;
+	}
+	ra_t_run = now_ns();
+	if (set_other(0))
+		ksft_print_msg("T cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * The same as reenter_pi_blocked_in_gap(), without the rt_mutex. P has
+ * one CPU:
+ * 1. T becomes a deadline task of 10ms in 20ms, every 500ms, at 0ms. It
+ *    spins 2ms and sleeps in a read of a pipe, with 8ms left. Its
+ *    deadline is 20ms. Its 0-lag time is 100ms.
+ * 2. At @at_ms, T is past its deadline and before its next period, at
+ *    500ms. The main thread switches T to SCHED_OTHER, then back to
+ *    SCHED_DEADLINE with the same parameters.
+ * 3. About 5ms later, the main thread wakes T up.
+ *
+ * Leaving the class and coming back must not give T a new period before
+ * 500ms. The case fails if T runs after its wakeup before 490ms.
+ */
+static int reenter_asleep_case(int at_ms)
+{
+	long long dl_gap = -1, dl_back = -1;
+	uint64_t back_at = 0, wake_at = 0;
+	int ret = KSFT_FAIL, err;
+	void *t_ret = NULL;
+	pthread_t t;
+
+	if (pipe(ra_fd)) {
+		ksft_print_msg("pipe: %s\n", strerror(errno));
+		return KSFT_FAIL;
+	}
+	ra_t_asleep = 0;
+	ra_t_tid = 0;
+	ra_t_start = 0;
+	ra_t_run = 0;
+	if (pthread_create(&t, NULL, ra_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		goto close;
+	}
+	if (wait_for(1000, ra_t_asleep &&
+		     (ra_t_asleep < 0 || proc_state_of(ra_t_tid) == 'S')) ||
+	    ra_t_asleep < 0) {
+		ksft_print_msg("T never slept\n");
+		goto out;
+	}
+	while (now_ns() - ra_t_start < (uint64_t)at_ms * NSEC_PER_MSEC)
+		sleep_ns(NSEC_PER_MSEC);
+	dl_gap = dl_deadline_of(ra_t_tid);
+	err = set_other(ra_t_tid);
+	if (err) {
+		ksft_print_msg("T cannot leave SCHED_DEADLINE: %s\n", strerror(-err));
+		goto out;
+	}
+	err = set_constrained(ra_t_tid, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);
+	back_at = now_ns();
+	if (err) {
+		ksft_print_msg("T refused back as a deadline task: %s\n", strerror(-err));
+		goto out;
+	}
+	dl_back = dl_deadline_of(ra_t_tid);
+	if (proc_state_of(ra_t_tid) != 'S') {
+		ksft_print_msg("T is no longer asleep\n");
+		goto out;
+	}
+	sleep_ns(5 * NSEC_PER_MSEC);
+	ret = KSFT_PASS;
+out:
+	wake_at = now_ns();
+	if (write(ra_fd[1], "x", 1) != 1)
+		ksft_print_msg("write: %s\n", strerror(errno));
+	if (pthread_join(t, &t_ret) || t_ret)
+		ret = KSFT_FAIL;	/* the thread said why */
+close:
+	close(ra_fd[0]);
+	close(ra_fd[1]);
+	if (ret != KSFT_PASS)
+		return KSFT_FAIL;
+	ksft_print_msg("T back at %lld ms, deadline %s%lld ms; next period at 500 ms\n",
+		       MS_FROM(ra_t_start, back_at),
+		       dl_back == 0 ? "is 0, moved by " : "moved by ",
+		       dl_back < 0 || dl_gap < 0 ? -1LL :
+		       (dl_back - dl_gap) / (long long)NSEC_PER_MSEC);
+	ksft_print_msg("T woken at %lld ms, ran at %lld ms\n",
+		       MS_FROM(ra_t_start, wake_at), MS_FROM(ra_t_start, ra_t_run));
+	if (MS_FROM(ra_t_start, ra_t_run) < 490) {
+		ksft_print_msg("T ran before its next period\n");
+		return KSFT_FAIL;
+	}
+	return KSFT_PASS;
+}
+
+/* Run reenter_asleep_case() before T's 0-lag time. */
+static int reenter_asleep_in_gap(void)
+{
+	return reenter_asleep_case(40);
+}
+
+/* Run reenter_asleep_case() after T's 0-lag time, before its next period. */
+static int reenter_asleep_late_in_gap(void)
+{
+	return reenter_asleep_case(150);
+}
+
+static atomic_int rr_t_ready, rr_stop;
+static _Atomic pid_t rr_t_tid;
+static _Atomic uint64_t rr_t_start, rr_back_at, rr_t_ran;
+
+/*
+ * Run as T of reenter_runnable_in_gap(). Become a deadline task of 10ms in
+ * 20ms, every 500ms, and spin until rr_stop. Store in rr_t_ran the first
+ * time T runs more than 2ms after rr_back_at. The 2ms leave out the time T
+ * may run as SCHED_OTHER before it is back. Return NULL, or 1 on an
+ * error.
+ */
+static void *rr_t(void *arg)
+{
+	int err;
+
+	rr_t_tid = gettid_();
+	err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);
+	rr_t_start = now_ns();
+	if (err) {
+		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
+		rr_t_ready = -1;
+		return (void *)1;
+	}
+	rr_t_ready = 1;
+	while (!rr_stop) {
+		uint64_t t = now_ns(), b = rr_back_at;
+
+		if (b && !rr_t_ran && t > b + 2 * NSEC_PER_MSEC)
+			rr_t_ran = t;
+	}
+	return NULL;
+}
+
+/*
+ * The same as reenter_asleep_in_gap(), for a task that stays runnable. P
+ * has one CPU:
+ * 1. T becomes a deadline task of 10ms in 20ms, every 500ms, at 0ms, and
+ *    spins. It is throttled at 10ms, until its next period at 500ms.
+ * 2. At 40ms, the main thread switches T to SCHED_OTHER, then back to
+ *    SCHED_DEADLINE with the same parameters.
+ *
+ * Leaving the class and coming back must not give T a new period before
+ * 500ms. With a new period, T would run at once. The case fails if T runs
+ * from 2ms to 50ms after rr_back_at.
+ */
+static int reenter_runnable_in_gap(void)
+{
+	int ret = KSFT_FAIL, err;
+	void *t_ret = NULL;
+	pthread_t t;
+
+	rr_t_ready = 0;
+	rr_stop = 0;
+	rr_t_tid = 0;
+	rr_t_start = 0;
+	rr_back_at = 0;
+	rr_t_ran = 0;
+	if (pthread_create(&t, NULL, rr_t, NULL)) {
+		ksft_print_msg("the T thread could not start\n");
+		return KSFT_FAIL;
+	}
+	if (wait_for(1000, rr_t_ready) || rr_t_ready < 0) {
+		ksft_print_msg("T never started\n");
+		goto out;
+	}
+	while (now_ns() - rr_t_start < 40 * NSEC_PER_MSEC)
+		sleep_ns(NSEC_PER_MSEC);
+	err = set_other(rr_t_tid);
+	if (err) {
+		ksft_print_msg("T cannot leave SCHED_DEADLINE: %s\n", strerror(-err));
+		goto out;
+	}
+	/* Store it before the switch back. A T given a new period runs at once. */
+	rr_back_at = now_ns();
+	err = set_constrained(rr_t_tid, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);
+	if (err) {
+		ksft_print_msg("T refused back as a deadline task: %s\n", strerror(-err));
+		goto out;
+	}
+	sleep_ns(50 * NSEC_PER_MSEC);
+	ret = KSFT_PASS;
+out:
+	set_other(rr_t_tid);
+	rr_stop = 1;
+	if (pthread_join(t, &t_ret) || t_ret)
+		ret = KSFT_FAIL;
+	if (ret != KSFT_PASS)
+		return KSFT_FAIL;
+	ksft_print_msg("T back at %lld ms, ran again at %lld ms\n",
+		       MS_FROM(rr_t_start, rr_back_at),
+		       rr_t_ran ? MS_FROM(rr_t_start, rr_t_ran) : -1LL);
+	if (rr_t_ran && rr_t_ran < rr_back_at + 50 * NSEC_PER_MSEC) {
+		ksft_print_msg("T ran before its next period\n");
+		return KSFT_FAIL;
+	}
+	return KSFT_PASS;
+}
+
+static sem_t rb_donor_go;
+static atomic_int rb_abort, rb_donor_locking, rb_donor_done, rb_waiter_locking;
+static _Atomic pid_t rb_waiter_tid;
+static _Atomic long long rb_spin_ns;
+
+/*
+ * Run as the owner O of deboost_new_params_reboost(). Its comment has
+ * the steps. Store in rb_spin_ns the time that O's last spin, 20ms of CPU
+ * time, takes. Return NULL, or 1 on an error.
+ */
+static void *reboost_owner(void *arg)
+{
+	uint64_t t0;
+	int err;
+
+	owner_tid = gettid_();
+	if (take_pi_lock())
+		return (void *)1;
+	owner_holds = 2;
+	sem_wait_sig(&owner_go);
+	if (rb_abort) {
+		drop_pi_lock();
+		return NULL;
+	}
+	err = set_deadline(0, 50 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("the owner refused as a deadline task: %s\n",
+			       strerror(-err));
+		goto out;
+	}
+	sem_post(&rb_donor_go);
+	t0 = now_ns();
+	while (!rb_donor_locking || proc_state_of(donor_tid) != 'S') {
+		if (now_ns() - t0 > NSEC_PER_SEC) {
+			ksft_print_msg("the donor did not block on the lock\n");
+			err = -1;
+			goto out;
+		}
+	}
+	err = set_deadline(rb_waiter_tid, 2 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("the waiter refused as a deadline task: %s\n",
+			       strerror(-err));
+		goto out;
+	}
+	err = set_deadline(0, 5 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("the owner could not change: %s\n",
+			       strerror(-err));
+		goto out;
+	}
+	t0 = now_ns();
+	while (!rb_donor_done) {
+		if (now_ns() - t0 > NSEC_PER_SEC) {
+			ksft_print_msg("the donor did not time out\n");
+			err = -1;
+			goto out;
+		}
+	}
+	t0 = now_ns();
+	spin_ns(20 * NSEC_PER_MSEC);
+	rb_spin_ns = now_ns() - t0;
+out:
+	drop_pi_lock();
+	if (set_other(0))
+		ksft_print_msg("the owner cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+/*
+ * Run as the donor D of deboost_new_params_reboost(). Become a deadline
+ * task of 5ms every 50ms, and sleep until rb_donor_go. Then wait 20ms for
+ * pi_lock. Return NULL if the wait timed out or the case gave up, or 1
+ * otherwise.
+ */
+static void *reboost_donor(void *arg)
+{
+	struct timespec ts;
+	int err;
+
+	err = set_deadline(0, 5 * NSEC_PER_MSEC, PERIOD / 2);
+	if (err) {
+		ksft_print_msg("the donor refused as a deadline task: %s\n",
+			       strerror(-err));
+		donor_tid = -1;
+		return (void *)1;
+	}
+	donor_tid = gettid_();
+	sem_wait_sig(&rb_donor_go);
+	if (rb_abort) {
+		set_other(0);
+		return NULL;
+	}
+	clock_gettime(CLOCK_REALTIME, &ts);
+	ts.tv_nsec += 20 * 1000000L;
+	ts.tv_sec += ts.tv_nsec / 1000000000L;
+	ts.tv_nsec %= 1000000000L;
+	rb_donor_locking = 1;
+	err = pthread_mutex_timedlock(&pi_lock, &ts);
+	rb_donor_done = 1;
+	if (!err)
+		pthread_mutex_unlock(&pi_lock);
+	if (set_other(0))
+		ksft_print_msg("the donor cannot leave SCHED_DEADLINE\n");
+	if (err != ETIMEDOUT) {
+		ksft_print_msg("the donor: %s, not a timeout\n",
+			       err ? strerror(err) : "got pi_lock");
+		return (void *)1;
+	}
+	return NULL;
+}
+
+/*
+ * Run as the waiter W of deboost_new_params_reboost(). Wait for pi_lock
+ * as a fair task. The owner makes W a deadline task during the wait.
+ * Return NULL, or 1 on an error.
+ */
+static void *reboost_waiter(void *arg)
+{
+	rb_waiter_tid = gettid_();
+	rb_waiter_locking = 1;
+	if (take_pi_lock())
+		return (void *)1;
+	drop_pi_lock();
+	if (set_other(0))
+		ksft_print_msg("the waiter cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+static int reboost_case(void);
+
+/*
+ * Check that a deboost boosts the owner again when the check of its new
+ * parameters moves its deadline after the one of its top waiter. The
+ * threads share the CPU of P:
+ *
+ *   owner O                     donor D               waiter W
+ *   fair                        5ms every 50ms        fair
+ *
+ *   takes pi_lock               sleeps
+ *                                                     blocks on pi_lock
+ *   becomes 50ms every 100ms
+ *   wakes D up
+ *                               preempts O
+ *                               waits 20ms for
+ *                                 pi_lock, boosts O
+ *   makes W 2ms every 100ms
+ *   changes itself to 5ms
+ *     every 100ms
+ *   spins
+ *                               times out: W is now
+ *                                 the top waiter
+ *   spins 20ms
+ *   unlocks
+ *                                                     takes pi_lock
+ *
+ * W gets its deadline after O does, so W's deadline is the later one.
+ * W blocks as a fair task: a deadline W could not preempt O to block.
+ *
+ * O has run about 20ms of its 50ms when D times out: 10ms more than its
+ * share. The deboost fits O's period to the new parameters. O keeps 5ms,
+ * and its next period starts once those 5ms and the 10ms of debt are
+ * paid at 5%: its deadline is about 300ms ahead. W's deadline is now the
+ * earlier one. W must boost O again. A boosted O is refilled from W, so
+ * its last spin takes about 20ms. Without the boost, O is throttled once
+ * its 5ms run out, until its new deadline. The case fails if the spin
+ * takes more than 50ms.
+ */
+static int deboost_new_params_reboost(void)
+{
+	return reboost_case();
+}
+
+/* Run deboost_new_params_reboost(). */
+static int reboost_case(void)
+{
+	void *o_ret = NULL, *d_ret = NULL, *w_ret = NULL;
+	int ret = KSFT_FAIL, have_d = 0, have_w = 0;
+	pthread_t o, d, w;
+
+	if (pi_init())
+		return KSFT_SKIP;
+	if (sem_init(&rb_donor_go, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		pi_fini();
+		return KSFT_FAIL;
+	}
+	donor_tid = 0;
+	rb_abort = 0;
+	rb_donor_locking = 0;
+	rb_donor_done = 0;
+	rb_waiter_locking = 0;
+	rb_waiter_tid = 0;
+	rb_spin_ns = -1;
+	if (pthread_create(&o, NULL, reboost_owner, NULL)) {
+		ksft_print_msg("the owner thread could not start\n");
+		goto out_fini;
+	}
+	if (wait_for(5000, owner_holds) || owner_holds != 2) {
+		ksft_print_msg("the owner never took pi_lock\n");
+		goto out;
+	}
+	have_d = !pthread_create(&d, NULL, reboost_donor, NULL);
+	if (!have_d || wait_for(1000, donor_tid &&
+				   proc_state_of(donor_tid) == 'S') ||
+	    donor_tid < 0) {
+		ksft_print_msg("the donor never slept\n");
+		goto out;
+	}
+	have_w = !pthread_create(&w, NULL, reboost_waiter, NULL);
+	if (!have_w || wait_for(1000, rb_waiter_locking &&
+				   proc_state_of(rb_waiter_tid) == 'S')) {
+		ksft_print_msg("the waiter never waited on pi_lock\n");
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	/* On a failure, the owner and the donor end without the steps. */
+	rb_abort = ret != KSFT_PASS;
+	sem_post(&owner_go);
+	if (pthread_join(o, &o_ret))
+		ret = KSFT_FAIL;
+	sem_post(&rb_donor_go);
+	if (have_d && pthread_join(d, &d_ret))
+		ret = KSFT_FAIL;
+	if (have_w && pthread_join(w, &w_ret))
+		ret = KSFT_FAIL;
+	if (o_ret || d_ret || w_ret) {
+		ret = KSFT_FAIL;	/* the thread said why */
+	} else if (ret == KSFT_PASS && rb_spin_ns > PERIOD / 2) {
+		ksft_print_msg("the spin took %lld ms: not boosted again\n",
+			       rb_spin_ns / (long long)NSEC_PER_MSEC);
+		ret = KSFT_FAIL;
+	}
+out_fini:
+	sem_destroy(&rb_donor_go);
+	pi_fini();
+	return ret;
+}
+
+static sem_t das_donor_ready, das_owner_locked;
+static atomic_int das_donor_locking;
+static _Atomic pid_t das_donor_tid;
+static _Atomic long long das_back_ms;
+
+/*
+ * Run as the donor D of deboost_asleep_new_params(). Become a deadline
+ * task of 1ms every 10ms. Once O holds pi_lock, wait 150ms for it. Return
+ * NULL if the wait timed out, or 1 otherwise.
+ */
+static void *das_donor(void *arg)
+{
+	struct timespec ts;
+	int err;
+
+	das_donor_tid = gettid_();
+	err = set_deadline(0, NSEC_PER_MSEC, 10 * NSEC_PER_MSEC);
+	sem_post(&das_donor_ready);
+	if (err) {
+		ksft_print_msg("the donor refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	if (sem_wait_for(&das_owner_locked, 5000)) {
+		ksft_print_msg("the owner did not take the lock\n");
+		set_other(0);
+		return (void *)1;
+	}
+	clock_gettime(CLOCK_REALTIME, &ts);
+	ts.tv_nsec += 150 * 1000000L;
+	ts.tv_sec += ts.tv_nsec / 1000000000L;
+	ts.tv_nsec %= 1000000000L;
+	das_donor_locking = 1;
+	err = pthread_mutex_timedlock(&pi_lock, &ts);
+	if (!err)
+		pthread_mutex_unlock(&pi_lock);
+	if (set_other(0))
+		ksft_print_msg("the donor cannot leave SCHED_DEADLINE\n");
+	if (err != ETIMEDOUT) {
+		ksft_print_msg("the donor: %s, not a timeout\n",
+			       err ? strerror(err) : "got pi_lock");
+		return (void *)1;
+	}
+	return NULL;
+}
+
+/*
+ * Run as the owner O of deboost_asleep_new_params(). Its comment has the
+ * steps. Store in das_back_ms the time at which O runs after its sleep.
+ * Return NULL, or 1 on an error.
+ */
+static void *das_owner(void *arg)
+{
+	struct timespec ts;
+	uint64_t t0, end;
+	int err;
+
+	err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, PERIOD);
+	t0 = now_ns();
+	if (err || take_pi_lock()) {
+		if (err)
+			ksft_print_msg("the owner refused as a deadline task: %s\n",
+				       strerror(-err));
+		sem_post(&das_owner_locked);
+		set_other(0);
+		return (void *)1;
+	}
+	sem_post(&das_owner_locked);
+	while (!das_donor_locking || proc_state_of(das_donor_tid) != 'S') {
+		if (now_ns() - t0 > NSEC_PER_SEC) {
+			ksft_print_msg("the donor did not block on the lock\n");
+			err = -1;
+			goto out;
+		}
+	}
+	err = set_constrained(0, 9 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("the owner could not change: %s\n", strerror(-err));
+		goto out;
+	}
+	end = t0 + 190 * NSEC_PER_MSEC;
+	ts.tv_sec = end / NSEC_PER_SEC;
+	ts.tv_nsec = end % NSEC_PER_SEC;
+	while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR)
+		;
+	das_back_ms = (now_ns() - t0) / NSEC_PER_MSEC;
+out:
+	drop_pi_lock();
+	if (set_other(0))
+		ksft_print_msg("the owner cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+/*
+ * Deboost a task that sleeps on a timer, after it changed its parameters
+ * while boosted. The threads share the CPU of P:
+ * 1. O becomes a deadline task of 10ms in 20ms, every 100ms, at 0ms. It
+ *    takes pi_lock.
+ * 2. D, a deadline task of 1ms every 10ms, waits 150ms for pi_lock. It
+ *    boosts O.
+ * 3. O changes itself to 9ms in 20ms, every 100ms. It sleeps until
+ *    190ms, holding pi_lock.
+ * 4. D times out at 150ms, while O sleeps.
+ * 5. O wakes up at 190ms. Its own period ended at 100ms. It must run at
+ *    once, in a new period.
+ *
+ * If the deboost checks O's new parameters while O sleeps, O starts a
+ * period at 150ms, with a deadline at 170ms. Its wakeup at 190ms is then
+ * between that deadline and the next period, at 250ms. It throttles O
+ * until 250ms. The case fails if O runs at 220ms or later.
+ */
+static int deboost_asleep_new_params(void)
+{
+	void *o_ret = NULL, *d_ret = NULL;
+	int ret = KSFT_FAIL;
+	pthread_t o, d;
+
+	if (pi_init())
+		return KSFT_SKIP;
+	if (sem_init(&das_donor_ready, 0, 0) || sem_init(&das_owner_locked, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		pi_fini();
+		return KSFT_FAIL;
+	}
+	das_donor_locking = 0;
+	das_donor_tid = 0;
+	das_back_ms = -1;
+	if (pthread_create(&d, NULL, das_donor, NULL)) {
+		ksft_print_msg("the donor thread could not start\n");
+		goto out;
+	}
+	if (sem_wait_for(&das_donor_ready, 5000)) {
+		sem_post(&das_owner_locked);
+		join(d);
+		goto out;
+	}
+	if (pthread_create(&o, NULL, das_owner, NULL)) {
+		ksft_print_msg("the owner thread could not start\n");
+		sem_post(&das_owner_locked);
+		join(d);
+		goto out;
+	}
+	pthread_join(o, &o_ret);
+	pthread_join(d, &d_ret);
+	if (o_ret || d_ret || das_back_ms < 0)
+		goto out;	/* the thread said why */
+	if (das_back_ms >= 220) {
+		ksft_print_msg("O ran again at %lld ms, after its wakeup at 190\n",
+			       (long long)das_back_ms);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&das_donor_ready);
+	sem_destroy(&das_owner_locked);
+	pi_fini();
+	return ret;
+}
+
+/* The kinds of owner_boost_case() */
+enum {
+	OB_GAP, OB_THROTTLED, OB_NEW_PARAMS, OB_RIVAL, OB_LONG,
+	OB_LATE_THROTTLE, OB_LATE_GAP,
+};
+
+static sem_t ob_locked, ob_go, ob_rival_go;
+static _Atomic unsigned long long ob_t0;
+static _Atomic long long ob_got_ms;
+static _Atomic pid_t ob_w_tid;
+static int ob_throttled, ob_kind;
+static atomic_int ob_w_locking;
+
+/*
+ * Run as the owner O of owner_boost_case(). Become a deadline task, take
+ * pi_lock, and act by ob_kind:
+ * - OB_GAP and OB_LATE_GAP: 10ms in 20ms, every 500ms. Sleep until 40ms.
+ *   O then wakes past its deadline, before its next period.
+ * - the other kinds: 10ms every 100ms. O runs out of runtime at 10ms,
+ *   holding the lock. Then:
+ *   - OB_THROTTLED and OB_RIVAL: spin 15ms of CPU time.
+ *   - OB_LATE_THROTTLE: sleep until W blocks on pi_lock, then spin 15ms.
+ *   - OB_NEW_PARAMS: spin 12ms. Change O to 9ms every 100ms, and W to 5ms
+ *     every 310ms. Then spin 3ms.
+ *   - OB_LONG: spin 12ms, then sleep until 250ms.
+ * Then unlock. Return NULL, or 1 on an error.
+ */
+static void *ob_owner(void *arg)
+{
+	struct timespec ts;
+	uint64_t end;
+	int err, bad = 0;
+
+	if (ob_throttled)
+		err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	else
+		err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC,
+				      5 * PERIOD);
+	ob_t0 = now_ns();
+	if (err || take_pi_lock()) {
+		if (err)
+			ksft_print_msg("the owner refused as a deadline task: %s\n",
+				       strerror(-err));
+		sem_post(&ob_locked);
+		set_other(0);
+		return (void *)1;
+	}
+	sem_post(&ob_locked);
+	if (ob_kind == OB_NEW_PARAMS) {
+		spin_ns(12 * NSEC_PER_MSEC);
+		err = set_deadline(0, 9 * NSEC_PER_MSEC, PERIOD);
+		if (!err)
+			err = set_deadline(ob_w_tid, 5 * NSEC_PER_MSEC,
+					   3 * PERIOD + 10 * NSEC_PER_MSEC);
+		if (err) {
+			ksft_print_msg("the owner could not change the parameters: %s\n",
+				       strerror(-err));
+			bad = 1;
+		}
+		spin_ns(3 * NSEC_PER_MSEC);
+	} else if (ob_kind == OB_LONG) {
+		spin_ns(12 * NSEC_PER_MSEC);
+		end = ob_t0 + 250 * NSEC_PER_MSEC;
+		ts.tv_sec = end / NSEC_PER_SEC;
+		ts.tv_nsec = end % NSEC_PER_SEC;
+		while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR)
+			;
+	} else if (ob_kind == OB_LATE_THROTTLE) {
+		end = now_ns();
+		while (!ob_w_locking || proc_state_of(ob_w_tid) != 'S') {
+			if (now_ns() - end > NSEC_PER_SEC) {
+				ksft_print_msg("the waiter did not block on the lock\n");
+				bad = 1;
+				break;
+			}
+			sleep_ns(NSEC_PER_MSEC);
+		}
+		spin_ns(15 * NSEC_PER_MSEC);
+	} else if (ob_throttled) {
+		spin_ns(15 * NSEC_PER_MSEC);
+	} else {
+		end = ob_t0 + 40 * NSEC_PER_MSEC;
+		ts.tv_sec = end / NSEC_PER_SEC;
+		ts.tv_nsec = end % NSEC_PER_SEC;
+		while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR)
+			;
+	}
+	drop_pi_lock();
+	if (set_other(0))
+		ksft_print_msg("the owner cannot leave SCHED_DEADLINE\n");
+	return bad ? (void *)1 : NULL;
+}
+
+/*
+ * Run as the waiter W of owner_boost_case(). Wait for ob_go. Then
+ * become a deadline task of 5ms every 300ms, or of 2ms every 10ms with
+ * OB_RIVAL, and take pi_lock. Store in ob_got_ms the time at which W gets
+ * it. Return NULL, or 1 on an error.
+ */
+static void *ob_waiter(void *arg)
+{
+	int err;
+
+	ob_w_tid = gettid_();
+	sem_wait_sig(&ob_go);
+	if (ob_kind == OB_RIVAL)
+		err = set_deadline(0, 2 * NSEC_PER_MSEC, 10 * NSEC_PER_MSEC);
+	else
+		err = set_deadline(0, 5 * NSEC_PER_MSEC, 3 * PERIOD);
+	if (err) {
+		ksft_print_msg("the waiter refused as a deadline task: %s\n",
+			       strerror(-err));
+		if (ob_kind == OB_RIVAL)
+			sem_post(&ob_rival_go);	/* release the rival */
+		return (void *)1;
+	}
+	if (ob_kind == OB_RIVAL)
+		sem_post(&ob_rival_go);
+	ob_w_locking = 1;
+	if (take_pi_lock()) {
+		set_other(0);
+		return (void *)1;
+	}
+	ob_got_ms = (now_ns() - ob_t0) / NSEC_PER_MSEC;
+	drop_pi_lock();
+	if (set_other(0))
+		ksft_print_msg("the waiter cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run as the rival C of pi_owner_throttled_rival(). Become a deadline
+ * task of 40ms in 60ms, every 100ms. Wait until W is about to block,
+ * then sleep until 13ms after O's start, and spin 40ms of CPU time.
+ * Return NULL, or 1 on an error.
+ */
+static void *ob_rival(void *arg)
+{
+	struct timespec ts;
+	uint64_t end;
+	int err;
+
+	err = set_constrained(0, 40 * NSEC_PER_MSEC, 60 * NSEC_PER_MSEC, PERIOD);
+	if (err) {
+		ksft_print_msg("the rival refused as a deadline task: %s\n",
+			       strerror(-err));
+		return (void *)1;
+	}
+	sem_wait_sig(&ob_rival_go);
+	end = ob_t0 + 13 * NSEC_PER_MSEC;
+	ts.tv_sec = end / NSEC_PER_SEC;
+	ts.tv_nsec = end % NSEC_PER_SEC;
+	while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR)
+		;
+	spin_ns(40 * NSEC_PER_MSEC);
+	if (set_other(0))
+		ksft_print_msg("the rival cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run an owner_boost case of @kind: ob_owner() and ob_waiter(), and
+ * ob_rival() with OB_RIVAL. W must get pi_lock within @limit_ms of O's
+ * start.
+ */
+static int owner_boost_case(int kind, int limit_ms)
+{
+	void *o_ret = NULL, *w_ret = NULL, *c_ret = NULL;
+	int throttled = kind != OB_GAP && kind != OB_LATE_GAP;
+	int ret = KSFT_FAIL;
+	pthread_t o, w, c;
+
+	if (pi_init())
+		return KSFT_SKIP;
+	if (kind == OB_LONG) {
+		int had = klog_has(DL_LAG_MSG);
+
+		if (had) {
+			ksft_print_msg(had < 0 ? "the kernel log cannot be read\n" :
+				       "the lag message was logged before this case\n");
+			pi_fini();
+			return KSFT_SKIP;
+		}
+	}
+	if (sem_init(&ob_locked, 0, 0) || sem_init(&ob_go, 0, 0) ||
+	    sem_init(&ob_rival_go, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		pi_fini();
+		return KSFT_FAIL;
+	}
+	ob_throttled = throttled;
+	ob_kind = kind;
+	ob_got_ms = -1;
+	ob_w_locking = 0;
+	if (pthread_create(&w, NULL, ob_waiter, NULL)) {
+		ksft_print_msg("the waiter thread could not start\n");
+		goto out;
+	}
+	if (pthread_create(&o, NULL, ob_owner, NULL)) {
+		ksft_print_msg("the owner thread could not start\n");
+		sem_post(&ob_go);
+		join(w);
+		goto out;
+	}
+	/* O holds pi_lock, and runs until it is throttled or asleep. */
+	if (sem_wait_for(&ob_locked, 5000)) {
+		sem_post(&ob_go);
+		join(o);
+		join(w);
+		goto out;
+	}
+	if (kind == OB_GAP)
+		sleep_ns(30 * NSEC_PER_MSEC);	/* O sleeps past its deadline */
+	if (kind == OB_RIVAL && pthread_create(&c, NULL, ob_rival, NULL)) {
+		ksft_print_msg("the rival thread could not start\n");
+		kind = OB_THROTTLED;
+		c_ret = (void *)1;
+	}
+	sem_post(&ob_go);
+	pthread_join(o, &o_ret);
+	pthread_join(w, &w_ret);
+	if (kind == OB_RIVAL)
+		pthread_join(c, &c_ret);
+	if (o_ret || w_ret || c_ret || ob_got_ms < 0)
+		goto out;	/* the thread said why */
+	if (ob_got_ms >= limit_ms) {
+		ksft_print_msg("the waiter got the lock at %lld ms, not before %d\n",
+			       (long long)ob_got_ms, limit_ms);
+		goto out;
+	}
+	if (kind == OB_LONG && klog_has(DL_LAG_MSG) == 1) {
+		ksft_print_msg("the deboost logged \"%s\"\n", DL_LAG_MSG);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&ob_locked);
+	sem_destroy(&ob_go);
+	sem_destroy(&ob_rival_go);
+	pi_fini();
+	return ret;
+}
+
+/*
+ * A deadline waiter blocks on a lock whose owner sleeps past its deadline:
+ * 1. O becomes a deadline task of 10ms in 20ms, every 500ms, at 0ms. It
+ *    takes pi_lock and sleeps until 40ms.
+ * 2. At 30ms, W becomes a deadline task of 5ms every 300ms and blocks on
+ *    pi_lock. O's deadline, 20ms, is the earlier one.
+ * 3. O wakes up at 40ms, between its deadline and its next period, at
+ *    500ms. The wakeup would throttle it until then.
+ *
+ * W must boost O: O cannot run on its own reservation. O then runs at
+ * 40ms and unlocks. The case fails if W gets pi_lock at 200ms or later.
+ */
+static int pi_owner_asleep_in_gap(void)
+{
+	return owner_boost_case(OB_GAP, 200);
+}
+
+/*
+ * A deadline waiter blocks on a lock whose owner ran out of runtime:
+ * 1. O becomes a deadline task of 10ms every 100ms, at 0ms. It takes
+ *    pi_lock and spins 15ms of CPU time. It is throttled at 10ms, until
+ *    100ms.
+ * 2. W then becomes a deadline task of 5ms every 300ms and blocks on
+ *    pi_lock. O's deadline, 100ms, is the earlier one.
+ *
+ * W must boost O: O cannot run on its own reservation. O then runs its
+ * last 5ms on W's runtime and unlocks. The case fails if W gets pi_lock
+ * at 60ms or later.
+ */
+static int pi_owner_throttled(void)
+{
+	return owner_boost_case(OB_THROTTLED, 60);
+}
+
+/*
+ * A deadline waiter blocks on a lock whose owner can still run on its own
+ * reservation, and the owner then runs out of runtime:
+ * 1. O becomes a deadline task of 10ms every 100ms, at 0ms. It takes
+ *    pi_lock, and sleeps until W blocks on it.
+ * 2. W becomes a deadline task of 5ms every 300ms and blocks on pi_lock.
+ *    O's deadline, 100ms, is the earlier one: W does not boost O.
+ * 3. O spins 15ms of CPU time. It runs out of runtime after 10ms, with
+ *    pi_lock.
+ *
+ * W must boost O then: O cannot run on its own reservation until 100ms.
+ * O then runs its last 5ms on W's runtime and unlocks. The case fails if
+ * W gets pi_lock at 60ms or later.
+ */
+static int pi_owner_runs_out_later(void)
+{
+	return owner_boost_case(OB_LATE_THROTTLE, 60);
+}
+
+/*
+ * A deadline waiter blocks on a lock whose owner sleeps before its
+ * deadline:
+ * 1. O becomes a deadline task of 10ms in 20ms, every 500ms, at 0ms. It
+ *    takes pi_lock and sleeps until 40ms.
+ * 2. W becomes a deadline task of 5ms every 300ms and blocks on pi_lock,
+ *    before 20ms. O's deadline, 20ms, is the earlier one: W does not
+ *    boost O.
+ * 3. O wakes up at 40ms, between its deadline and its next period, at
+ *    500ms. The wakeup would throttle it until then.
+ *
+ * W must boost O at that wakeup. O then runs at 40ms and unlocks. The
+ * case fails if W gets pi_lock at 200ms or later.
+ */
+static int pi_owner_wakes_in_gap_later(void)
+{
+	return owner_boost_case(OB_LATE_GAP, 200);
+}
+
+static _Atomic unsigned long long ho_t0;
+static _Atomic long long ho_w_got_ms;
+static _Atomic pid_t ho_o_tid, ho_w_tid;
+static atomic_int ho_o_locking, ho_w_locking, ho_w_queued;
+
+/*
+ * Run as the owner O of pi_owner_handed_off(). Become a deadline task of
+ * 10ms every 100ms, and take pi_lock, which A holds. Once O has it, set
+ * ho_w_queued if W still waits for it. Spin 15ms of CPU time and unlock.
+ * Return NULL, or 1 on an error.
+ */
+static void *ho_owner(void *arg)
+{
+	int err;
+
+	ho_o_tid = gettid_();
+	err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	ho_t0 = now_ns();
+	if (err) {
+		ksft_print_msg("the owner refused as a deadline task: %s\n",
+			       strerror(-err));
+		return (void *)1;
+	}
+	ho_o_locking = 1;
+	if (take_pi_lock()) {
+		set_other(0);
+		return (void *)1;
+	}
+	ho_w_queued = ho_w_got_ms < 0 && proc_state_of(ho_w_tid) == 'S';
+	spin_ns(15 * NSEC_PER_MSEC);
+	drop_pi_lock();
+	if (set_other(0))
+		ksft_print_msg("the owner cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run as the waiter W of pi_owner_handed_off(). Become a deadline task of
+ * 5ms every 300ms and take pi_lock. Store in ho_w_got_ms the time at
+ * which W gets it. Return NULL, or 1 on an error.
+ */
+static void *ho_waiter(void *arg)
+{
+	int err;
+
+	ho_w_tid = gettid_();
+	err = set_deadline(0, 5 * NSEC_PER_MSEC, 3 * PERIOD);
+	if (err) {
+		ksft_print_msg("the waiter refused as a deadline task: %s\n",
+			       strerror(-err));
+		return (void *)1;
+	}
+	ho_w_locking = 1;
+	if (take_pi_lock()) {
+		set_other(0);
+		return (void *)1;
+	}
+	ho_w_got_ms = (now_ns() - ho_t0) / NSEC_PER_MSEC;
+	drop_pi_lock();
+	if (set_other(0))
+		ksft_print_msg("the waiter cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * A variant of pi_owner_runs_out_later(): the owner gets the lock by a
+ * hand-off, with the waiter already queued on it. A, the main thread of
+ * the case, is a SCHED_OTHER task:
+ * 1. A takes pi_lock.
+ * 2. O becomes a deadline task of 10ms every 100ms, at 0ms. It blocks on
+ *    pi_lock.
+ * 3. W becomes a deadline task of 5ms every 300ms. It blocks on pi_lock.
+ * 4. A unlocks. O's deadline, about 100ms, is the earlier one. So O gets
+ *    pi_lock, and W stays queued on it. O can still run on its own
+ *    reservation, so W does not boost it.
+ * 5. O spins 15ms of CPU time. It runs out of runtime after 10ms, with
+ *    pi_lock.
+ *
+ * W must boost O then: O cannot run on its own reservation until about
+ * 100ms. W blocked on pi_lock before O owned it. So the boost must find W
+ * among the waiters that O got with the lock. O then runs its last 5ms on
+ * W's runtime and unlocks. The case fails if W does not wait for pi_lock
+ * when O gets it, or if W gets pi_lock at 60ms or later.
+ */
+static int pi_owner_handed_off(void)
+{
+	void *o_ret = NULL, *w_ret = NULL;
+	int ret = KSFT_FAIL, w_blocked;
+	pthread_t o, w;
+
+	if (pi_init())
+		return KSFT_SKIP;
+	ho_o_tid = 0;
+	ho_w_tid = 0;
+	ho_o_locking = 0;
+	ho_w_locking = 0;
+	ho_w_queued = 0;
+	ho_w_got_ms = -1;
+	if (take_pi_lock())
+		goto out;
+	w_blocked = 1;
+	if (pthread_create(&o, NULL, ho_owner, NULL)) {
+		ksft_print_msg("the owner thread could not start\n");
+		drop_pi_lock();
+		goto out;
+	}
+	if (wait_for(1000, ho_o_locking && proc_state_of(ho_o_tid) == 'S')) {
+		ksft_print_msg("the owner did not block on the lock\n");
+		drop_pi_lock();
+		join(o);
+		goto out;
+	}
+	if (pthread_create(&w, NULL, ho_waiter, NULL)) {
+		ksft_print_msg("the waiter thread could not start\n");
+		drop_pi_lock();
+		join(o);
+		goto out;
+	}
+	if (wait_for(1000, ho_w_locking && proc_state_of(ho_w_tid) == 'S')) {
+		ksft_print_msg("the waiter did not block on the lock\n");
+		w_blocked = 0;
+	}
+	drop_pi_lock();
+	pthread_join(o, &o_ret);
+	pthread_join(w, &w_ret);
+	if (!w_blocked || o_ret || w_ret || ho_w_got_ms < 0)
+		goto out;	/* the thread said why */
+	if (!ho_w_queued) {
+		ksft_print_msg("the waiter did not wait when the owner got the lock\n");
+		goto out;
+	}
+	if (ho_w_got_ms >= 60) {
+		ksft_print_msg("the waiter got the lock at %lld ms, not before 60\n",
+			       (long long)ho_w_got_ms);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	pi_fini();
+	return ret;
+}
+
+/*
+ * The owner of pi_owner_throttled() changes its parameters while boosted:
+ * 1. As in pi_owner_throttled(), O is throttled at 10ms, and W boosts it.
+ * 2. After 12ms of CPU time, O changes itself to 9ms every 100ms. Then it
+ *    changes W to 5ms every 310ms. This change of W walks the chain to O.
+ *    O has new parameters, so rt_mutex_setprio() deboosts O before it
+ *    compares O with W.
+ *
+ * O has used up its own runtime until 100ms, so W must boost it again.
+ * O then runs its last 3ms and unlocks. The case fails if W gets pi_lock
+ * at 60ms or later.
+ */
+static int pi_owner_held_new_params(void)
+{
+	return owner_boost_case(OB_NEW_PARAMS, 60);
+}
+
+/*
+ * A deadline task C competes with the boosted owner of
+ * pi_owner_throttled():
+ * 1. O becomes a deadline task of 10ms every 100ms, at 0ms. Its deadline
+ *    is 100ms. It takes pi_lock and spins 15ms of CPU time. It is
+ *    throttled at 10ms.
+ * 2. W then becomes a deadline task of 2ms every 10ms, and blocks on
+ *    pi_lock. Its deadline is about 20ms. W boosts O.
+ * 3. C becomes a deadline task of 40ms in 60ms, every 100ms. It wakes up
+ *    at 13ms, with a deadline of about 70ms, and spins 40ms.
+ *
+ * Boosted, O must run on W's deadlines, before C's. O then runs its last
+ * 5ms and unlocks. Refilled from its own deadline, O would get a deadline
+ * of 110ms. That is after C's, so O would wait for C. The case fails if W
+ * gets pi_lock at 35ms or later.
+ */
+static int pi_owner_throttled_rival(void)
+{
+	return owner_boost_case(OB_RIVAL, 35);
+}
+
+/*
+ * The owner of pi_owner_throttled() stays boosted past its own next
+ * period:
+ * 1. As in pi_owner_throttled(), O is throttled at 10ms, and W boosts it.
+ * 2. After 12ms of CPU time, O sleeps until 250ms with the lock. Its own
+ *    period ends at 100ms, during that sleep.
+ * 3. O unlocks at 250ms.
+ *
+ * The deboost must start a period of O's own. Putting back the period
+ * that ended at 100ms would make the next refill print "sched: DL
+ * replenish lagged too much". The case fails if that message is logged,
+ * or if W gets pi_lock at 400ms or later. It skips if the message was
+ * logged before: the kernel prints it once.
+ */
+static int pi_owner_held_long(void)
+{
+	return owner_boost_case(OB_LONG, 400);
+}
+
+/*
+ * The threads of reboost_loop_case(): rb_owner() for each owner, rb_waiter()
+ * and rb_victim(). Each owner holds its own lock in rb_lock[].
+ */
+#define RB_OWNERS	2	/* the most owners of a case */
+#define RB_JOBS		20	/* periods of the victim */
+#define RB_RUNTIME	(35 * NSEC_PER_MSEC)	/* of the victim */
+#define RB_PERIOD	(50 * NSEC_PER_MSEC)	/* of the victim */
+
+static pthread_mutex_t rb_lock[RB_OWNERS];
+static sem_t rb_locked, rb_ready, rb_go, rb_go_w;
+static atomic_int rb_stop, rb_release;
+static uint64_t rb_victim_ns, rb_waits;
+
+/*
+ * Run as an owner of reboost_loop_case(). Become a deadline task of 1ms
+ * every 3s, take rb_lock[@arg] and post rb_locked. Spin until rb_release
+ * is set, then unlock. Return NULL, or 1 on an error.
+ */
+static void *rb_owner(void *arg)
+{
+	long i = (long)arg;
+	int err = set_deadline(0, NSEC_PER_MSEC, 30 * PERIOD);
+
+	if (err) {
+		ksft_print_msg("an owner refused as a deadline task: %s\n",
+			       strerror(-err));
+		sem_post(&rb_locked);
+		return (void *)1;
+	}
+	err = pthread_mutex_lock(&rb_lock[i]);
+	sem_post(&rb_locked);
+	if (err) {
+		ksft_print_msg("an owner cannot take its lock: %s\n", strerror(err));
+		set_other(0);
+		return (void *)1;
+	}
+	while (!atomic_load(&rb_release))
+		;
+	err = pthread_mutex_unlock(&rb_lock[i]);
+	if (err)
+		ksft_print_msg("an owner cannot unlock: %s\n", strerror(err));
+	if (set_other(0))
+		ksft_print_msg("an owner cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+/*
+ * Run as the waiter of reboost_loop_case(), with @arg owners. Become a
+ * deadline task of 1ms every 10ms, post rb_ready and wait for rb_go_w.
+ * Until rb_stop is set, wait 1ms for each lock in turn, and count the
+ * waits in rb_waits. Each wait boosts the owner, and must time out. Then
+ * set rb_release, and take each lock without a timeout: its owner runs
+ * on the boost and unlocks. Return NULL, or 1 on an error.
+ */
+static void *rb_waiter(void *arg)
+{
+	int n = (long)arg, i = 0, err, bad = 0;
+
+	err = set_deadline(0, NSEC_PER_MSEC, 10 * NSEC_PER_MSEC);
+	if (err) {
+		ksft_print_msg("the waiter refused as a deadline task: %s\n",
+			       strerror(-err));
+		bad = 1;
+	}
+	sem_post(&rb_ready);
+	sem_wait_sig(&rb_go_w);
+	while (!bad && !atomic_load(&rb_stop)) {
+		struct timespec ts;
+
+		clock_gettime(CLOCK_REALTIME, &ts);
+		ts.tv_nsec += 1000000L;
+		ts.tv_sec += ts.tv_nsec / 1000000000L;
+		ts.tv_nsec %= 1000000000L;
+		err = pthread_mutex_timedlock(&rb_lock[i], &ts);
+		if (err != ETIMEDOUT) {
+			ksft_print_msg("a wait of 1ms for a lock: %s, not a timeout\n",
+				       err ? strerror(err) : "got it");
+			if (!err)
+				pthread_mutex_unlock(&rb_lock[i]);
+			bad = 1;
+			break;
+		}
+		rb_waits++;
+		i = (i + 1) % n;
+	}
+	atomic_store(&rb_release, 1);
+	for (i = 0; i < n; i++) {
+		err = pthread_mutex_lock(&rb_lock[i]);
+		if (err) {
+			ksft_print_msg("the waiter cannot take a lock: %s\n", strerror(err));
+			bad = 1;
+			continue;
+		}
+		pthread_mutex_unlock(&rb_lock[i]);
+	}
+	if (set_other(0))
+		ksft_print_msg("the waiter cannot leave SCHED_DEADLINE\n");
+	return bad ? (void *)1 : NULL;
+}
+
+/*
+ * Run as the victim of reboost_loop_case(). Become a deadline task of
+ * RB_RUNTIME every RB_PERIOD, post rb_ready and wait for rb_go. Then
+ * start the waiter with rb_go_w. In each of RB_JOBS periods, spin until
+ * this thread has run RB_RUNTIME in the period or the period ends. Then
+ * sleep until the next period. Store the CPU time it got in rb_victim_ns,
+ * and set rb_stop. Return NULL, or 1 on an error.
+ */
+static void *rb_victim(void *arg)
+{
+	uint64_t next, cpu;
+	int err, j;
+
+	err = set_deadline(0, RB_RUNTIME, RB_PERIOD);
+	if (err) {
+		ksft_print_msg("the victim refused as a deadline task: %s\n",
+			       strerror(-err));
+		atomic_store(&rb_stop, 1);
+		sem_post(&rb_ready);
+		sem_post(&rb_go_w);
+		return (void *)1;
+	}
+	sem_post(&rb_ready);
+	sem_wait_sig(&rb_go);
+	cpu = thread_time_ns();
+	next = now_ns();
+	sem_post(&rb_go_w);
+	for (j = 0; j < RB_JOBS; j++) {
+		uint64_t job = thread_time_ns();
+		struct timespec ts;
+
+		next += RB_PERIOD;
+		while (thread_time_ns() - job < RB_RUNTIME && now_ns() < next)
+			;
+		ts.tv_sec = next / NSEC_PER_SEC;
+		ts.tv_nsec = next % NSEC_PER_SEC;
+		while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR)
+			;
+	}
+	rb_victim_ns = thread_time_ns() - cpu;
+	atomic_store(&rb_stop, 1);
+	if (set_other(0))
+		ksft_print_msg("the victim cannot leave SCHED_DEADLINE\n");
+	return NULL;
+}
+
+/*
+ * Run the scenario of pi_owner_reboost_loop() with @n owners: start
+ * rb_owner() for each, then rb_waiter() and rb_victim(). Fail if the
+ * waiter waits fewer than 100 times, or if the victim gets less than 95%
+ * of its runtime.
+ */
+static int reboost_loop_case(int n)
+{
+	uint64_t need = RB_JOBS * RB_RUNTIME;
+	void *r, *bad = NULL;
+	pthread_mutexattr_t a;
+	pthread_t o[RB_OWNERS], w, v;
+	int i, started = 0, inited = 0, ret = KSFT_FAIL;
+
+	if (pthread_mutexattr_init(&a))
+		return KSFT_SKIP;
+	if (pthread_mutexattr_setprotocol(&a, PTHREAD_PRIO_INHERIT)) {
+		pthread_mutexattr_destroy(&a);
+		ksft_print_msg("no priority inheritance mutex\n");
+		return KSFT_SKIP;
+	}
+	for (; inited < n; inited++)
+		if (pthread_mutex_init(&rb_lock[inited], &a))
+			break;
+	pthread_mutexattr_destroy(&a);
+	if (inited < n || sem_init(&rb_locked, 0, 0) || sem_init(&rb_ready, 0, 0) ||
+	    sem_init(&rb_go, 0, 0) || sem_init(&rb_go_w, 0, 0)) {
+		ksft_print_msg("the locks or semaphores cannot be set up\n");
+		goto out_locks;
+	}
+	atomic_store(&rb_stop, 0);
+	atomic_store(&rb_release, 0);
+	rb_victim_ns = 0;
+	rb_waits = 0;
+	for (; started < n; started++) {
+		if (pthread_create(&o[started], NULL, rb_owner, (void *)(long)started)) {
+			ksft_print_msg("an owner thread could not start\n");
+			break;
+		}
+	}
+	for (i = 0; i < started; i++)
+		if (sem_wait_for(&rb_locked, 5000))
+			break;
+	if (started < n || i < started)
+		goto out_owners;
+	/* Each owner holds its lock, and is throttled after 1ms. */
+	sleep_ns(20 * NSEC_PER_MSEC);
+	if (pthread_create(&w, NULL, rb_waiter, (void *)(long)n)) {
+		ksft_print_msg("the waiter thread could not start\n");
+		goto out_owners;
+	}
+	if (pthread_create(&v, NULL, rb_victim, NULL)) {
+		ksft_print_msg("the victim thread could not start\n");
+		atomic_store(&rb_stop, 1);
+		sem_post(&rb_go_w);
+		pthread_join(w, &r);
+		goto out_owners;
+	}
+	/*
+	 * Wait until the waiter and the victim are deadline tasks. Then start
+	 * the victim, which starts the waiter. This thread is not a deadline
+	 * task. If it posted to both, the boosted owner could keep it off the
+	 * CPU between the two posts.
+	 */
+	if (sem_wait_for(&rb_ready, 5000) || sem_wait_for(&rb_ready, 5000))
+		atomic_store(&rb_stop, 1);
+	sem_post(&rb_go);
+	pthread_join(v, &r);
+	bad = r;
+	pthread_join(w, &r);
+	bad = bad ? bad : r;
+	for (i = 0; i < started; i++) {
+		pthread_join(o[i], &r);
+		bad = bad ? bad : r;
+	}
+	started = 0;
+	if (bad)
+		goto out;	/* the thread said why */
+	if (rb_waits < 100) {
+		ksft_print_msg("the waiter waited only %llu times\n",
+			       (unsigned long long)rb_waits);
+		goto out;
+	}
+	if (rb_victim_ns * 100 < need * 95) {
+		ksft_print_msg("the victim ran %llu of its %llu ms, after %llu waits\n",
+			       (unsigned long long)(rb_victim_ns / NSEC_PER_MSEC),
+			       (unsigned long long)(need / NSEC_PER_MSEC),
+			       (unsigned long long)rb_waits);
+		goto out;
+	}
+	ret = KSFT_PASS;
+	goto out;
+out_owners:
+	/*
+	 * A throttled owner runs again at its next period, within 3s, and
+	 * sees rb_release.
+	 */
+	atomic_store(&rb_stop, 1);
+	atomic_store(&rb_release, 1);
+	for (i = 0; i < started; i++)
+		join(o[i]);
+out:
+	sem_destroy(&rb_locked);
+	sem_destroy(&rb_ready);
+	sem_destroy(&rb_go);
+	sem_destroy(&rb_go_w);
+out_locks:
+	while (inited--)
+		pthread_mutex_destroy(&rb_lock[inited]);
+	return ret;
+}
+
+/*
+ * A waiter boosts a throttled owner over and over:
+ * 1. O becomes a deadline task of 1ms every 3s. It takes a lock and
+ *    spins. It is throttled after 1ms, until its next period.
+ * 2. 20ms later, W becomes a deadline task of 1ms every 10ms. It waits
+ *    for the lock again and again, until V is done. Each wait boosts O
+ *    and times out after 1ms.
+ * 3. At the same time, V becomes a deadline task of 35ms every 50ms. It
+ *    spins 35ms in each of 20 periods, for 1s in all.
+ *
+ * O runs only while W boosts it. It must get at most W's runtime in each
+ * of W's periods: 10% of the CPU. That fits with V's 70%. If each boost
+ * started a new period of W for O, O would get 1ms at every wait, with a
+ * deadline 10ms away. It would then run at every boost, before V. The
+ * case fails if V runs less than 95% of its 700ms, or if W waits fewer
+ * than 100 times.
+ */
+static int pi_owner_reboost_loop(void)
+{
+	return reboost_loop_case(1);
+}
+
+/*
+ * As pi_owner_reboost_loop(), with two owners, each holding its own lock.
+ * W waits for the two locks in turn. The limit applies to each owner
+ * separately: each can get W's runtime in each of W's periods. Together
+ * they can get 20% of the CPU, which still fits with V's 70%. The case
+ * fails as pi_owner_reboost_loop() does.
+ */
+static int pi_owners_reboost_loop(void)
+{
+	return reboost_loop_case(2);
+}
+
+static sem_t ota_locked, ota_wgo, ota_wout, ota_owake;
+static atomic_int ota_wlocking;
+static _Atomic pid_t ota_o_tid, ota_w_tid;
+static _Atomic unsigned long long ota_t0;
+
+/*
+ * Run as the owner O of pi_owner_throttled_asleep(). Its comment has the
+ * steps. Return NULL, or 1 on an error.
+ */
+static void *ota_owner(void *arg)
+{
+	uint64_t t0;
+	int err;
+
+	ota_o_tid = gettid_();
+	err = set_deadline(0, 10 * NSEC_PER_MSEC, PERIOD);
+	ota_t0 = now_ns();
+	if (err || take_pi_lock()) {
+		if (err)
+			ksft_print_msg("the owner refused as a deadline task: %s\n",
+				       strerror(-err));
+		sem_post(&ota_locked);
+		set_other(0);
+		return (void *)1;
+	}
+	sem_post(&ota_locked);
+	spin_ns(12 * NSEC_PER_MSEC);	/* throttled at 10ms: W boosts it */
+	t0 = now_ns();
+	while (!ota_wlocking || proc_state_of(ota_w_tid) != 'S') {
+		if (now_ns() - t0 > NSEC_PER_SEC) {
+			ksft_print_msg("the waiter did not block on the lock\n");
+			drop_pi_lock();
+			set_other(0);
+			return (void *)1;
+		}
+	}
+	spin_ns(3 * NSEC_PER_MSEC);	/* on W's runtime */
+	sem_wait_sig(&ota_owake);
+	drop_pi_lock();
+	set_other(0);
+	return NULL;
+}
+
+/*
+ * Run as the waiter W of pi_owner_throttled_asleep(). Wait for ota_wgo.
+ * Then become a deadline task of 5ms every 300ms, wait 50ms for pi_lock,
+ * and leave the class. Return NULL if the wait timed out, or 1 otherwise.
+ */
+static void *ota_waiter(void *arg)
+{
+	struct timespec ts;
+	int err;
+
+	ota_w_tid = gettid_();
+	sem_wait_sig(&ota_wgo);
+	err = set_deadline(0, 5 * NSEC_PER_MSEC, 3 * PERIOD);
+	if (err) {
+		ksft_print_msg("the waiter refused as a deadline task: %s\n",
+			       strerror(-err));
+		sem_post(&ota_wout);
+		return (void *)1;
+	}
+	clock_gettime(CLOCK_REALTIME, &ts);
+	ts.tv_nsec += 50 * 1000000L;
+	ts.tv_sec += ts.tv_nsec / 1000000000L;
+	ts.tv_nsec %= 1000000000L;
+	ota_wlocking = 1;
+	err = pthread_mutex_timedlock(&pi_lock, &ts);
+	if (!err)
+		pthread_mutex_unlock(&pi_lock);
+	if (set_other(0))
+		ksft_print_msg("the waiter cannot leave SCHED_DEADLINE\n");
+	sem_post(&ota_wout);
+	if (err != ETIMEDOUT) {
+		ksft_print_msg("the waiter: %s, not a timeout\n",
+			       err ? strerror(err) : "got pi_lock");
+		return (void *)1;
+	}
+	return NULL;
+}
+
+/*
+ * A deboost puts back the reservation of an owner that sleeps. The
+ * threads share the CPU of P:
+ * 1. O becomes a deadline task of 10ms every 100ms, at 0ms. It takes
+ *    pi_lock and spins. It runs out of runtime at 10ms, until 100ms.
+ * 2. W becomes a deadline task of 5ms every 300ms, and waits 50ms for
+ *    pi_lock. O cannot run on its own reservation: W boosts it.
+ * 3. O runs 3ms on W's runtime, then sleeps, boosted.
+ * 4. W times out, at about 60ms, and leaves the class.
+ * 5. The main thread switches O to SCHED_OTHER. At 180ms, it reads
+ *    total_bw.
+ *
+ * O went to sleep with the runtime and the deadline of W's refill. Mixed
+ * with O's own parameters, they put its 0-lag time more than 200ms
+ * ahead. The deboost puts back O's own runtime and deadline. Their 0-lag
+ * time is about 100ms. O's bandwidth must be gone from total_bw at
+ * 180ms.
+ */
+static int pi_owner_throttled_asleep(void)
+{
+	void *o_ret = NULL, *w_ret = NULL;
+	long long base, bw = -1;
+	int err, ret = KSFT_FAIL;
+	pthread_t o, w;
+	uint64_t at;
+
+	if (total_bw_of(top_cpu(1)) < 0) {
+		ksft_print_msg("sched_debug tells of no total_bw\n");
+		return KSFT_SKIP;
+	}
+	if (pi_init())
+		return KSFT_SKIP;
+	if (sem_init(&ota_locked, 0, 0) || sem_init(&ota_wgo, 0, 0) ||
+	    sem_init(&ota_wout, 0, 0) || sem_init(&ota_owake, 0, 0)) {
+		ksft_print_msg("sem_init: %s\n", strerror(errno));
+		pi_fini();
+		return KSFT_SKIP;
+	}
+	ota_wlocking = 0;
+	ota_w_tid = 0;
+	ota_o_tid = 0;
+	base = total_bw_of(top_cpu(1));	/* without O and W */
+	if (pthread_create(&w, NULL, ota_waiter, NULL)) {
+		ksft_print_msg("the waiter thread could not start\n");
+		goto out;
+	}
+	if (pthread_create(&o, NULL, ota_owner, NULL)) {
+		ksft_print_msg("the owner thread could not start\n");
+		sem_post(&ota_wgo);
+		join(w);
+		goto out;
+	}
+	/* The main thread runs once O is throttled. */
+	if (sem_wait_for(&ota_locked, 5000)) {
+		sem_post(&ota_wgo);
+		sem_post(&ota_owake);
+		join(w);
+		join(o);
+		goto out;
+	}
+	sem_post(&ota_wgo);
+	if (sem_wait_for(&ota_wout, 5000)) {
+		ksft_print_msg("the waiter did not time out\n");
+	} else if (wait_for(1000, proc_state_of(ota_o_tid) == 'S')) {
+		ksft_print_msg("the owner is not asleep\n");
+	} else {
+		err = set_other(ota_o_tid);
+		if (err) {
+			ksft_print_msg("the owner cannot leave SCHED_DEADLINE: %s\n",
+				       strerror(-err));
+		} else {
+			at = ota_t0 + 180 * NSEC_PER_MSEC;
+			while (now_ns() < at)
+				sleep_ns(NSEC_PER_MSEC);
+			bw = total_bw_of(top_cpu(1));
+		}
+	}
+	sem_post(&ota_owake);
+	pthread_join(w, &w_ret);
+	pthread_join(o, &o_ret);
+	if (o_ret || w_ret || bw < 0)
+		goto out;	/* a thread said why */
+	if (bw != base) {
+		ksft_print_msg("total_bw %lld at 180ms, %lld expected\n", bw, base);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_destroy(&ota_locked);
+	sem_destroy(&ota_wgo);
+	sem_destroy(&ota_wout);
+	sem_destroy(&ota_owake);
+	pi_fini();
+	return ret;
+}
+
 static pthread_mutex_t pi_lock2;
 static sem_t holder_go;
 static atomic_int holder_holds, chain_waits, donor_done, x_waits, l2_takes;
@@ -2885,8 +6134,8 @@ static int take_l2_ranked(atomic_int *rank)
  * boost refills its runtime from the donor's 40ms. Then wait on pi_lock2
  * while holding pi_lock. The donor's timeout deboosts the owner during
  * that wait. The owner then has more runtime left than its own 10ms.
- * Return NULL, 1 on an error, or 2 if the spin took over 50ms: the owner
- * was throttled, so it was not boosted.
+ * Return NULL, or 1 on an error. Return 2 if the spin took over 50ms.
+ * The owner was then throttled, so it was not boosted.
  */
 static void *chain_owner(void *arg)
 {
@@ -3224,6 +6473,137 @@ static int boost_blocked_keeps_order(void)
 	return blocked_keeps_order(1);
 }
 
+static int dl_waiter_spin_ms;
+
+/*
+ * A waiter of pi_lock2 that is a deadline task of 400ms every 1s. It
+ * spins dl_waiter_spin_ms of CPU time once it starts its period, then
+ * waits. It leaves the class at the end.
+ */
+static void *dl_waiter(void *arg)
+{
+	int err;
+
+	fair_tid = gettid_();
+	err = set_deadline(0, 400 * NSEC_PER_MSEC, NSEC_PER_SEC);
+	if (err) {
+		ksft_print_msg("a waiter refused as a deadline task: %s\n", strerror(-err));
+		return (void *)1;
+	}
+	spin_ns(dl_waiter_spin_ms * NSEC_PER_MSEC);
+	chain_waits = 1;
+	err = take_l2_ranked(&chain_rank);
+	if (set_other(0))
+		ksft_print_msg("a waiter cannot leave SCHED_DEADLINE\n");
+	return err ? (void *)1 : NULL;
+}
+
+static int setattr_blocked_case(int reenter);
+
+/*
+ * Check the order of the waiters of pi_lock2 when sched_setattr() changes
+ * the parameters of one of them while it waits. The holder has pi_lock2:
+ * 1. W, a deadline task of 400ms every 1s, waits on pi_lock2. Its
+ *    deadline is about 1s ahead.
+ * 2. The other waiter, a deadline task of 5ms every 50ms, waits on
+ *    pi_lock2. Its deadline is about 50ms ahead.
+ * 3. The main thread gives W 1ms every 10ms. W has not run, so it owes
+ *    nothing: it starts a new period at once. Its deadline is 10ms ahead.
+ * 4. The holder drops pi_lock2.
+ *
+ * W must take pi_lock2 first. W is not queued at step 3. Unless its
+ * period is fitted to its new parameters then, its waiter node keeps the
+ * deadline 1s ahead.
+ */
+static int setattr_blocked_new_period(void)
+{
+	return setattr_blocked_case(0);
+}
+
+/*
+ * The same, when W leaves the class and comes back while it waits. W
+ * first spins 100ms: 60ms more than its share, so its 0-lag time is about
+ * 250ms ahead. At step 3, the main thread switches W to SCHED_OTHER, then
+ * back to SCHED_DEADLINE with 3ms every 10ms. W keeps its parameters
+ * until its 0-lag time, so it comes back with that debt. Repaid at 30%,
+ * the debt puts W's next period about 190ms ahead. W must take pi_lock2
+ * after the other waiter. A new period at once, as a wakeup would start,
+ * would let W take it first.
+ */
+static int setattr_blocked_reenter(void)
+{
+	return setattr_blocked_case(1);
+}
+
+/*
+ * Run setattr_blocked_new_period(), or setattr_blocked_reenter() if
+ * @reenter is set.
+ */
+static int setattr_blocked_case(int reenter)
+{
+	void *w_ret = NULL, *x_ret = NULL;
+	int ret = KSFT_FAIL, have_w = 0, have_x = 0, err;
+	pthread_t h, w, x;
+
+	if (pi_init())
+		return KSFT_SKIP;
+	if (pi_init_lock2()) {
+		pi_fini();
+		return KSFT_SKIP;
+	}
+	if (pthread_create(&h, NULL, l2_holder, NULL)) {
+		ksft_print_msg("the holder thread could not start\n");
+		goto out_fini;
+	}
+	if (wait_for(5000, holder_holds) || holder_holds != 1) {
+		ksft_print_msg("the holder never took pi_lock2\n");
+		goto out;
+	}
+	dl_waiter_spin_ms = reenter ? 100 : 0;
+	have_w = !pthread_create(&w, NULL, dl_waiter, NULL);
+	if (!have_w || wait_for(1000, chain_waits && proc_state_of(fair_tid) == 'S')) {
+		ksft_print_msg("the waiter W never waited on pi_lock2\n");
+		goto out;
+	}
+	have_x = !pthread_create(&x, NULL, early_waiter, NULL);
+	if (!have_x || wait_for(1000, x_waits && proc_state_of(x_tid) == 'S')) {
+		ksft_print_msg("the other waiter never waited on pi_lock2\n");
+		goto out;
+	}
+	err = reenter ? set_other(fair_tid) : 0;
+	if (err) {
+		ksft_print_msg("W cannot leave SCHED_DEADLINE: %s\n", strerror(-err));
+		goto out;
+	}
+	err = set_deadline(fair_tid, (reenter ? 3 : 1) * NSEC_PER_MSEC, 10 * NSEC_PER_MSEC);
+	if (err) {
+		ksft_print_msg("new parameters for W refused: %s\n", strerror(-err));
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	sem_post(&holder_go);	/* pi_lock2 goes to its top waiter */
+	if (have_x && pthread_join(x, &x_ret))
+		ret = KSFT_FAIL;
+	if (have_w && pthread_join(w, &w_ret))
+		ret = KSFT_FAIL;
+	join(h);
+	if (w_ret || x_ret) {
+		ret = KSFT_FAIL;	/* the thread said why */
+	} else if (ret == KSFT_PASS && !reenter && chain_rank > x_rank) {
+		ksft_print_msg("W took pi_lock2 after the other waiter\n");
+		ret = KSFT_FAIL;
+	} else if (ret == KSFT_PASS && reenter && chain_rank < x_rank) {
+		ksft_print_msg("W took pi_lock2 before the other waiter\n");
+		ret = KSFT_FAIL;
+	}
+out_fini:
+	pthread_mutex_destroy(&pi_lock2);
+	sem_destroy(&holder_go);
+	pi_fini();
+	return ret;
+}
+
 /*
  * The threads of pi_chain_donor_leaves(): O, M, W, Z and Y. leave_tid[]
  * holds their tids. leave_y_ns is the CPU time Y gets in O's window, or
@@ -7171,6 +10551,144 @@ static int params_waking(void)
 	return ret;
 }
 
+/* Two tasks that pass a large runtime back and forth */
+
+#define SW_BIG		(70 * NSEC_PER_MSEC)
+#define SW_SMALL	NSEC_PER_MSEC
+#define SW_MARGIN	(10 * NSEC_PER_MSEC)	/* raise a task of 1ms below this */
+#define SW_SETTLE	(500 * NSEC_PER_MSEC)
+#define SW_WINDOW	(2 * NSEC_PER_SEC)
+#define SW_MAX_SHARE	85			/* fail at this % of P's CPU */
+
+/*
+ * sw_state[i] is 1 once task i is in P, and -1 if it could not enter.
+ * sw_state[2 + i] is the CPU time it used, in us.
+ */
+static atomic_int *sw_state;
+
+/*
+ * Fork task @i of params_swap_overload() into P. It spins, and writes
+ * the CPU time it used to sw_state[2 + @i]. Return its pid, or -1.
+ */
+static pid_t sw_task(int i)
+{
+	pid_t pid = fork_child("a task of the swap");
+	uint64_t c0;
+
+	if (pid)
+		return pid;
+	if (enter(cg_p, getpid())) {
+		sw_state[i] = -1;
+		_exit(1);
+	}
+	c0 = thread_time_ns();
+	sw_state[i] = 1;
+	for (;;)
+		sw_state[2 + i] = (thread_time_ns() - c0) / NSEC_PER_USEC;
+}
+
+/*
+ * Pass a runtime of 70ms back and forth between two tasks, as in
+ * Example 1 of "On the Defectiveness of SCHED_DEADLINE w.r.t. Tardiness
+ * and Affinities, and a Partial Fix", Tang, Anderson and Abeni, RTNS
+ * 2021. P has one CPU. A and B are processes in P that spin. The main
+ * process, outside P, changes their parameters with sched_setattr():
+ * 1. It makes A a deadline task of 70ms every 100ms. This releases a
+ *    job of 70ms. It then cuts the runtime of A to 1ms.
+ * 2. It does the same with B.
+ * 3. For 2.5s, it polls the runtime left of A and B in /proc. It cuts a
+ *    task of 70ms to 1ms once the task is refilled. It raises a task of
+ *    1ms to 70ms when less than 10ms is left, if the other one is a task
+ *    of 1ms. The next job of the raised task then gets 70ms.
+ *
+ * Admission control sees at most 71% of the CPU, plus the fair server.
+ * If a change keeps the runtime of the job in progress, every job gets
+ * 70ms. A and B then ask for 140% of the CPU, and get the whole CPU. A
+ * change must cap the runtime left at the new runtime, and keep the debt
+ * of the task. A and B then get no more than their 71%. The case fails if
+ * they get 85% of the CPU or more in the last 2s.
+ *
+ * The paper uses 94ms. P cannot admit 94ms and 1ms: its limit is 95%,
+ * and its fair server takes 5% of it. In the paper, the tardiness also
+ * grows without bound. Here it does not: a change of a task past its
+ * deadline starts a new period. So the case measures the CPU time of A
+ * and B, not their deadlines.
+ */
+static int params_swap_overload(void)
+{
+	uint64_t param[2] = { SW_SMALL, SW_SMALL }, start, t, t0 = 0, t1;
+	int cpu0[2] = { 0, 0 }, err = 0, i, changes = 0, ret = KSFT_FAIL;
+	pid_t pid[2] = { -1, -1 };
+	long long used[2];
+
+	sw_state = mv_state + 8;
+	for (i = 0; i < 4; i++)
+		sw_state[i] = 0;
+	pid[0] = sw_task(0);
+	pid[1] = sw_task(1);
+	if (pid[0] < 0 || pid[1] < 0)
+		goto out;
+	if (wait_for(5000, sw_state[0] && sw_state[1]) ||
+	    sw_state[0] < 0 || sw_state[1] < 0) {
+		ksft_print_msg("the tasks could not enter P\n");
+		goto out;
+	}
+	for (i = 0; i < 2 && !err; i++) {
+		err = set_deadline(pid[i], SW_BIG, PERIOD);
+		if (!err)
+			err = set_deadline(pid[i], SW_SMALL, PERIOD);
+	}
+	if (err) {
+		ksft_print_msg("no room for a task of 70ms in P: %s\n", strerror(-err));
+		ret = err == -EBUSY ? KSFT_SKIP : KSFT_FAIL;
+		goto out;
+	}
+	start = now_ns();
+	while (!err && (t = now_ns()) < start + SW_SETTLE + SW_WINDOW) {
+		if (!t0 && t >= start + SW_SETTLE) {
+			t0 = t;
+			cpu0[0] = sw_state[2];
+			cpu0[1] = sw_state[3];
+		}
+		for (i = 0; i < 2 && !err; i++) {
+			long long left = dl_runtime_left(pid[i]);
+			uint64_t to;
+
+			if (param[i] == SW_BIG && left > (long long)SW_BIG / 2)
+				to = SW_SMALL;
+			else if (param[i] == SW_SMALL && left < (long long)SW_MARGIN &&
+				 param[!i] == SW_SMALL)
+				to = SW_BIG;
+			else
+				continue;
+			err = set_deadline(pid[i], to, PERIOD);
+			param[i] = to;
+			changes++;
+		}
+		sleep_ns(100 * NSEC_PER_USEC);
+	}
+	t1 = now_ns();
+	used[0] = sw_state[2] - cpu0[0];
+	used[1] = sw_state[3] - cpu0[1];
+	if (err) {
+		ksft_print_msg("a change refused: %s\n", strerror(-err));
+		goto out;
+	}
+	if (100000 * (used[0] + used[1]) >= SW_MAX_SHARE * (long long)(t1 - t0)) {
+		ksft_print_msg("A %lld%%, B %lld%% of the CPU, %d changes\n",
+			       100000 * used[0] / (long long)(t1 - t0),
+			       100000 * used[1] / (long long)(t1 - t0), changes);
+		ksft_print_msg("A and B got %d%% or more, with 71%% admitted\n",
+			       SW_MAX_SHARE);
+		goto out;
+	}
+	ret = KSFT_PASS;
+out:
+	reap(pid[0]);
+	reap(pid[1]);
+	return ret;
+}
+
 /* A random mix of the transitions above */
 
 #define MIX_WORKERS	6
@@ -11452,11 +14970,49 @@ static const struct p_case {
 	{ "deboost_out_after_donor_refill", deboost_out_after_donor_refill, MEASURED_IN_P },
 	{ "deboost_out_asleep_after_refill", deboost_out_asleep_after_refill, MEASURED_IN_P },
 	{ "deboost_in_asleep_after_refill", deboost_in_asleep_after_refill, MEASURED_IN_P },
+	{ "deboost_out_new_params", deboost_out_new_params, MEASURED_IN_P },
 	{ "requeue_pi_new_period", requeue_pi_new_period, MEASURED_IN_P },
 	{ "deboost_keeps_own_runtime", deboost_keeps_own_runtime, MEASURED_IN_P },
+	{ "return_running_new_params", return_running_new_params, MEASURED_IN_P },
 	{ "return_asleep_new_params", return_asleep_new_params, MEASURED_IN_P },
+	{ "change_running_new_params", change_running_new_params, MEASURED_IN_P },
+	{ "change_boosted_new_params", change_boosted_new_params, MEASURED_IN_P },
+	{ "change_constrained_new_params", change_constrained_new_params, MEASURED_IN_P },
+	{ "wake_constrained_new_params", wake_constrained_new_params, MEASURED_IN_P },
+	{ "constrained_gap_change_running", constrained_gap_change_running, MEASURED_IN_P },
+	{ "reenter_pi_blocked_in_gap", reenter_pi_blocked_in_gap, MEASURED_IN_P },
+	{ "reenter_asleep_in_gap", reenter_asleep_in_gap, MEASURED_IN_P },
+	{ "reenter_asleep_late_in_gap", reenter_asleep_late_in_gap, MEASURED_IN_P },
+	{ "reenter_runnable_in_gap", reenter_runnable_in_gap, MEASURED_IN_P },
+	{ "wake_after_deadline_shrunk", wake_after_deadline_shrunk, MEASURED_IN_P },
+	{ "deadline_grows_running", deadline_grows_running, MEASURED_IN_P },
+	{ "deadline_widened_asleep", deadline_widened_asleep, MEASURED_IN_P },
+	{ "period_shrunk_throttled", period_shrunk_throttled, MEASURED_IN_P },
+	{ "period_shrunk_throttled_started", period_shrunk_throttled_started, MEASURED_IN_P },
+	{ "period_shrunk_running", period_shrunk_running, MEASURED_IN_P },
+	{ "period_grown_running", period_grown_running, MEASURED_IN_P },
+	{ "period_grown_untouched", period_grown_untouched, MEASURED_IN_P },
+	{ "runtime_raised_waited", runtime_raised_waited, MEASURED_IN_P },
+	{ "params_flip_no_gain", params_flip_no_gain, MEASURED_IN_P },
+	{ "period_shrunk_no_burst", period_shrunk_no_burst, MEASURED_IN_P },
+	{ "constrained_after_job", constrained_after_job, MEASURED_IN_P },
+	{ "deboost_new_params_reboost", deboost_new_params_reboost, MEASURED_IN_P },
+	{ "deboost_asleep_new_params", deboost_asleep_new_params, MEASURED_IN_P },
+	{ "pi_owner_asleep_in_gap", pi_owner_asleep_in_gap, MEASURED_IN_P },
+	{ "pi_owner_throttled", pi_owner_throttled, MEASURED_IN_P },
+	{ "pi_owner_runs_out_later", pi_owner_runs_out_later, MEASURED_IN_P },
+	{ "pi_owner_wakes_in_gap_later", pi_owner_wakes_in_gap_later, MEASURED_IN_P },
+	{ "pi_owner_handed_off", pi_owner_handed_off, MEASURED_IN_P },
+	{ "pi_owner_throttled_asleep", pi_owner_throttled_asleep, MEASURED_IN_P },
+	{ "pi_owner_held_new_params", pi_owner_held_new_params, MEASURED_IN_P },
+	{ "pi_owner_throttled_rival", pi_owner_throttled_rival, MEASURED_IN_P },
+	{ "pi_owner_held_long", pi_owner_held_long, MEASURED_IN_P },
+	{ "pi_owner_reboost_loop", pi_owner_reboost_loop, MEASURED_IN_P },
+	{ "pi_owners_reboost_loop", pi_owners_reboost_loop, MEASURED_IN_P },
 	{ "deboost_blocked_keeps_order", deboost_blocked_keeps_order, MEASURED_IN_P },
 	{ "setattr_blocked_keeps_order", setattr_blocked_keeps_order, MEASURED_IN_P },
+	{ "setattr_blocked_new_period", setattr_blocked_new_period, MEASURED_IN_P },
+	{ "setattr_blocked_reenter", setattr_blocked_reenter, MEASURED_IN_P },
 	{ "boost_blocked_keeps_order", boost_blocked_keeps_order, MEASURED_IN_P },
 	{ "pi_chain_donor_leaves", pi_chain_donor_leaves, MEASURED_IN_P },
 	{ "pi_chain_top_moves", pi_chain_top_moves, MEASURED_IN_P },
@@ -11510,6 +15066,7 @@ static const struct p_case {
 	{ "server_states", server_states, FROM_OUTSIDE },
 	{ "server_reclaim", server_reclaim, MEASURED_IN_P },
 	{ "params_waking", params_waking, FROM_OUTSIDE },
+	{ "params_swap_overload", params_swap_overload, FROM_OUTSIDE },
 	{ "random_mix", random_mix, FROM_OUTSIDE },
 	{ "move_normalized", move_normalized, FROM_OUTSIDE },
 };
@@ -11842,6 +15399,7 @@ static void run_p_cases(void)
 	}
 	for (i = 0; i < N_P_CASES; i++) {
 		const struct p_case *c = &p_cases[i];
+		long long bw0 = total_bw_of(top_cpu(1));
 
 		if (ok && make_p()) {
 			remove_p();
@@ -11861,6 +15419,19 @@ static void run_p_cases(void)
 			ret = c->fn();
 		remove_p();
 		server_restore();
+		/*
+		 * A task of the case can keep its bandwidth counted after it
+		 * exits: until its 0-lag time, or until its debt is repaid. Wait
+		 * for that, so that the next case starts from the same total_bw.
+		 * A lower total_bw also ends the wait. Bandwidth lost by a case
+		 * would never come back, and the wait would then cost the whole
+		 * 10s.
+		 */
+		if (bw0 >= 0 &&
+		    wait_for_step(10000, 10 * NSEC_PER_MSEC,
+				  total_bw_of(top_cpu(1)) <= bw0))
+			ksft_print_msg("%s: total_bw %lld after the case, %lld before\n",
+				       c->name, total_bw_of(top_cpu(1)), bw0);
 		report(c->name, ret);
 	}
 	if (added && write_file(root, "cgroup.subtree_control", "-cpuset"))
-- 
2.47.3


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

* [PATCH v11 43/43] selftests/sched: Share the helpers of the deadline tests
  2026-11-26  1:07 [PATCH v11 00/43] sched/deadline: bandwidth accounting fixes and selftests Mathieu Desnoyers
                   ` (41 preceding siblings ...)
  2026-11-26  1:08 ` [PATCH v11 42/43] selftests/sched: Test parameter changes in deadline_bw_test Mathieu Desnoyers
@ 2026-11-26  1:08 ` Mathieu Desnoyers
  42 siblings, 0 replies; 59+ messages in thread
From: Mathieu Desnoyers @ 2026-11-26  1:08 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

deadline_bw_test, deadline_rebuild_test and deadline_switch_test each
have a copy of the same helpers. Move these to deadline_util.h:
- now_ns(), thread_time_ns() and sleep_ns();
- report();
- read_file(), write_file() and enter().

deadline_rebuild_test uses thread_time_ns() in place of its own
cpu_time_ns(). The helpers that differ from one test to the other stay
in each test. The Makefile adds the header to LOCAL_HDRS, so that
lib.mk rebuilds the tests when the header changes.

The Sashiko AI review of this series asked for this. No case changes.

Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
---
 .../testing/selftests/sched/deadline/Makefile |   2 +
 .../sched/deadline/deadline_bw_test.c         |  86 +-------------
 .../sched/deadline/deadline_rebuild_test.c    |  94 +---------------
 .../sched/deadline/deadline_switch_test.c     |  36 +-----
 .../selftests/sched/deadline/deadline_util.h  | 106 ++++++++++++++++++
 5 files changed, 116 insertions(+), 208 deletions(-)
 create mode 100644 tools/testing/selftests/sched/deadline/deadline_util.h

diff --git a/tools/testing/selftests/sched/deadline/Makefile b/tools/testing/selftests/sched/deadline/Makefile
index 15f1e96a21e6..a81aa97c6cc6 100644
--- a/tools/testing/selftests/sched/deadline/Makefile
+++ b/tools/testing/selftests/sched/deadline/Makefile
@@ -5,4 +5,6 @@ LDLIBS += -lpthread
 
 TEST_GEN_PROGS := deadline_switch_test deadline_rebuild_test deadline_bw_test
 
+LOCAL_HDRS += deadline_util.h
+
 include ../../lib.mk
diff --git a/tools/testing/selftests/sched/deadline/deadline_bw_test.c b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
index 78b58888e9d5..56dc73264e0a 100644
--- a/tools/testing/selftests/sched/deadline/deadline_bw_test.c
+++ b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
@@ -97,6 +97,8 @@
 #define NSEC_PER_MSEC	1000000ULL
 #define NSEC_PER_SEC	1000000000ULL
 
+#include "deadline_util.h"
+
 /* The threads of probe() and hold() do nothing: a small stack will do. */
 #define THREAD_STACK	(64 * 1024 > PTHREAD_STACK_MIN ? 64 * 1024 : PTHREAD_STACK_MIN)
 
@@ -127,34 +129,6 @@ static int top_cpu(int n)
 	return online[ncpus - n];
 }
 
-/*
- * clock_gettime() cannot fail in now_ns() and thread_time_ns(). Both
- * clocks are always supported, and the pointer is valid.
- */
-static uint64_t now_ns(void)
-{
-	struct timespec ts;
-
-	clock_gettime(CLOCK_MONOTONIC, &ts);
-	return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
-}
-
-static uint64_t thread_time_ns(void)
-{
-	struct timespec ts;
-
-	clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
-	return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
-}
-
-static void sleep_ns(uint64_t ns)
-{
-	struct timespec ts = { .tv_sec = ns / NSEC_PER_SEC, .tv_nsec = ns % NSEC_PER_SEC };
-
-	while (nanosleep(&ts, &ts) && errno == EINTR)
-		;
-}
-
 static void spin_ns(uint64_t ns)
 {
 	uint64_t end = thread_time_ns() + ns;
@@ -308,52 +282,6 @@ static int set_other(pid_t tid)
 	return syscall(SYS_sched_setattr, tid, &attr, 0) ? -errno : 0;
 }
 
-static int write_file(const char *dir, const char *name, const char *val)
-{
-	char path[PATH_MAX];
-	int fd, err = 0;
-	ssize_t n;
-
-	if (snprintf(path, sizeof(path), "%s/%s", dir, name) >= (int)sizeof(path))
-		return -ENAMETOOLONG;
-	fd = open(path, O_WRONLY);
-	if (fd < 0)
-		return -errno;
-	n = write(fd, val, strlen(val));
-	if (n < 0)
-		err = -errno;
-	else if (n != (ssize_t)strlen(val))
-		err = -EIO;
-	if (close(fd) && !err)
-		err = -errno;
-	return err;
-}
-
-static int read_file(const char *path, char *buf, size_t len)
-{
-	int fd = open(path, O_RDONLY);
-	ssize_t n;
-
-	if (fd < 0)
-		return -1;
-	do {
-		n = read(fd, buf, len - 1);
-	} while (n < 0 && errno == EINTR);
-	close(fd);
-	if (n < 0)
-		return -1;
-	buf[n] = 0;
-	return 0;
-}
-
-static int enter(const char *cg, pid_t pid)
-{
-	char buf[16];
-
-	snprintf(buf, sizeof(buf), "%d", pid);
-	return write_file(cg, "cgroup.procs", buf);
-}
-
 /* Return whether @list, words separated by blanks, holds the word @w. */
 static int has_word(const char *list, const char *w)
 {
@@ -14797,16 +14725,6 @@ static int find_cgroup2(void)
 	return found ? 0 : -1;
 }
 
-static void report(const char *name, int ret)
-{
-	if (ret == KSFT_PASS)
-		ksft_test_result_pass("%s\n", name);
-	else if (ret == KSFT_SKIP)
-		ksft_test_result_skip("%s\n", name);
-	else
-		ksft_test_result_fail("%s\n", name);
-}
-
 /* sched_setaffinity() against sched_setattr(), with no P */
 
 /*
diff --git a/tools/testing/selftests/sched/deadline/deadline_rebuild_test.c b/tools/testing/selftests/sched/deadline/deadline_rebuild_test.c
index 735c3c65e156..e0ec2a559632 100644
--- a/tools/testing/selftests/sched/deadline/deadline_rebuild_test.c
+++ b/tools/testing/selftests/sched/deadline/deadline_rebuild_test.c
@@ -52,6 +52,8 @@
 #define NSEC_PER_MSEC	1000000ULL
 #define NSEC_PER_SEC	1000000000ULL
 
+#include "deadline_util.h"
+
 struct dl_attr {
 	uint32_t size;
 	uint32_t sched_policy;
@@ -87,26 +89,6 @@ static int set_other(pid_t pid)
 	return sched_setscheduler(pid, SCHED_OTHER, &sp) ? -errno : 0;
 }
 
-/*
- * Return the CLOCK_MONOTONIC time in ns. clock_gettime() cannot fail: the
- * clock is always supported, and the pointer is valid.
- */
-static uint64_t now_ns(void)
-{
-	struct timespec ts;
-
-	clock_gettime(CLOCK_MONOTONIC, &ts);
-	return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
-}
-
-static void sleep_ns(uint64_t ns)
-{
-	struct timespec ts = { .tv_sec = ns / NSEC_PER_SEC, .tv_nsec = ns % NSEC_PER_SEC };
-
-	while (nanosleep(&ts, &ts) && errno == EINTR)
-		;
-}
-
 static void reap(pid_t pid)
 {
 	int status;
@@ -125,52 +107,6 @@ static void reap(pid_t pid)
 	}
 }
 
-static int write_file(const char *dir, const char *name, const char *val)
-{
-	char path[PATH_MAX];
-	int fd, err = 0;
-	ssize_t n;
-
-	if (snprintf(path, sizeof(path), "%s/%s", dir, name) >= (int)sizeof(path))
-		return -ENAMETOOLONG;
-	fd = open(path, O_WRONLY);
-	if (fd < 0)
-		return -errno;
-	n = write(fd, val, strlen(val));
-	if (n < 0)
-		err = -errno;
-	else if (n != (ssize_t)strlen(val))
-		err = -EIO;
-	if (close(fd) && !err)
-		err = -errno;
-	return err;
-}
-
-static int read_file(const char *path, char *buf, size_t len)
-{
-	int fd = open(path, O_RDONLY);
-	ssize_t n;
-
-	if (fd < 0)
-		return -1;
-	do {
-		n = read(fd, buf, len - 1);
-	} while (n < 0 && errno == EINTR);
-	close(fd);
-	if (n < 0)
-		return -1;
-	buf[n] = 0;
-	return 0;
-}
-
-static int enter(const char *cg, pid_t pid)
-{
-	char buf[16];
-
-	snprintf(buf, sizeof(buf), "%d", pid);
-	return write_file(cg, "cgroup.procs", buf);
-}
-
 /* Make @cg a partition root of CPU @cpu alone. Return 0, or -1 on error. */
 static int make_partition(const char *cg, int cpu)
 {
@@ -207,18 +143,6 @@ static void remove_partition(const char *cg)
 	}
 }
 
-/*
- * Return the CPU time of the calling thread in ns. clock_gettime() cannot
- * fail: the clock is always supported, and the pointer is valid.
- */
-static uint64_t cpu_time_ns(void)
-{
-	struct timespec ts;
-
-	clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
-	return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
-}
-
 enum depart { DIES, SWITCHED_OUT };
 
 /* Kill the calling child if the test exits, so that no deadline task stays. */
@@ -250,8 +174,8 @@ static pid_t departing(const char *cg, enum depart how, int fd[2])
 			_exit(2);
 		if (set_deadline(0, 400 * NSEC_PER_MSEC))
 			_exit(3);
-		t0 = cpu_time_ns();
-		while (cpu_time_ns() - t0 < 380 * NSEC_PER_MSEC)
+		t0 = thread_time_ns();
+		while (thread_time_ns() - t0 < 380 * NSEC_PER_MSEC)
 			;
 		if (how == DIES)
 			_exit(0);
@@ -531,16 +455,6 @@ static int find_cgroup2(void)
 	return found ? 0 : -1;
 }
 
-static void report(const char *name, int ret)
-{
-	if (ret == KSFT_PASS)
-		ksft_test_result_pass("%s\n", name);
-	else if (ret == KSFT_SKIP)
-		ksft_test_result_skip("%s\n", name);
-	else
-		ksft_test_result_fail("%s\n", name);
-}
-
 int main(void)
 {
 	char buf[256], path[PATH_MAX + 32];
diff --git a/tools/testing/selftests/sched/deadline/deadline_switch_test.c b/tools/testing/selftests/sched/deadline/deadline_switch_test.c
index 40c7c6bafc2b..a544bee5af5a 100644
--- a/tools/testing/selftests/sched/deadline/deadline_switch_test.c
+++ b/tools/testing/selftests/sched/deadline/deadline_switch_test.c
@@ -51,6 +51,8 @@
 #define NSEC_PER_MSEC	1000000ULL
 #define NSEC_PER_SEC	1000000000ULL
 
+#include "deadline_util.h"
+
 struct dl_attr {
 	uint32_t size;
 	uint32_t sched_policy;
@@ -70,22 +72,6 @@ struct shared {
 	uint64_t sleeps;	/* sleeps begun */
 };
 
-static uint64_t now_ns(void)
-{
-	struct timespec ts;
-
-	clock_gettime(CLOCK_MONOTONIC, &ts);
-	return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
-}
-
-static void sleep_ns(uint64_t ns)
-{
-	struct timespec ts = { .tv_sec = ns / NSEC_PER_SEC, .tv_nsec = ns % NSEC_PER_SEC };
-
-	while (nanosleep(&ts, &ts) && errno == EINTR)
-		;
-}
-
 static void sleep_until(uint64_t t)
 {
 	struct timespec ts = { .tv_sec = t / NSEC_PER_SEC, .tv_nsec = t % NSEC_PER_SEC };
@@ -518,14 +504,6 @@ static sem_t owner_locked, owner_go;
 static pid_t owner_tid;
 static int owner_ms;		/* the owner's CPU time in its first period */
 
-static uint64_t thread_time_ns(void)
-{
-	struct timespec ts;
-
-	clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
-	return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
-}
-
 /*
  * Wait on @s for at most @ms, retrying on signals. Return 0, or -1 on a
  * timeout or an error.
@@ -1081,16 +1059,6 @@ static int test_sysrq_running_owner(int normalized)
 	return ret;
 }
 
-static void report(const char *name, int ret)
-{
-	if (ret == KSFT_PASS)
-		ksft_test_result_pass("%s\n", name);
-	else if (ret == KSFT_SKIP)
-		ksft_test_result_skip("%s\n", name);
-	else
-		ksft_test_result_fail("%s\n", name);
-}
-
 int main(void)
 {
 	int ret;
diff --git a/tools/testing/selftests/sched/deadline/deadline_util.h b/tools/testing/selftests/sched/deadline/deadline_util.h
new file mode 100644
index 000000000000..489233a32cbd
--- /dev/null
+++ b/tools/testing/selftests/sched/deadline/deadline_util.h
@@ -0,0 +1,106 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* Helpers that the deadline selftests share. */
+#ifndef DEADLINE_UTIL_H
+#define DEADLINE_UTIL_H
+
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/types.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "../../kselftest.h"
+
+#ifndef NSEC_PER_SEC
+#define NSEC_PER_SEC	1000000000ULL
+#endif
+
+/*
+ * clock_gettime() cannot fail in now_ns() and thread_time_ns(). Both
+ * clocks are always supported, and the pointer is valid.
+ */
+static inline uint64_t now_ns(void)
+{
+	struct timespec ts;
+
+	clock_gettime(CLOCK_MONOTONIC, &ts);
+	return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
+}
+
+static inline uint64_t thread_time_ns(void)
+{
+	struct timespec ts;
+
+	clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
+	return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
+}
+
+static inline void sleep_ns(uint64_t ns)
+{
+	struct timespec ts = { .tv_sec = ns / NSEC_PER_SEC, .tv_nsec = ns % NSEC_PER_SEC };
+
+	while (nanosleep(&ts, &ts) && errno == EINTR)
+		;
+}
+
+static inline void report(const char *name, int ret)
+{
+	if (ret == KSFT_PASS)
+		ksft_test_result_pass("%s\n", name);
+	else if (ret == KSFT_SKIP)
+		ksft_test_result_skip("%s\n", name);
+	else
+		ksft_test_result_fail("%s\n", name);
+}
+
+static inline int read_file(const char *path, char *buf, size_t len)
+{
+	int fd = open(path, O_RDONLY);
+	ssize_t n;
+
+	if (fd < 0)
+		return -1;
+	do {
+		n = read(fd, buf, len - 1);
+	} while (n < 0 && errno == EINTR);
+	close(fd);
+	if (n < 0)
+		return -1;
+	buf[n] = 0;
+	return 0;
+}
+
+static inline int write_file(const char *dir, const char *name, const char *val)
+{
+	char path[PATH_MAX];
+	int fd, err = 0;
+	ssize_t n;
+
+	if (snprintf(path, sizeof(path), "%s/%s", dir, name) >= (int)sizeof(path))
+		return -ENAMETOOLONG;
+	fd = open(path, O_WRONLY);
+	if (fd < 0)
+		return -errno;
+	n = write(fd, val, strlen(val));
+	if (n < 0)
+		err = -errno;
+	else if (n != (ssize_t)strlen(val))
+		err = -EIO;
+	if (close(fd) && !err)
+		err = -errno;
+	return err;
+}
+
+static inline int enter(const char *cg, pid_t pid)
+{
+	char buf[16];
+
+	snprintf(buf, sizeof(buf), "%d", pid);
+	return write_file(cg, "cgroup.procs", buf);
+}
+
+#endif /* DEADLINE_UTIL_H */
-- 
2.47.3


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

* Re: [PATCH v11 21/43] rtmutex: Continue the chain walk when a waiter's deadline donor changes
  2026-11-26  1:08 ` [PATCH v11 21/43] rtmutex: Continue the chain walk when a waiter's deadline donor changes Mathieu Desnoyers
@ 2026-11-26  1:32   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  1:32 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] rtmutex: waiter->pi_se desynchronizes from owner->dl.pi_se
  after unlocking pi_lock
--

commit 20b64bd5f85400f14e722790295c12b998e0b8ee
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

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

This commit records a task's deadline donor in struct rt_mutex_waiter and
includes it in the chain-walk termination check so that donor changes on a
blocked task propagate to downstream lock owners even when the waiter's
priority and deadline sort keys remain unchanged.

> diff --git a/kernel/locking/rtmutex.c b/kernel/locking/rtmutex.c
> index 5a9534c715b84..c78dfe9c93fc5 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;
> +}

[Severity: Medium]
Can waiter->pi_se get out of sync with the donor that rt_mutex_setprio()
copies to the lock owner?

In rt_mutex_adjust_prio_chain(), waiter_update_prio() snapshots
waiter->pi_se from task->dl.pi_se at [7], then drops task->pi_lock at [8]
before taking owner->pi_lock and calling rt_mutex_adjust_prio() at [11]:

kernel/locking/rtmutex.c:rt_mutex_adjust_prio_chain() {
    ...
	waiter_update_prio(waiter, task);

	rt_mutex_enqueue(lock, waiter);
	...
	raw_spin_unlock(&task->pi_lock);
	put_task_struct(task);
	...
	task = get_task_struct(rt_mutex_owner(lock));
	raw_spin_lock(&task->pi_lock);

	/* [11] requeue the pi waiters if necessary */
	if (waiter == rt_mutex_top_waiter(lock)) {
		rt_mutex_dequeue_pi(task, prerequeue_top_waiter);
		waiter_clone_prio(waiter, task);
		rt_mutex_enqueue_pi(task, waiter);
		rt_mutex_adjust_prio(lock, task);
    ...
}

Because rt_mutex_adjust_prio() -> rt_mutex_setprio() reads pi_task->dl.pi_se
directly from the task rather than from the waiter, a concurrent boost and
deboost on an intermediate task M (holding L1 and L1', blocked on L2 owned
by O, already boosted by deadline task H on L1') can update O->dl.pi_se to
a new deadline waiter W on L1 while M's waiter w_M on L2 still records
&H->dl:

CPU0 (walk for H on L1')          CPU1 (W blocks on L1, then leaves)
------------------------          ----------------------------------
rt_mutex_adjust_prio_chain(M)
  raw_spin_lock(&M->pi_lock)
  [7] waiter_update_prio(w_M, M)
        w_M->pi_se = &H->dl
  [8] raw_spin_unlock(&M->pi_lock)
                                  task_blocks_on_rt_mutex(L1, W)
                                    raw_spin_lock(&M->pi_lock)
                                    rt_mutex_setprio(M, W)
                                      M->dl.pi_se = &W->dl
                                    raw_spin_unlock(&M->pi_lock)
  [10] raw_spin_lock(&O->pi_lock)
  [11] rt_mutex_adjust_prio(L2, O)
         rt_mutex_setprio(O, M)
           O->dl.pi_se = M->dl.pi_se
           /* O->dl.pi_se is &W->dl */
  [13] raw_spin_unlock(&O->pi_lock)
                                  remove_waiter(L1, W)
                                    raw_spin_lock(&M->pi_lock)
                                    rt_mutex_setprio(M, H)
                                      M->dl.pi_se = &H->dl
                                    raw_spin_unlock(&M->pi_lock)
                                  rt_mutex_adjust_prio_chain(M)
                                    raw_spin_lock(&M->pi_lock)
                                    rt_waiter_up_to_date(w_M, M)
                                      /* w_M->pi_se == M->dl.pi_se == &H->dl */
                                      goto out_unlock_pi;
                                  W exits
O refills from W->dl  <-- use-after-free

Even with commit "sched/deadline: Hold a reference on the deadline donor of
a boosted task" keeping W's task_struct alive, the chain walk still stops
early at M and leaves O running on the departed donor W's parameters instead
of H's.

Copying waiter->pi_se into waiter->pi_tree in waiter_clone_prio() and having
rt_mutex_setprio() read the donor from the top pi_waiter (or holding the
donor's pi_lock across the read) would keep waiter->pi_se and owner->dl.pi_se
consistent.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=21

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

* Re: [PATCH v11 25/43] sched/deadline: Count the 0-lag time from the next period
  2026-11-26  1:08 ` [PATCH v11 25/43] sched/deadline: Count the 0-lag time from the next period Mathieu Desnoyers
@ 2026-11-26  1:35   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  1:35 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] sched/deadline: dl_time_to_zerolag() miscomputes 0-lag when
  deadline is 0
--

commit 03d5dc8d2f6d0b382a7bed954bd1379667e09042
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

sched/deadline: Count the 0-lag time from the next period

This commit computes a deadline entity's 0-lag time relative to
dl_next_period(dl_se) rather than dl_se->deadline so that tasks with
constrained deadlines do not reach their 0-lag time prematurely.

> diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
> index 74b3c6b967eee..1d2dcf478f95d 100644
> --- a/kernel/sched/deadline.c
> +++ b/kernel/sched/deadline.c
[ ... ]
> @@ -633,12 +637,12 @@ 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);

[Severity: Medium]
Can dl_time_to_zerolag() return a positive delay when dl_se->deadline is 0?

If a sleeping task with no active period (dl_se->deadline == 0 and
dl_se->runtime == 0) is switched into SCHED_DEADLINE with a constrained
deadline (dl_deadline < dl_period) and then switched back out while still
asleep, switched_from_dl() -> task_non_contending() calls
dl_time_to_zerolag().  Previously, dl_se->deadline - rq_clock(rq) was
negative and the bandwidth was released immediately.  With dl_next_period(),
0 - dl_deadline + dl_period evaluates to dl_period - dl_deadline; whenever
rq_clock(rq) is smaller than that difference, left is non-negative and
inactive_timer is armed, holding the task's bandwidth in root-domain
total_bw and causing subsequent admission checks to fail with -EBUSY.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=25

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

* Re: [PATCH v11 16/43] sched/deadline: Keep the last CPU a task has in its root domain
  2026-11-26  1:08 ` [PATCH v11 16/43] sched/deadline: Keep the last CPU a task has in its root domain Mathieu Desnoyers
@ 2026-11-26  1:35   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  1:35 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] cgroup/cpuset: wrong v1 ancestor walk in
  cpuset_cpus_allowed_without()
--

commit e0e4cf76f577347925934619360185ec78904567
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

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

This commit refuses CPU offline operations with -EBUSY when taking the CPU
offline would move a SCHED_DEADLINE task out of the root domain that
admitted its bandwidth.

> diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c
> index 7bdb9e21a7edb..37d04b08996ec 100644
> --- a/kernel/cgroup/cpuset.c
> +++ b/kernel/cgroup/cpuset.c
[ ... ]
> @@ -4312,6 +4334,292 @@ void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask)
>  	spin_unlock_irqrestore(&callback_lock, flags);
>  }
>  
[ ... ]
> +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_intersects(pmask, possible))
> +				break;
> +		}

[Severity: Medium]
Should the cgroup v1 loop break on !cpumask_empty(pmask) instead of
cpumask_intersects(pmask, possible)?

On cgroup v1, cpuset1_hotplug_update_tasks() only considers a cpuset empty
and moves its tasks to an ancestor when cs->cpus_allowed becomes completely
empty:

kernel/cgroup/cpuset-v1.c:cpuset1_hotplug_update_tasks() {
    ...
	is_empty = cpumask_empty(cs->cpus_allowed) ||
		   nodes_empty(cs->mems_allowed);
    ...
	if (is_empty)
		remove_tasks_in_empty_cpuset(cs);
}

On systems with asymmetric 32-bit support where task_cpu_possible_mask(tsk)
is a subset of cpu_possible_mask, a cpuset can retain active 64-bit-only
CPUs after the offline while having no CPUs left in possible.  In that case
cgroup v1 leaves the task in cs and falls back to select_fallback_rq(),
whereas this loop walks up to parent_cs(from) and can return an ancestor's
32-bit-capable CPUs in pmask, allowing dl_task_leaves_span() to accept an
offline that moves a deadline task to another root domain or reject a valid
one with -EBUSY.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=16

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

* Re: [PATCH v11 15/43] sched/deadline: Keep a task in the root domain that counts its bandwidth
  2026-11-26  1:08 ` [PATCH v11 15/43] sched/deadline: Keep a task in the root domain that counts its bandwidth Mathieu Desnoyers
@ 2026-11-26  1:38   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  1:38 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [Medium] sched/deadline: select_fallback_rq() bypasses local NUMA node
  search
- [Medium] sched/deadline: __set_cpus_allowed_ptr_locked() clobbers
  valid wake_cpu
--

commit 4af84b97f62357ff3460aae481348b8b367fe8d9
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

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

This commit introduces dl_task_bw_span() and updates CPU selection paths
during affinity changes, wakeups, CPU offline, and sched domain rebuilds
to prefer CPUs within the root domain that accounts for a deadline task's
bandwidth.

> diff --git a/kernel/sched/core.c b/kernel/sched/core.c
> index 7615ba02d52b3..3dd42581cc177 100644
> --- a/kernel/sched/core.c
> +++ b/kernel/sched/core.c
> @@ -3264,6 +3264,27 @@ 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. 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))
> +				p->wake_cpu = dest_cpu;
> +		}
>  	}

[Severity: Medium]
Does this overwrite p->wake_cpu for a sleeping deadline task even when
its existing p->wake_cpu is still valid in ctx->new_mask and span?

dest_cpu is chosen earlier via cpumask_any_and_distribute(cpu_valid_mask,
ctx->new_mask).  Unlike a queued task (where affine_move_task() leaves p
on task_cpu(p) if it remains in the new mask), a sleeping deadline task
has p->wake_cpu unconditionally replaced with the pseudo-random dest_cpu
whenever span is non-NULL, forcing an unnecessary migration on the next
wakeup.

Only updating p->wake_cpu when it is not already in cpu_valid_mask,
ctx->new_mask, and span would preserve wakeup locality.

> @@ -3668,8 +3689,22 @@ 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) {
> +		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

[Severity: Medium]
Does this early return bypass the local NUMA node search in
select_fallback_rq() for deadline tasks?

Because dl_task_bw_span(p) returns rd->span for any admitted deadline
task outside a domain rebuild, scanning span & p->cpus_ptr in ascending
CPU order and returning before the cpumask_of_node(nid) loop below skips
same-node CPU selection on multi-node NUMA systems and always sends the
task to the lowest-numbered allowed CPU in its root domain.

Checking cpumask_of_node(nid) intersected with span first when span is
non-NULL would keep the task in its root domain while preserving NUMA
locality.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=15

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

* Re: [PATCH v11 17/43] cgroup/cpuset: Refuse to take a deadline task out of its root domain
  2026-11-26  1:08 ` [PATCH v11 17/43] cgroup/cpuset: Refuse to take a deadline task out of " Mathieu Desnoyers
@ 2026-11-26  1:41   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  1:41 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [Medium] cgroup/cpuset: unnecessary hierarchy and task walks in
  dl_tasks_keep_*()
- [Medium] cgroup/cpuset: dl_tasks_keep_without() omits pending CPUs for
  PRS_ISOLATED
--

commit 0cb8536a44f47c8f95c649627afa6a220c61e952
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

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

This commit refuses cpuset CPU mask updates and invalidates partitions that
would move a deadline task out of the root domain accounting its bandwidth.

> diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c
> index 37d04b08996ec..67b2429c0e22f 100644
> --- a/kernel/cgroup/cpuset.c
> +++ b/kernel/cgroup/cpuset.c
[ ... ]
> @@ -1148,6 +1181,91 @@ 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.
> +	 */
> +	if (root->partition_root_state == PRS_ROOT) {
> +		pending = dl_pending_cpus;
> +		cpumask_copy(pending, root->effective_cpus);
> +		if (root == &top_cpuset)
> +			cpumask_and(pending, pending,
> +				    housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT));
> +	}

[Severity: Medium]
Should pending also be populated when root->partition_root_state is
PRS_ISOLATED (or via is_partition_valid(root))?

An isolated partition root can have an invalid child isolated partition and
hold deadline tasks counted in def_root_domain.  When that isolated parent
grows to include a new CPU before rebuild_sched_domains_locked() runs at
the end of the change, def_root_domain.span does not include the new CPU
yet.  Because pending is left NULL here, re-evaluating the child during
update_cpumasks_hier() -> update_parent_effective_cpumask() rejects the
child with PERR_DLTASK even though the rebuild will attach the parent's new
CPU to def_root_domain.

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

[Severity: Medium]
Does dl_tasks_keep_without() (and dl_tasks_keep_root_domain() below) walk
the cpuset hierarchy and iterate every task in affected cpusets even when
no deadline tasks hold bandwidth or admission control is disabled?

Commit "sched/deadline: Keep the last CPU a task has in its root domain"
earlier in this series guards dl_cpu_last_of_task() with
!dl_bandwidth_enabled() || !atomic_read(&dl_nr_bw_tasks), whereas here
dl_bandwidth_enabled() is only checked per task inside
dl_task_keeps_root_domain() after css_task_iter has already locked
css_set_lock and pinned each task, and dl_nr_bw_tasks is not checked.

In addition, when cpumask_equal(cp->effective_cpus, new_cpus) is true in
either function, continuing without advancing pos_css =
css_rightmost_descendant(pos_css) visits all descendants of an unchanged
subtree even though their effective_cpus cannot change either.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=17

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

* Re: [PATCH v11 26/43] sched/deadline: Keep a departing constrained task until its next period
  2026-11-26  1:08 ` [PATCH v11 26/43] sched/deadline: Keep a departing constrained task until its " Mathieu Desnoyers
@ 2026-11-26  1:44   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  1:44 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [Medium] sched/deadline: dl_task_timer() advances period before
  inactive_task_timer()
- [Medium] sched/deadline: HRTIMER_RESTART in inactive_task_timer()
  races with cancel
--

commit 43e71343c7049144c9877a7ba7fddb15005d58e2
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

sched/deadline: Keep a departing constrained task until its next period

This commit keeps a departing constrained SCHED_DEADLINE task's bandwidth
and deadline until the later of its 0-lag time and its next period in
task_non_contending() and inactive_task_timer().

> diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
> index 1d2dcf478f95d..11774b3b9fe93 100644
> --- a/kernel/sched/deadline.c
> +++ b/kernel/sched/deadline.c

[ ... ]

> @@ -2598,6 +2614,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);

[Severity: Medium]
Can dl_task_timer() advance dl_se->deadline before inactive_task_timer()
computes dl_next_period(dl_se), holding the departed task's bandwidth for
an extra period?

When a constrained task is throttled before leaving SCHED_DEADLINE,
dl_se->dl_timer remains armed for the end of the departure period while
dl_se->inactive_timer is armed for max(0-lag time, dl_next_period(dl_se)).
When dl_task_timer() fires at the period boundary while !dl_task(p), it
replenishes the entity:

kernel/sched/deadline.c:dl_task_timer() {
    ...
	if (!dl_task(p)) {
		if (dl_se->dl_throttled && !is_dl_boosted(dl_se)) {
			sched_clock_tick();
			update_rq_clock(rq);
			replenish_dl_entity(dl_se);
		}
		goto unlock;
	}
    ...
}

replenish_dl_entity() adds dl_se->dl_period to dl_se->deadline until
dl_se->runtime > 0.  When inactive_task_timer() then runs at the period
boundary (or later at the 0-lag time after an overrun), dl_next_period()
is computed from the replenished dl_se->deadline, so left > 0 and
inactive_task_timer() restarts for another full period instead of
releasing the task's bandwidth and clearing its parameters.  If the task
re-enters SCHED_DEADLINE during that extra period after the advanced
deadline, dl_check_constrained_dl() also throttles it until the end of the
second period.

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

[Severity: Medium]
Can returning HRTIMER_RESTART after task_rq_unlock() race with
cancel_inactive_timer() in switched_to_dl() and leave inactive_timer
queued after the task returns to SCHED_DEADLINE?

cancel_dl_timer() assumes that when hrtimer_try_to_cancel() returns -1,
the running callback will finish with HRTIMER_NORESTART and drop the task
reference.  Because __run_hrtimer() only re-acquires cpu_base->lock and
re-enqueues the timer after inactive_task_timer() returns, another CPU can
run switched_to_dl() in between:

CPU0                                  CPU1
__run_hrtimer()
  inactive_task_timer()
    hrtimer_set_expires(timer, at)
    task_rq_unlock(rq, p, &rf)
                                      __sched_setscheduler()
                                        task_rq_lock(p, &rf)
                                        switched_to_dl()
                                          cancel_inactive_timer(&p->dl)
                                            hrtimer_try_to_cancel() -> -1
                                        task_rq_unlock(rq, p, &rf)
    return HRTIMER_RESTART
  raw_spin_lock(&cpu_base->lock)
  enqueue_hrtimer(timer, base, ...)   <-- queued while p is in DL

p is then back in SCHED_DEADLINE with dl_non_contending == 0 while
hrtimer_active(&p->dl.inactive_timer) is true.  If p blocks or leaves
SCHED_DEADLINE before that stale timer fires, task_non_contending() sees
hrtimer_active(&dl_se->inactive_timer) and immediately subtracts
running_bw or releases the task's bandwidth and clears its deadline before
the 0-lag time.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=26

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

* Re: [PATCH v11 34/43] sched/deadline: Cancel the replenishment timer with the parameters
  2026-11-26  1:08 ` [PATCH v11 34/43] sched/deadline: Cancel the replenishment timer with the parameters Mathieu Desnoyers
@ 2026-11-26  1:45   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  1:45 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] sched/deadline: dl_task_timer() extends departed constrained
  task by a period
--

commit b4f4668865f16f00f3ee081d72d2725e00494e96
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

sched/deadline: Cancel the replenishment timer with the parameters

This commit cancels a task's deadline replenishment timer alongside
clearing its deadline parameters in task_non_contending() and
inactive_task_timer().

> diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
> index c59953e80b1a9..828923a771076 100644
> --- a/kernel/sched/deadline.c
> +++ b/kernel/sched/deadline.c

[ ... ]

> @@ -2895,6 +2896,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;

[Severity: Medium]
Can dl_task_timer() fire before inactive_task_timer() at
dl_next_period(dl_se) for a departed constrained-deadline task, pushing
its bandwidth release and parameter reset out by an extra period?

When a constrained-deadline task is throttled without a runtime overrun
(for example via sched_yield()), start_dl_timer() queues dl_se->dl_timer
for dl_next_period(dl_se).  If the task then leaves SCHED_DEADLINE,
task_non_contending() or inactive_task_timer() queues
dl_se->inactive_timer for that same dl_next_period(dl_se) timestamp
without cancelling dl_timer.  Because dl_timer was queued in the hrtimer
tree first, it fires first at dl_next_period(dl_se):

kernel/sched/deadline.c:dl_task_timer() {
    ...
	if (!dl_task(p)) {
		if (dl_se->dl_throttled && !is_dl_boosted(dl_se)) {
			sched_clock_tick();
			update_rq_clock(rq);
			replenish_dl_entity(dl_se);
		}
		goto unlock;
	}
    ...
}

replenish_dl_entity() advances dl_se->deadline by dl_period.  When
inactive_task_timer() runs right after, it sees
dl_next_period(dl_se) - rq_clock(rq) == dl_period > 0 and returns
HRTIMER_RESTART instead of reaching dl_task_release_bw(),
cancel_replenish_timer(), and __dl_clear_params():

kernel/sched/deadline.c:inactive_task_timer() {
    ...
	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;
		}
	}
    ...
}

The departed task's bandwidth remains locked in dl_b->total_bw for an
extra period, and if the task returns to SCHED_DEADLINE after the phantom
deadline it is throttled with zero runtime until that extra period ends.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=34

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

* Re: [PATCH v11 31/43] sched/deadline: Restore the owner's period at a deboost out of the class
  2026-11-26  1:08 ` [PATCH v11 31/43] sched/deadline: Restore the owner's period at a deboost out of the class Mathieu Desnoyers
@ 2026-11-26  1:50   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  1:50 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] sched/deadline: missing throttle after held boost ends in
  switched_from_dl()
--

commit 7695498ee5152a5e36e39a21aef4b92a39936d61
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

sched/deadline: Restore the owner's period at a deboost out of the class

This commit restores the lock owner's own deadline and runtime parameters
in switched_from_dl() when a priority-inheritance boost ends as the task
leaves SCHED_DEADLINE, and recalculates the 0-lag inactive timer from the
restored parameters.

> diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
> index 4d46d1c9c6981..5d1d4ea288788 100644
> --- a/kernel/sched/deadline.c
> +++ b/kernel/sched/deadline.c
> @@ -4802,6 +4802,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);
> +	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);

[Severity: Medium]
Should switched_from_dl() also throttle p->dl and arm p->dl.dl_timer when
held is true and p->dl.runtime <= 0, the way dl_deboost() does?

When a task exhausts its own runtime while boosted, replenish_dl_entity()
clears dl_throttled and dl_hold_refilled_boost() saves own_runtime = 0.
If the task leaves SCHED_DEADLINE at the deboost before own_deadline,
dl_end_held_boost() restores p->dl.deadline = own_deadline and
p->dl.runtime = 0, leaving p->dl.dl_throttled == 0.

If the task switches back to SCHED_DEADLINE before p->dl.deadline,
enqueue_dl_entity() sees dl_throttled == 0 and a deadline still in the
future, so it enqueues the task onto dl_rq with runtime == 0 and lets it
run past its reserved budget in the current period.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=31

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

* Re: [PATCH v11 30/43] sched/deadline: Start a period for a task that enters the class blocked
  2026-11-26  1:08 ` [PATCH v11 30/43] sched/deadline: Start a period for a task that enters the class blocked Mathieu Desnoyers
@ 2026-11-26  1:53   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  1:53 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [Medium] sched/deadline: missing zero-deadline check in
  switched_to_dl()
- [Medium] sched/deadline: dl_boost_blocked() skips tasks with non-zero
  dl_deadline
- [Medium] sched/deadline: switched_to_dl() skips donor period when
  throttled task is boosted
--

commit e2fecf170ee9d540debd8f3437e1896d21f58e13
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

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

This commit starts a deadline period for a task blocked on an rt_mutex
when it enters SCHED_DEADLINE via switched_to_dl() or receives a new
priority-inheritance donor via dl_boost_blocked(), so that the rt_mutex
chain walk sorts its waiter with a current deadline rather than 0.

> diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
> index 5ec1c5eaf7647..4d46d1c9c6981 100644
> --- a/kernel/sched/deadline.c
> +++ b/kernel/sched/deadline.c
[ ... ]
> @@ -1301,6 +1312,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

[Severity: Medium]
Can dl_boost_blocked() leave an expired p->dl.deadline in place when a
blocked task still has a non-zero dl_se->dl_deadline?

When a SCHED_DEADLINE task leaves the class before its 0-lag time,
switched_from_dl() leaves dl_se->dl_deadline and dl_se->deadline non-zero
until inactive_timer fires.  If that task holds an rt_mutex, blocks on a
second rt_mutex, and gets boosted back into dl_sched_class before
dl_se->deadline passes, switched_to_dl() cancels inactive_timer (so
__dl_clear_params() never clears dl_se->dl_deadline) and does not start a
new period.  If a second deadline donor with an earlier deadline boosts
the task after dl_se->deadline has passed, dl_boost_blocked() returns
early because dl_se->dl_deadline is non-zero, and the chain walk requeues
the waiter with the expired dl_se->deadline ahead of waiters with current
deadlines.

> @@ -4866,6 +4901,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;
>  	}

[Severity: Medium]
Does switched_to_dl() skip replenish_dl_new_period() when a task with
p->dl.deadline == 0 enters SCHED_DEADLINE with a constrained reservation
while blocked on an rt_mutex?

__setparam_dl() writes p->dl.dl_deadline and p->dl.dl_period before
switched_to_dl() runs.  When p->dl.deadline is 0, dl_next_period(&p->dl)
evaluates to dl_period - dl_deadline.  If rq_clock(rq) < dl_period -
dl_deadline, dl_time_before(rq_clock(rq), dl_next_period(&p->dl)) is
true, so switched_to_dl() treats the never-initialized deadline as being
in a constrained gap and leaves p->dl.deadline at 0 for the rt_mutex
chain walk.

In addition, if a blocked task returning to SCHED_DEADLINE before its
0-lag time changes its dl_deadline or dl_period via sched_setattr(),
dl_next_period(&p->dl) mixes the old p->dl.deadline with the newly
overwritten p->dl.dl_deadline and p->dl.dl_period.  Even after the later
commit "sched/deadline: Keep the debt of a task across a change of
parameters" replaces the dl_next_period() check with
dl_in_constrained_gap(), dl_in_constrained_gap() still returns true when
deadline == 0 and period_start == 0 while now < dl_period unless
!p->dl.deadline is checked first.

[Severity: Medium]
Does the !p->dl.dl_throttled check in switched_to_dl() also prevent a
throttled departed task from receiving a donor period when it is boosted
back into SCHED_DEADLINE?

If a constrained SCHED_DEADLINE task exhausts its runtime
(p->dl.dl_throttled = 1), switches to SCHED_OTHER before its next period,
and blocks on an rt_mutex while holding another rt_mutex, a PI boost back
into dl_sched_class after p->dl.deadline has passed sees
p->dl.dl_throttled == 1 in switched_to_dl() and skips
replenish_dl_new_period().  The chain walk then queues the waiter with
the expired p->dl.deadline instead of the donor's deadline, and on unlock
enqueue_task_dl() clears dl_throttled because is_dl_boosted(&p->dl) is
true, letting the task run immediately ahead of earlier-deadline waiters.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=30

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

* Re: [PATCH v11 28/43] sched/deadline: Restore the owner's period at a deboost in the class
  2026-11-26  1:08 ` [PATCH v11 28/43] sched/deadline: Restore the owner's period at a deboost in the class Mathieu Desnoyers
@ 2026-11-26  1:57   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  1:57 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [Medium] sched/deadline: missing dl_note_donor_refill() in
  replenish_dl_entity()
- [Medium] sched/deadline: dl_note_donor_refill() holds boost when
  deadline is 0
- [Medium] sched/deadline: running_bw under-accounting in dl_deboost()
  for blocked task
- [Medium] sched/deadline: dl_deboost() starts or arms period for
  sleeping task
--

commit 9f6872fae6d8bfd66c95f630e6a2c4067df9ded7
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

sched/deadline: Restore the owner's period at a deboost in the class

This commit saves a boosted task's own deadline and remaining runtime on
its first donor replenishment and restores or restarts its own period when
it is deboosted while staying in the deadline class.

> diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
> index 172fb2811d4a0..100cb4b5fdb6d 100644
> --- a/kernel/sched/deadline.c
> +++ b/kernel/sched/deadline.c
> @@ -83,6 +83,53 @@ 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.
> + */
> +static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se)
> +{
> +	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 {
> +		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 +140,104 @@ 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 has no period to save. 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->dl_boost_held)
> +		dl_hold_refilled_boost(dl_se);
> +}

[Severity: Medium]
Can dl_note_donor_refill() call dl_hold_refilled_boost() when
dl_se->deadline is still 0?

If an rt_mutex owner is boosted while sleeping on a non-PI waitqueue and is
given SCHED_DEADLINE parameters via sched_setattr() before waking up,
__setparam_dl() sets dl_se->dl_runtime > 0 while leaving dl_se->deadline at
0 because the task is not queued.  When the task wakes up while still
boosted, update_dl_entity() -> replenish_dl_new_period() ->
dl_note_donor_refill() sees dl_se->dl_runtime != 0 and calls
dl_hold_refilled_boost(), saving own_deadline = 0 and own_runtime = 0 with
dl_boost_held = 1 even though the task has never started a period of its
own.

At deboost, if dl_time_before(now, next) holds in dl_end_held_boost(), it
restores dl_se->deadline = 0 and dl_se->runtime = 0 and throttles the task
instead of starting its first own period.  With commit "sched/deadline:
Keep the debt of a task across a change of parameters" later in this
series, a subsequent sched_setattr() while running in this held boost sees
own_runtime == 0 and starts the task's own period while it is still
boosted, consuming its own deadline window while running for the donor.
Also, prior to commit "sched/deadline: Boost an owner that cannot run on
its own reservation" later in this series, another rt_mutex_setprio() on
the sleeping task evaluates dl_time_before(pi_task->dl.deadline, 0) as
false and deboosts it.

Checking dl_se->deadline != 0 before calling dl_hold_refilled_boost() would
leave only dl_donor_refill = 1 set so deboost starts a fresh own period.

> +
> +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.
> + *  - 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 held = dl_end_held_boost(dl_se);
> +	bool own = held;
> +
> +	if (dl_se->dl_donor_refill) {
> +		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);
> +	}

[Severity: Medium]
Can this leave rq->dl.running_bw under-accounted when a task blocks after a
donor refill and is deboosted while still blocked?

When a boosted deadline task blocks after a donor refill (with
dl_boost_held set), dequeue_dl_entity() calls task_non_contending() ->
dl_time_to_zerolag(), which compares the donor's refilled dl_se->runtime
against the task's own dl_runtime and dl_period:

kernel/sched/deadline.c:dl_time_to_zerolag() {
    ...
	if (dl_se->runtime > mul_u64_u64_div_u64(left, dl_se->dl_runtime,
						 dl_se->dl_period)) {
		return -1;
	}
    ...
}

If the donor's remaining runtime exceeds what the task's own bandwidth
could leave, dl_time_to_zerolag() returns -1 (or an early 0-lag time whose
inactive_timer expires before the task's own 0-lag time), so
task_non_contending() calls sub_running_bw() immediately and leaves
dl_se->dl_non_contending == 0.  When dl_deboost() later restores the task's
exhausted own_runtime and own_deadline while the task is still blocked,
dl_se->dl_non_contending is 0, so the task's dl_bw is not added back to
rq->dl.running_bw and inactive_timer is not armed for its true 0-lag time,
allowing GRUB tasks on the runqueue to reclaim bandwidth the task already
used in its period.

> +	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.
> +	 */
> +	if (held && dl_se->runtime <= 0) {
> +		struct rq *rq = task_rq(p);
> +
> +		dl_se->dl_throttled = 1;
> +		if (!start_dl_timer(dl_se)) {
> +			dl_se->dl_throttled = 0;
> +			dl_start_own_period(dl_se);
> +		} else if (task_current_donor(rq, p)) {
> +			resched_curr(rq);
> +		}
> +	}
> +}

[Severity: Medium]
Does dl_deboost() start a new period (or arm dl_timer to replenish one)
while a constrained-deadline task is sleeping on a non-PI waitqueue?

If a constrained-deadline task (dl_deadline < dl_period) holding an
rt_mutex is deboosted while sleeping (!task_on_rq_queued(p) &&
!p->pi_blocked_on), dl_end_held_boost() and dl_deboost() either call
dl_start_own_period() immediately or arm dl_timer via start_dl_timer(),
which replenishes and starts a period in dl_task_timer() while the task
remains asleep.  Because that period ticks while the task is sleeping,
waking up before the deadline causes update_dl_revised_wakeup() to trim its
runtime for the time spent asleep, and waking up in the constrained gap
between the deadline and the next period causes dl_check_constrained_dl()
to throttle the task until the following period even though it never ran.

Commit "sched/deadline: Keep the debt of a task across a change of
parameters" later in this series avoids starting a period or arming
dl_timer for an asleep constrained-deadline task in dl_setattr_place() so
that wakeup either throttles it until next or starts a fresh period on
wakeup.

[ ... ]

> @@ -1231,8 +1373,10 @@ static void replenish_dl_entity(struct sched_dl_entity *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;

[Severity: Medium]
When a boosted task with !dl_se->dl_deadline is replenished after its
donor's parameters were cleared (!runtime || !deadline || !period), does
this miss calling dl_note_donor_refill(dl_se)?

The !dl_se->dl_deadline block sets dl_se->deadline = rq_clock(rq) and
dl_se->runtime = 0 without calling dl_note_donor_refill(dl_se), and zeroing
dl_se->runtime prevents the following dl_se->runtime < 0 check from calling
it either.  If sched_setattr() then gives the task SCHED_DEADLINE
parameters during the boost, dl_deboost() sees both dl_boost_held == 0 and
dl_donor_refill == 0 and leaves the task with runtime == 0 and the stale
rq_clock(rq) deadline instead of starting its own period (or a subsequent
donor refill sees first == true and saves that artificial deadline and 0
runtime as own_deadline and own_runtime).

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=28

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

* Re: [PATCH v11 32/43] sched/deadline: Start a period for a task requeued onto an rt_mutex
  2026-11-26  1:08 ` [PATCH v11 32/43] sched/deadline: Start a period for a task requeued onto an rt_mutex Mathieu Desnoyers
@ 2026-11-26  1:57   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  1:57 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [Medium] sched/deadline: dl_proxy_block() skips overflow check for
  boosted tasks
- [Medium] locking/rtmutex: race in __rt_mutex_start_proxy_lock() after
  dl_proxy_block()
- [Medium] sched/deadline: dl_note_donor_refill() saves zero
  own_deadline
- [Medium] sched/deadline: missing dl_proxy_block() in
  futex_proxy_trylock_atomic()
--

commit fbb8bd3107eb7bdbd7615a1083bdbc46d1982421
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

sched/deadline: Start a period for a task requeued onto an rt_mutex

This commit adds dl_proxy_block() and calls it from
__rt_mutex_start_proxy_lock() so that a sleeping SCHED_DEADLINE task
requeued onto an rt_mutex via FUTEX_CMP_REQUEUE_PI has its deadline
updated before the trylock and waiter insertion.

> diff --git a/kernel/locking/rtmutex_api.c b/kernel/locking/rtmutex_api.c
> index 6bdbd36bac949..f1246efc62d3a 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);
> +	}

[Severity: Medium]
Can releasing task->pi_lock here before task->pi_blocked_on is set race
with sched_setattr() or PI boosting on another CPU?

If task is not in SCHED_DEADLINE when dl_proxy_block() runs, it returns
with task->dl.deadline still at 0.  Before task_blocks_on_rt_mutex()
re-acquires task->pi_lock and sets task->pi_blocked_on, another CPU can
switch or boost task into SCHED_DEADLINE:

CPU0                                  CPU1
__rt_mutex_start_proxy_lock()
  raw_spin_lock(&task->pi_lock)
  dl_proxy_block(task)
    !dl_task(task) -> returns
  raw_spin_unlock(&task->pi_lock)
                                      __sched_setscheduler(task, ...)
                                        raw_spin_lock(&task->pi_lock)
                                        switched_to_dl()
                                          !dl_task_pi_blocked(task)
                                          /* task->dl.deadline stays 0 */
                                        raw_spin_unlock(&task->pi_lock)
  try_to_take_rt_mutex() /
  task_blocks_on_rt_mutex()
    raw_spin_lock(&task->pi_lock)
    waiter_update_prio(waiter, task)  <-- copies deadline == 0
    task->pi_blocked_on = waiter
    raw_spin_unlock(&task->pi_lock)

Because task->pi_blocked_on is still NULL when switched_to_dl() runs on
CPU1, switched_to_dl() leaves task->dl.deadline at 0.  CPU0 then uses
deadline 0 to steal the lock or enqueue the waiter ahead of all real
deadline waiters.

> +
>  	if (try_to_take_rt_mutex(lock, task, NULL))
>  		return 1;

[Severity: Medium]
Does the uncontended FUTEX_CMP_REQUEUE_PI fast path in
futex_proxy_trylock_atomic() also need to call dl_proxy_block() on the
new owner?

When the target PI futex is uncontended and nr_requeue >= 1,
futex_requeue() acquires the futex for top_waiter->task via
futex_proxy_trylock_atomic() -> futex_lock_pi_atomic(), attaches
top_waiter->task as the pi_mutex owner, and wakes it without going
through __rt_mutex_start_proxy_lock():

kernel/futex/requeue.c:futex_proxy_trylock_atomic() {
	...
	ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
				   exiting, set_waiters);
	if (ret == 1) {
		requeue_pi_wake_futex(top_waiter, key2, hb2);
	...
}

If try_to_wake_up() queues top_waiter->task on a remote CPU's wake_list
via ttwu_queue_wakelist(), enqueue_task_dl() -> update_dl_entity() has
not run yet when futex_requeue() loops to requeue the next waiter onto
that pi_mutex via rt_mutex_start_proxy_lock().  The boost check against
the new owner then sees top_waiter->task's stale deadline (0, expired, or
overflowed), which can miss a boost from a waiter or cause the subsequent
donor refill at wakeup on the remote CPU to save the unreplenished stale
deadline as own_deadline.

> diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
> index 5d1d4ea288788..c59953e80b1a9 100644
> --- a/kernel/sched/deadline.c
> +++ b/kernel/sched/deadline.c
> @@ -1682,6 +1682,59 @@ 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. 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)))
> +			replenish_dl_new_period(dl_se, rq);

[Severity: Medium]
When a boosted sleeping task has dl_se->deadline == 0 and
dl_se->dl_runtime > 0, does replenish_dl_new_period() here record
own_deadline = 0 via dl_note_donor_refill()?

If a sleeping non-deadline task is first PI-boosted via an rt_mutex it
owns and then given its own SCHED_DEADLINE parameters via sched_setattr()
while still asleep, dl_se->dl_runtime is non-zero while dl_se->deadline
and dl_se->dl_donor_refill are still 0.  Calling replenish_dl_new_period()
from dl_proxy_block() runs dl_note_donor_refill():

kernel/sched/deadline.c:dl_note_donor_refill() {
	...
	first = !dl_se->dl_donor_refill;
	dl_se->dl_donor_refill = 1;
	if (first && dl_se->dl_runtime && !dl_se->dl_boost_held)
		dl_hold_refilled_boost(dl_se);
}

Because dl_note_donor_refill() checks dl_se->dl_runtime without checking
whether dl_se->deadline is non-zero, dl_hold_refilled_boost() saves
own_deadline = 0 and sets dl_boost_held = 1.  When the boost ends,
dl_end_held_boost() can restore dl_se->deadline = 0 and throttle the task
with a zero deadline, causing its waiter node to sort ahead of all real
deadlines.

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

[Severity: Medium]
Should the boosted branch in dl_proxy_block() also check
dl_entity_overflow(dl_se, rq_clock(rq)) as update_dl_entity() does?

In update_dl_entity(), a boosted task whose deadline has not yet passed
still gets a new donor period when dl_entity_overflow(dl_se, rq_clock(rq))
is true:

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

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

Because dl_proxy_block() only tests !dl_se->deadline ||
dl_time_before(dl_se->deadline, rq_clock(rq)) for boosted tasks and then
jumps to unlock, a boosted task requeued after its overflow threshold but
before dl_se->deadline keeps its stale earlier deadline for the trylock,
waiter sorting, and owner boosting, even though waking it would
immediately postpone its deadline to a new donor period.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=32

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

* Re: [PATCH v11 42/43] selftests/sched: Test parameter changes in deadline_bw_test
  2026-11-26  1:08 ` [PATCH v11 42/43] selftests/sched: Test parameter changes in deadline_bw_test Mathieu Desnoyers
@ 2026-11-26  2:01   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  2:01 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [Medium] selftests/sched: premature bandwidth probe after
  reenter_runnable_in_gap()
- [Medium] selftests/sched: missing rival readiness wait in
  owner_boost_case()
--

commit 1245641ca231366ed56f97e5e4afa480f85900ad
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

selftests/sched: Test parameter changes in deadline_bw_test

This commit adds 39 test cases to deadline_bw_test covering SCHED_DEADLINE
parameter changes, priority inheritance boosting, and tasks re-entering the
deadline class during a constrained gap, and waits for total_bw to drain
between partition test cases.

> diff --git a/tools/testing/selftests/sched/deadline/deadline_bw_test.c b/tools/testing/selftests/sched/deadline/deadline_bw_test.c
> index 83dd8b4e79a3d..78b58888e9d54 100644
> --- a/tools/testing/selftests/sched/deadline/deadline_bw_test.c
> +++ b/tools/testing/selftests/sched/deadline/deadline_bw_test.c

[ ... ]

> @@ -2749,93 +2923,3168 @@ static int requeue_pi_new_period(void)

[ ... ]

> +static void *rr_t(void *arg)
> +{
> +	int err;
> +
> +	rr_t_tid = gettid_();
> +	err = set_constrained(0, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);
> +	rr_t_start = now_ns();
> +	if (err) {
> +		ksft_print_msg("T refused as a deadline task: %s\n", strerror(-err));
> +		rr_t_ready = -1;
> +		return (void *)1;
> +	}
> +	rr_t_ready = 1;
> +	while (!rr_stop) {
> +		uint64_t t = now_ns(), b = rr_back_at;
> +
> +		if (b && !rr_t_ran && t > b + 2 * NSEC_PER_MSEC)
> +			rr_t_ran = t;
> +	}
> +	return NULL;
> +}
> +
> +/*
> + * The same as reenter_asleep_in_gap(), for a task that stays runnable. P
> + * has one CPU:
> + * 1. T becomes a deadline task of 10ms in 20ms, every 500ms, at 0ms, and
> + *    spins. It is throttled at 10ms, until its next period at 500ms.
> + * 2. At 40ms, the main thread switches T to SCHED_OTHER, then back to
> + *    SCHED_DEADLINE with the same parameters.
> + *
> + * Leaving the class and coming back must not give T a new period before
> + * 500ms. With a new period, T would run at once. The case fails if T runs
> + * from 2ms to 50ms after rr_back_at.
> + */
> +static int reenter_runnable_in_gap(void)
> +{
> +	int ret = KSFT_FAIL, err;
> +	void *t_ret = NULL;
> +	pthread_t t;
> +
> +	rr_t_ready = 0;
> +	rr_stop = 0;
> +	rr_t_tid = 0;
> +	rr_t_start = 0;
> +	rr_back_at = 0;
> +	rr_t_ran = 0;
> +	if (pthread_create(&t, NULL, rr_t, NULL)) {
> +		ksft_print_msg("the T thread could not start\n");
> +		return KSFT_FAIL;
> +	}
> +	if (wait_for(1000, rr_t_ready) || rr_t_ready < 0) {
> +		ksft_print_msg("T never started\n");
> +		goto out;
> +	}
> +	while (now_ns() - rr_t_start < 40 * NSEC_PER_MSEC)
> +		sleep_ns(NSEC_PER_MSEC);
> +	err = set_other(rr_t_tid);
> +	if (err) {
> +		ksft_print_msg("T cannot leave SCHED_DEADLINE: %s\n", strerror(-err));
> +		goto out;
> +	}
> +	/* Store it before the switch back. A T given a new period runs at once. */
> +	rr_back_at = now_ns();
> +	err = set_constrained(rr_t_tid, 10 * NSEC_PER_MSEC, 20 * NSEC_PER_MSEC, 5 * PERIOD);
> +	if (err) {
> +		ksft_print_msg("T refused back as a deadline task: %s\n", strerror(-err));
> +		goto out;
> +	}
> +	sleep_ns(50 * NSEC_PER_MSEC);
> +	ret = KSFT_PASS;
> +out:
> +	set_other(rr_t_tid);
> +	rr_stop = 1;
> +	if (pthread_join(t, &t_ret) || t_ret)
> +		ret = KSFT_FAIL;

[Severity: Medium]
Can measured() probe cg_p before rr_t's 0-lag time at 500ms and report a
false bandwidth leak?

Unlike reenter_pi_blocked_in_gap() and reenter_asleep_case(), which wait
for T to run at 500ms before returning, reenter_runnable_in_gap() switches
rr_t to SCHED_OTHER and returns at about 90ms while rr_t's 2% bandwidth is
still held by its inactive timer until 500ms.  Because the case is
registered as MEASURED_IN_P, measured() only waits 3 * PERIOD (300ms,
reaching about 390ms) before running probe(cg_p):

tools/testing/selftests/sched/deadline/deadline_bw_test.c:measured() {
    ...
	ret = run_in(cg, fn);
	sleep_ns(3 * PERIOD);
	after = probe(cg);
    ...
}

If probe(cg_p) spawns its nine 10% tasks before 500ms, the ninth task fails
admission with -EBUSY (5% fair server + 2% rr_t + 90% > 95%) and fails the
test.

[ ... ]

> +/*
> + * Run as the rival C of pi_owner_throttled_rival(). Become a deadline
> + * task of 40ms in 60ms, every 100ms. Wait until W is about to block,
> + * then sleep until 13ms after O's start, and spin 40ms of CPU time.
> + * Return NULL, or 1 on an error.
> + */
> +static void *ob_rival(void *arg)
> +{
> +	struct timespec ts;
> +	uint64_t end;
> +	int err;
> +
> +	err = set_constrained(0, 40 * NSEC_PER_MSEC, 60 * NSEC_PER_MSEC, PERIOD);
> +	if (err) {
> +		ksft_print_msg("the rival refused as a deadline task: %s\n",
> +			       strerror(-err));
> +		return (void *)1;
> +	}
> +	sem_wait_sig(&ob_rival_go);
> +	end = ob_t0 + 13 * NSEC_PER_MSEC;
> +	ts.tv_sec = end / NSEC_PER_SEC;
> +	ts.tv_nsec = end % NSEC_PER_SEC;
> +	while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR)
> +		;
> +	spin_ns(40 * NSEC_PER_MSEC);
> +	if (set_other(0))
> +		ksft_print_msg("the rival cannot leave SCHED_DEADLINE\n");
> +	return NULL;
> +}
> +
> +/*
> + * Run an owner_boost case of @kind: ob_owner() and ob_waiter(), and
> + * ob_rival() with OB_RIVAL. W must get pi_lock within @limit_ms of O's
> + * start.
> + */
> +static int owner_boost_case(int kind, int limit_ms)
> +{
> +	void *o_ret = NULL, *w_ret = NULL, *c_ret = NULL;
> +	int throttled = kind != OB_GAP && kind != OB_LATE_GAP;
> +	int ret = KSFT_FAIL;
> +	pthread_t o, w, c;

[ ... ]

> +	if (kind == OB_GAP)
> +		sleep_ns(30 * NSEC_PER_MSEC);	/* O sleeps past its deadline */
> +	if (kind == OB_RIVAL && pthread_create(&c, NULL, ob_rival, NULL)) {
> +		ksft_print_msg("the rival thread could not start\n");
> +		kind = OB_THROTTLED;
> +		c_ret = (void *)1;
> +	}
> +	sem_post(&ob_go);

[Severity: Medium]
Can ob_waiter preempt ob_rival before ob_rival enters SCHED_DEADLINE?

On P's single CPU, owner_boost_case() creates ob_rival and immediately
posts ob_go to wake ob_waiter without waiting for ob_rival to finish
set_constrained():

  main thread (CPU of P)        ob_waiter             ob_rival
  ----------------------        ---------             --------
  pthread_create(..., ob_rival)
  sem_post(&ob_go)
                                wakes as SCHED_OTHER
                                set_deadline(2ms, 10ms)
                                sem_post(&ob_rival_go)
                                take_pi_lock()
                                  boosts ob_owner
                                  ob_owner spins 5ms
                                  unlocks at 15ms
                                                      first scheduled
                                                      set_constrained(...)

When ob_waiter runs before the newly created ob_rival thread, ob_waiter
and the boosted ob_owner keep the single CPU in SCHED_DEADLINE until the
lock hand-off is already over at 15ms, so pi_owner_throttled_rival()
passes without ob_rival competing at 13ms.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=42

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

* Re: [PATCH v11 41/43] sched/deadline: Run a boost held at its first refill on a donor period
  2026-11-26  1:08 ` [PATCH v11 41/43] sched/deadline: Run a boost held at its first refill on a donor period Mathieu Desnoyers
@ 2026-11-26  2:02   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  2:02 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [Medium] sched/deadline: corrupted donor period state when donor
  params are cleared
- [Medium] sched/deadline: stale donor period or zero runtime in
  dl_boost_donor_period()
--

commit 5fe21dc7cf6ba0759a7b3c870c560c1b847c8ab3
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

sched/deadline: Run a boost held at its first refill on a donor period

This commit updates dl_hold_refilled_boost() and replenish_dl_new_period()
so that a boost held at its first refill from a donor runs on a resumed or
newly started donor period via dl_boost_donor_period().

> diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
> index 52095e24638cc..3d573bf812eed 100644
> --- a/kernel/sched/deadline.c
> +++ b/kernel/sched/deadline.c

[ ... ]

> @@ -1663,11 +1668,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;
> +	}

[Severity: Medium]
Can keeping the period placed by dl_note_donor_refill() here leave
dl_se->runtime at 0 or resume a stale donor's deadline and runtime?

kernel/sched/deadline.c:dl_boost_donor_period() {
	...
	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->boost_deadline;
		dl_se->runtime = dl_se->boost_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;
	}
	...
}

When replenish_dl_new_period() is the first refill that holds the boost
(for example from update_dl_entity() on wakeup, or at the end of
replenish_dl_entity() when the owner still had positive runtime left past
its own deadline), there is no while (dl_se->runtime <= 0) loop after it.
If dl_boost_donor_period() resumes a granted period where boost_runtime is
0, or where the density calculation near boost_deadline truncates to 0,
replenish_dl_new_period() returns with dl_se->runtime == 0.

In addition, if the previous held boost came from a different donor (or the
same donor before sched_setattr()) with a longer deadline and larger
runtime, dl_boost_donor_period() resumes boost_deadline and boost_runtime
as long as now is before boost_period_start + period, without checking that
they match the current donor's dl_deadline and dl_runtime.  That can give
the owner a deadline later than the current waiter's (or its own) and a
runtime larger than the current donor's dl_runtime.

[ ... ]

> @@ -6016,11 +6026,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;
> @@ -6037,6 +6051,14 @@ static void dl_hold_refilled_boost(struct sched_dl_entity *dl_se)
>  		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);
> +	/*
> +	 * 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;
>  }

[Severity: Medium]
When the donor leaves SCHED_DEADLINE and has its parameters cleared on
another CPU before the rt_mutex chain walk deboosts the owner, can
returning false here after setting dl_se->dl_boost_held = 1 corrupt the
owner's period and saved boost state?

First, in replenish_dl_entity(), if the donor's parameters are already
cleared at the initial check, dl_note_donor_refill() is called when
dl_se->runtime < 0 or dl_se->dl_yielded is set.  dl_hold_refilled_boost()
sets dl_se->dl_boost_held = 1 and returns false without placing a donor
period, leaving dl_se->deadline and dl_se->period_start set to the owner's
own period with dl_se->runtime == 0.  When the boost ends,
dl_end_held_boost() sees dl_boost_held == 1 and saves the owner's own
period with boost_runtime = 0 into boost_* and sets dl_boost_granted = 1,
so the next held boost from a valid donor resumes the owner's old period
with 0 runtime.

Second, when dl_note_donor_refill() is called from
replenish_dl_new_period(), returning false from dl_hold_refilled_boost()
causes replenish_dl_new_period() to enter the !dl_note_donor_refill(dl_se)
branch and overwrite dl_se->period_start = rq_clock(rq), dl_se->deadline =
dl_se->period_start + 0, and dl_se->runtime = 0 from the cleared donor
parameters anyway.

Third, because dl_hold_refilled_boost() (which also omits checking
pi_se->dl_period), dl_boost_donor_period(), and replenish_dl_new_period()
re-read pi_se's parameters instead of using replenish_dl_entity()'s
validated snapshot, a concurrent __dl_clear_params(pi_se) after
replenish_dl_entity()'s initial check makes dl_hold_refilled_boost() return
false while replenish_dl_entity() proceeds to the while (dl_se->runtime <=
0) loop, advancing the owner's own deadline by the donor's period.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=41

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

* Re: [PATCH v11 37/43] sched/deadline: Keep the debt of a task across a change of parameters
  2026-11-26  1:08 ` [PATCH v11 37/43] sched/deadline: Keep the debt of a task across a change of parameters Mathieu Desnoyers
@ 2026-11-26  2:16   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  2:16 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 8 potential
issues to consider:
- [Medium] sched/deadline: unthrottled zero-runtime wakeup in
  dl_setattr_place()
- [Medium] sched/deadline: deferred boost debt and timer race in
  dl_setattr_period()
- [Medium] sched/deadline: missing zero-deadline check in
  dl_in_constrained_gap()
- [Medium] sched/deadline: redundant update_dl_entity() check after
  dl_setattr_period()
- [Medium] sched/deadline: mismatched period fitting in
  dl_drop_boost_out()
- [Medium] sched/deadline: own_runtime zeroed before debt calc in
  dl_hold_refilled_boost()
- [Medium] sched/deadline: extra period bw retention when
  dl_task_timer() refills departed task
- [Medium] sched/deadline: stale inactive_timer when sched_setattr()
  keeps same dl_bw
--

commit c657dc02c2b65f18247904268d2a021787f80d4c
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

sched/deadline: Keep the debt of a task across a change of parameters

This commit fits the period in progress of a SCHED_DEADLINE task to new
parameters across sched_setattr() so that any accumulated runtime debt is
preserved and repaid at the new bandwidth.

> diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
> index 23186eb9968e8..1ec7789e81b86 100644
> --- a/kernel/sched/deadline.c
> +++ b/kernel/sched/deadline.c
[ ... ]
> @@ -130,6 +132,19 @@ 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 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_is_implicit(dl_se) && dl_time_before(dl_se->deadline, now) &&
> +	       dl_time_before(now, dl_se->period_start + dl_se->dl_period);
> +}

[Severity: Medium]
Should dl_in_constrained_gap() check that dl_se->deadline is non-zero
first, as dl_proxy_block() does?

For a task new to SCHED_DEADLINE (or after __dl_clear_params()), both
deadline and period_start are 0.  If the task is blocked on an rt_mutex
and given a constrained deadline while rq_clock(rq) < dl_se->dl_period,
dl_in_constrained_gap() returns true, so both dl_check_blocked_params()
and switched_to_dl() skip starting a period and leave deadline == 0 in
the task's rt_mutex waiter node.

[ ... ]

> @@ -227,12 +272,80 @@ void dl_deboost(struct sched_dl_entity *dl_se)
[ ... ]
> +void dl_drop_boost_out(struct sched_dl_entity *dl_se)
> +{
> +	bool saved = dl_se->dl_setattr_saved && !dl_se->dl_donor_refill;
> +
> +	dl_drop_boost(dl_se);
> +	if (saved)
> +		dl_setattr_period(dl_se, dl_se->setattr_runtime,
> +				  dl_se->setattr_deadline, dl_se->setattr_period);
> +}

[Severity: Medium]
Does dl_drop_boost_out() fit the period with different rules from the
ones switched_from_dl() just used to arm inactive_timer?

When a boosted task with dl_setattr_saved leaves SCHED_DEADLINE,
switched_from_dl() runs first and computes the 0-lag time via
dl_zerolag_period(), which calls dl_setattr_place() with run = false
(so keep = 0).  dl_drop_boost_out() then calls dl_setattr_period(),
which passes run = !dl_se->dl_throttled && !asleep.  For a queued or
pi-blocked task with runtime > 0, dl_setattr_place() keeps up to
dl_runtime, pushes period_start and deadline past the 0-lag time that
inactive_timer was armed for, and leaves runtime = keep unthrottled (or,
when keep == 0 and debt > 0, sets dl_throttled = 1 and arms dl_timer on
a task that has already left SCHED_DEADLINE).

[ ... ]

> @@ -1934,6 +2108,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;

[Severity: Medium]
When a throttled constrained-deadline task leaves SCHED_DEADLINE, can
replenishing it here in dl_task_timer() cause inactive_task_timer() to
hold its bandwidth for an extra period?

Both dl_timer and inactive_timer are armed for dl_next_period(dl_se)
(or dl_timer fires first when an overrun places the 0-lag time after
dl_next_period(dl_se)).  When dl_task_timer() runs replenish_dl_entity(),
it advances dl_se->period_start by dl_period, so inactive_task_timer()
then sees dl_next_period(dl_se) - rq_clock(rq) > 0 and restarts itself
for another full period before releasing total_bw:

kernel/sched/deadline.c:inactive_task_timer() {
    ...
	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;
		}
	}
    ...
}

[ ... ]

> @@ -3159,12 +3361,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, or its parameters change, while
> -		 * it is 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) &&

[Severity: Medium]
Does testing (flags & ENQUEUE_CLASS) here run update_dl_entity() on a
period that dl_setattr_period() has already fitted?

When a runnable task leaves SCHED_DEADLINE and re-enters before its
0-lag time with modified parameters, __setparam_dl() fits the period
via dl_setattr_period() and clears dl_new_params.  As noted in the
comment on dl_setattr_period(), running update_dl_entity() afterward
checks dl_entity_overflow() at microsecond granularity, which can see a
rounding overflow on the just-fitted period and call
replenish_dl_new_period(), wiping out the debt.  In __setparam_dl(),
the !pending guard has the same effect when dl_new_params was already
set before a change that dl_setattr_period() fits.

[ ... ]

> @@ -5325,47 +5529,298 @@ int sched_dl_overflow(struct task_struct *p, int policy,
[ ... ]
> +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)
> +{
[ ... ]
> +	*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;
> +	}

[Severity: Medium]
What happens if a sleeping task with a new constrained deadline wakes up
before *deadline?

When next - now >= dl_period - dl_deadline (for instance, when debt
repayment exceeds the constrained gap, or when now < release + dl_deadline
forces next >= release + dl_period), *deadline = next - dl_period +
dl_deadline is in the future while *runtime is set to 0 and
dl_setattr_place() returns false (clearing dl_throttled).  If the task
wakes up before *deadline, dl_check_constrained_dl() does not throttle
it because deadline >= now, and dl_entity_overflow() returns false
because left = (dl_deadline >> DL_SCALE) * (0 >> DL_SCALE) = 0 is not
greater than right >= 0.  The task is then enqueued unthrottled with
runtime == 0 before its next period at next.

> +	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;
> +}
> +
[ ... ]
> +static bool dl_setattr_period(struct sched_dl_entity *dl_se, u64 old_runtime,
> +			      u64 old_deadline, u64 old_period)
> +{
[ ... ]
> +	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;
> +	}

[Severity: Medium]
When a boosted task's bandwidth is reduced before any donor refill, does
deferring the fit until deboost or refill repay the debt at the old
bandwidth instead of the new one?

sched_dl_overflow() immediately releases the old bandwidth in total_bw
at sched_setattr(), but dl_setattr_place() is only called later at the
deboost or first donor refill with that later timestamp as now.
Computing debt = (zerolag - now) * old_runtime / old_period at the later
timestamp credits the entire interval since sched_setattr() at
old_runtime / old_period rather than the new bandwidth.  Also, because
setattr_* are only recorded when !dl_setattr_saved, a second
sched_setattr() back to the original parameters before deboost leaves
dl_setattr_saved set and still fits against the first period's state.

> +
> +	/*
> +	 * 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);

[Severity: Medium]
If a sleeping task has dl_non_contending set and sched_setattr() changes
its period without changing dl_bw, can the old inactive_timer fire too
early if the task then leaves SCHED_DEADLINE?

When new_bw == dl_se->dl_bw (for example, when changing a constrained
dl_deadline to implicit while keeping dl_runtime and dl_period, or
scaling both proportionally), dl_change_utilization() returns early and
leaves inactive_timer armed for the old 0-lag time.  dl_setattr_period()
then updates period_start, deadline and runtime, and if the sleeping
task subsequently leaves SCHED_DEADLINE, switched_from_dl() sees
p->dl.dl_non_contending == 1 and skips task_non_contending(), so
inactive_task_timer() fires at the stale pre-setattr 0-lag time and
releases the bandwidth and clears the parameters early.

[ ... ]

> +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_period_start = dl_se->period_start;
> +	dl_se->dl_boost_held = 1;
> +	dl_se->dl_setattr_saved = 0;
> +	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);
> +}

[Severity: Medium]
Does zeroing or clamping dl_se->own_runtime before calling
dl_setattr_place() corrupt the debt calculation?

dl_setattr_place() uses the incoming *runtime to compute how much of the
old period's runtime was used (adjusting zerolag by *runtime *
old_period / old_runtime) before setting *runtime = 0 when run is false.
When a boosted constrained task has unused runtime (dl_se->runtime > 0)
and its first donor refill happens after dl_se->deadline (or when
sched_setattr() is called later while dl_boost_held is set), zeroing
own_runtime first makes dl_setattr_place() treat the entire old_runtime
as consumed and charge debt for runtime the task never used.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=37

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

* Re: [PATCH v11 38/43] sched/deadline: Boost an owner that cannot run on its own reservation
  2026-11-26  1:08 ` [PATCH v11 38/43] sched/deadline: Boost an owner that cannot run on its own reservation Mathieu Desnoyers
@ 2026-11-26  2:17   ` sashiko-bot
  0 siblings, 0 replies; 59+ messages in thread
From: sashiko-bot @ 2026-11-26  2:17 UTC (permalink / raw)
  To: Mathieu Desnoyers; +Cc: linux-rt-devel, tj, hannes, mkoutny, linux-kernel

Thank you for your contribution! Sashiko AI review found 10 potential
issues to consider:
- [High] sched/deadline: self-donor cycle after policy change skips
  enqueue_dl_entity()
- [Medium] sched/deadline: mismatched donor parameters in
  dl_boost_donor_period()
- [Medium] sched/deadline: missed deadline update on donor change in
  rt_mutex_setprio()
- [Medium] sched/deadline: inconsistent throttle state after
  dl_end_held_boost()
- [Medium] sched/deadline: stale or expired deadline propagated on
  rt_mutex PI chains
- [Medium] sched/deadline: stale past deadline kept when boosting
  unqueued owner
- [Medium] sched/deadline: dl_waiter_boosts() ignores positive
  own_runtime on held boost
- [Medium] sched/deadline: deboost of sleeping constrained task wastes
  period and runtime
- [Medium] sched/deadline: dl_end_held_boost() zeroes negative
  own_runtime overrun debt
- [Medium] sched/deadline: rt_mutex_setprio() skips dl_boost_start() for
  departed task
--

commit 32b5d84720d53a30b294628db937bed83d5c70cf
Author: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>

sched/deadline: Boost an owner that cannot run on its own reservation

This commit updates SCHED_DEADLINE priority inheritance so that a lock owner
that is throttled or in its constrained deadline gap is boosted and runs on a
donor period, while preserving and resuming the donor period across
repeated boosts.

> diff --git a/kernel/sched/core.c b/kernel/sched/core.c
> index fa032d6dc873a..c1e043d27b67c 100644
> --- a/kernel/sched/core.c
> +++ b/kernel/sched/core.c
> @@ -7961,9 +7961,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)) {
>  			/*
> @@ -7975,13 +7975,27 @@ 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) &&
>  			     !(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);
> +				if (!dl_set_donor(&p->dl, pi_task)) {
> +					/*
> +					 * The donor of the top waiter is @p: @p waits
> +					 * on a lock that it owns. End the boost of a
> +					 * deadline task, as a deboost does. Another
> +					 * task keeps its donor: a deboost would leave
> +					 * it in the class with no parameters.
> +					 */
> +					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);

[Severity: Medium]
Does gating dl_boost_start(&p->dl) on dl_prio(p->normal_prio) skip holding
the boost for a departed deadline task that still carries its own parameters
until its 0-lag time?

When a SCHED_DEADLINE task leaves the class while throttled or in its
constrained gap, it keeps its non-zero p->dl.dl_runtime and
p->dl.dl_throttled state until inactive_timer fires.  If a deadline waiter
boosts it back into dl_sched_class while !dl_prio(p->normal_prio),
dl_boost_start() is skipped here.  Although commit "sched/deadline: Run a
boost held at its first refill on a donor period" later in this series routes
runnable refills through dl_hold_refilled_boost(), an unqueued throttled
departed task is still not replenished by dl_boost_blocked() or
switched_to_dl(); if it is blocked on another rt_mutex it propagates its
stale deadline along the PI chain, and if it wakes up while boosted before
p->dl.deadline, enqueue_task_dl() clears dl_throttled and update_dl_entity()
enqueues it with runtime <= 0.  Since dl_boost_start() already checks
!dl_se->dl_runtime, the dl_prio(p->normal_prio) check here can be dropped.

> +					scope->flags |= ENQUEUE_REPLENISH;

[Severity: Medium]
When p is already in a held boost (old_donor != &p->dl) and a new top waiter
with an earlier deadline replaces old_donor, does skipping dl_boost_start()
leave p running on the previous donor's later deadline?

Because p->dl.dl_deadline is non-zero and p still has positive donor runtime
and a future deadline from old_donor, neither replenish_dl_entity() (via
ENQUEUE_REPLENISH) nor dl_boost_blocked() updates p->dl.deadline or
p->dl.runtime to the new donor's reservation.  If an intermediate-deadline
task preempts p, p cannot consume the remaining runtime from old_donor to
trigger a refill, causing priority inversion for the urgent new waiter.

> +					if (!scope->queued && p->dl.pi_se != old_donor)
> +						dl_boost_blocked(p);
> +				}

[Severity: Medium]
When a deadline owner p (with p->dl.dl_deadline != 0) is blocked on another
rt_mutex (!scope->queued), can the PI chain walk propagate a stale or
expired p->dl.deadline to the next lock?

Because scope->queued is false, sched_change_end() does not run
enqueue_task_dl(), and dl_boost_blocked() returns early whenever
dl_se->dl_deadline != 0.  If p is boosted while not throttled and not in its
constrained gap, dl_boost_start() also returns early, so waiter_update_prio()
and dl_waiter_boosts() on the outer lock use p's own deadline instead of the
donor's.  Conversely, if p is deboosted while in its constrained gap and
blocked on an outer lock, dl_end_held_boost() and dl_deboost() restore
p->dl.deadline to own_deadline in the past and set dl_throttled = 1, causing
the chain walk to queue p on the outer lock with an expired deadline that
spuriously boosts the outer lock's owner.

[ ... ]

> diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c
> index 1ec7789e81b86..a526497c099c3 100644
> --- a/kernel/sched/deadline.c
> +++ b/kernel/sched/deadline.c

[ ... ]

> @@ -126,7 +134,15 @@ static inline bool dl_end_held_boost(struct sched_dl_entity *dl_se)
>  					       (dl_se->dl_density *
>  						(dl_se->deadline - now)) >> BW_SHIFT);
>  	} else {
> +		/*
> +		 * A new period lifts the throttle. A task asleep since
> +		 * before the boost still has its replenishment timer armed
> +		 * for its old next period: cancel it.
> +		 */
>  		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));
>  	}

[Severity: Medium]
If a constrained-deadline task goes to sleep holding a lock with remaining
runtime > 0 and is boosted and deboosted while asleep during or after its
constrained gap, does deboosting it waste its remaining runtime and start a
new period while it is still asleep?

When the boost ends before own_period_start + dl_period, dl_end_held_boost()
zeroes dl_se->runtime (recording false runtime consumption for 0-lag and
sched_setattr() debt calculations) and dl_deboost() throttles the sleeping
task and arms dl_timer, which fires and starts a new period while the task
sleeps.  When the boost ends at or after own_period_start + dl_period,
dl_end_held_boost() calls dl_start_own_period() immediately while the task is
asleep.  In both cases, if the task wakes up after the constrained deadline
of that new period, dl_check_constrained_dl() throttles it on wakeup even
though it slept through the entire period.

[ ... ]

> @@ -264,6 +283,13 @@ void dl_deboost(struct sched_dl_entity *dl_se)
>  	if (held && dl_se->runtime <= 0) {
>  		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)) {

[Severity: Medium]
Can dl_se->dl_throttled and dl_se->dl_timer be left out of sync with the
runtime restored by dl_end_held_boost()?

There are two cases where the throttle state does not match the restored
period:
1. switched_from_dl() calls dl_end_held_boost(&p->dl) when a task leaves
SCHED_DEADLINE during a held boost, but lacks this re-throttling block; if
the task was runnable during the boost, enqueue_task_dl() cleared
dl_throttled and canceled dl_timer, leaving p with runtime <= 0 and
dl_throttled == 0 (so returning to SCHED_DEADLINE with identical parameters
before own_deadline enqueues p with runtime <= 0 or wraps negative runtime
into an early period).
2. If a task was throttled while asleep (dl_throttled == 1, dl_timer armed),
boosted while asleep, and sched_setattr() started a new period in own_* with
own_runtime > 0 via dl_setattr_place() when debt == 0, dl_end_held_boost()
takes the now < own_period_start + dl_period branch and restores runtime > 0
without clearing dl_throttled or canceling dl_timer, leaving the deboosted
task throttled with positive runtime.

> @@ -347,6 +373,114 @@ 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) {
> +		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);
> +	}

[Severity: Medium]
Does dl_waiter_boosts() keep a held boost when p has positive own_runtime
and an own_deadline earlier than pi_task->dl.deadline?

dl_hold_refilled_boost() also sets dl_boost_held = 1 on a wakeup refill when
the donor's density cannot accommodate p's remaining runtime, saving
own_runtime > 0 with now < own_deadline.  If that early waiter leaves while
a waiter with a deadline later than own_deadline remains, returning true here
keeps p boosted on the later waiter's deadline instead of deboosting p back
to its own earlier deadline and remaining runtime.

> +	if (!is_dl_boosted(dl_se)) {
> +		if (dl_se->dl_throttled || dl_in_constrained_gap(dl_se))
> +			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);
> +}

[Severity: Medium]
When dl_waiter_boosts() boosts an unqueued owner whose deadline is in the
past (dl_time_before(dl_se->deadline, now)) and that is neither throttled
nor in its constrained gap, what updates p->dl.deadline?

Because p is not queued, sched_change_end() does not run enqueue_task_dl();
dl_boost_start() returns early because p is neither throttled nor in its
constrained gap; and dl_boost_blocked() returns early because
p->dl.dl_deadline is non-zero.  As a result, p becomes boosted with
dl_boost_held == 0 while p->dl.deadline remains in the past, so subsequent
dl_waiter_boosts() calls on p and waiter_update_prio() in an rt_mutex chain
walk compare against p's stale past deadline.

> +
> +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);
> +
> +	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->boost_deadline;
> +		dl_se->runtime = dl_se->boost_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);
> +}

[Severity: Medium]
Can dl_boost_donor_period() resume boost_deadline and boost_runtime from a
different donor with incompatible parameters?

dl_end_held_boost() saves boost_deadline, boost_runtime, and
boost_period_start without recording which donor or relative deadline
produced them.  If a previous held boost ran under a donor with a long
relative deadline and large runtime and deboosted, and a more urgent donor
with a shorter dl_deadline and smaller dl_runtime boosts the same owner
before boost_period_start + pi_se->dl_period, dl_boost_donor_period() gives
the owner the old donor's far-future boost_deadline (causing priority
inversion for the urgent waiter) and caps runtime to
(pi_se->dl_density * (boost_deadline - now)) >> BW_SHIFT without capping to
pi_se->dl_runtime, which can grant several multiples of the new donor's
dl_runtime.  Conversely, if the previous boost had a much shorter
boost_deadline that has already passed, advancing dl_se->deadline by
boost_deadline + period instead of dl_se->period_start + pi_se->dl_deadline
sets the new deadline too early and causes dl_entity_overflow() to truncate
the new period's runtime.

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

[Severity: Medium]
When dl_boost_start() saves a negative dl_se->runtime from a throttled task
that overran its budget, does dl_end_held_boost() erase that overrun debt if
the boost ends after own_deadline?

In dl_end_held_boost(), when now < own_period_start + dl_period and
!dl_time_before(now, dl_se->deadline) (for example, during the constrained
gap of a constrained-deadline task), dl_se->runtime is unconditionally set
to 0 instead of only clamping positive runtime, forgiving the negative
overrun saved in own_runtime.

[ ... ]

> diff --git a/kernel/sched/syscalls.c b/kernel/sched/syscalls.c
> index 4f26601f0530a..165f407f45b34 100644
> --- a/kernel/sched/syscalls.c
> +++ b/kernel/sched/syscalls.c
> @@ -315,10 +315,8 @@ static inline void __setscheduler_dl_pi(int newprio, int policy,
>  	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);
> +		if (pi_task && dl_set_donor(&p->dl, pi_task))
>  			scope->flags |= ENQUEUE_REPLENISH;
> -		}
>  	}

[Severity: High]
What happens if a SCHED_DEADLINE task p is the root donor in an rt_mutex
lock cycle (so its top waiter pi_task has pi_task->dl.pi_se == &p->dl) and p
changes its policy to a non-deadline policy?

Because pi_task->prio is deadline priority, rt_effective_prio() keeps p in
dl_sched_class while __setscheduler_params() sets !dl_prio(p->normal_prio).
dl_set_donor(&p->dl, pi_task) then sees pi_se == &p->dl and returns false,
leaving p->dl.pi_se == &p->dl (!is_dl_boosted(&p->dl)) and omitting
ENQUEUE_REPLENISH (the same happens in rt_mutex_setprio() if a waiter still
carrying pi_se == &p->dl blocks on p after p left SCHED_DEADLINE).  When
sched_change_end() or a later wakeup calls enqueue_task_dl(), it hits the
!is_dl_boosted(dl_se) && !dl_prio(p->normal_prio) early return without
calling enqueue_dl_entity(), leaving p marked TASK_ON_RQ_QUEUED with
rq->nr_running incremented while absent from rq->dl.root.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1795646914.git.mathieu.desnoyers@efficios.com?part=38

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

end of thread, other threads:[~2026-11-26  2:17 UTC | newest]

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

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