[PATCH v7 03/14] KEYS: Add key_gc_flush() for draining RCU callbacks

Jarkko Sakkinen jarkko at kernel.org
Sun Nov 29 17:05:32 UTC 2026


keyring_clear() and key_unlink() release keyring links via call_rcu(),
and key_put() defers final key destruction to key_gc_work.

Once keys and keyring restrictions pin their key type, callers that
clear an internal cache before module unload need a synchronous barrier
so module references can be dropped before delete_module() checks the
refcount.

Track active and pending-GC reference counts on struct key_type and add
key_gc_flush(type) to drain pending RCU callbacks and synchronously reap
unreferenced keys referencing that type in a single bounded pass without
waiting on unrelated or newly created keys.

Signed-off-by: Jarkko Sakkinen <jarkko at kernel.org>
---
 include/linux/key-type.h |   2 +
 include/linux/key.h      |   6 ++
 security/keys/gc.c       | 165 +++++++++++++++++++++++++++++++++++----
 security/keys/key.c      |   8 ++
 security/keys/keyring.c  |  17 ++--
 5 files changed, 176 insertions(+), 22 deletions(-)

diff --git a/include/linux/key-type.h b/include/linux/key-type.h
index c4f329b6ae3f..668793bf613a 100644
--- a/include/linux/key-type.h
+++ b/include/linux/key-type.h
@@ -162,6 +162,8 @@ struct key_type {
 
 	/* internal fields */
 	atomic64_t		index_id;	/* Opaque keyring index ID */
+	atomic_t		nr_keys;	/* Number of allocated keys */
+	atomic_t		gc_pending;	/* Unreferenced keys pending GC */
 	struct list_head	link;		/* link in types list */
 	struct lock_class_key	lock_class;	/* key->sem lock class */
 } __randomize_layout;
diff --git a/include/linux/key.h b/include/linux/key.h
index 420412aab926..edd852608763 100644
--- a/include/linux/key.h
+++ b/include/linux/key.h
@@ -31,6 +31,7 @@ typedef int32_t key_serial_t;
 typedef uint32_t key_perm_t;
 
 struct key;
+struct key_type;
 struct net;
 
 #ifdef CONFIG_KEYS
@@ -439,6 +440,7 @@ extern int restrict_link_reject(struct key *keyring,
 				struct key *restriction_key);
 
 extern int keyring_clear(struct key *keyring);
+void key_gc_flush(struct key_type *type);
 
 extern key_ref_t keyring_search(key_ref_t keyring,
 				struct key_type *type,
@@ -527,6 +529,10 @@ extern void key_init(void);
 #define key_remove_domain(d)		do { } while(0)
 #define key_lookup(k)			NULL
 
+static inline void key_gc_flush(struct key_type *type)
+{
+}
+
 #endif /* CONFIG_KEYS */
 #endif /* __KERNEL__ */
 #endif /* _LINUX_KEY_H */
diff --git a/security/keys/gc.c b/security/keys/gc.c
index e38ee4839885..ca5c1a6bdd45 100644
--- a/security/keys/gc.c
+++ b/security/keys/gc.c
@@ -5,6 +5,7 @@
  * Written by David Howells (dhowells at redhat.com)
  */
 
+#include <linux/mutex.h>
 #include <linux/slab.h>
 #include <linux/security.h>
 #include <keys/keyring-type.h>
@@ -29,6 +30,10 @@ static struct {
 	.work = __WORK_INITIALIZER(key_gc_work.work, key_garbage_collector),
 };
 
+static LIST_HEAD(key_gc_graveyard);
+static DEFINE_MUTEX(key_gc_lock);
+static DEFINE_MUTEX(key_gc_flush_lock);
+
 /*
  * Delay between key revocation/expiry in seconds
  */
@@ -163,6 +168,9 @@ static noinline void key_gc_unused_keys(struct list_head *keys)
 	while (!list_empty(keys) && chunk--) {
 		struct key *key =
 			list_entry(keys->next, struct key, graveyard_link);
+		struct key_type *type = key->type;
+		struct key_type *restrict_type =
+			key->restrict_link ? key->restrict_link->keytype : NULL;
 		short state = key->state;
 
 		list_del(&key->graveyard_link);
@@ -176,8 +184,8 @@ static noinline void key_gc_unused_keys(struct list_head *keys)
 #endif
 
 		/* Throw away the key data if the key is instantiated */
-		if (state == KEY_IS_POSITIVE && key->type->destroy)
-			key->type->destroy(key);
+		if (state == KEY_IS_POSITIVE && type->destroy)
+			type->destroy(key);
 
 		security_key_free(key);
 
@@ -191,9 +199,107 @@ static noinline void key_gc_unused_keys(struct list_head *keys)
 
 		memzero_explicit(key, sizeof(*key));
 		kmem_cache_free(key_jar, key);
+		if (restrict_type) {
+			atomic_dec_return_release(&restrict_type->nr_keys);
+			atomic_dec_return_release(&restrict_type->gc_pending);
+		}
+		atomic_dec_return_release(&type->nr_keys);
+		atomic_dec_return_release(&type->gc_pending);
 	}
 }
 
