[RFC] percpu_ref: deadlock when release calls exit on an atomic ref

From: Egor Shalashnov

Date: Mon Nov 30 2026 - 11:47:58 EST


Hi,

After implementing hashed switch locks, I continued experimenting
with percpu_ref and came across a deadlock when killing a ref that
is already in atomic mode and whose release callback calls
percpu_ref_exit(). This also reproduces with the original global
switch lock.

A minimal example is:

static void release(struct percpu_ref *ref)
{
percpu_ref_exit(ref);
}

static int reproduce(void)
{
struct percpu_ref ref;
int ret;

ret = percpu_ref_init(&ref, release, PERCPU_REF_INIT_ATOMIC,
GFP_KERNEL);
if (ret)
return ret;

percpu_ref_kill(&ref);
return 0;
}

percpu_ref_kill_and_confirm() holds percpu_ref_switch_lock while
dropping the initial reference. With no additional references,
percpu_ref_put() decrements the count from 1 to 0 and invokes
release() synchronously. percpu_ref_exit() then tries to acquire
the same lock:

percpu_ref_kill()
percpu_ref_kill_and_confirm()
spin_lock_irqsave()
percpu_ref_put()
release()
percpu_ref_exit()
spin_lock_irqsave() /* recursive acquisition */

The same situation can arise after explicitly switching a ref
to atomic mode. I have not identified an in-tree caller that
triggers this exact sequence, but the documentation
for percpu_ref_exit() explicitly says:

"The usual places to invoke this function from are the
@ref->release() callback or in init failure path [...]"

When kill starts from percpu mode, the transition to atomic mode
takes an extra reference, which is dropped from the RCU callback.
This prevents the put in percpu_ref_kill_and_confirm() from
invoking release() while holding the switch lock. No such extra
reference is taken when the ref is already in atomic mode.

My codex agent suggested the following fix:
diff --git a/lib/percpu-refcount.c b/lib/percpu-refcount.c
--- a/lib/percpu-refcount.c
+++ b/lib/percpu-refcount.c
@@ -393,9 +393,10 @@

ref->percpu_count_ptr |= __PERCPU_REF_DEAD;
__percpu_ref_switch_mode(ref, confirm_kill);
+
+ spin_unlock_irqrestore(&percpu_ref_switch_lock, flags);
+
percpu_ref_put(ref);
-
- spin_unlock_irqrestore(&percpu_ref_switch_lock, flags);
}
EXPORT_SYMBOL_GPL(percpu_ref_kill_and_confirm);

However, I'm not sure whether moving the put outside the lock
could introduce races with concurrent mode switching or
reinitialization. Is there a reason the initial reference needs
to be dropped while holding the switch lock?

If this usage is intentionally unsupported, should the
documentation explicitly warn that calling percpu_ref_exit()
from the release callback can deadlock when kill drops the last
reference on a ref already in atomic mode?

Thanks,
Egor