Re: [PATCH v3 2/2] sched/uclamp: Add uclamp_is_used() check before enable it

From: Qais Yousef
Date: Mon Feb 24 2025 - 18:47:59 EST


On 02/20/25 13:59, Xuewen Yan wrote:
> Because the static_branch_enable() would get the cpus_read_lock(),
> and sometimes users may frequently set the uclamp value of tasks,
> and this operation would call the static_branch_enable()
> frequently, so add the uclamp_is_used() check to prevent calling
> the cpus_read_lock() frequently.
> And to make the code more concise, add a helper function to encapsulate
> this and use it everywhere we enable sched_uclamp_used.
>
> Signed-off-by: Xuewen Yan <xuewen.yan@xxxxxxxxxx>
> Reviewed-by: Vincent Guittot <vincent.guittot@xxxxxxxxxx>
> Reviewed-by: Christian Loehle <christian.loehle@xxxxxxx>
> ---

[...]

> +/*
> + * Enabling static branches would get the cpus_read_lock(),
> + * check uclamp_is_used before enabling it. There is no race
> + * issue because we never disable this static key once enabled.
> + */
> +static inline void sched_uclamp_enable(void)
> +{
> + if (!uclamp_is_used())
> + static_branch_enable(&sched_uclamp_used);
> +}
> +

As I indicated in [1] I think the pattern of repeatedly enable is actually sane
and what we probably should be doing is modify the static_key_enable() logic to
do the early bail out logic outside of the lock. I had this code this way FWIW
initially and Peter asked for it to be called unconditionally instead.

I think repeated calls to static_key_enable/disable() should be made cheap and
I don't see a side effect of _replicating_ the early bail out logic outside of
the lock so that if we have already enabled/disabled we just return immediately
without any side effect (holding the lock in this case). I agree the hotplug
lock is ugly and if we can avoid touching it when we don't really need to that
would be better.

--->8---

diff --git a/kernel/jump_label.c b/kernel/jump_label.c
index d9c822bbffb8..17583c98c447 100644
--- a/kernel/jump_label.c
+++ b/kernel/jump_label.c
@@ -214,6 +214,13 @@ EXPORT_SYMBOL_GPL(static_key_enable_cpuslocked);

void static_key_enable(struct static_key *key)
{
+ STATIC_KEY_CHECK_USE(key);
+
+ if (atomic_read(&key->enabled) > 0) {
+ WARN_ON_ONCE(atomic_read(&key->enabled) != 1);
+ return;
+ }
+
cpus_read_lock();
static_key_enable_cpuslocked(key);
cpus_read_unlock();
@@ -239,6 +246,13 @@ EXPORT_SYMBOL_GPL(static_key_disable_cpuslocked);

void static_key_disable(struct static_key *key)
{
+ STATIC_KEY_CHECK_USE(key);
+
+ if (atomic_read(&key->enabled) > 0) {
+ WARN_ON_ONCE(atomic_read(&key->enabled) != 1);
+ return;
+ }
+
cpus_read_lock();
static_key_disable_cpuslocked(key);
cpus_read_unlock();

--->8---

[1] https://lore.kernel.org/all/20250222233627.3yx55ks5lnq3elby@airbuntu/