+static unsigned int key_type_refs(const struct key *key,
+				  const struct key_type *type)
+{
+	return (key->type == type) +
+	       (key->restrict_link && key->restrict_link->keytype == type);
+}
+
+/**
+ * key_gc_flush - Drain unreferenced keys of a given key type
+ * @type: Key type whose unreferenced keys and keyring-unlink RCU callbacks to
+ *        drain.
+ *
+ * Context: Process context. May sleep.
+ */
+void key_gc_flush(struct key_type *type)
+{
+	struct key *key, *tmp;
+	struct rb_node *cursor;
+	int detached = 0;
+	LIST_HEAD(graveyard);
+
+	if (!atomic_read_acquire(&type->nr_keys))
+		return;
+
+	rcu_barrier();
+	if (!atomic_read_acquire(&type->gc_pending))
+		return;
+
+	mutex_lock(&key_gc_flush_lock);
+	if (!atomic_read_acquire(&type->gc_pending))
+		goto out_unlock;
+
+	mutex_lock(&key_gc_lock);
+
+	list_for_each_entry_safe(key, tmp, &key_gc_graveyard, graveyard_link) {
+		unsigned int refs = key_type_refs(key, type);
+
+		if (refs) {
+			list_move_tail(&key->graveyard_link, &graveyard);
+			detached += refs;
+		}
+	}
+
+	if (detached < atomic_read_acquire(&type->gc_pending)) {
+		spin_lock(&key_serial_lock);
+		cursor = rb_first(&key_serial_tree);
+		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)) {
+				if (key_gc_work.cursor == &key->serial_node)
+					key_gc_work.cursor = cursor;
+				rb_erase(&key->serial_node, &key_serial_tree);
+				list_add_tail(&key->graveyard_link, &graveyard);
+				detached += refs;
+				if (detached >=
+				    atomic_read_acquire(&type->gc_pending))
+					break;
+			}
+
+			if (cursor &&
+			    (spin_is_contended(&key_serial_lock) ||
+			     need_resched())) {
+				spin_unlock(&key_serial_lock);
+				cond_resched();
+				spin_lock(&key_serial_lock);
+			}
+		}
+		spin_unlock(&key_serial_lock);
+	}
+
+	mutex_unlock(&key_gc_lock);
+
+	if (!list_empty(&graveyard)) {
+		synchronize_rcu();
+		while (!list_empty(&graveyard)) {
+			key_gc_unused_keys(&graveyard);
+			cond_resched();
+		}
+	}
+
+out_unlock:
+	mutex_unlock(&key_gc_flush_lock);
+}
+EXPORT_SYMBOL_GPL(key_gc_flush);
+
 /*
  * Garbage collector for unused keys.
  *
@@ -203,11 +309,11 @@ static noinline void key_gc_unused_keys(struct list_head *keys)
  */
 static void key_garbage_collector(struct work_struct *work)
 {
-	static LIST_HEAD(graveyard);
 	typeof(key_gc_work) *gc = &key_gc_work;
 #define KEY_GC_REAP_AGAIN	0x01	/* - Need another cycle */
 #define KEY_GC_REAPING_LINKS	0x02	/* - We need to reap links */
 #define KEY_GC_DESTROYING	0x04	/* - We need to destroy keys */
+#define KEY_GC_SCANNING		0x08	/* - Scan in progress */
 #define KEY_GC_REAPING_DEAD_1	0x10	/* - We need to mark dead keys */
 #define KEY_GC_REAPING_DEAD_2	0x20	/* - We need to reap dead key links */
 #define KEY_GC_REAPING_DEAD_3	0x40	/* - We need to reap dead keys */
@@ -220,9 +326,11 @@ static void key_garbage_collector(struct work_struct *work)
 
 	kenter("[%lx,%x]", key_gc_flags, gc->state);
 
+	mutex_lock(&key_gc_lock);
+
 	if (gc->state & KEY_GC_DESTROYING)
 		goto destroy_keys;
-	if (gc->cursor) {
+	if (gc->state & KEY_GC_SCANNING) {
 		spin_lock(&key_serial_lock);
 		goto continue_scanning;
 	}
@@ -244,17 +352,20 @@ static void key_garbage_collector(struct work_struct *work)
 
 	gc->end = TIME64_MAX;
 
-	/* As only this function is permitted to remove things from the key
-	 * serial tree, if cursor is non-NULL then it will always point to a
-	 * valid node in the tree - even if lock got dropped.
+	/* Only holders of key_gc_lock remove entries from key_serial_tree,
+	 * so a non-NULL cursor remains valid when key_serial_lock is dropped.
 	 */
 	spin_lock(&key_serial_lock);
 	gc->cursor = rb_first(&key_serial_tree);
+	if (gc->cursor)
+		gc->state |= KEY_GC_SCANNING;
 
 continue_scanning:
 	while (gc->cursor && chunk) {
 		key = rb_entry(gc->cursor, struct key, serial_node);
 		gc->cursor = rb_next(gc->cursor);
+		if (!gc->cursor)
+			gc->state &= ~KEY_GC_SCANNING;
 		chunk--;
 
 		if (!test_bit_acquire(KEY_FLAG_USER_ALIVE, &key->flags)) {
@@ -270,7 +381,9 @@ static void key_garbage_collector(struct work_struct *work)
 				goto skip_dead_key;
 			} else if (key->type == &key_type_keyring &&
 				   key->restrict_link) {
-				goto found_restricted_keyring;
+				if (refcount_inc_not_zero(&key->usage))
+					goto found_restricted_keyring;
+				goto wait_unreferenced_key;
 			}
 		}
 
@@ -295,9 +408,13 @@ static void key_garbage_collector(struct work_struct *work)
 				goto found_keyring;
 		}
 
-		if (unlikely(gc->state & KEY_GC_REAPING_DEAD_3))
-			if (key->type == key_gc_dead_keytype)
-				goto destroy_dead_key;
+		if (unlikely(gc->state & KEY_GC_REAPING_DEAD_3)) {
+			if (key->type == key_gc_dead_keytype) {
+				if (refcount_inc_not_zero(&key->usage))
+					goto destroy_dead_key;
+				goto wait_unreferenced_key;
+			}
+		}
 
 	skip_dead_key:
 		if (spin_is_contended(&key_serial_lock) || need_resched())
@@ -305,10 +422,12 @@ static void key_garbage_collector(struct work_struct *work)
 	}
 
 contended:
