softirq: fix idle accounting for an interrupted idle task
Subsystems (2)
cover softirq: fix idle accounting for an interrupted idle task
tick_irq_exit() skips tick_nohz_irq_exit() whenever the CPU's run queue has tasks on it, even though the CPU is sitting in the idle loop. Under sched_ext that is an ordinary steady state - a BPF scheduler holding a runnable task back, e.g. a cgroup at its CPU limit - and with an unstable sched_clock the CPU's clock is then never resynchronized on the way out of idle, so the idle stretch is charged to the next task as runtime.
Patch 1 adds scx_tickbug, an example scheduler that holds one tagged task runnable on an idling CPU for a configurable stretch. It exists because the in-tree example schedulers do reach that state but leave it within microseconds, so nothing accumulates and the bug is invisible. Patch 2 is the fix, one line of behaviour: ask is_idle_task(current) instead of sched_core_idle_cpu().
The patches are independent in the files they touch, but patch 1 comes first because without it nothing in this tree can produce the state patch 2 is about.
Measurements
------------
Two kernels built from this tree, differing only in patch 2, booted in turn on one 16-CPU x86_64 KVM guest with "no-kvmclock tsc=unstable". Both are needed: tsc=unstable alone only marks the clocksource, because mark_tsc_unstable() clears sched_clock stability only when using_native_sched_clock(), which is false under kvm-clock.
Load: 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. The figure 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 have used, so correct is <= 1.00:
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. At the 23 ms hold the matched pair is 0.087 CPU of real work charged as 0.173 unfixed against 0.084 fixed, with 173 and 172 releases respectively - the same work, accounted twice over.
The unfixed kernel also understates how long it held the task, which is the same bug from the other side: the scheduler measures the hold with scx_bpf_now(), the sched_clock that is not being resynchronized. For a 23 ms configured hold it reported a 5.2 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.
An earlier measurement, with an out-of-tree sched_ext scheduler that caps how many threads of a cgroup run at once: one thread spinning in a cgroup limited to 0.1 CPU in an 8-vCPU guest was charged 0.27 CPUs, and four such threads 1.12 CPUs, while a sched_switch trace and the work completed both showed 0.100. With nohz=off, idle=poll or a stable sched_clock the three agree. That scheduler is not part of this series, so that one cannot be reproduced from this tree; patch 1 is what makes everything above reproducible.
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 in 548796e2e70b. 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, so that bounds the mechanism rather than measuring it.
The ttwu_pending widening described in patch 2 was reached by reading the code, not measured on its own. The control arm above bounds any effect on an ordinary workload (1.005 against 1.006) without isolating that path.
There is no automated test, and I do not see how to write a useful one. The wrong number only appears with an unstable sched_clock, which takes a command line, so a selftest on a machine with a stable TSC would pass on an unfixed kernel and prove nothing. scx_tickbug reproduces the state and reports counters, but it asserts nothing and is not a selftest.
All of the figures come from one 16-CPU x86_64 KVM guest on one host. No other architecture, topology or guest clocksource was tried.
Open question
-------------
The Fixes: tag on patch 2 names f0e1a0643a59, the commit that made "the idle task runs while nr_running > 0" reachable without CONFIG_SCHED_CORE. 548796e2e70b is arguable instead, as the commit that fixed this same gate for core scheduling with a predicate narrower than the problem; and the ttwu_pending case predates both. Happy to retag.
Tooling
-------
The bug was found, and both patches, both changelogs and this cover letter were written, by Claude Opus 5 (Claude Code), in a session measuring cgroup CPU limit enforcement under sched_ext. The prompts were about why a cgroup's measured CPU usage disagreed with a sched_switch trace by a factor of 2.7; the model localized that to this gate, wrote the fix and the reproducer, ran the measurements and wrote the text. The content is tool-generated throughout, per Documentation/process/generated-content.rst. I have reviewed it, I am signing off on it under the DCO, and I can answer for it in review.
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 | 364 ++++++++++++++++++++++++++++++ tools/sched_ext/scx_tickbug.c | 166 ++++++++++++++ 7 files changed, 554 insertions(+), 17 deletions(-) create mode 100644 tools/sched_ext/scx_tickbug.bpf.c create mode 100644 tools/sched_ext/scx_tickbug.c
base-commit: 05441d697f7f9a927264f4058cbbc6a03dfcac9d
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.
Two things it has to get right, both of which cost a measurement round before they were found. 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. And a tagged task that is already running goes straight back into the local DSQ instead of being held, so the hold only ever delays the start of a run - the state the gate under test mis-judges - and never interrupts one. nr_requeue counts the second case so a run can show whether it happened.
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 | 364 ++++++++++++++++++++++++++++++ tools/sched_ext/scx_tickbug.c | 166 ++++++++++++++ 4 files changed, 544 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 +364 -0
364 lines not on this page · raw message
tools/sched_ext/scx_tickbug.c new file +166 -0
166 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 6 potential issue(s) to consider: - [Medium] sched_ext: SCX_OPS_ENQ_LAST in tickbug_enqueue() fails to hold or stalls tasks - [Medium]…
Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider:
- [Medium] sched_ext: SCX_OPS_ENQ_LAST in tickbug_enqueue() fails to hold or stalls tasks
- [Medium] sched_ext: global held_at overwritten across queued tasks in tickbug_enqueue()
- [Medium] sched_ext: missing ops.dequeue in scx_tickbug corrupts hold_q and nr_held_now
- [Medium] sched_ext: scx_tickbug fails to ensure release_timer is armed on timer_cpu
- [Medium] sched_ext: scx_tickbug runs untagged tasks on target_cpu during hold
- [Medium] sched_ext: missing nr_cpu_ids check for default timer_cpu in scx_tickbug --
commit 1398ab9e5efd3cabedac623d79d370424ce29d54
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 to hold tasks named "spin" runnable in a BPF queue while the target CPU remains in the idle loop until a periodic timer pinned to another CPU releases them.
Quoted 5 lines
tools/sched_ext/scx_tickbug.bpf.c new file +0
-0
[ ... ]
tools/sched_ext/scx_tickbug.bpf.c line 108
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]
What happens when an untagged task wakes up with prev_cpu == target_cpu while target_cpu is idling with a tagged task held in hold_q?
Because tickbug_select_cpu() returns prev_cpu, ttwu_do_activate() enqueues the untagged task on target_cpu and calls wakeup_preempt(), which sees rq->next_class == &idle_sched_class and calls resched_curr() on target_cpu. That forces target_cpu out of do_idle() (calling tick_nohz_idle_exit()) and into tickbug_dispatch():
if (cpu == target_cpu && release_now) {
release_now = false;
if (release_one())
return;
}
scx_bpf_dsq_move_to_local(SHARED_DSQ, 0);When release_now is false, tickbug_dispatch() falls through to scx_bpf_dsq_move_to_local(SHARED_DSQ, 0) even while nr_held_now > 0 (or when prev on target_cpu is a tagged task whose slice just expired), so target_cpu executes untagged tasks from SHARED_DSQ instead of remaining idle. Later, release_one() still credits the entire now - held_at interval to total_held_ns and max_held_ns as if target_cpu had been idle the whole time.
Should tickbug_select_cpu() avoid returning target_cpu for untagged tasks, and should tickbug_dispatch() avoid pulling from SHARED_DSQ onto target_cpu while a tagged task is held?
Quoted 49 lines
tools/sched_ext/scx_tickbug.bpf.c new file +49
-0+ +void BPF_STRUCT_OPS (tickbug_enqueue ,struct task_struct *p,u64 enq_flags) +{ +s32 pid = p->pid; + +__sync_fetch_and_add (&nr_enq,1 ); + +/* +* Per-CPU kthreads go to the head of their own CPU's local DSQ with +* preemption. The release timer runs from a softirq, so if a kthread +* such as ksoftirqd were starved behind a user task the held task +* would never be released. +*/ +if ((p->flags &PF_KTHREAD ) && p->nr_cpus_allowed ==1 ) { +__sync_fetch_and_add (&nr_locals,1 ); +scx_bpf_dsq_insert (p,SCX_DSQ_LOCAL , slice_ns, + enq_flags |SCX_ENQ_PREEMPT ); +return ; + } + +if (is_tagged (p)) { +if (scx_bpf_task_cpu (p) != target_cpu) { +/* +* ops.select_cpu() is only a hint and is not called on +* every path. Counted rather than forced: a run with a +* non-zero count here did not test what it meant to. +*/ +__sync_fetch_and_add (&nr_other_cpu,1 ); + }else if (scx_bpf_task_running (p)) { +/* +* Already on the CPU and merely re-enqueued, 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. +*/ +__sync_fetch_and_add (&nr_requeue,1 ); +scx_bpf_dsq_insert (p,SCX_DSQ_LOCAL , slice_ns, enq_flags); +return ; + }else if (bpf_map_push_elem (&hold_q, &pid,0 )) { +__sync_fetch_and_add (&nr_overflow,1 ); + }else { +/* +* This is the whole scheduler. The task is already in +* target_cpu's rq->nr_running; parking its pid here +* and deliberately not kicking the CPU leaves it in +* the idle loop with a runnable task queued. +*/
tools/sched_ext/scx_tickbug.bpf.c line 167
Quoted 10 lines
tools/sched_ext/scx_tickbug.bpf.c new file +10
-0+ held_at =scx_bpf_now () ?:1 ; +__sync_fetch_and_add (&nr_held,1 ); +__sync_fetch_and_add (&nr_held_now,1 ); +return ; + } + } + +__sync_fetch_and_add (&nr_passthru,1 ); +scx_bpf_dsq_insert (p,SHARED_DSQ , slice_ns, enq_flags); +}
[Severity: Medium]
Does SCX_OPS_ENQ_LAST in tickbug_ops work as intended with tickbug_enqueue()?
When the sole runnable task on a CPU exhausts its slice and SHARED_DSQ is empty, SCX_OPS_ENQ_LAST prevents dispatch_one() from keeping prev running via SCX_DSP_PREV. Instead, __pick_next_task() picks next = rq->idle and put_prev_set_next_task() calls:
put_prev_task_scx(rq, prev, rq->idle)
-> scx_do_enqueue_task(rq, prev, SCX_ENQ_LAST, -1)
-> tickbug_enqueue(prev, SCX_ENQ_LAST)Because __schedule() only updates rq->donor to next via rq_set_donor(rq, next) after pick_next_task() returns, task_rq(p)->donor is still p throughout put_prev_task_scx(). As a result, scx_bpf_task_running(p) (which checks rcu_access_pointer(task_rq(p)->donor) == p) is always true on every SCX_ENQ_LAST enqueue:
1. For a tagged spin task on target_cpu, tickbug_enqueue() always takes the scx_bpf_task_running(p) branch, increments nr_requeue, and inserts p back into SCX_DSQ_LOCAL instead of holding it in hold_q. In put_prev_task_scx(), going_idle && p->scx.dsq == &rq->scx.local_dsq then sets need_resched on rq->idle, so target_cpu switches to rq->idle, enters do_idle() (calling tick_nohz_idle_enter() and tick_nohz_idle_exit()), and immediately switches back to spin on every slice expiry.
2. For an untagged task (or a tagged task not on target_cpu) enqueued with SCX_ENQ_LAST, tickbug_enqueue() inserts it into SHARED_DSQ without kicking the CPU. Because p->scx.dsq is not &rq->scx.local_dsq, put_prev_task_scx() does not set need_resched on rq->idle, and the CPU switches to rq->idle and goes to sleep with the task stranded in SHARED_DSQ.
Should tickbug_enqueue() check (enq_flags & SCX_ENQ_LAST) before treating scx_bpf_task_running(p) as a mid-run preemption, and either insert untagged SCX_ENQ_LAST tasks into SCX_DSQ_LOCAL or kick the CPU?
Quoted 46 lines
tools/sched_ext/scx_tickbug.bpf.c new file +46
-0+ +/* Let one held task run on the CPU we are dispatching for. */ +static bool release_one (void ) +{ +struct task_struct *p; +s32 pid; + +bpf_repeat (BPF_MAX_LOOPS ) { +u64 now, at; + +if (bpf_map_pop_elem (&hold_q, &pid)) +return false; + + p =bpf_task_from_pid (pid); +if (!p) { +__sync_fetch_and_add (&nr_lost,1 ); +__sync_fetch_and_sub (&nr_held_now,1 ); +continue ; + } + +/* +* Affinity may have changed while the task sat in the queue. +* Such a task goes to the shared DSQ instead of being pinned +* to a CPU it is no longer allowed on. +*/ +if (!bpf_cpumask_test_cpu (target_cpu, p->cpus_ptr) || +is_migration_disabled (p)) { +scx_bpf_dsq_insert (p,SHARED_DSQ , slice_ns,0 ); +bpf_task_release (p); +__sync_fetch_and_sub (&nr_held_now,1 ); +if (!scx_bpf_dispatch_nr_slots ()) +return false; +continue ; + } + +scx_bpf_dsq_insert (p,SCX_DSQ_LOCAL , slice_ns,0 ); +bpf_task_release (p); +__sync_fetch_and_sub (&nr_held_now,1 ); + + at = held_at; + now =scx_bpf_now (); +if (at && now > at) { +u64 d = now - at; + +__sync_fetch_and_add (&total_held_ns, d); +if (d > max_held_ns)
tools/sched_ext/scx_tickbug.bpf.c line 223
Quoted 10 lines
tools/sched_ext/scx_tickbug.bpf.c new file +10
-0+ max_held_ns = d; + } + held_at =0 ; + +__sync_fetch_and_add (&nr_released,1 ); +return true; + } + +return false; +}
[Severity: Medium]
Can a single global held_at variable track hold duration when multiple tagged tasks are queued in hold_q?
hold_q has 1024 entries and nr_held_now counts how many tagged tasks are currently held, but held_at is a single global scalar. If two spin tasks are queued in hold_q before release_one() runs:
1. The second task's tickbug_enqueue() overwrites held_at with its own timestamp and increments nr_held_now to 2.
2. When release_one() pops the first task, it computes now - held_at using the second task's timestamp, clears held_at = 0, decrements nr_held_now to 1, and increments nr_released.
3. On the next timer tick, nr_held_now is still 1, so release_timerfn() kicks target_cpu with SCX_KICK_PREEMPT (preempting the first released task mid-run), and release_one() pops the second task with held_at == 0, adding nothing to total_held_ns while incrementing nr_released again, which skews the mean hold reported by main() (total_held_ns / released).
Should the enqueue timestamp be stored alongside pid in the hold_q map value struct instead of in a single global variable?
[ ... ]
tools/sched_ext/scx_tickbug.bpf.c line 261
Quoted 8 lines
tools/sched_ext/scx_tickbug.bpf.c new file +8
-0+void BPF_STRUCT_OPS (tickbug_dispatch ,s32 cpu,struct task_struct *prev) +{ +/* +* Arm the timer from the CPU it must be pinned to. ops.init() runs in +* whatever context loaded the scheduler, which is the wrong CPU. +*/ +if (cpu == timer_cpu) +start_release_timer ();
[Severity: Medium]
Can start_release_timer() pin release_timer to the wrong CPU or fail to run when timer_cpu is busy?
First, start_release_timer() calls bpf_timer_start(timer, hold_ns, BPF_F_TIMER_CPU_PIN), which pins the hrtimer to bpf_get_smp_processor_id() rather than the cpu argument passed to tickbug_dispatch(). Under CONFIG_SCHED_CORE, pick_next_task() on target_cpu can invoke dispatch_core_pick() -> tickbug_dispatch(timer_cpu, prev) for its SMT sibling while executing on target_cpu. Because cpu == timer_cpu is true while bpf_get_smp_processor_id() == target_cpu, release_timer is pinned to target_cpu and release_timerfn() then aborts the scheduler via scx_bpf_error() when curr_cpu == target_cpu.
Second, tickbug_init() calls scx_bpf_kick_cpu(timer_cpu, 0) before __scx_enabled is set and before tasks are switched to ext_sched_class. When SCX is enabled and resched_curr() runs on timer_cpu, if timer_cpu is running a task with remaining slice (prev->scx.slice > 0), dispatch_one() returns SCX_DSP_PREV without calling tickbug_dispatch(), leaving release_timer unstarted unless timer_cpu is kicked with SCX_KICK_PREEMPT when !timer_started.
Should start_release_timer() check bpf_get_smp_processor_id() == timer_cpu, and should tickbug_enqueue() kick timer_cpu with SCX_KICK_PREEMPT if !timer_started?
[ ... ]
tools/sched_ext/scx_tickbug.bpf.c line 358
Quoted 13 lines
tools/sched_ext/scx_tickbug.bpf.c new file +13
-0+SCX_OPS_DEFINE(tickbug_ops, + /* + * The last runnable task on a CPU has to come through + * ops.enqueue() too, otherwise the tagged task would simply + * keep running on @target_cpu and never be held. + */ + .flags = SCX_OPS_ENQ_LAST, + + .select_cpu = (void *)tickbug_select_cpu, + .enqueue = (void *)tickbug_enqueue, + .dispatch = (void *)tickbug_dispatch, + .init = (void *)tickbug_init, + .exit = (void *)tickbug_exit,
[Severity: Medium]
Does tickbug_ops need an ops.dequeue callback to keep hold_q and nr_held_now consistent when a held task leaves BPF custody?
In release_one(), the code checks whether a held task's affinity changed while it sat in hold_q:
if (!bpf_cpumask_test_cpu(target_cpu, p->cpus_ptr) ||
is_migration_disabled(p)) {However, when a task parked in hold_q undergoes an affinity change via sched_setaffinity() (or a property change such as setpriority(), sched_setscheduler(), or cgroup migration), the scheduler core calls dequeue_task_scx() followed by enqueue_task_scx(). Without ops.dequeue:
1. If affinity changed away from target_cpu, move_queued_task() dequeues p from target_cpu without decrementing nr_held_now and re-enqueues p on dest_cpu != target_cpu, where tickbug_enqueue() dispatches it immediately to SHARED_DSQ while leaving a stale pid in hold_q and nr_held_now inflated.
2. If the property change keeps p on target_cpu, enqueue_task_scx() calls tickbug_enqueue() again while scx_bpf_task_running(p) is false, pushing a duplicate pid into hold_q and incrementing nr_held_now to 2 for a single task. When the first timer tick releases the task, nr_held_now stays at 1, so the next release_timerfn() tick kicks target_cpu with SCX_KICK_PREEMPT and preempts the running task.
Quoted 5 lines
tools/sched_ext/scx_tickbug.c new file +0
-0
[ ... ]
Quoted 32 lines
tools/sched_ext/scx_tickbug.c new file +32
-0+ nr_cpu_ids =libbpf_num_possible_cpus (); +assert (nr_cpu_ids >0 ); +assert (nr_cpu_ids <=INT32_MAX ); + + skel->rodata->nr_cpu_ids = nr_cpu_ids; + skel->rodata->target_cpu =0 ; + skel->rodata->timer_cpu =1 ; + skel->rodata->hold_ns =10ULL *1000 *1000 ; + skel->rodata->slice_ns =__COMPAT_ENUM_OR_ZERO ("scx_public_consts" ,"SCX_SLICE_DFL" ); + +while ((opt =getopt (argc, argv,"c:t:H:s:vh" )) !=-1 ) { +switch (opt) { +case 'c' : +case 't' : { +unsigned long cpu =strtoul (optarg,NULL ,0 ); + +if (cpu >= nr_cpu_ids) { +fprintf (stderr,"invalid CPU id %lu (%u max)\n" , + cpu, nr_cpu_ids -1 ); +scx_tickbug__destroy (skel); +return 1 ; + } +if (opt =='c' ) + skel->rodata->target_cpu = (s32 )cpu; +else + skel->rodata->timer_cpu = (s32 )cpu; +break ; + } +case 'H' : + skel->rodata->hold_ns =strtoull (optarg,NULL ,0 ) *1000 *1000 ; +break ; +case 's' :
tools/sched_ext/scx_tickbug.c line 106
Quoted 10 lines
tools/sched_ext/scx_tickbug.c new file +10
-0+ skel->rodata->slice_ns =strtoull (optarg,NULL ,0 ) *1000 ; +break ; +case 'v' : + verbose = true; +break ; +default : +fprintf (stderr, help_fmt,basename (argv[0 ])); +return opt !='h' ; + } + }
[Severity: Medium]
What happens if scx_tickbug is run without -t on a single-CPU system where nr_cpu_ids == 1?
In main(), skel->rodata->timer_cpu defaults to 1 while cpu >= nr_cpu_ids is only checked inside the getopt() cases for -c and -t (and rodata->nr_cpu_ids is never referenced in scx_tickbug.bpf.c). On a 1-CPU system, timer_cpu = 1 passes the target_cpu == timer_cpu check, loads the BPF program, and then triggers scx_error() in scx_cpu_valid() when tickbug_init() calls scx_bpf_kick_cpu(timer_cpu, 0). Also, the default branch in the getopt() loop returns without calling scx_tickbug__destroy(skel).
Should main() verify that nr_cpu_ids >= 2 (or validate timer_cpu < nr_cpu_ids after the getopt() loop) and destroy skel before returning in the default case?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
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