softirq: fix idle accounting for an interrupted idle task
Subsystems (3)
cover softirq: fix idle accounting for an interrupted idle task
tick_irq_exit() decides whether an interrupt that just finished ended inside the idle loop, and it asked sched_core_idle_cpu(), which is idle_cpu(): false whenever the run queue is not empty. But a CPU can be in the idle loop with tasks queued on it - forced idle under core scheduling, and any task a sched_ext BPF scheduler holds back while leaving it runnable - and every interrupt taken in that state skipped tick_nohz_irq_exit(). The fix asks is_idle_task(current) instead, which is the question the function means to ask.
Patch 1 adds the scheduler that holds the state open long enough to measure, patch 2 is the one-line change.
Measurements:
One thread spinning 10 ms in every 100 ms in a cgroup, pinned to the CPU the scheduler holds it on, 20 s windows, three repetitions per cell, arms interleaved, on one 16-CPU KVM guest booted with "no-kvmclock tsc=unstable" - which is what it takes to get an unstable sched_clock in a guest, because mark_tsc_unstable() clears sched_clock stability only when using_native_sched_clock(). Two kernels from this tree differing only in patch 2, booted in turn.
The number is the cgroup's cpu.stat usage_usec over the thread's own CLOCK_MONOTONIC measurement of its busy time, which is an upper bound on the CPU it can possibly have used. 1.00 is correct accounting; above 1.00 the kernel charged the task time it did not spend.
hold (ms) without patch 2 with patch 2
7 1.32 0.964
13 1.21 0.963
23 2.00 0.963
37 1.69 0.964
53 1.33 0.964control, fair class, no BPF scheduler loaded:
1.005 1.006
Nothing in the fixed kernel's figures varies with the hold, and none of the unfixed kernel's is within 20% of correct. The three repetitions of each cell span at most 0.04.
The unfixed kernel also understates how long it held the task, which is the same bug seen from the other side: the scheduler measures the hold with scx_bpf_now(), the sched_clock that is not being resynchronized. For the 23 ms cell it reported a 5.1 ms mean hold where the fixed kernel reported 15.2 ms for the identical configuration. So the fixed kernel accounts correctly across holds three times longer than the ones the unfixed kernel gets wrong.
What is not shown, and what was not done:
No loss in /proc/stat. The sum of that CPU's fields 2 to 9 over the window stayed within 0.6% of the window on both kernels, so in this configuration the kcpustat_irq_exit() half of what tick_nohz_irq_exit() does has no visible effect, unlike the forced idle case that commit 548796e2e70b ("sched/core: introduce sched_core_idle_cpu()") widened the gate for.
The mechanism is bounded rather than measured. A kprobe on tick_nohz_irq_exit() filtered to the idle task counted 998 calls per 20 s window on the held CPU without patch 2 against 1321 with it, n=3 each, but those ranges overlap and the two kernels run the load on different timings.
The forced-idle half of the problem is not measured here at all. Patch 2 changes the same gate for core scheduling, where that commit first widened it, but every number above comes from the sched_ext path.
The figures were taken with an earlier revision of patch 1, before an automated review of the tool found six defects in it. Four of them cannot move these numbers: the per-task hold timestamp (only one task was ever held, so the global it replaces was never overwritten), the ops.dequeue() bookkeeping (the load never changes affinity or priority while parked), the release timer's pinning check (a mispinned timer fails the run loudly, and no run failed) and the userspace CPU validation. Two could: @target_cpu now stays in the idle loop while it holds something instead of taking shared work, and a %SCX_ENQ_LAST enqueue of the tagged task is now held rather than put back. Both make the held state wider, so both move the unfixed kernel further from 1.00, not closer. The load exhausted a 20 ms slice only if a 10 ms burst ran long, so the second one was rarely reached. The test machines are gone and this was not re-measured.
Open question:
The Fixes: tag. The sched_ext path this was found on dates from commit f0e1a0643a59 ("sched_ext: Implement BPF extensible scheduler class"), which is what patch 2 carries. But the gate was idle_cpu() before that, and what put sched_core_idle_cpu() there was commit 548796e2e70b ("sched/core: introduce sched_core_idle_cpu()"). Whichever of the two you prefer, or neither, is yours to pick.
Tooling:
Both patches were written by Claude Opus 5 (Claude Code), including the test scheduler, the measurement harness and these changelogs. The measurements were run and the results checked by hand. The one-line change in patch 2 and the reasoning for it are in Documentation terms tool-generated content; review it as such.
Radu Toader (2):
sched_ext: Add scx_tickbug, a scheduler that holds a task on an idle
CPU
softirq: Treat an interrupted idle task as idle in tick_irq_exit()
include/linux/sched.h | 2 - kernel/sched/syscalls.c | 12 - kernel/softirq.c | 12 +- tools/sched_ext/Makefile | 2 +- tools/sched_ext/README.md | 13 + tools/sched_ext/scx_tickbug.bpf.c | 534 ++++++++++++++++++++++++++++++ tools/sched_ext/scx_tickbug.c | 177 ++++++++++ 7 files changed, 735 insertions(+), 17 deletions(-) create mode 100644 tools/sched_ext/scx_tickbug.bpf.c create mode 100644 tools/sched_ext/scx_tickbug.c
base-commit: f66469d9905b39d2c260a15d7d6db450f4db67c1
Signature · 1 line
2.43.0
PATCH 1/2 sched_ext: Add scx_tickbug, a scheduler that holds a task on an idle CPU
The state behind the tick_irq_exit() gate - the idle task running on a CPU whose run queue is not empty - is reachable with the existing example schedulers but not holdable with them, which makes everything that depends on how long it lasts impossible to measure.
enqueue_task_scx() raises rq->nr_running before it calls ops.enqueue(), so a scheduler that stashes the task in a map of its own leaves it runnable and accounted on that CPU with nothing for the CPU to pick. scx_central already does exactly that, and then calls scx_bpf_kick_cpu() immediately, so the window is microseconds wide.
This scheduler is the same thing with the kick removed: a tagged task is parked on the target CPU's run queue and released only by a timer pinned to another CPU, so the window is as wide as -H says. Untagged tasks go through a shared DSQ and per-CPU kthreads keep their local DSQ and preemption, so the machine stays usable and the timer's softirq cannot be starved.
Three things it has to get right. The release timer must kick @target_cpu only when something is actually held: an unconditional SCX_KICK_PREEMPT lands on the task released a moment earlier and throws it off the CPU mid-run, whereupon ops.enqueue() holds it again, and the load then reports using half the CPU it asked for. @target_cpu must not take work from the shared DSQ while it is holding something, or the idle stretch under test ends early and the hold reported for the task covers time the CPU spent running. And a tagged task re-enqueued while it is the current scheduling context goes back to its local DSQ instead of being held, so a hold only ever delays the start of a run and never interrupts one - with %SCX_ENQ_LAST excluded from that test, because it arrives from put_prev_task_scx(), where rq->donor is still the task, so scx_bpf_task_running() is true for every enqueue on that path while the CPU is in fact about to go idle with that task as the only runnable one.
The hold is tracked per task rather than globally: the timestamp travels with the pid through the queue, and ops.dequeue() gives up the hold when a parked task leaves BPF custody behind the scheduler's back, so a stale queue entry cannot leave the release timer kicking a CPU that is holding nothing.
It reports the mean and worst hold it actually achieved, which is the independent variable of any experiment using it and is not otherwise observable from userspace. Do not use a hold that divides the load's
period: with a 100 ms spinner, holds of 5/10/20 ms phase-lock and the task is only ever held for microseconds.
Tooling: written by Claude Opus 5 (Claude Code) while measuring what the tick_irq_exit() idle gate changes. All of this patch is tool-generated.
--- tools/sched_ext/Makefile | 2 +- tools/sched_ext/README.md | 13 + tools/sched_ext/scx_tickbug.bpf.c | 534 ++++++++++++++++++++++++++++++ tools/sched_ext/scx_tickbug.c | 177 ++++++++++ 4 files changed, 725 insertions(+), 1 deletion(-) create mode 100644 tools/sched_ext/scx_tickbug.bpf.c create mode 100644 tools/sched_ext/scx_tickbug.c
tools/sched_ext/Makefile +1 -1
@@ -191,7 +191,7 @@ $(INCLUDE_DIR)/%.bpf.skel.h: $(SCXOBJ_DIR)/%.bpf.o $(INCLUDE_DIR)/vmlinux.h $(BP SCX_COMMON_DEPS := include/scx/common.h include/scx/user_exit_info.h | $(BINDIR) -c-sched-targets = scx_simple scx_cpu0 scx_qmap scx_central scx_flatcg scx_userland scx_pair scx_sdt +c-sched-targets = scx_simple scx_cpu0 scx_qmap scx_central scx_tickbug scx_flatcg scx_userland scx_pair scx_sdt $(addprefix $(BINDIR)/,$(c-sched-targets)): \ $(BINDIR)/%: \
tools/sched_ext/README.md +13 -0
@@ -185,6 +185,19 @@ where this could be particularly useful is running VMs, where running with infinite slices and no timer ticks allows the VM to avoid unnecessary expensive vmexits. +## scx_tickbug + +A scheduler whose only job is to keep one task runnable on a CPU that is in the +idle loop, for a length of time given on the command line. That state - the +idle task running while the run queue is not empty - is reachable by several of +the schedulers here, but none of them holds it long enough to observe what +depends on it. Tasks named "spin" are parked on the target CPU's run queue and +released only by a periodic timer; everything else runs through a shared DSQ so +the machine stays usable. + +This is a test scheduler, not a policy. It exists so that the idle-time +bookkeeping skipped by an interrupt taken in that state can be measured. + ## scx_flatcg A flattened cgroup hierarchy scheduler. This scheduler implements hierarchical
tools/sched_ext/scx_tickbug.bpf.c new file +534 -0
534 lines not on this page · raw message
tools/sched_ext/scx_tickbug.c new file +177 -0
177 lines not on this page · raw message
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH 1/2] sched_ext: Add scx_tickbug, a scheduler that holds a task on an idle CPU
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] sched_ext: stale hold_q entry consumed in release_one() after dequeue - [Medium] sched_ext…
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] sched_ext: stale hold_q entry consumed in release_one() after dequeue
- [Medium] sched_ext: skipped hold and local DSQ trap in handle_tagged()
- [Medium] sched_ext: untagged SCX_ENQ_LAST tasks kept on target_cpu in tickbug_enqueue()
- [Medium] sched_ext: untagged wakeups disturb target_cpu in tickbug_select_cpu()
--
commit 36aa4109ffa11a9bc7eddd270c091950516a7eb6
Author: Radu Toader <[email protected]>
sched_ext: Add scx_tickbug, a scheduler that holds a task on an idle CPU
This commit adds the scx_tickbug test scheduler, which parks tasks named "spin" in a BPF queue on a target CPU's run queue without kicking the CPU, releasing them periodically via a timer pinned to another CPU.
Quoted 5 lines
tools/sched_ext/scx_tickbug.bpf.c new file +0
-0
[ ... ]
tools/sched_ext/scx_tickbug.bpf.c line 147
Quoted 7 lines
tools/sched_ext/scx_tickbug.bpf.c new file +7
-0+s32 BPF_STRUCT_OPS (tickbug_select_cpu ,struct task_struct *p, +s32 prev_cpu,u64 wake_flags) +{ +if (is_tagged (p)) +return target_cpu; +return prev_cpu; +}
[Severity: Medium]
When an untagged task with prev_cpu == target_cpu wakes up while target_cpu is idling with a held task, doesn't returning prev_cpu here break target_cpu out of the idle loop under test?
ttwu_do_activate() activates the task on target_cpu's run queue and wakeup_preempt() calls resched_curr() because ext_sched_class is above idle_sched_class. That forces target_cpu out of do_idle() through tick_nohz_idle_exit() and back into tick_nohz_idle_enter(), resetting TS_FLAG_IDLE_ACTIVE mid-hold, while tickbug_enqueue() places the task into SHARED_DSQ without kicking an idle non-target CPU to run it.
[ ... ]
Quoted 3 lines
tools/sched_ext/scx_tickbug.bpf.c new file +3
-0+static bool handle_tagged (struct task_struct *p,struct task_ctx *tctx, +u64 enq_flags) +{
[ ... ]
Quoted 9 lines
tools/sched_ext/scx_tickbug.bpf.c new file +9
-0+if (!(enq_flags &SCX_ENQ_LAST ) &&scx_bpf_task_running (p)) { +/* +* Re-enqueued while it is the current scheduling context, e.g. +* after a kthread preempted it. Holding it here would take CPU +* away from work already in progress, which is not the state +* under test: the hold belongs at the start of a run, not in +* the middle of one. Put it straight back so it carries on. +* +* %SCX_ENQ_LAST is excluded because it is not that case. It
tools/sched_ext/scx_tickbug.bpf.c line 197
Quoted 10 lines
tools/sched_ext/scx_tickbug.bpf.c new file +10
-0+* arrives from put_prev_task_scx(), where rq->donor is still +* @p - put_prev_set_next_task() asserts as much - so +* scx_bpf_task_running() is true for every enqueue on that +* path, while the CPU is in fact about to go idle with @p as +* the only runnable task. That is what has to be held. +*/ +__sync_fetch_and_add (&nr_requeue,1 ); +scx_bpf_dsq_insert (p,SCX_DSQ_LOCAL , slice_ns, enq_flags); +return true; + }
[Severity: Medium]
Can a tagged task exhausting its slice in put_prev_task_scx() hit this branch and skip being held when next is not the idle task?
When a running tagged task on target_cpu runs out of slice, do_pick_task_scx() calls tickbug_dispatch() before put_prev_task_scx() enqueues the outgoing task. Because nr_held_now is 0 during tickbug_dispatch(), target_cpu pulls from SHARED_DSQ; if an untagged task is moved to the local DSQ, put_prev_task_scx() sees going_idle == false and enqueues the slice-expired tagged task without SCX_ENQ_LAST while rq->donor is still that task, so handle_tagged() inserts it into SCX_DSQ_LOCAL instead of holding it.
Similarly, if two tagged tasks are held in hold_q, the timer firing for the second task while the first is running preempts the first task and dispatches the second into SCX_DSQ_LOCAL. put_prev_task_scx() then re-enqueues the first task without SCX_ENQ_LAST into SCX_DSQ_LOCAL, after which both tasks stay in SCX_DSQ_LOCAL trading slices forever without calling tickbug_dispatch() or being held again.
[ ... ]
Quoted 2 lines
tools/sched_ext/scx_tickbug.bpf.c new file +2
-0+void BPF_STRUCT_OPS (tickbug_enqueue ,struct task_struct *p,u64 enq_flags) +{
[ ... ]
tools/sched_ext/scx_tickbug.bpf.c line 268
Quoted 11 lines
tools/sched_ext/scx_tickbug.bpf.c new file +11
-0+/* +* A %SCX_ENQ_LAST task stays on its own CPU. put_prev_task_scx() sets +* need_resched on the incoming idle task only if the enqueue landed on +* the local DSQ, so a task left in a shared DSQ here would sit there +* until some other CPU happened to drain it. +*/ +if (last) +scx_bpf_dsq_insert (p,SCX_DSQ_LOCAL , slice_ns, enq_flags); +else +scx_bpf_dsq_insert (p,SHARED_DSQ , slice_ns, enq_flags); +}
[Severity: Medium]
If an untagged task is running on target_cpu when a tagged task wakes up and is parked in hold_q, won't inserting the untagged task into SCX_DSQ_LOCAL on SCX_ENQ_LAST keep target_cpu busy throughout the hold?
When the untagged task's slice expires on target_cpu, tickbug_dispatch() sees nr_held_now > 0 and returns early so target_cpu will enter the idle loop. That makes pick_next_task() select rq->idle, so put_prev_task_scx() calls tickbug_enqueue() with SCX_ENQ_LAST for the untagged task; putting it back into SCX_DSQ_LOCAL causes put_prev_task_scx() to set need_resched on rq->idle and immediately run the untagged task again, inflating total_held_ns and max_held_ns with time target_cpu spent running.
Quoted 28 lines
tools/sched_ext/scx_tickbug.bpf.c new file +28
-0+ +void BPF_STRUCT_OPS (tickbug_dequeue ,struct task_struct *p,u64 deq_flags) +{ +struct task_ctx *tctx; + + tctx =bpf_task_storage_get (&task_ctx_stor, p,0 ,0 ); +if (!tctx || !tctx->held) +return ; + +/* +* A parked task is leaving BPF custody without going through +* release_one(): an affinity or property change, a class change, or +* exit. Give up the hold now. Its entry stays in @hold_q, where +* release_one() recognises it by this flag and drops it. +*/ + tctx->held = false; +__sync_fetch_and_add (&nr_undone,1 ); +__sync_fetch_and_sub (&nr_held_now,1 ); +} + +/* Let one held task run on the CPU we are dispatching for. */ +static bool release_one (void ) +{ +struct hold_entry ent; +struct task_ctx *tctx; +struct task_struct *p; + +bpf_repeat (BPF_MAX_LOOPS ) {
[ ... ]
tools/sched_ext/scx_tickbug.bpf.c line 320
Quoted 9 lines
tools/sched_ext/scx_tickbug.bpf.c new file +9
-0+ tctx =bpf_task_storage_get (&task_ctx_stor, p,0 ,0 ); +if (!tctx || !tctx->held) { +__sync_fetch_and_add (&nr_stale,1 ); +bpf_task_release (p); +continue ; + } + + tctx->held = false; +__sync_fetch_and_sub (&nr_held_now,1 );
[Severity: Medium]
What happens in release_one() if a parked task goes through tickbug_dequeue() and is re-enqueued into hold_q before its undone entry is popped?
A property or affinity change on a parked task (such as setpriority() or sched_setaffinity()) runs tickbug_dequeue(), which clears tctx->held while leaving the older hold_entry in hold_q, and then immediately calls tickbug_enqueue(), which sees tctx->held == false, pushes a second hold_entry for the same pid, and sets tctx->held = true. When release_one() pops the older undone entry first, it sees tctx->held == true and consumes the stale entry as live, leaving hold_q off by one for that task and corrupting total_held_ns and max_held_ns with the older timestamp on every subsequent release. Storing the active hold timestamp (or a sequence number) in task_ctx and matching it against ent.at in release_one() would distinguish stale entries from the current hold.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
Tejun Heo
reviewerRe: [PATCH 1/2] sched_ext: Add scx_tickbug, a scheduler that holds a task on an idle CPU
In reply to Radu ToaderHello,
On Fri, Nov 06, 2026 at 09:43:42AM +0000, Radu Toader wrote:
...
Quoted 6 lines
This scheduler is the same thing with the kick removed: a tagged task is parked on the target CPU's run queue and released only by a timer pinned to another CPU, so the window is as wide as -H says. Untagged tasks go through a shared DSQ and per-CPU kthreads keep their local DSQ and preemption, so the machine stays usable and the timer's softirq cannot be starved.
Thanks for catching the bug. However, this scheduler is more of an one-off debug code and I'm not sure we want to carry this in tree. Maybe put it in a github gist or sth and point to it from the fix patch?
Thanks.
Signature · 1 line
tejun
Re: [PATCH 1/2] sched_ext: Add scx_tickbug, a scheduler that holds a task on an idle CPU
Quoted 3 lines · Tejun Heo
Thanks for catching the bug. However, this scheduler is more of an one-off debug code and I'm not sure we want to carry this in tree. Maybe put it in a github gist or sth and point to it from the fix patch?
Fair enough. v2 is the one-line fix on its own.
Rather than a gist, the fix points at the v1 posting of this patch in the archive, so the link cannot rot and needs no account:
https://lore.kernel.org/lkml/[email protected]/
One offer before I drop it entirely. tools/testing/selftests/sched_ext already carries nohz_tick, which asserts that a finite-slice EXT task restarts the scheduler tick after an idle interval on a NOHZ_FULL CPU. The condition this scheduler holds could be asserted there as a selftest instead of carried as an example scheduler in tools/sched_ext. If a regression guard for this is worth having I will post it separately; if not, the archive link is enough and I will leave it alone.
Either way, the reproducer turned out to have a bug of its own, which the CI review found on the same posting: an untagged task pinned to the target CPU starved in the shared DSQ, because the target CPU stops consuming that DSQ while it is holding something and no other CPU may take a task pinned there. With two tagged tasks handing off it could sit until the watchdog unloaded the scheduler, which contradicts the "the machine stays usable" claim in the commit message. Dispatching anything with nr_cpus_allowed == 1 to its local DSQ fixes it. Noting it here in case someone takes the thing out of the archive.
Thanks for the quick look.
Disclosure: this reply was written by Claude Opus 5 (Claude Code) and sent on my behalf, in the same session as the patch; the patch changelog carries the same note.
[email protected]
AI reviewRe: [PATCH 1/2] sched_ext: Add scx_tickbug, a scheduler that holds a task on an idle CPU
In reply to Radu ToaderTL;DR: - Possible starvation of a task pinned to the target CPU until the sched_ext watchdog unloads the scheduler - Question whether this debug scheduler belongs in tree - README tense and a…
Quoted 1 line
sched_ext: Addscx_tickbug, a scheduler that holds a task on an idle CPU
TL;DR:
- Possible starvation of a task pinned to the target CPU until the sched_ext watchdog unloads the scheduler
- Question whether this debug scheduler belongs in tree
- README tense and a sleepable-comment nit
Quoted 1 line
sched_ext: Addscx_tickbug, a scheduler that holds a task on an idle CPU
Tejun Heo replied to the posting of this patch:
Quoted 3 lines
this scheduler is more of an one-off debug code and I'm not sure we want to carry this in tree. Maybe put it in a github gist or sth and point to it from the fix patch?
I didn't see a reply to this. Is the plan still to carry scx_tickbug in tools/sched_ext?
Quoted 3 lines
tools/sched_ext/README.md +0
-0
[ ... ]
tools/sched_ext/README.md where this could be particularly useful is running VMs, where running with · line 199
Quoted 2 lines
tools/sched_ext/README.md +2
-0+This is a test scheduler, not a policy. It exists so that the idle-time +bookkeeping skipped by an interrupt taken in that state can be measured.
The README says the scheduler measures the bookkeeping skipped by an interrupt in that state, which matches tick_irq_exit() at this commit. The next commit in the series, 24b81cae8220 ("softirq: Treat an interrupted idle task as idle in tick_irq_exit()"), changes the gate so that skip no longer happens, and does not update this README.
Meanwhile the header comment in scx_tickbug.bpf.c already says "tick_irq_exit() used to ask idle_cpu()", which is past tense.
Could the README say that the scheduler reproduces the condition handled by the tick_irq_exit() change and can be used to check it, and could the README and the BPF header comment use the same tense?
Quoted 3 lines
tools/sched_ext/scx_tickbug.bpf.c new file +0
-0
[ ... ]
Quoted 2 lines
tools/sched_ext/scx_tickbug.bpf.c new file +2
-0+void BPF_STRUCT_OPS (tickbug_dispatch ,s32 cpu,struct task_struct *prev) +{
[ ... ]
Quoted 6 lines
tools/sched_ext/scx_tickbug.bpf.c new file +6
-0+if (cpu == target_cpu) { +if (release_now) { + release_now = false; +if (release_one ()) +return ; + }
tools/sched_ext/scx_tickbug.bpf.c line 418
Quoted 10 lines
tools/sched_ext/scx_tickbug.bpf.c new file +10
-0+ +/* +* Leave @target_cpu in the idle loop for as long as it is +* holding something. Taking shared work here would end the +* idle stretch under test, and the hold reported for the task +* would cover time the CPU spent running. +*/ +if (nr_held_now) +return ; + }
Can this starve an untagged task that is pinned to @target_cpu?
tickbug_enqueue() sends everything except per-CPU kthreads and SCX_ENQ_LAST tasks to SHARED_DSQ, which includes a user task pinned with something like taskset -c 0. While nr_held_now is non-zero, the early return above skips:
scx_bpf_dsq_move_to_local(SHARED_DSQ, 0);
and no other CPU can consume that task, because it fails task_allowed_on_cpu() there.
nr_held_now can stay non-zero at every dispatch when two tagged tasks hand off to each other. For example, A wakes B and blocks; B's wakeup on @target_cpu is held, so nr_held_now is 1; ops.dispatch(target_cpu) returns early and the CPU idles; the timer releases B, B wakes A, A is held, B blocks, and so on.
The pinned task would then sit on the runnable list until the watchdog (timeout_ms of 5000) raises SCX_EXIT_ERROR_STALL and unloads the scheduler, which doesn't match the commit message's "the machine stays usable".
Would sending any task with nr_cpus_allowed == 1 to SCX_DSQ_LOCAL, as is done for per-CPU kthreads, address this?
[ ... ]
tools/sched_ext/scx_tickbug.bpf.c line 469
Quoted 8 lines
tools/sched_ext/scx_tickbug.bpf.c new file +8
-0+s32 BPF_STRUCT_OPS (tickbug_init_task ,struct task_struct *p, +struct scx_init_task_args *args) +{ +struct task_ctx *tctx; + +/* Sleepable, so this allocation can use GFP_KERNEL. */ + tctx =bpf_task_storage_get (&task_ctx_stor, p,0 , +BPF_LOCAL_STORAGE_GET_F_CREATE );
This isn't a bug, but is this comment accurate? tickbug_init_task() is declared with BPF_STRUCT_OPS(), not BPF_STRUCT_OPS_SLEEPABLE() as scx_qmap and scx_sdt do for their init_task, so the program isn't sleepable.
Also, since commit 136deea435dc ("bpf: Remove gfp_flags plumbing from bpf_local_storage_update()"), bpf_task_storage_get() allocates with bpf_map_kmalloc_nolock() regardless of sleepability.
Should the comment be dropped, or should the op be declared with BPF_STRUCT_OPS_SLEEPABLE() if sleepability was intended?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/42280840441
Re: [PATCH 1/2] sched_ext: Add scx_tickbug, a scheduler that holds a task on an idle CPU
All three are right. This patch is dropped from v2 at Tejun's request, so none of it lands, but the fixes are worth recording for anyone who takes the reproducer out of the archive.
The starvation is a real bug, not a theoretical one. tickbug_enqueue() routed to the local DSQ only tasks with PF_KTHREAD and nr_cpus_allowed == 1, so a user task pinned with taskset went to SHARED_DSQ; task_allowed_on_cpu() then stops any other CPU from taking it, and tickbug_dispatch() returns before scx_bpf_dsq_move_to_local(SHARED_DSQ, 0) for as long as nr_held_now is non-zero. With the hand-off you describe that is unbounded and ends at the 5 s watchdog, which contradicts the commit message. Your suggested fix is what I used: dispatch anything with nr_cpus_allowed == 1 to its local DSQ. A task pinned to a subset of CPUs containing the target CPU is still delayed by the length of one hold, which -H bounds; the comment now says that rather than implying the case is covered.
The sleepable comment was wrong twice over, as you note: the op is declared with BPF_STRUCT_OPS() and not BPF_STRUCT_OPS_SLEEPABLE() as scx_qmap and scx_sdt do, and since 136deea435dc bpf_task_storage_get() allocates with bpf_map_kmalloc_nolock() regardless. The comment is dropped rather than the declaration changed, since nothing here needs to sleep.
The README now says the scheduler reproduces the condition tick_irq_exit() handles and can be used to check it, which also matches the past tense the BPF header comment was already using.
Disclosure: this reply was written by Claude Opus 5 (Claude Code) and sent on my behalf, in the same session as the patch; the patch changelog carries the same note.
PATCH 2/2 softirq: Treat an interrupted idle task as idle in tick_irq_exit()
In reply to Radu Toadertick_irq_exit() only runs tick_nohz_irq_exit() if sched_core_idle_cpu(), which is idle_cpu() unless core scheduling is built in. idle_cpu() is false when the run queue has tasks while the idle task runs.
That is the normal state of a CPU under sched_ext whose BPF scheduler holds back a runnable task of that CPU in one of its queues, e.g. a task of a cgroup at its CPU limit: the task stays queued on the CPU's run queue and counts in rq->nr_running, while the CPU sits in the idle loop.
tick_nohz_irq_exit() is what marks an idle CPU as idle again for the scheduler clock after an interrupt in the idle loop (TS_FLAG_IDLE_ACTIVE, sched_clock_idle_sleep_event()). Without it, the next exit from the idle loop doesn't resynchronize the CPU's sched_clock with sched_clock_idle_wakeup_event(). With an unstable sched_clock, e.g. under kvm-clock without a stable TSC, the clock of a CPU in tick-stopped idle is clamped to its last stamp plus a tick, so a task picked after a reschedule IPI (which doesn't go through irq_enter()) starts with a stale exec_start, and the next tick charges the whole idle stretch to it. A cgroup holding one such task was charged twice the CPU time it could possibly have used; numbers are in the cover letter.
Commit 548796e2e70b ("sched/core: introduce sched_core_idle_cpu()") fixed this same gate for the other case of "the idle task runs while nr_running > 0", forced idle under core scheduling, where the symptom was too little idle time in /proc/stat. sched_ext made that state reachable without CONFIG_SCHED_CORE, and there the symptom is idle time charged to a task as runtime.
Ask whether the idle task is running, which covers both cases. CPUs whose run queue is really empty are unaffected; a CPU interrupted between leaving the idle loop and switching to a task has need_resched() set or has already left the idle accounting, see tick_nohz_irq_exit(). sched_core_idle_cpu() has no users left and goes.
The new gate is strictly wider than the old one, and deliberately so. idle_cpu() is idle_rq(), rq->curr == rq->idle && !rq->nr_running && !rq->ttwu_pending, so besides the two cases above it also skipped a CPU idling with a wakeup queued by TTWU_QUEUE whose IPI has not run yet. That case is now covered too, on any kernel and not just under sched_ext. It is the same latch failure for a shorter window, so covering it looks right rather than merely harmless, but it was reached by reading the code and not measured on its own. What keeps the wider gate from giving a CPU idle accounting it should not have is that tick_nohz_irq_exit() tests TS_FLAG_INIDLE itself and only does the idle bookkeeping inside the idle loop.
Compile-tested in four x86_64 defconfig variants - SCHED_CORE=y with NO_HZ_FULL=y, SCHED_CORE=n, NO_HZ_COMMON=n, and SCHED_CLASS_EXT=y with SCHED_CORE=y and NO_HZ_FULL=y - with no new warnings at W=1.
Tooling: the bug was found and this patch and changelog were written by Claude Opus 5 (Claude Code), in a session measuring cgroup CPU limit enforcement under sched_ext. All of the patch and all of the changelog are tool-generated; the cover letter says what was and was not measured. By the threat model in Documentation/process/threat-model.rst this is a regular bug and not a vulnerability: it misreports CPU time under a legitimate configuration and crosses no privilege or isolation boundary.
--- include/linux/sched.h | 2 -- kernel/sched/syscalls.c | 12 ------------ kernel/softirq.c | 12 ++++++++++-- 3 files changed, 10 insertions(+), 16 deletions(-)
include/linux/sched.h +0 -2
@@ -2326,11 +2326,9 @@ extern void sched_core_free(struct task_struct *tsk);extern void sched_core_fork (struct task_struct *p);extern int sched_core_share_pid (unsigned int cmd,pid_t pid,enum pid_type type,unsigned long uaddr); -extern int sched_core_idle_cpu (int cpu);#else static inline void sched_core_free (struct task_struct *tsk) { }static inline void sched_core_fork (struct task_struct *p) { } -static inline int sched_core_idle_cpu (int cpu) {return idle_cpu (cpu); }#endif extern void sched_set_stop_task (int cpu,struct task_struct *stop);
kernel/sched/syscalls.c +0 -12
@@ -194,18 +194,6 @@ struct task_struct *idle_task(int cpu)return cpu_rq (cpu)->idle; } -#ifdef CONFIG_SCHED_CORE -int sched_core_idle_cpu (int cpu) -{ -struct rq *rq =cpu_rq (cpu); - -if (sched_core_enabled (rq) && rq->curr == rq->idle) -return 1 ; - -return idle_cpu (cpu); -} -#endif /* CONFIG_SCHED_CORE */ -/** * find_process_by_pid - find a process with a matching PID value. * @pid: the pid in question.
kernel/softirq.c +10 -2
@@ -738,8 +738,16 @@ static inline void tick_irq_exit(void)#ifdef CONFIG_NO_HZ_COMMON int cpu =smp_processor_id (); -/* Make sure that timer wheel updates are propagated */ -if ((sched_core_idle_cpu (cpu) && !need_resched ()) ||tick_nohz_full_cpu (cpu)) { +/* +* Make sure that timer wheel updates are propagated. An interrupted +* idle loop counts as idle even with runnable tasks queued on the +* CPU: forced idle under core scheduling, and the tasks sched_ext +* keeps on a CPU's run queue while its BPF scheduler holds them back. +* idle_cpu() would skip the idle bookkeeping of tick_nohz_irq_exit() +* for those, and with an unstable sched_clock the CPU's clock then +* isn't resynchronized when it leaves the idle loop. +*/ +if ((is_idle_task (current) && !need_resched ()) ||tick_nohz_full_cpu (cpu)) {if (hardirq_count () ==HARDIRQ_OFFSET )tick_nohz_irq_exit (); }
Signature · 1 line
2.43.0
Peter Zijlstra
maintainerRe: [PATCH 2/2] softirq: Treat an interrupted idle task as idle in tick_irq_exit()
Quoted 8 lines · Radu Toader
kernel/softirq.c +0
-0@@ -738,8 +738,16 @@ static inline void tick_irq_exit(void)#ifdef CONFIG_NO_HZ_COMMON int cpu =smp_processor_id ();
kernel/softirq.c static inline void tick_irq_exit(void) · line 750
Quoted 10 lines
kernel/softirq.c +10
-0+/* +* Make sure that timer wheel updates are propagated. An interrupted +* idle loop counts as idle even with runnable tasks queued on the +* CPU: forced idle under core scheduling, and the tasks sched_ext +* keeps on a CPU's run queue while its BPF scheduler holds them back. +* idle_cpu() would skip the idle bookkeeping of tick_nohz_irq_exit() +* for those, and with an unstable sched_clock the CPU's clock then +* isn't resynchronized when it leaves the idle loop. +*/ +if ((is_idle_task (current) && !need_resched ()) ||tick_nohz_full_cpu (cpu)) {
So is_idle_task() is also true for idle-injection tasks. I *think* that is also right in this case, but it wasn't mentioned.
That is, we can have tasks that are not rq->idle for which is_idle_task()/PF_IDLE is true, those tasks will also 'run' an idle state, see play_idle_precise() and its users.
Quoted 6 lines
kernel/softirq.c +0
-0if (hardirq_count () ==HARDIRQ_OFFSET )tick_nohz_irq_exit (); }Signature · 1 line
2.43.0
Re: [PATCH 2/2] softirq: Treat an interrupted idle task as idle in tick_irq_exit()
Quoted 6 lines · Peter Zijlstra
So
is_idle_task()is also true for idle-injection tasks. I *think* that is also right in this case, but it wasn't mentioned.That is, we can have tasks that are not
rq->idlefor which is_idle_task()/PF_IDLE is true, those tasks will also 'run' an idle state, seeplay_idle_precise()and its users.
You are right on both counts, and it should have been mentioned. v2 names it.
I agree it is also right here, for the same reason the idle task needs
it: during injection the CPU does run an idle state. play_idle_precise() sets PF_IDLE and loops on do_idle(), so TS_FLAG_INIDLE is set and tick_nohz_irq_exit() has exactly the work to do there that it has for the idle task. What it is not is confined to sched_ext - it reaches the idle_inject() users, intel_powerclamp and cpuidle_cooling - and v2 says so rather than leaving that for a reviewer to find.
Writing it up also showed that my claim the new gate is "strictly wider" than the old one is wrong, so it is gone. PF_IDLE is set by cpu_startup_entry() and not by init_idle(), so a CPU on its idle task before that point satisfies idle_cpu() but not is_idle_task(current). Nothing is lost there, since TS_FLAG_INIDLE is only set inside do_idle() and so tick_nohz_irq_exit() had nothing to do, and nohz_full CPUs are covered by tick_nohz_full_cpu(cpu) either way. But the gates overlap rather than one containing the other, and v2 states that instead.
Patch 1 is dropped from v2 at Tejun's request; the reproducer stays in the archive and the fix links to it.
Disclosure: this reply was written by Claude Opus 5 (Claude Code) and sent on my behalf, in the same session as the patch; the patch changelog carries the same note.
[email protected]
AI reviewRe: [PATCH 2/2] softirq: Treat an interrupted idle task as idle in tick_irq_exit()
In reply to Radu ToaderTL;DR: Commit message only: claims the new is_idle_task() gate is "strictly wider", but it also now covers idle-injection kthreads (PF_IDLE) and not some early-boot cases; the changelog should say so.
Quoted 1 line
softirq: Treat an interrupted idle task as idle in
tick_irq_exit()
TL;DR: Commit message only: claims the new is_idle_task() gate is "strictly wider", but it also now covers idle-injection kthreads (PF_IDLE) and not some early-boot cases; the changelog should say so.
Quoted 60 lines
softirq: Treat an interrupted idle task as idle in
tick_irq_exit()
tick_irq_exit()only runstick_nohz_irq_exit()ifsched_core_idle_cpu(), which isidle_cpu()unless core scheduling is built in.idle_cpu()is false when the run queue has tasks while the idle task runs.That is the normal state of a CPU under
sched_extwhose BPF scheduler holds back a runnable task of that CPU in one of its queues, e.g. a task of a cgroup at its CPU limit: the task stays queued on the CPU's run queue and counts inrq->nr_running, while the CPU sits in the idle loop.
tick_nohz_irq_exit()is what marks an idle CPU as idle again for the scheduler clock after an interrupt in the idle loop (TS_FLAG_IDLE_ACTIVE,sched_clock_idle_sleep_event()). Without it, the next exit from the idle loop doesn't resynchronize the CPU'ssched_clockwithsched_clock_idle_wakeup_event(). With an unstablesched_clock, e.g. under kvm-clock without a stable TSC, the clock of a CPU in tick-stopped idle is clamped to its last stamp plus a tick, so a task picked after a reschedule IPI (which doesn't go throughirq_enter()) starts with a staleexec_start, and the next tick charges the whole idle stretch to it. A cgroup holding one such task was charged twice the CPU time it could possibly have used; numbers are in the cover letter.Commit
548796e2e70b("sched/core: introducesched_core_idle_cpu()") fixed this same gate for the other case of "the idle task runs whilenr_running> 0", forced idle under core scheduling, where the symptom was too little idle time in/proc/stat.sched_extmade that state reachable withoutCONFIG_SCHED_CORE, and there the symptom is idle time charged to a task as runtime.Ask whether the idle task is running, which covers both cases. CPUs whose run queue is really empty are unaffected; a CPU interrupted between leaving the idle loop and switching to a task has
need_resched()set or has already left the idle accounting, seetick_nohz_irq_exit().sched_core_idle_cpu()has no users left and goes.The new gate is strictly wider than the old one, and deliberately so.
idle_cpu()isidle_rq(),rq->curr==rq->idle&& !rq->nr_running && !rq->ttwu_pending, so besides the two cases above it also skipped a CPU idling with a wakeup queued byTTWU_QUEUEwhose IPI has not run yet. That case is now covered too, on any kernel and not just undersched_ext. It is the same latch failure for a shorter window, so covering it looks right rather than merely harmless, but it was reached by reading the code and not measured on its own. What keeps the wider gate from giving a CPU idle accounting it should not have is thattick_nohz_irq_exit()testsTS_FLAG_INIDLEitself and only does the idle bookkeeping inside the idle loop.Compile-tested in four
x86_64defconfig variants - SCHED_CORE=y with NO_HZ_FULL=y, SCHED_CORE=n, NO_HZ_COMMON=n, and SCHED_CLASS_EXT=y with SCHED_CORE=y and NO_HZ_FULL=y - with no new warnings at W=1.Tooling: the bug was found and this patch and changelog were written by Claude Opus 5 (Claude Code), in a session measuring cgroup CPU limit enforcement under
sched_ext. All of the patch and all of the changelog are tool-generated; the cover letter says what was and was not measured. By the threat model inDocumentation/process/threat-model.rstthis is a regular bug and not a vulnerability: it misreports CPU time under a legitimate configuration and crosses no privilege or isolation boundary.
Quoted 3 lines
Fixes f0e1a0643a59 ("sched_ext: Implement BPF extensible scheduler class")Signed-off-by Radu Toader <[email protected]>
The commit message says "The new gate is strictly wider than the old one, and deliberately so", and lists the newly covered cases as nr_running > 0 while the idle task runs, and a queued TTWU_QUEUE wakeup. Is that accurate?
is_idle_task() tests PF_IDLE on current, which is a different predicate from rq->curr == rq->idle. play_idle_precise() sets PF_IDLE on a SCHED_FIFO kthread and then loops on do_idle():
kernel/sched/idle.c:play_idle_precise() {
...
current->flags |= PF_IDLE;
...
while (!READ_ONCE(it.done))
do_idle();
...
}During idle injection rq->curr is that kthread, so the old gate was false (except on nohz_full CPUs), while the new gate is true whenever need_resched() is clear. Interrupts during injected idle will now run tick_nohz_irq_exit() with TS_FLAG_INIDLE set, which does tick_nohz_clock_sleep(), updates ts->idle_entrytime, and may start kcpustat idle accounting. This affects users such as intel_powerclamp, cpuidle_cooling and idle_inject, and is not limited to sched_ext.
Peter Zijlstra raised the same point on the earlier posting: "So is_idle_task() is also true for idle-injection tasks. I *think* that is also right in this case, but it wasn't mentioned." No reply or changelog update addressing it is visible.
Conversely, PF_IDLE is set by cpu_startup_entry(), not by init_idle(), so a CPU running its idle task before that point (rq->curr == rq->idle, nr_running == 0) satisfied idle_cpu() but does not satisfy is_idle_task(current). That looks harmless, since TS_FLAG_INIDLE is only set inside do_idle() and nohz_full CPUs are still covered by tick_nohz_full_cpu(cpu), but it means the gate is not strictly wider.
Could the commit message name the idle injection case among the newly covered states, and replace "strictly wider" with wording that matches the PF_IDLE semantics?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/42280840441
Re: [PATCH 2/2] softirq: Treat an interrupted idle task as idle in tick_irq_exit()
Both points are right and both are changelog-only, as the report says. Fixed in v2.
On the first: PF_IDLE is indeed set by cpu_startup_entry() and not by init_idle(), which I checked - init_idle() sets PF_KTHREAD and PF_NO_SETAFFINITY only. So the gates overlap rather than one containing the other, and "strictly wider" is wrong. v2 drops it, names the state that is no longer covered, and says why nothing is lost there:TS_FLAG_INIDLE is only set inside do_idle(), so tick_nohz_irq_exit() had nothing to do before cpu_startup_entry(), and nohz_full CPUs stay covered by tick_nohz_full_cpu(cpu).
On the second: injected idle is now named among the newly covered states, with play_idle_precise() cited and the reach beyond sched_ext spelled out - intel_powerclamp and cpuidle_cooling via drivers/powercap/idle_inject.c. Peter Zijlstra raised the same point and has a reply of his own in the thread; the gap in the changelog was real and is closed.
No code change in v2.
Disclosure: this reply was written by Claude Opus 5 (Claude Code) and sent on my behalf, in the same session as the patch; the patch changelog carries the same note.