+	if (!gc->cursor)
+		gc->state &= ~KEY_GC_SCANNING;
 	spin_unlock(&key_serial_lock);
 
 maybe_resched:
-	if (gc->cursor) {
+	if (gc->state & KEY_GC_SCANNING) {
 		if (!chunk) {
 			queue_work(key_gc_wq, &key_gc_work.work);
 			goto out;
@@ -339,7 +458,7 @@ static void key_garbage_collector(struct work_struct *work)
 	}
 
 	if (unlikely(gc->state & KEY_GC_REAPING_DEAD_2) ||
-	    !list_empty(&graveyard)) {
+	    !list_empty(&key_gc_graveyard)) {
 		/* Make sure that all pending keyring payload destructions are
 		 * fulfilled and that people aren't now looking at dead or
 		 * dying keys that they don't have a reference upon or a link
@@ -352,10 +471,10 @@ static void key_garbage_collector(struct work_struct *work)
 	gc->state |= KEY_GC_DESTROYING;
 
 destroy_keys:
-	if (!list_empty(&graveyard)) {
+	if (!list_empty(&key_gc_graveyard)) {
 		kdebug("gc keys");
-		key_gc_unused_keys(&graveyard);
-		if (!list_empty(&graveyard)) {
+		key_gc_unused_keys(&key_gc_graveyard);
+		if (!list_empty(&key_gc_graveyard)) {
 			queue_work(key_gc_wq, &key_gc_work.work);
 			goto out;
 		}
@@ -385,9 +504,17 @@ static void key_garbage_collector(struct work_struct *work)
 	    test_bit(KEY_GC_REAP_REQUESTED, &key_gc_flags))
 		queue_work(key_gc_wq, &key_gc_work.work);
 out:
+	mutex_unlock(&key_gc_lock);
 	kleave(" [end %x]", gc->state);
 	return;
 
+	/* Wait for an in-flight final key_put() to finish clearing USER_ALIVE. */
+wait_unreferenced_key:
+	spin_unlock(&key_serial_lock);
+	while (test_bit_acquire(KEY_FLAG_USER_ALIVE, &key->flags))
+		cpu_relax();
+	spin_lock(&key_serial_lock);
+
 	/* We found an unreferenced key - once we've removed it from the tree,
 	 * we can safely drop the lock.
 	 */
@@ -396,7 +523,7 @@ static void key_garbage_collector(struct work_struct *work)
 	rb_erase(&key->serial_node, &key_serial_tree);
 	spin_unlock(&key_serial_lock);
 
-	list_add_tail(&key->graveyard_link, &graveyard);
+	list_add_tail(&key->graveyard_link, &key_gc_graveyard);
 	gc->state |= KEY_GC_REAP_AGAIN;
 	goto maybe_resched;
 
@@ -406,6 +533,7 @@ static void key_garbage_collector(struct work_struct *work)
 found_restricted_keyring:
 	spin_unlock(&key_serial_lock);
 	keyring_restriction_gc(key, key_gc_dead_keytype);
+	key_put(key);
 	goto maybe_resched;
 
 	/* We found a keyring and we need to check the payload for links to
@@ -425,10 +553,13 @@ static void key_garbage_collector(struct work_struct *work)
 	spin_unlock(&key_serial_lock);
 	kdebug("destroy key %d", key->serial);
 	down_write(&key->sem);
+	atomic_inc(&key_type_dead.nr_keys);
+	atomic_dec_return_release(&key_gc_dead_keytype->nr_keys);
 	key->type = &key_type_dead;
 	if (key_gc_dead_keytype->destroy)
 		key_gc_dead_keytype->destroy(key);
 	memset(&key->payload, KEY_DESTROY, sizeof(key->payload));
 	up_write(&key->sem);
+	key_put(key);
 	goto maybe_resched;
 }
diff --git a/security/keys/key.c b/security/keys/key.c
index ec789a264412..fecf8c3a991c 100644
--- a/security/keys/key.c
+++ b/security/keys/key.c
@@ -235,6 +235,8 @@ struct key *key_alloc(struct key_type *type, const char *desc,
 	key = ERR_PTR(-EINVAL);
 	if (!desc || !*desc)
 		goto error;
+	if (restrict_link && type != &key_type_keyring)
+		goto error;
 
 	if (type->vet_description) {
 		ret = type->vet_description(desc);
@@ -322,6 +324,9 @@ struct key *key_alloc(struct key_type *type, const char *desc,
 	/* publish the key by giving it a serial number */
 	refcount_inc(&key->domain_tag->usage);
 	atomic_inc(&user->nkeys);
+	atomic_inc(&type->nr_keys);
+	if (restrict_link && restrict_link->keytype)
+		atomic_inc(&restrict_link->keytype->nr_keys);
 	key_alloc_serial(key);
 
 error:
@@ -741,6 +746,9 @@ void key_put(struct key *key)
 				spin_unlock_irqrestore(&key->user->lock, flags);
 			}
 			/* Mark key as safe for GC after key->user done. */
+			if (key->restrict_link && key->restrict_link->keytype)
+				atomic_inc(&key->restrict_link->keytype->gc_pending);
+			atomic_inc(&key->type->gc_pending);
 			clear_bit_unlock(KEY_FLAG_USER_ALIVE, &key->flags);
 			key_schedule_gc_work(false);
 		}
diff --git a/security/keys/keyring.c b/security/keys/keyring.c
index 5aa8d706c238..4f906073d312 100644
--- a/security/keys/keyring.c
+++ b/security/keys/keyring.c
@@ -540,6 +540,9 @@ struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,
 	if (!IS_ERR(keyring)) {
 		ret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL);
 		if (ret < 0) {
+			if (restrict_link && restrict_link->keytype)
+				atomic_dec_return_release(&restrict_link->keytype->nr_keys);
+			keyring->restrict_link = NULL;
 			key_put(keyring);
 			keyring = ERR_PTR(ret);
 		}
@@ -1081,6 +1084,8 @@ int keyring_restrict(key_ref_t keyring_ref, const char *type,
 	} else if (keyring_detect_restriction_cycle(keyring, restrict_link)) {
 		ret = -EDEADLK;
 	} else {
+		if (restrict_link->keytype)
+			atomic_inc(&restrict_link->keytype->nr_keys);
 		keyring->restrict_link = restrict_link;
 		notify_key(keyring, NOTIFY_KEY_SETATTR, 0);
 	}
@@ -1808,12 +1813,14 @@ void keyring_restriction_gc(struct key *keyring, struct key_type *dead_type)
 	down_write(&keyring->sem);
 
 	keyres = keyring->restrict_link;
+	if (keyres->keytype == dead_type) {
+		keyres->check = restrict_link_reject;
 
-	keyres->check = restrict_link_reject;
-
-	key_put(keyres->key);
-	keyres->key = NULL;
-	keyres->keytype = NULL;
+		key_put(keyres->key);
+		keyres->key = NULL;
+		atomic_dec_return_release(&dead_type->nr_keys);
+		keyres->keytype = NULL;
+	}
 
 	up_write(&keyring->sem);
 
-- 
2.47.3




More information about the Linux-security-module-archive mailing list