Re: [PATCH v7 14/14] KEYS: Remove key_type_dead

From: Guicai Ma

Date: Mon Nov 30 2026 - 04:07:05 EST


On Sun, Nov 29, 2026 at 07:05:43PM +0200, Jarkko Sakkinen wrote:
> void unregister_key_type(struct key_type *ktype)
> {
> down_write(&key_types_sem);
> + WARN_ON_ONCE(atomic_read(&ktype->nr_keys));
> list_del_init(&ktype->link);
> - downgrade_write(&key_types_sem);
> - key_gc_keytype(ktype);
> pr_notice("Key type %s unregistered\n", ktype->name);
> - up_read(&key_types_sem);
> + up_write(&key_types_sem);
> }

I think there is a narrow window where this WARN_ON_ONCE() fires
spuriously when key_gc_unused_keys() from patch 13/14 races with
unregister_key_type():

rcu_read_lock();
...
module_put(owner);
atomic_dec_return_release(&type->nr_keys);
atomic_dec_return_release(&type->gc_pending);
rcu_read_unlock();

try_stop_module() proceeds once module_put(owner) drops the refcount
to zero, and delete_module() then calls mod->exit() ->
unregister_key_type() before free_module() gets to its
synchronize_rcu(). rcu_read_lock() keeps struct key_type mapped, but
it does not stop rmmod from reaching the WARN_ON_ONCE() check before
the nr_keys decrement runs.

Swapping the two would close this window but open another:
key_gc_flush()'s unlocked fast path keys off nr_keys, so a decrement
landing before module_put() would let a concurrent flush return early
while the module refcount is still held, and an rmmod right after it
would get -EWOULDBLOCK. Waiting out the RCU read side only in the
slow case should be enough:

if (atomic_read_acquire(&ktype->nr_keys))
synchronize_rcu();

before taking key_types_sem and checking
WARN_ON_ONCE(atomic_read(&ktype->nr_keys)).

Thanks,
Guicai