Re: [PATCH v2] percpu_ref: replace the global switch lock with hashed locks
From: Andrew Morton
Date: Sun Nov 29 2026 - 15:05:03 EST
On Sun, 29 Nov 2026 17:10:59 +0300 Egor Shalashnov <shalasheg@xxxxxxxxx> wrote:
> 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 a hashed array of 64 cacheline-separated
> spinlocks to fix this issue without introducing a separate
> spinlock for each percpu_ref.
Nice, thanks.
Please summarize the microbenchmark speedups in the changelog?
And briefly describe the real-world workload - tell readers "how come
Egor is the first person to report this".
It would be nice to summarize observed improvements in that workload,
but I wouldn't spend a lot of time over this - the patch will obviously
help a lot.
> --- a/lib/percpu-refcount.c
> +++ b/lib/percpu-refcount.c
> @@ -36,7 +39,26 @@
>
> #define PERCPU_COUNT_BIAS (1LU << (BITS_PER_LONG - 1))
>
> -static DEFINE_SPINLOCK(percpu_ref_switch_lock);
> +#define NR_LOCKS 64
Let's remember CONFIG_SMP=n. I guess making this "1" on !SMP will
sufficiently take care of this.
Also
#else
static inline spinlock_t *lock_addr(const struct percpu_ref *ref)
{
return &percpu_switch_lock[0].lock;
}
#endif /* CONFIG_SMP */
I suspect/hope gcc will do exactly this when NR_LOCKS=1, but not if we
switch lock_addr() to hash_ptr() (below).
> +
> +/*
> + * Ensure each lock is in a separate cacheline.
> + */
> +static union {
> + /* Serializes mode switching and teardown within this hash bucket. */
> + spinlock_t lock;
> + char pad[L1_CACHE_BYTES];
> +} percpu_switch_lock[NR_LOCKS] __cacheline_aligned_in_smp;
I agree with Sashiko ;) Can we statically initialize this at compile
time and remove init_percpu_ref_lock().
L1_CACHE_BYTES is too small on machines where SMP_CACHE_BYTES is larger
(ARC and sparc64) - using SMP_CACHE_BYTES here would address that.
I think this:
static struct {
spinlock_t lock;
} ____cacheline_aligned_in_smp percpu_switch_lock[NR_LOCKS] = {
[0 ... NR_LOCKS - 1] = {
.lock = __SPIN_LOCK_UNLOCKED(percpu_switch_lock.lock),
},
};
will address these things.
> +static inline spinlock_t *lock_addr(const struct percpu_ref *ref)
> +{
> + unsigned long addr = (unsigned long)ref;
> +
> + addr >>= L1_CACHE_SHIFT;
> + addr ^= (addr >> 8) ^ (addr >> 16);
> + return &percpu_switch_lock[addr & (NR_LOCKS - 1)].lock;
> +}
<ai>The hash is correct for serialization, but it omits address bits 12
and 13 with 64-byte L1 lines. Four refs at the same offset in
consecutive 4 KiB pages can therefore collide.</ai>
Using hash_ptr() here should address.