kernel: usage: Fix CPU stats retrieval in z_sched_cpu_usage()

The z_sched_cpu_usage() function was incorrectly using _current_cpu
instead of the requested cpu_id parameter when retrieving CPU usage
statistics. This caused it to always return stats from the current CPU
rather than the specified CPU.

This bug manifested in SMP systems when k_thread_runtime_stats_all_get()
looped through all CPUs - it would get stats from the wrong CPU for
each iteration, leading to inconsistent time values. For example, in
the times() POSIX function, this caused time to appear to move backwards:

  t0: utime: 59908
  t1: utime: 824

The fix ensures that:
1. cpu pointer is set to &_kernel.cpus[cpu_id] (the requested CPU)
2. The check for "is this the current CPU" is correctly written as
   (cpu == _current_cpu)

This fixes the portability.posix.muti_process.newlib test failure
on FVP SMP platforms where times() was reporting backwards time.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
This commit is contained in:
Nicolas Pitre
2025-10-18 19:34:14 -04:00
committed by Benjamin Cabé
parent 5149463f79
commit b5363d5fff

View File

@@ -125,10 +125,9 @@ void z_sched_cpu_usage(uint8_t cpu_id, struct k_thread_runtime_stats *stats)
struct _cpu *cpu;
key = k_spin_lock(&usage_lock);
cpu = _current_cpu;
cpu = &_kernel.cpus[cpu_id];
if (&_kernel.cpus[cpu_id] == cpu) {
if (cpu == _current_cpu) {
uint32_t now = usage_now();
uint32_t cycles = now - cpu->usage0;