Re: [PATCH v3] percpu_ref: replace the global switch lock with hashed locks

From: Andrew Morton

Date: Sun Nov 29 2026 - 20:28:26 EST


On Mon, 30 Nov 2026 02:43:26 +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.
>
> The contention was observed during full-volume discard in a
> thin-provisioning implementation in an out-of-tree module.
> Logical regions are processed concurrently, each requiring its
> reference to be killed, drained, and reinitialized after processing
> discard. Reinitialization also clears the per-CPU counters while
> holding the switch lock.
>
> In module-local fio discard benchmarks with 128 jobs, one pinned
> to each logical CPU, the 64-lock implementation gave the following
> completion times in seconds:
>
> Volume (TB) Global Hash64 Speedup
> 1 3.393 0.722 4.70x
> 2 5.039 1.399 3.60x
> 4 8.705 1.471 5.92x
> 8 16.955 2.834 5.98x
> 16 34.056 4.997 6.82x
> 32 67.177 9.467 7.10x
> 64 134.081 20.311 6.60x
> 128 263.881 40.135 6.57x
> 256 543.297 83.590 6.50x

Thanks, lgtm.

> --- a/lib/percpu-refcount.c
> +++ b/lib/percpu-refcount.c
> @@ -1,12 +1,15 @@
> // SPDX-License-Identifier: GPL-2.0-only
> #define pr_fmt(fmt) "%s: " fmt, __func__
>
> +#include <linux/cache.h>
> +#include <linux/hash.h>
> #include <linux/kernel.h>
> #include <linux/sched.h>
> #include <linux/wait.h>
> #include <linux/slab.h>
> #include <linux/mm.h>
> #include <linux/percpu-refcount.h>
> +#include <linux/spinlock.h>

I'll slip a #include <linux/log2.h> in here and I'll queue this for
test and more review.