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

From: Qais Yousef

Date: Tue Nov 24 2026 - 02:41:01 EST


On 11/23/26 14:38, Christian Loehle wrote:
> On 11/21/26 04:15, Qais Yousef wrote:
> > Static keys are not guaranteed to be enabled atomically across CPUs. Or
> > across callsites on the same CPUs. Which means when sched_uclamp_used is
> > enabled, some CPUs/callsites will return true for uclamp_is_used() while
> > others won't, leading to asymmetric uclamp_rq_{inc, dec}_id. If we
> > decrement without increment this is safe as documented in the code. But
> > an increment without a decrement is a problem and will leave the
> > uclamp_rq in a corrupt state.
>
> So if we only need decrement to work then we can rely on
> p's uclamp_se.active and decrement regardless of uclamp_is_used() and call it
> a day?

Removing the static key could bring back the complaints about the overhead as
Vincent pointed out.

> > + /*
> > + * 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.
> > + *
> > + * We need to be careful of some paths that can force idle with tasks
> > + * are still queued.
>
> It wouldn't hurt spelling these paths out IMO.

I prefer not to, this means maintaining such list. git history has info why
this was originally introduced.

>
> > + */
> > + if (uclamp_is_used() &&
> > + !rq->nr_running && unlikely(!uclamp_rq_is_idle(rq)))
> > + init_uclamp_rq(rq);
>
> I guess this means init_uclamp_rq() will need to use WRITE_ONCE() for .value at least?

Hmm maybe. Peter let me know if this is worth respinning another version.