Re: [PATCH] percpu_ref: make percpu_ref_switch_lock per percpu_ref

From: Andrew Morton

Date: Wed Nov 25 2026 - 14:35:46 EST


On Wed, 25 Nov 2026 18:55:55 +0300 Egor Shalashnov <shalasheg@xxxxxxxxx> wrote:

> From: Qi Zheng <zhengqi.arch@xxxxxxxxxxxxx>
>
> Currently, percpu_ref uses the global percpu_ref_switch_lock to
> protect the mode switching operation. When multiple percpu_ref
> perform mode switching at the same time, the lock may become a
> performance bottleneck.
>
> This patch introduces per percpu_ref percpu_ref_switch_lock to
> fixes this situation.
>
> ...
>
> I would like to revive Qi Zheng's per-reference switch lock patch
> from 2022 as a standalone change.

This is a nice little change - it's a shame it was buried inside in a
larger patchset back in 2022.

> Our workload maintains many independent percpu_ref instances and
> repeatedly performs kill, waits for references to drain, and reinitializes
> them. Multiple CPUs execute these cycles concurrently on different
> instances.
>
> All these transitions compete for the same global switch lock.
> Reinitialization also clears the per-CPU counters while holding it.
> As the number of concurrent transitions grows, this shared lock
> becomes a significant bottleneck.
>
> With a module-local adaptation of Qi's per-reference locking change,
> we observed approximately 2.8x to 6.5x lower operation completion times
> in the measured workload. This motivates using a lock per instance
> so that independent transitions can proceed concurrently.

Well, an unpublished module isn't very useful for us.

And an intense microbenchmark isn't as interesting as a real-world
workload. So can you please provide more details about what "our
workload" is doing and some measurements on how much this patch
improves that workload?

> @@ -109,6 +110,8 @@ struct percpu_ref {
> */
> unsigned long percpu_count_ptr;
>
> + spinlock_t percpu_ref_switch_lock;
> +
> /*
> * 'percpu_ref' is often embedded into user structure, and only
> * 'percpu_count_ptr' is required in fast path, move other fields
> diff --git a/lib/percpu-refcount.c b/lib/percpu-refcount.c
> index f8d9068..5d46602 100644
> --- a/lib/percpu-refcount.c
> +++ b/lib/percpu-refcount.c
> @@ -36,7 +36,6 @@
>
> #define PERCPU_COUNT_BIAS (1LU << (BITS_PER_LONG - 1))
>
> -static DEFINE_SPINLOCK(percpu_ref_switch_lock);

lol, yeah, that'll do it!

It does grow percpu_ref by 4 bytes, but LLM estimates that a busy
machine will have 10k-100k of these floating around so not to bad.

And I'm told that this will cause io_ring_ctx's hot fields to spill
into a second cacheline, but that can be fixed up by reordering
io_ring_ctx fields.

Alternatively, this looks like somewhere where a hashed spinlock will
work well. A static array of 32(?) cacheline_aligned spinlocks, hash
the percpu_ref* onto one of those. That'll get 90% of the benefit
without growing percpu_ref.