Re: [PATCH v7 03/14] KEYS: Add key_gc_flush() for draining RCU callbacks
From: Guicai Ma
Date: Mon Nov 30 2026 - 03:43:05 EST
On Sun, Nov 29, 2026 at 07:05:32PM +0200, Jarkko Sakkinen wrote:
> + while (cursor) {
> + unsigned int refs;
> +
> + key = rb_entry(cursor, struct key, serial_node);
> + cursor = rb_next(cursor);
> + refs = key_type_refs(key, type);
> +
> + if (refs &&
> + !test_bit_acquire(KEY_FLAG_USER_ALIVE,
> + &key->flags)) {
Is calling key_type_refs() before checking KEY_FLAG_USER_ALIVE
intentional here?
key_gc_flush() only holds key_gc_lock and key_serial_lock during the
tree walk, so calling key_type_refs() first reads key->restrict_link
and key->restrict_link->keytype on live keyrings without keyring->sem.
That races with keyring_restrict(), which assigns keyring->restrict_link
plainly under keyring->sem. It also races with keyring_alloc()'s error
path: key_alloc() has already published the keyring into
key_serial_tree with restrict_link set, and on failure keyring_alloc()
clears keyring->restrict_link to NULL without key_serial_lock before
calling key_put(), leaving the caller to free restrict_link. A
concurrent key_gc_flush() that already saw the old pointer can then
dereference a freed or nulled restrict_link->keytype.
Checking KEY_FLAG_USER_ALIVE first skips live keys altogether:
if (!test_bit_acquire(KEY_FLAG_USER_ALIVE, &key->flags)) {
unsigned int refs = key_type_refs(key, type);
if (refs) {
...
Once the acquire check sees KEY_FLAG_USER_ALIVE clear, restrict_link
cannot change anymore: keyring_alloc()'s error path NULLs it before
key_put() runs clear_bit_unlock(), and keyring_restrict() always holds
a reference on the keyring while modifying it.
Thanks,
Guicai