]> git.ipfire.org Git - thirdparty/linux.git/commitdiff
clocksource: Improve randomness in clocksource_verify_choose_cpus()
authorYury Norov [NVIDIA] <yury.norov@gmail.com>
Thu, 19 Jun 2025 18:26:25 +0000 (14:26 -0400)
committerYury Norov <yury.norov@gmail.com>
Thu, 31 Jul 2025 15:27:48 +0000 (11:27 -0400)
The current algorithm of picking a random CPU works OK for dense online
cpumask, but if cpumask is non-dense, the distribution of picked CPUs
is skewed.

For example, on 8-CPU board with CPUs 4-7 offlined, the probability of
selecting CPU 0 is 5/8. Accordingly, cpus 1, 2 and 3 are chosen with
probability 1/8 each. The proper algorithm should pick each online CPU
with probability 1/4.

Switch it to cpumask_random(), which has better statistical
characteristics.

CC: Andrew Morton <akpm@linux-foundation.org>
Acked-by: John Stultz <jstultz@google.com>
Reviewed-by: Thomas Gleixner <tglx@linutronix.de>
Signed-off-by: "Yury Norov [NVIDIA]" <yury.norov@gmail.com>
kernel/time/clocksource.c

index 6a8bc7da906263319fc73ea55a220144feb79636..4b005b2f3ef557e227a151af835bdb678c0c1c80 100644 (file)
@@ -342,10 +342,7 @@ static void clocksource_verify_choose_cpus(void)
         * CPUs that are currently online.
         */
        for (i = 1; i < n; i++) {
-               cpu = get_random_u32_below(nr_cpu_ids);
-               cpu = cpumask_next(cpu - 1, cpu_online_mask);
-               if (cpu >= nr_cpu_ids)
-                       cpu = cpumask_first(cpu_online_mask);
+               cpu = cpumask_random(cpu_online_mask);
                if (!WARN_ON_ONCE(cpu >= nr_cpu_ids))
                        cpumask_set_cpu(cpu, &cpus_chosen);
        }