Re: [PATCH v3 1/2] sched/uclamp: Fix race condition leading to imbalanced uclamp_rq

From: Peter Zijlstra

Date: Wed Oct 28 2026 - 06:56:54 EST


On Wed, Oct 28, 2026 at 02:05:11AM +0000, Qais Yousef wrote:

> --- a/kernel/sched/idle.c
> +++ b/kernel/sched/idle.c
> @@ -502,6 +502,23 @@ static void set_next_task_idle(struct rq *rq, struct task_struct *next, enum snt
> * lost_idle_time of clock_pelt
> */
> update_idle_rq_clock_pelt(rq);
> +
> + /*
> + * Due to a race condition when enabling sched_uclamp_used static key,
> + * we can end up with imbalance where uclamp_rq_inc_id() has happened
> + * on a CPU without uclamp_rq_dec_id() on another CPU that hasn't seen
> + * the static key flipped. The race condition is unlikely, but ensure
> + * the uclamp_rq() state is set properly on each entry to idle.
> + *
> + * The reset will cause the uclamp_max from uclamp_idle_value() to be
> + * lost. Since we are imbalanced, hard to know what is right. So just
> + * cleanup. This should be a transient error state once we recover
> + * everything should work as expected.
> + */
> + if (uclamp_is_used()) {
> + if (unlikely(!uclamp_rq_is_idle(rq)))
> + init_uclamp_rq(rq);
> + }
> }

Much nicer! Would you mind terribly if I make that:

if (unlikely(uclamp_is_used() && !uclamp_rq_is_idle(rq)))
init_uclamp_rq(rq);

?