AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/11/16 00:55 flow patch-triage
4m Args:
null

Results:
{
  "EnableConfigs": [
    "KEYS",
    "RXRPC_KEYS",
    "AF_RXRPC",
    "RXKAD",
    "RXGK",
    "DNS_KEY",
    "DNS_RESOLVER",
    "CIFS",
    "CIFS_UPCALL",
    "NFS_FS",
    "NFS_V4"
  ],
  "FocusSymbols": [
    "key_garbage_collector",
    "key_gc_unused_keys",
    "key_schedule_gc_work",
    "key_gc_flush",
    "key_alloc",
    "keyring_restrict",
    "__register_key_type",
    "unregister_key_type",
    "rxrpc_preparse_s",
    "rxrpc_request_key",
    "rxrpc_server_keyring"
  ],
  "KMSANReasoning": "The patch series refactors the kernel keys subsystem to manage key type module ownership (adding `struct module *owner` to `struct key_type`), introduces module refcounting on key allocation and restriction, and redesigns the key garbage collector (`security/keys/gc.c`) by removing the old dead-keytype sweep in favor of module pinning and iterative workqueue-based garbage collection with `key_gc_flush()`. It also splits key type registrations into dedicated modules for DNS resolver and RxRPC, adds serialization and keyring clearing on session termination in NFS and CIFS/SMB, and adds mutex protection for trusted TEE keys.\n\nPrimary risks associated with these changes are reference counting errors (leaks or premature puts), module unload use-after-free, synchronization issues, and potential lock ordering deadlocks. These failure modes are reliably caught by KASAN, refcount checks, and LOCKDEP in standard debugging builds.\n\nThe changes do not introduce or modify any kernel structures copied to user space, do not alter buffer length or bounds calculations, do not create paths reading uninitialized heap/stack memory, and all introduced variables and struct instances are fully initialized prior to access. Consequently, KMSAN is not needed.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch series introduces significant architectural refactorings to the kernel keys subsystem, specifically key garbage collection and key type lifetime management. It eliminates the 3-pass dead-keytype GC cycle in favor of module refcounting (try_module_get/module_put) on key allocation and destruction, reworks the key garbage collector to scan the serial rb_tree in chunks with an explicit cursor, and introduces key_gc_flush() to synchronize deferred key and credential destruction. In addition, RxRPC and DNS resolver key types are split into separate modules, with RxRPC server key preparsing restructured and key flushing integrated into NFSv4 idmap and CIFS session teardowns. These paths are in core subsystems and directly reachable via keyctl(), add_key(), request_key(), and RxRPC socket options, warranting fuzzing.",
  "WorthFuzzing": true
}

1/1 2026/11/16 00:55 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit bfe32f9841a590f04284c65f8e4157bba77792b8\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Mon Nov 16 00:55:37 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/networking/rxrpc.rst b/Documentation/networking/rxrpc.rst\nindex eca055a536aa1b..394190c40d6ee9 100644\n--- a/Documentation/networking/rxrpc.rst\n+++ b/Documentation/networking/rxrpc.rst\n@@ -1165,5 +1165,5 @@ API Function Reference\n .. kernel-doc:: net/rxrpc/recvmsg.c\n .. kernel-doc:: net/rxrpc/rxgk.c\n .. kernel-doc:: net/rxrpc/rxkad.c\n+.. kernel-doc:: net/rxrpc/security.c\n .. kernel-doc:: net/rxrpc/sendmsg.c\n-.. kernel-doc:: net/rxrpc/server_key.c\ndiff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c\nindex 998f2da5617500..ab1a78cdfd4ceb 100644\n--- a/arch/s390/kernel/cert_store.c\n+++ b/arch/s390/kernel/cert_store.c\n@@ -17,6 +17,7 @@\n #include \u003clinux/key.h\u003e\n #include \u003clinux/keyctl.h\u003e\n #include \u003clinux/kobject.h\u003e\n+#include \u003clinux/list.h\u003e\n #include \u003clinux/module.h\u003e\n #include \u003clinux/seq_file.h\u003e\n #include \u003clinux/slab.h\u003e\n@@ -296,6 +297,18 @@ static int check_certificate_valid(const struct vce *vce)\n \treturn check_certificate_hash(vce);\n }\n \n+struct cert_store_key {\n+\tstruct list_head list;\n+\tstruct key *key;\n+};\n+\n+static DEFINE_MUTEX(cs_refresh_lock);\n+/* Owned references, protected by cs_refresh_lock. */\n+static LIST_HEAD(cs_keys);\n+static struct key *active_cs_keyring;\n+static struct key *cs_keyring_parent;\n+\n+/* Return an owned reference to the user session keyring. */\n static struct key *get_user_session_keyring(void)\n {\n \tkey_ref_t us_keyring_ref;\n@@ -305,118 +318,66 @@ static struct key *get_user_session_keyring(void)\n \tif (IS_ERR(us_keyring_ref)) {\n \t\tpr_dbf_msg(\"Couldn't get user session keyring: %ld\",\n \t\t\t   PTR_ERR(us_keyring_ref));\n-\t\treturn ERR_PTR(-ENOKEY);\n+\t\treturn ERR_CAST(us_keyring_ref);\n \t}\n-\tkey_ref_put(us_keyring_ref);\n \treturn key_ref_to_ptr(us_keyring_ref);\n }\n \n-/* Invalidate all keys from cert_store keyring. */\n-static int invalidate_keyring_keys(struct key *keyring)\n-{\n-\tunsigned long num_keys, key_index;\n-\tsize_t keyring_payload_len;\n-\tkey_serial_t *key_array;\n-\tstruct key *current_key;\n-\tint rc;\n-\n-\tkeyring_payload_len = key_type_keyring.read(keyring, NULL, 0);\n-\tnum_keys = keyring_payload_len / sizeof(key_serial_t);\n-\tkey_array = kzalloc_objs(key_serial_t, num_keys);\n-\tif (!key_array)\n-\t\treturn -ENOMEM;\n-\n-\trc = key_type_keyring.read(keyring, (char *)key_array, keyring_payload_len);\n-\tif (rc != keyring_payload_len) {\n-\t\tpr_dbf_msg(\"Couldn't read keyring payload\");\n-\t\tgoto out;\n-\t}\n-\n-\tfor (key_index = 0; key_index \u003c num_keys; key_index++) {\n-\t\tcurrent_key = key_lookup(key_array[key_index]);\n-\t\tpr_dbf_msg(\"Invalidating key %08x\", current_key-\u003eserial);\n-\n-\t\tkey_invalidate(current_key);\n-\t\tkey_put(current_key);\n-\t\trc = key_unlink(keyring, current_key);\n-\t\tif (rc) {\n-\t\t\tpr_dbf_msg(\"Couldn't unlink key %08x: %d\", current_key-\u003eserial, rc);\n-\t\t\tbreak;\n-\t\t}\n-\t}\n-out:\n-\tkfree(key_array);\n-\treturn rc;\n-}\n-\n-static struct key *find_cs_keyring(void)\n-{\n-\tkey_ref_t cs_keyring_ref;\n-\tstruct key *cs_keyring;\n-\n-\tcs_keyring_ref = keyring_search(make_key_ref(get_user_session_keyring(), true),\n-\t\t\t\t\t\u0026key_type_keyring, CERT_STORE_KEYRING_NAME,\n-\t\t\t\t\tfalse);\n-\tif (!IS_ERR(cs_keyring_ref)) {\n-\t\tcs_keyring = key_ref_to_ptr(cs_keyring_ref);\n-\t\tkey_ref_put(cs_keyring_ref);\n-\t\tgoto found;\n-\t}\n-\t/* Search default locations: thread, process, session keyrings */\n-\tcs_keyring = request_key(\u0026key_type_keyring, CERT_STORE_KEYRING_NAME, NULL);\n-\tif (IS_ERR(cs_keyring))\n-\t\treturn NULL;\n-\tkey_put(cs_keyring);\n-found:\n-\treturn cs_keyring;\n-}\n-\n static void cleanup_cs_keys(void)\n {\n-\tstruct key *cs_keyring;\n+\tstruct cert_store_key *entry, *tmp;\n+\tint rc;\n \n-\tcs_keyring = find_cs_keyring();\n-\tif (!cs_keyring)\n+\tif (!active_cs_keyring)\n \t\treturn;\n \n-\tpr_dbf_msg(\"Found cert_store keyring. Purging...\");\n-\t/*\n-\t * Remove cert_store_key_type in case invalidation\n-\t * of old cert_store keys failed (= severe error).\n-\t */\n-\tif (invalidate_keyring_keys(cs_keyring))\n-\t\tunregister_key_type(\u0026key_type_cert_store_key);\n+\t/* Invalidate even certificates unlinked or linked into other keyrings. */\n+\tlist_for_each_entry_safe(entry, tmp, \u0026cs_keys, list) {\n+\t\tkey_invalidate(entry-\u003ekey);\n+\t\tkey_put(entry-\u003ekey);\n+\t\tlist_del(\u0026entry-\u003elist);\n+\t\tkfree(entry);\n+\t}\n \n-\tkeyring_clear(cs_keyring);\n-\tkey_invalidate(cs_keyring);\n-\tkey_put(cs_keyring);\n-\tkey_unlink(get_user_session_keyring(), cs_keyring);\n+\trc = keyring_clear(active_cs_keyring);\n+\tif (rc)\n+\t\tpr_dbf_msg(\"Couldn't clear cert_store keyring: %d\", rc);\n+\tkey_invalidate(active_cs_keyring);\n+\trc = key_unlink(cs_keyring_parent, active_cs_keyring);\n+\tif (rc)\n+\t\tpr_dbf_msg(\"Couldn't unlink cert_store keyring: %d\", rc);\n+\tkey_put(active_cs_keyring);\n+\tkey_put(cs_keyring_parent);\n+\tactive_cs_keyring = NULL;\n+\tcs_keyring_parent = NULL;\n }\n \n+/* Return a borrowed reference; cleanup_cs_keys() owns the keyring. */\n static struct key *create_cs_keyring(void)\n {\n-\tstatic struct key *cs_keyring;\n+\tstruct key *cs_keyring, *parent;\n \n \t/* Cleanup previous cs_keyring and all associated keys if any. */\n \tcleanup_cs_keys();\n+\tparent = get_user_session_keyring();\n+\tif (IS_ERR(parent))\n+\t\treturn parent;\n+\n \tcs_keyring = keyring_alloc(CERT_STORE_KEYRING_NAME, GLOBAL_ROOT_UID,\n \t\t\t\t   GLOBAL_ROOT_GID, current_cred(),\n \t\t\t\t   (KEY_POS_ALL \u0026 ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ,\n \t\t\t\t   KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_SET_KEEP,\n-\t\t\t\t   NULL, get_user_session_keyring());\n+\t\t\t\t   NULL, parent);\n \tif (IS_ERR(cs_keyring)) {\n \t\tpr_dbf_msg(\"Can't allocate cert_store keyring\");\n-\t\treturn NULL;\n+\t\tkey_put(parent);\n+\t\treturn cs_keyring;\n \t}\n \n+\tactive_cs_keyring = cs_keyring;\n+\tcs_keyring_parent = parent;\n \tpr_dbf_msg(\"Successfully allocated cert_store keyring: %08x\", cs_keyring-\u003eserial);\n \n-\t/*\n-\t * In case a previous clean-up ran into an\n-\t * error and unregistered key type.\n-\t */\n-\tregister_key_type(\u0026key_type_cert_store_key);\n-\n \treturn cs_keyring;\n }\n \n@@ -454,6 +415,7 @@ static char *get_key_description(struct vcssb *vcssb, const struct vce *vce)\n static int create_key_from_vce(struct vcssb *vcssb, struct vce *vce,\n \t\t\t       struct key *keyring)\n {\n+\tstruct cert_store_key *entry;\n \tkey_ref_t newkey;\n \tchar *desc;\n \tint rc;\n@@ -462,6 +424,13 @@ static int create_key_from_vce(struct vcssb *vcssb, struct vce *vce,\n \tif (!desc)\n \t\treturn -ENOMEM;\n \n+\t/* Reserve cleanup tracking before the key can be linked elsewhere. */\n+\tentry = kmalloc_obj(*entry);\n+\tif (!entry) {\n+\t\trc = -ENOMEM;\n+\t\tgoto out;\n+\t}\n+\n \tnewkey = key_create_or_update(\n \t\tmake_key_ref(keyring, true), CERT_STORE_KEY_TYPE_NAME,\n \t\tdesc, (u8 *)vce + vce-\u003evce_hdr.vc_offset,\n@@ -473,10 +442,12 @@ static int create_key_from_vce(struct vcssb *vcssb, struct vce *vce,\n \tif (rc) {\n \t\tpr_dbf_msg(\"Couldn't create a key from Certificate Entry (%d)\", rc);\n \t\trc = -ENOKEY;\n+\t\tkfree(entry);\n \t\tgoto out;\n \t}\n \n-\tkey_ref_put(newkey);\n+\tentry-\u003ekey = key_ref_to_ptr(newkey);\n+\tlist_add_tail(\u0026entry-\u003elist, \u0026cs_keys);\n out:\n \tkfree(desc);\n \treturn rc;\n@@ -704,19 +675,18 @@ static int fill_cs_keyring(void)\n \tif (rc)\n \t\tgoto cleanup_keys;\n \n-\trc = -ENOMEM;\n \tcs_keyring = create_cs_keyring();\n-\tif (!cs_keyring)\n+\tif (IS_ERR(cs_keyring)) {\n+\t\trc = PTR_ERR(cs_keyring);\n \t\tgoto cleanup_keys;\n+\t}\n \n \trc = add_certificates_to_keyring(vcssb, cs_keyring);\n \tif (rc)\n-\t\tgoto cleanup_cs_keyring;\n+\t\tgoto cleanup_keys;\n \n \tgoto out;\n \n-cleanup_cs_keyring:\n-\tkey_put(cs_keyring);\n cleanup_keys:\n \tcleanup_cs_keys();\n out:\n@@ -724,7 +694,6 @@ static int fill_cs_keyring(void)\n \treturn rc;\n }\n \n-static DEFINE_MUTEX(cs_refresh_lock);\n static int cs_status_val = -1;\n \n static ssize_t cs_status_show(struct kobject *kobj,\n@@ -794,14 +763,18 @@ static int __init cert_store_init(void)\n \tif (!cert_store_kobj)\n \t\tgoto cleanup_dbf;\n \n-\trc = sysfs_create_files(cert_store_kobj, cert_store_attrs);\n+\trc = register_key_type(\u0026key_type_cert_store_key);\n \tif (rc)\n \t\tgoto cleanup_kobj;\n \n-\tregister_key_type(\u0026key_type_cert_store_key);\n+\trc = sysfs_create_files(cert_store_kobj, cert_store_attrs);\n+\tif (rc)\n+\t\tgoto cleanup_key_type;\n \n \treturn rc;\n \n+cleanup_key_type:\n+\tunregister_key_type(\u0026key_type_cert_store_key);\n cleanup_kobj:\n \tkobject_put(cert_store_kobj);\n cleanup_dbf:\ndiff --git a/fs/nfs/nfs4idmap.c b/fs/nfs/nfs4idmap.c\nindex bc397110d977f5..c88444cc6bf682 100644\n--- a/fs/nfs/nfs4idmap.c\n+++ b/fs/nfs/nfs4idmap.c\n@@ -47,6 +47,8 @@\n #include \u003ckeys/request_key_auth-type.h\u003e\n #include \u003clinux/module.h\u003e\n #include \u003clinux/user_namespace.h\u003e\n+#include \u003clinux/mutex.h\u003e\n+#include \u003clinux/ratelimit.h\u003e\n \n #include \"internal.h\"\n #include \"netns.h\"\n@@ -58,6 +60,10 @@\n static const struct cred *id_resolver_cache;\n static struct key_type key_type_id_resolver_legacy;\n \n+/* Serializes the idmap cache. */\n+static DEFINE_MUTEX(nfs_idmap_cache_mutex);\n+static unsigned int nfs_idmap_users;\n+\n struct idmap_legacy_upcalldata {\n \tstruct rpc_pipe_msg pipe_msg;\n \tstruct idmap_msg idmap_msg;\n@@ -469,7 +475,10 @@ nfs_idmap_new(struct nfs_client *clp)\n \tif (error)\n \t\tgoto err_destroy_pipe;\n \n+\tmutex_lock(\u0026nfs_idmap_cache_mutex);\n+\tnfs_idmap_users++;\n \tclp-\u003ecl_idmap = idmap;\n+\tmutex_unlock(\u0026nfs_idmap_cache_mutex);\n \treturn 0;\n err_destroy_pipe:\n \trpc_destroy_pipe_data(idmap-\u003eidmap_pipe);\n@@ -483,6 +492,7 @@ void\n nfs_idmap_delete(struct nfs_client *clp)\n {\n \tstruct idmap *idmap = clp-\u003ecl_idmap;\n+\tint ret;\n \n \tif (!idmap)\n \t\treturn;\n@@ -493,6 +503,17 @@ nfs_idmap_delete(struct nfs_client *clp)\n \trpc_destroy_pipe_data(idmap-\u003eidmap_pipe);\n \tput_user_ns(idmap-\u003euser_ns);\n \tkfree(idmap);\n+\n+\tmutex_lock(\u0026nfs_idmap_cache_mutex);\n+\tif (--nfs_idmap_users == 0) {\n+\t\tret = keyring_clear(id_resolver_cache-\u003ethread_keyring);\n+\t\tif (ret)\n+\t\t\tpr_warn_ratelimited(\"NFS: Failed to clear idmap cache: %d; cache pins remain\\n\",\n+\t\t\t\t\t    ret);\n+\t\telse\n+\t\t\tkey_gc_flush();\n+\t}\n+\tmutex_unlock(\u0026nfs_idmap_cache_mutex);\n }\n \n static int nfs_idmap_prepare_message(char *desc, struct idmap *idmap,\ndiff --git a/fs/smb/client/cifs_spnego.c b/fs/smb/client/cifs_spnego.c\nindex 44c40727568042..e974f396e07f62 100644\n--- a/fs/smb/client/cifs_spnego.c\n+++ b/fs/smb/client/cifs_spnego.c\n@@ -15,6 +15,7 @@\n #include \u003clinux/key-type.h\u003e\n #include \u003clinux/keyctl.h\u003e\n #include \u003clinux/inet.h\u003e\n+#include \u003clinux/ratelimit.h\u003e\n #include \"cifsglob.h\"\n #include \"cifs_spnego.h\"\n #include \"cifs_debug.h\"\n@@ -190,6 +191,17 @@ cifs_get_spnego_key(struct cifs_ses *sesInfo,\n \treturn spnego_key;\n }\n \n+void\n+cifs_spnego_clear_cache(void)\n+{\n+\tint ret;\n+\n+\tret = keyring_clear(spnego_cred-\u003ethread_keyring);\n+\tif (ret)\n+\t\tpr_warn_ratelimited(\"Failed to clear SPNEGO cache: %d; cache pins remain\\n\",\n+\t\t\t\t    ret);\n+}\n+\n int\n init_cifs_spnego(void)\n {\ndiff --git a/fs/smb/client/cifsacl.c b/fs/smb/client/cifsacl.c\nindex 346899da91eb21..60c60c23dd34e2 100644\n--- a/fs/smb/client/cifsacl.c\n+++ b/fs/smb/client/cifsacl.c\n@@ -13,6 +13,7 @@\n #include \u003clinux/string.h\u003e\n #include \u003clinux/keyctl.h\u003e\n #include \u003clinux/key-type.h\u003e\n+#include \u003clinux/ratelimit.h\u003e\n #include \u003cuapi/linux/posix_acl.h\u003e\n #include \u003clinux/posix_acl.h\u003e\n #include \u003clinux/posix_acl_xattr.h\u003e\n@@ -539,6 +540,17 @@ sid_to_id(struct cifs_sb_info *cifs_sb, struct smb_sid *psid,\n \treturn 0;\n }\n \n+void\n+cifs_idmap_clear_cache(void)\n+{\n+\tint ret;\n+\n+\tret = keyring_clear(root_cred-\u003ethread_keyring);\n+\tif (ret)\n+\t\tpr_warn_ratelimited(\"Failed to clear idmap cache: %d; cache pins remain\\n\",\n+\t\t\t\t    ret);\n+}\n+\n int\n init_cifs_idmap(void)\n {\ndiff --git a/fs/smb/client/cifsproto.h b/fs/smb/client/cifsproto.h\nindex f9ea35597bc27f..2930a40d1b673a 100644\n--- a/fs/smb/client/cifsproto.h\n+++ b/fs/smb/client/cifsproto.h\n@@ -58,8 +58,16 @@ do {\t\t\t\t\t\t\t\t\t\\\n } while (0)\n int init_cifs_idmap(void);\n void exit_cifs_idmap(void);\n+void cifs_idmap_clear_cache(void);\n int init_cifs_spnego(void);\n void exit_cifs_spnego(void);\n+#ifdef CONFIG_CIFS_UPCALL\n+void cifs_spnego_clear_cache(void);\n+#else\n+static inline void cifs_spnego_clear_cache(void)\n+{\n+}\n+#endif\n const char *build_path_from_dentry(struct dentry *direntry, void *page);\n char *__build_path_from_dentry_optional_prefix(struct dentry *direntry,\n \t\t\t\t\t       void *page, const char *tree,\ndiff --git a/fs/smb/client/misc.c b/fs/smb/client/misc.c\nindex ec28f102ea08a1..11c0330be489bd 100644\n--- a/fs/smb/client/misc.c\n+++ b/fs/smb/client/misc.c\n@@ -9,6 +9,8 @@\n #include \u003clinux/slab.h\u003e\n #include \u003clinux/ctype.h\u003e\n #include \u003clinux/mempool.h\u003e\n+#include \u003clinux/key.h\u003e\n+#include \u003clinux/mutex.h\u003e\n #include \u003clinux/vmalloc.h\u003e\n #include \"cifsglob.h\"\n #include \"cifsproto.h\"\n@@ -33,6 +35,9 @@ struct tcon_list {\n \tstruct cifs_tcon *tcon;\n };\n \n+/* Serialize session admission with the last session's cache clear. */\n+static DEFINE_MUTEX(cifs_session_mutex);\n+\n /* The xid serves as a useful identifier for each incoming vfs request,\n    in a similar way to the mid which is useful to track each sent smb,\n    and CurrentXid can also provide a running counter (although it\n@@ -74,7 +79,6 @@ sesInfoAlloc(void)\n \n \tret_buf = kzalloc_obj(struct cifs_ses);\n \tif (ret_buf) {\n-\t\tatomic_inc(\u0026sesInfoAllocCount);\n \t\tspin_lock_init(\u0026ret_buf-\u003eses_lock);\n \t\tret_buf-\u003eses_status = SES_NEW;\n \t\t++ret_buf-\u003eses_count;\n@@ -84,6 +88,10 @@ sesInfoAlloc(void)\n \t\tspin_lock_init(\u0026ret_buf-\u003eiface_lock);\n \t\tINIT_LIST_HEAD(\u0026ret_buf-\u003eiface_list);\n \t\tspin_lock_init(\u0026ret_buf-\u003echan_lock);\n+\n+\t\tmutex_lock(\u0026cifs_session_mutex);\n+\t\tatomic_inc(\u0026sesInfoAllocCount);\n+\t\tmutex_unlock(\u0026cifs_session_mutex);\n \t}\n \treturn ret_buf;\n }\n@@ -99,7 +107,6 @@ sesInfoFree(struct cifs_ses *buf_to_free)\n \t}\n \n \tunload_nls(buf_to_free-\u003elocal_nls);\n-\tatomic_dec(\u0026sesInfoAllocCount);\n \tkfree(buf_to_free-\u003eserverOS);\n \tkfree(buf_to_free-\u003eserverDomain);\n \tkfree(buf_to_free-\u003eserverNOS);\n@@ -115,6 +122,14 @@ sesInfoFree(struct cifs_ses *buf_to_free)\n \t\tkref_put(\u0026iface-\u003erefcount, release_iface);\n \tspin_unlock(\u0026buf_to_free-\u003eiface_lock);\n \tkfree_sensitive(buf_to_free);\n+\n+\tmutex_lock(\u0026cifs_session_mutex);\n+\tif (atomic_dec_and_test(\u0026sesInfoAllocCount)) {\n+\t\tcifs_idmap_clear_cache();\n+\t\tcifs_spnego_clear_cache();\n+\t\tkey_gc_flush();\n+\t}\n+\tmutex_unlock(\u0026cifs_session_mutex);\n }\n \n struct cifs_tcon *\ndiff --git a/include/linux/key-type.h b/include/linux/key-type.h\nindex c4f329b6ae3fed..9ecec31ad57162 100644\n--- a/include/linux/key-type.h\n+++ b/include/linux/key-type.h\n@@ -10,9 +10,11 @@\n \n #include \u003clinux/key.h\u003e\n #include \u003clinux/errno.h\u003e\n+#include \u003clinux/init.h\u003e\n \n #ifdef CONFIG_KEYS\n \n+struct module;\n struct kernel_pkey_query;\n struct kernel_pkey_params;\n \n@@ -161,6 +163,7 @@ struct key_type {\n \t\t\t\t     const void *in, const void *in2);\n \n \t/* internal fields */\n+\tstruct module\t\t*owner;\n \tatomic64_t\t\tindex_id;\t/* Opaque keyring index ID */\n \tstruct list_head\tlink;\t\t/* link in types list */\n \tstruct lock_class_key\tlock_class;\t/* key-\u003esem lock class */\n@@ -168,7 +171,8 @@ struct key_type {\n \n extern struct key_type key_type_keyring;\n \n-extern int register_key_type(struct key_type *ktype);\n+int __register_key_type(struct key_type *ktype, struct module *owner);\n+#define register_key_type(ktype) __register_key_type(ktype, THIS_MODULE)\n extern void unregister_key_type(struct key_type *ktype);\n \n extern int key_payload_reserve(struct key *key, size_t datalen);\ndiff --git a/include/linux/key.h b/include/linux/key.h\nindex 420412aab9263a..0f408255f7406a 100644\n--- a/include/linux/key.h\n+++ b/include/linux/key.h\n@@ -439,6 +439,7 @@ extern int restrict_link_reject(struct key *keyring,\n \t\t\t\tstruct key *restriction_key);\n \n extern int keyring_clear(struct key *keyring);\n+void key_gc_flush(void);\n \n extern key_ref_t keyring_search(key_ref_t keyring,\n \t\t\t\tstruct key_type *type,\n@@ -526,6 +527,7 @@ extern void key_init(void);\n #define key_free_user_ns(ns)\t\tdo { } while(0)\n #define key_remove_domain(d)\t\tdo { } while(0)\n #define key_lookup(k)\t\t\tNULL\n+#define key_gc_flush()\t\t\tdo { } while (0)\n \n #endif /* CONFIG_KEYS */\n #endif /* __KERNEL__ */\ndiff --git a/net/Makefile b/net/Makefile\nindex 5b2dd7f07a85e9..97b2bd2ace7b5a 100644\n--- a/net/Makefile\n+++ b/net/Makefile\n@@ -30,7 +30,7 @@ obj-$(CONFIG_LAPB)\t\t+= lapb/\n obj-$(CONFIG_CAN)\t\t+= can/\n obj-$(CONFIG_BT)\t\t+= bluetooth/\n obj-$(CONFIG_SUNRPC)\t\t+= sunrpc/\n-obj-$(CONFIG_AF_RXRPC)\t\t+= rxrpc/\n+obj-$(CONFIG_RXRPC_KEYS)\t+= rxrpc/\n obj-$(CONFIG_AF_KCM)\t\t+= kcm/\n obj-$(CONFIG_STREAM_PARSER)\t+= strparser/\n obj-$(CONFIG_ATM)\t\t+= atm/\n@@ -55,7 +55,7 @@ obj-$(CONFIG_IEEE802154)\t+= ieee802154/\n obj-$(CONFIG_MAC802154)\t\t+= mac802154/\n \n obj-$(CONFIG_SYSCTL)\t\t+= sysctl_net.o\n-obj-$(CONFIG_DNS_RESOLVER)\t+= dns_resolver/\n+obj-$(CONFIG_DNS_KEY)\t\t+= dns_resolver/\n obj-$(CONFIG_CEPH_LIB)\t\t+= ceph/\n obj-$(CONFIG_BATMAN_ADV)\t+= batman-adv/\n obj-$(CONFIG_NFC)\t\t+= nfc/\ndiff --git a/net/dns_resolver/Kconfig b/net/dns_resolver/Kconfig\nindex 7c2dba273e358c..2618bad2e771e9 100644\n--- a/net/dns_resolver/Kconfig\n+++ b/net/dns_resolver/Kconfig\n@@ -1,10 +1,25 @@\n # SPDX-License-Identifier: GPL-2.0-only\n+\n+#\n+# Configuration for DNS Resolver key type\n+#\n+config DNS_KEY\n+\ttristate \"DNS Resolver key type\"\n+\tdepends on KEYS\n+\thelp\n+\t  Support the key type used to cache DNS lookups independently of\n+\t  the in-kernel DNS query service.\n+\n+\t  To compile this as a module, choose M here: the module is called\n+\t  dns_resolver_key.\n+\n #\n # Configuration for DNS Resolver\n #\n config DNS_RESOLVER\n \ttristate \"DNS Resolver support\"\n \tdepends on KEYS\n+\tselect DNS_KEY\n \thelp\n \t  Saying Y here will include support for the DNS Resolver key type\n \t  which can be used to make upcalls to perform DNS lookups in\ndiff --git a/net/dns_resolver/Makefile b/net/dns_resolver/Makefile\nindex 877532d662d05d..586e4c6514de81 100644\n--- a/net/dns_resolver/Makefile\n+++ b/net/dns_resolver/Makefile\n@@ -3,6 +3,8 @@\n # Makefile for the Linux DNS Resolver.\n #\n \n+obj-$(CONFIG_DNS_KEY) += dns_resolver_key.o\n obj-$(CONFIG_DNS_RESOLVER) += dns_resolver.o\n \n-dns_resolver-y :=  dns_key.o dns_query.o\n+dns_resolver-y := dns_query.o\n+dns_resolver_key-y := dns_key.o\ndiff --git a/net/dns_resolver/dns_key.c b/net/dns_resolver/dns_key.c\nindex 451247864a638b..fecbdc1d6beb10 100644\n--- a/net/dns_resolver/dns_key.c\n+++ b/net/dns_resolver/dns_key.c\n@@ -9,8 +9,8 @@\n  *              Wang Lei (wang840925@gmail.com)\n  *\t\tDavid Howells (dhowells@redhat.com)\n  */\n+\n #include \u003clinux/module.h\u003e\n-#include \u003clinux/moduleparam.h\u003e\n #include \u003clinux/slab.h\u003e\n #include \u003clinux/string.h\u003e\n #include \u003clinux/kernel.h\u003e\n@@ -22,15 +22,12 @@\n #include \u003ckeys/user-type.h\u003e\n #include \"internal.h\"\n \n-MODULE_DESCRIPTION(\"DNS Resolver\");\n+MODULE_DESCRIPTION(\"DNS Resolver key type\");\n MODULE_AUTHOR(\"Wang Lei\");\n MODULE_LICENSE(\"GPL\");\n \n unsigned int dns_resolver_debug;\n-module_param_named(debug, dns_resolver_debug, uint, 0644);\n-MODULE_PARM_DESC(debug, \"DNS Resolver debugging mask\");\n-\n-const struct cred *dns_resolver_cache;\n+EXPORT_SYMBOL_GPL(dns_resolver_debug);\n \n #define\tDNS_ERRORNO_OPTION\t\"dnserror\"\n \n@@ -318,61 +315,17 @@ struct key_type key_type_dns_resolver = {\n \t.describe\t= dns_resolver_describe,\n \t.read\t\t= dns_resolver_read,\n };\n+EXPORT_SYMBOL_GPL(key_type_dns_resolver);\n \n-static int __init init_dns_resolver(void)\n+static int __init init_dns_key(void)\n {\n-\tstruct cred *cred;\n-\tstruct key *keyring;\n-\tint ret;\n-\n-\t/* create an override credential set with a special thread keyring in\n-\t * which DNS requests are cached\n-\t *\n-\t * this is used to prevent malicious redirections from being installed\n-\t * with add_key().\n-\t */\n-\tcred = prepare_kernel_cred(\u0026init_task);\n-\tif (!cred)\n-\t\treturn -ENOMEM;\n-\n-\tkeyring = keyring_alloc(\".dns_resolver\",\n-\t\t\t\tGLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,\n-\t\t\t\t(KEY_POS_ALL \u0026 ~KEY_POS_SETATTR) |\n-\t\t\t\tKEY_USR_VIEW | KEY_USR_READ,\n-\t\t\t\tKEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);\n-\tif (IS_ERR(keyring)) {\n-\t\tret = PTR_ERR(keyring);\n-\t\tgoto failed_put_cred;\n-\t}\n-\n-\tret = register_key_type(\u0026key_type_dns_resolver);\n-\tif (ret \u003c 0)\n-\t\tgoto failed_put_key;\n-\n-\t/* instruct request_key() to use this special keyring as a cache for\n-\t * the results it looks up */\n-\tset_bit(KEY_FLAG_ROOT_CAN_CLEAR, \u0026keyring-\u003eflags);\n-\tcred-\u003ethread_keyring = keyring;\n-\tcred-\u003ejit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;\n-\tdns_resolver_cache = cred;\n-\n-\tkdebug(\"DNS resolver keyring: %d\\n\", key_serial(keyring));\n-\treturn 0;\n-\n-failed_put_key:\n-\tkey_put(keyring);\n-failed_put_cred:\n-\tput_cred(cred);\n-\treturn ret;\n+\treturn register_key_type(\u0026key_type_dns_resolver);\n }\n \n-static void __exit exit_dns_resolver(void)\n+static void __exit exit_dns_key(void)\n {\n-\tkey_revoke(dns_resolver_cache-\u003ethread_keyring);\n \tunregister_key_type(\u0026key_type_dns_resolver);\n-\tput_cred(dns_resolver_cache);\n }\n \n-module_init(init_dns_resolver)\n-module_exit(exit_dns_resolver)\n-MODULE_LICENSE(\"GPL\");\n+module_init(init_dns_key);\n+module_exit(exit_dns_key);\ndiff --git a/net/dns_resolver/dns_query.c b/net/dns_resolver/dns_query.c\nindex b8fb9a1245bf3a..ae4dde190101d7 100644\n--- a/net/dns_resolver/dns_query.c\n+++ b/net/dns_resolver/dns_query.c\n@@ -24,8 +24,10 @@\n  */\n \n #include \u003clinux/module.h\u003e\n+#include \u003clinux/moduleparam.h\u003e\n #include \u003clinux/slab.h\u003e\n #include \u003clinux/cred.h\u003e\n+#include \u003clinux/keyctl.h\u003e\n #include \u003clinux/dns_resolver.h\u003e\n #include \u003clinux/err.h\u003e\n #include \u003cnet/net_namespace.h\u003e\n@@ -35,6 +37,8 @@\n \n #include \"internal.h\"\n \n+static const struct cred *dns_resolver_cache;\n+\n /**\n  * dns_query - Query the DNS\n  * @net: The network namespace to operate in.\n@@ -137,3 +141,63 @@ int dns_query(struct net *net,\n \treturn ret;\n }\n EXPORT_SYMBOL(dns_query);\n+\n+static int __init init_dns_resolver(void)\n+{\n+\tstruct cred *cred;\n+\tstruct key *keyring;\n+\tint ret;\n+\n+\t/*\n+\t * Create an override credential set with a special thread keyring in\n+\t * which DNS requests are cached.  This prevents malicious redirections\n+\t * from being installed with add_key().\n+\t */\n+\tcred = prepare_kernel_cred(\u0026init_task);\n+\tif (!cred)\n+\t\treturn -ENOMEM;\n+\n+\tkeyring = keyring_alloc(\".dns_resolver\",\n+\t\t\t\tGLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,\n+\t\t\t\t(KEY_POS_ALL \u0026 ~KEY_POS_SETATTR) |\n+\t\t\t\tKEY_USR_VIEW | KEY_USR_READ,\n+\t\t\t\tKEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);\n+\tif (IS_ERR(keyring)) {\n+\t\tret = PTR_ERR(keyring);\n+\t\tgoto failed_put_cred;\n+\t}\n+\n+\t/*\n+\t * Instruct request_key() to use this special keyring as a cache for\n+\t * the results it looks up.\n+\t */\n+\tset_bit(KEY_FLAG_ROOT_CAN_CLEAR, \u0026keyring-\u003eflags);\n+\tcred-\u003ethread_keyring = keyring;\n+\tcred-\u003ejit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;\n+\tdns_resolver_cache = cred;\n+\n+\tkdebug(\"DNS resolver keyring: %d\\n\", key_serial(keyring));\n+\treturn 0;\n+\n+failed_put_cred:\n+\tput_cred(cred);\n+\treturn ret;\n+}\n+\n+static void __exit exit_dns_resolver(void)\n+{\n+\tkey_revoke(dns_resolver_cache-\u003ethread_keyring);\n+\tput_cred(dns_resolver_cache);\n+\t/* Drain deferred credential and keyring destruction. */\n+\tkey_gc_flush();\n+}\n+\n+module_init(init_dns_resolver);\n+module_exit(exit_dns_resolver);\n+\n+MODULE_DESCRIPTION(\"DNS Resolver\");\n+MODULE_AUTHOR(\"Wang Lei\");\n+MODULE_LICENSE(\"GPL\");\n+\n+module_param_named(debug, dns_resolver_debug, uint, 0644);\n+MODULE_PARM_DESC(debug, \"DNS Resolver debugging mask\");\ndiff --git a/net/dns_resolver/internal.h b/net/dns_resolver/internal.h\nindex d0d8edcea09227..3478bad78a9a75 100644\n--- a/net/dns_resolver/internal.h\n+++ b/net/dns_resolver/internal.h\n@@ -18,11 +18,6 @@ enum {\n \tdns_key_error,\n };\n \n-/*\n- * dns_key.c\n- */\n-extern const struct cred *dns_resolver_cache;\n-\n /*\n  * debug tracing\n  */\ndiff --git a/net/rxrpc/Kconfig b/net/rxrpc/Kconfig\nindex 2cebb666dc0711..30135ae62bd6ac 100644\n--- a/net/rxrpc/Kconfig\n+++ b/net/rxrpc/Kconfig\n@@ -3,6 +3,18 @@\n # RxRPC session sockets\n #\n \n+config RXRPC_KEYS\n+\ttristate \"RxRPC key types\"\n+\tselect CRYPTO\n+\tselect CRYPTO_LIB_DES if RXKAD\n+\tselect KEYS\n+\thelp\n+\t  Say Y or M here to include support for rxrpc and rxrpc_s key types\n+\t  independently of RxRPC session sockets.\n+\n+\t  To compile this as a module, choose M here: the module will be called\n+\t  rxrpc_keys.\n+\n config AF_RXRPC\n \ttristate \"RxRPC session sockets\"\n \tdepends on INET\n@@ -10,6 +22,7 @@ config AF_RXRPC\n \tselect CRYPTO_LIB_DES if RXKAD\n \tselect KEYS\n \tselect NET_UDP_TUNNEL\n+\tselect RXRPC_KEYS\n \thelp\n \t  Say Y or M here to include support for RxRPC session sockets (just\n \t  the transport part, not the presentation part: (un)marshalling is\n@@ -54,6 +67,9 @@ config AF_RXRPC_DEBUG\n \n \t  See Documentation/networking/rxrpc.rst.\n \n+endif\n+\n+if RXRPC_KEYS\n \n config RXKAD\n \tbool \"RxRPC Kerberos security\"\n@@ -86,6 +102,10 @@ config RXGK\n \n \t  See Documentation/networking/rxrpc.rst.\n \n+endif\n+\n+if AF_RXRPC\n+\n config RXPERF\n \ttristate \"RxRPC test service\"\n \thelp\ndiff --git a/net/rxrpc/Makefile b/net/rxrpc/Makefile\nindex f994f9f30a29d4..196e0ce085bae1 100644\n--- a/net/rxrpc/Makefile\n+++ b/net/rxrpc/Makefile\n@@ -3,6 +3,7 @@\n # Makefile for Linux kernel RxRPC\n #\n \n+obj-$(CONFIG_RXRPC_KEYS) += rxrpc_keys.o\n obj-$(CONFIG_AF_RXRPC) += rxrpc.o\n \n rxrpc-y := \\\n@@ -19,7 +20,6 @@ rxrpc-y := \\\n \tinput_rack.o \\\n \tinsecure.o \\\n \tio_thread.o \\\n-\tkey.o \\\n \tlocal_event.o \\\n \tlocal_object.o \\\n \tmisc.o \\\n@@ -32,7 +32,6 @@ rxrpc-y := \\\n \trtt.o \\\n \tsecurity.o \\\n \tsendmsg.o \\\n-\tserver_key.o \\\n \tskbuff.o \\\n \ttxbuf.o \\\n \tutils.o\n@@ -45,5 +44,9 @@ rxrpc-$(CONFIG_RXGK) += \\\n \trxgk_app.o \\\n \trxgk_kdf.o\n \n+rxrpc_keys-y := \\\n+\tkey.o \\\n+\tserver_key.o\n+\n obj-$(CONFIG_RXPERF) += rxperf.o\n obj-$(CONFIG_KUNIT) += tests/\ndiff --git a/net/rxrpc/af_rxrpc.c b/net/rxrpc/af_rxrpc.c\nindex 9ab0f22c881ec5..6ccb99a992b925 100644\n--- a/net/rxrpc/af_rxrpc.c\n+++ b/net/rxrpc/af_rxrpc.c\n@@ -1077,18 +1077,6 @@ static int __init af_rxrpc_init(void)\n \t\tgoto error_sock;\n \t}\n \n-\tret = register_key_type(\u0026key_type_rxrpc);\n-\tif (ret \u003c 0) {\n-\t\tpr_crit(\"Cannot register client key type\\n\");\n-\t\tgoto error_key_type;\n-\t}\n-\n-\tret = register_key_type(\u0026key_type_rxrpc_s);\n-\tif (ret \u003c 0) {\n-\t\tpr_crit(\"Cannot register server key type\\n\");\n-\t\tgoto error_key_type_s;\n-\t}\n-\n \tret = rxrpc_sysctl_init();\n \tif (ret \u003c 0) {\n \t\tpr_crit(\"Cannot register sysctls\\n\");\n@@ -1098,10 +1086,6 @@ static int __init af_rxrpc_init(void)\n \treturn 0;\n \n error_sysctls:\n-\tunregister_key_type(\u0026key_type_rxrpc_s);\n-error_key_type_s:\n-\tunregister_key_type(\u0026key_type_rxrpc);\n-error_key_type:\n \tsock_unregister(PF_RXRPC);\n error_sock:\n \tproto_unregister(\u0026rxrpc_proto);\n@@ -1124,8 +1108,6 @@ static void __exit af_rxrpc_exit(void)\n {\n \t_enter(\"\");\n \trxrpc_sysctl_exit();\n-\tunregister_key_type(\u0026key_type_rxrpc_s);\n-\tunregister_key_type(\u0026key_type_rxrpc);\n \tsock_unregister(PF_RXRPC);\n \tproto_unregister(\u0026rxrpc_proto);\n \tunregister_pernet_device(\u0026rxrpc_net_ops);\n@@ -1139,6 +1121,7 @@ static void __exit af_rxrpc_exit(void)\n \tdestroy_workqueue(rxrpc_workqueue);\n \trxrpc_exit_security();\n \tkmem_cache_destroy(rxrpc_call_jar);\n+\tkey_gc_flush();\n \t_leave(\"\");\n }\n \ndiff --git a/net/rxrpc/ar-internal.h b/net/rxrpc/ar-internal.h\nindex 865f05fe37ab96..b5deab0e1ed9d1 100644\n--- a/net/rxrpc/ar-internal.h\n+++ b/net/rxrpc/ar-internal.h\n@@ -273,18 +273,6 @@ struct rxrpc_security {\n \t/* Clean up a security service */\n \tvoid (*exit)(void);\n \n-\t/* Parse the information from a server key */\n-\tint (*preparse_server_key)(struct key_preparsed_payload *);\n-\n-\t/* Clean up the preparse buffer after parsing a server key */\n-\tvoid (*free_preparse_server_key)(struct key_preparsed_payload *);\n-\n-\t/* Destroy the payload of a server key */\n-\tvoid (*destroy_server_key)(struct key *);\n-\n-\t/* Describe a server key */\n-\tvoid (*describe_server_key)(const struct key *, struct seq_file *);\n-\n \t/* initialise a connection's security */\n \tint (*init_connection_security)(struct rxrpc_connection *,\n \t\t\t\t\tstruct rxrpc_key_token *);\n@@ -1307,10 +1295,6 @@ extern const struct rxrpc_security rxrpc_no_security;\n  */\n extern struct key_type key_type_rxrpc;\n \n-int rxrpc_request_key(struct rxrpc_sock *, sockptr_t , int);\n-int rxrpc_get_server_data_key(struct rxrpc_connection *, const void *, time64_t,\n-\t\t\t      u32);\n-\n /*\n  * local_event.c\n  */\n@@ -1492,6 +1476,11 @@ const struct rxrpc_security *rxrpc_get_incoming_security(struct rxrpc_sock *,\n \t\t\t\t\t\t\t struct sk_buff *);\n struct key *rxrpc_look_up_server_security(struct rxrpc_connection *,\n \t\t\t\t\t  struct sk_buff *, u32, u32);\n+int rxrpc_request_key(struct rxrpc_sock *rx, sockptr_t optval, int optlen);\n+int rxrpc_get_server_data_key(struct rxrpc_connection *conn,\n+\t\t\t      const void *session_key, time64_t expiry,\n+\t\t\t      u32 kvno);\n+int rxrpc_server_keyring(struct rxrpc_sock *rx, sockptr_t optval, int optlen);\n \n /*\n  * sendmsg.c\n@@ -1505,8 +1494,6 @@ int rxrpc_do_sendmsg(struct rxrpc_sock *, struct msghdr *, size_t);\n  */\n extern struct key_type key_type_rxrpc_s;\n \n-int rxrpc_server_keyring(struct rxrpc_sock *, sockptr_t, int);\n-\n /*\n  * skbuff.c\n  */\n@@ -1633,7 +1620,7 @@ extern unsigned int rxrpc_debug;\n #define _leave(FMT,...)\tkleave(FMT,##__VA_ARGS__)\n #define _debug(FMT,...)\tkdebug(FMT,##__VA_ARGS__)\n \n-#elif defined(CONFIG_AF_RXRPC_DEBUG)\n+#elif defined(CONFIG_AF_RXRPC_DEBUG) \u0026\u0026 !defined(RXRPC_KEY_PROVIDER)\n #define RXRPC_DEBUG_KENTER\t0x01\n #define RXRPC_DEBUG_KLEAVE\t0x02\n #define RXRPC_DEBUG_KDEBUG\t0x04\ndiff --git a/net/rxrpc/conn_event.c b/net/rxrpc/conn_event.c\nindex 611c790bc6d0ce..096807f133546e 100644\n--- a/net/rxrpc/conn_event.c\n+++ b/net/rxrpc/conn_event.c\n@@ -298,8 +298,13 @@ static int rxrpc_process_event(struct rxrpc_connection *conn,\n \n \t\tret = conn-\u003esecurity-\u003einit_connection_security(\n \t\t\tconn, conn-\u003ekey-\u003epayload.data[0]);\n-\t\tif (ret \u003c 0)\n+\t\tif (ret \u003c 0) {\n+\t\t\tstruct key *key = conn-\u003ekey;\n+\n+\t\t\tWRITE_ONCE(conn-\u003ekey, NULL);\n+\t\t\tkey_put(key);\n \t\t\treturn ret;\n+\t\t}\n \n \t\tspin_lock_irq(\u0026conn-\u003estate_lock);\n \t\tif (conn-\u003estate == RXRPC_CONN_SERVICE_CHALLENGING) {\ndiff --git a/net/rxrpc/key.c b/net/rxrpc/key.c\nindex cbd26da4495107..49d0871beaf9cd 100644\n--- a/net/rxrpc/key.c\n+++ b/net/rxrpc/key.c\n@@ -9,6 +9,7 @@\n  */\n \n #define pr_fmt(fmt) KBUILD_MODNAME \": \" fmt\n+#define RXRPC_KEY_PROVIDER\n \n #include \u003clinux/module.h\u003e\n #include \u003clinux/net.h\u003e\n@@ -615,89 +616,6 @@ static void rxrpc_describe(const struct key *key, struct seq_file *m)\n \t}\n }\n \n-/*\n- * grab the security key for a socket\n- */\n-int rxrpc_request_key(struct rxrpc_sock *rx, sockptr_t optval, int optlen)\n-{\n-\tstruct key *key;\n-\tchar *description;\n-\n-\t_enter(\"\");\n-\n-\tif (optlen \u003c= 0 || optlen \u003e PAGE_SIZE - 1 || rx-\u003ekey)\n-\t\treturn -EINVAL;\n-\n-\tdescription = memdup_sockptr_nul(optval, optlen);\n-\tif (IS_ERR(description))\n-\t\treturn PTR_ERR(description);\n-\n-\tkey = request_key_net(\u0026key_type_rxrpc, description, sock_net(\u0026rx-\u003esk), NULL);\n-\tif (IS_ERR(key)) {\n-\t\tkfree(description);\n-\t\t_leave(\" = %ld\", PTR_ERR(key));\n-\t\treturn PTR_ERR(key);\n-\t}\n-\n-\trx-\u003ekey = key;\n-\tkfree(description);\n-\t_leave(\" = 0 [key %x]\", key-\u003eserial);\n-\treturn 0;\n-}\n-\n-/*\n- * generate a server data key\n- */\n-int rxrpc_get_server_data_key(struct rxrpc_connection *conn,\n-\t\t\t      const void *session_key,\n-\t\t\t      time64_t expiry,\n-\t\t\t      u32 kvno)\n-{\n-\tconst struct cred *cred = current_cred();\n-\tstruct key *key;\n-\tint ret;\n-\n-\tstruct {\n-\t\tu32 kver;\n-\t\tstruct rxrpc_key_data_v1 v1;\n-\t} data;\n-\n-\t_enter(\"\");\n-\n-\tkey = key_alloc(\u0026key_type_rxrpc, \"x\",\n-\t\t\tGLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred, 0,\n-\t\t\tKEY_ALLOC_NOT_IN_QUOTA, NULL);\n-\tif (IS_ERR(key)) {\n-\t\t_leave(\" = -ENOMEM [alloc %ld]\", PTR_ERR(key));\n-\t\treturn -ENOMEM;\n-\t}\n-\n-\t_debug(\"key %d\", key_serial(key));\n-\n-\tdata.kver = 1;\n-\tdata.v1.security_index = RXRPC_SECURITY_RXKAD;\n-\tdata.v1.ticket_length = 0;\n-\tdata.v1.expiry = rxrpc_time64_to_u32(expiry);\n-\tdata.v1.kvno = 0;\n-\n-\tmemcpy(\u0026data.v1.session_key, session_key, sizeof(data.v1.session_key));\n-\n-\tret = key_instantiate_and_link(key, \u0026data, sizeof(data), NULL, NULL);\n-\tif (ret \u003c 0)\n-\t\tgoto error;\n-\n-\tconn-\u003ekey = key;\n-\t_leave(\" = 0 [%d]\", key_serial(key));\n-\treturn 0;\n-\n-error:\n-\tkey_revoke(key);\n-\tkey_put(key);\n-\t_leave(\" = -ENOMEM [ins %d]\", ret);\n-\treturn -ENOMEM;\n-}\n-EXPORT_SYMBOL(rxrpc_get_server_data_key);\n-\n /**\n  * rxrpc_get_null_key - Generate a null RxRPC key\n  * @keyname: The name to give the key.\n@@ -893,3 +811,41 @@ static long rxrpc_read(const struct key *key,\n \t_leave(\" = %zu\", size);\n \treturn size;\n }\n+\n+static int __init rxrpc_keys_init(void)\n+{\n+\tint ret;\n+\n+\tret = register_key_type(\u0026key_type_rxrpc);\n+\tif (ret \u003c 0) {\n+\t\tpr_crit(\"Cannot register client key type\\n\");\n+\t\tgoto error_key_type;\n+\t}\n+\n+\tret = register_key_type(\u0026key_type_rxrpc_s);\n+\tif (ret \u003c 0) {\n+\t\tpr_crit(\"Cannot register server key type\\n\");\n+\t\tgoto error_key_type_s;\n+\t}\n+\n+\treturn 0;\n+\n+error_key_type_s:\n+\tunregister_key_type(\u0026key_type_rxrpc);\n+\n+error_key_type:\n+\treturn ret;\n+}\n+\n+static void __exit rxrpc_keys_exit(void)\n+{\n+\tunregister_key_type(\u0026key_type_rxrpc_s);\n+\tunregister_key_type(\u0026key_type_rxrpc);\n+}\n+\n+module_init(rxrpc_keys_init);\n+module_exit(rxrpc_keys_exit);\n+\n+MODULE_DESCRIPTION(\"RxRPC key types\");\n+MODULE_AUTHOR(\"David Howells \u003cdhowells@redhat.com\u003e\");\n+MODULE_LICENSE(\"GPL\");\ndiff --git a/net/rxrpc/proc.c b/net/rxrpc/proc.c\nindex e9a27fa7b25d8b..2bf34b85c2f990 100644\n--- a/net/rxrpc/proc.c\n+++ b/net/rxrpc/proc.c\n@@ -182,7 +182,7 @@ static int rxrpc_connection_seq_show(struct seq_file *seq, void *v)\n \t\t   refcount_read(\u0026conn-\u003eref),\n \t\t   atomic_read(\u0026conn-\u003eactive),\n \t\t   state,\n-\t\t   key_serial(conn-\u003ekey),\n+\t\t   key_serial(READ_ONCE(conn-\u003ekey)),\n \t\t   conn-\u003etx_serial,\n \t\t   conn-\u003ehi_serial,\n \t\t   conn-\u003echannels[0].call_id,\ndiff --git a/net/rxrpc/rxgk.c b/net/rxrpc/rxgk.c\nindex 77a67ace1d2481..5fb3ce15cac402 100644\n--- a/net/rxrpc/rxgk.c\n+++ b/net/rxrpc/rxgk.c\n@@ -14,68 +14,6 @@\n #include \"ar-internal.h\"\n #include \"rxgk_common.h\"\n \n-/*\n- * Parse the information from a server key\n- */\n-static int rxgk_preparse_server_key(struct key_preparsed_payload *prep)\n-{\n-\tconst struct krb5_enctype *krb5;\n-\tstruct krb5_buffer *server_key = (void *)\u0026prep-\u003epayload.data[2];\n-\tunsigned int service, sec_class, kvno, enctype;\n-\tint n = 0;\n-\n-\t_enter(\"%zu\", prep-\u003edatalen);\n-\n-\tif (sscanf(prep-\u003eorig_description, \"%u:%u:%u:%u%n\",\n-\t\t   \u0026service, \u0026sec_class, \u0026kvno, \u0026enctype, \u0026n) != 4)\n-\t\treturn -EINVAL;\n-\n-\tif (prep-\u003eorig_description[n])\n-\t\treturn -EINVAL;\n-\n-\tkrb5 = crypto_krb5_find_enctype(enctype);\n-\tif (!krb5)\n-\t\treturn -ENOPKG;\n-\n-\tprep-\u003epayload.data[0] = (struct krb5_enctype *)krb5;\n-\n-\tif (prep-\u003edatalen != krb5-\u003ekey_len)\n-\t\treturn -EKEYREJECTED;\n-\n-\tserver_key-\u003elen = prep-\u003edatalen;\n-\tserver_key-\u003edata = kmemdup(prep-\u003edata, prep-\u003edatalen, GFP_KERNEL);\n-\tif (!server_key-\u003edata)\n-\t\treturn -ENOMEM;\n-\n-\t_leave(\" = 0\");\n-\treturn 0;\n-}\n-\n-static void rxgk_free_server_key(union key_payload *payload)\n-{\n-\tstruct krb5_buffer *server_key = (void *)\u0026payload-\u003edata[2];\n-\n-\tkfree_sensitive(server_key-\u003edata);\n-}\n-\n-static void rxgk_free_preparse_server_key(struct key_preparsed_payload *prep)\n-{\n-\trxgk_free_server_key(\u0026prep-\u003epayload);\n-}\n-\n-static void rxgk_destroy_server_key(struct key *key)\n-{\n-\trxgk_free_server_key(\u0026key-\u003epayload);\n-}\n-\n-static void rxgk_describe_server_key(const struct key *key, struct seq_file *m)\n-{\n-\tconst struct krb5_enctype *krb5 = key-\u003epayload.data[0];\n-\n-\tif (krb5)\n-\t\tseq_printf(m, \": %s\", krb5-\u003ename);\n-}\n-\n /*\n  * Handle rekeying the connection when we see our limits overrun or when the\n  * far side decided to rekey.\n@@ -1335,10 +1273,6 @@ const struct rxrpc_security rxgk_yfs = {\n \t.no_key_abort\t\t\t= RXGK_NOTAUTH,\n \t.init\t\t\t\t= rxgk_init,\n \t.exit\t\t\t\t= rxgk_exit,\n-\t.preparse_server_key\t\t= rxgk_preparse_server_key,\n-\t.free_preparse_server_key\t= rxgk_free_preparse_server_key,\n-\t.destroy_server_key\t\t= rxgk_destroy_server_key,\n-\t.describe_server_key\t\t= rxgk_describe_server_key,\n \t.init_connection_security\t= rxgk_init_connection_security,\n \t.alloc_txbuf\t\t\t= rxgk_alloc_txbuf,\n \t.secure_packet\t\t\t= rxgk_secure_packet,\ndiff --git a/net/rxrpc/rxkad.c b/net/rxrpc/rxkad.c\nindex ca9f0e82cb9ac7..2936c6effae396 100644\n--- a/net/rxrpc/rxkad.c\n+++ b/net/rxrpc/rxkad.c\n@@ -47,50 +47,6 @@ struct rxkad_level2_hdr {\n static void rxkad_prime_packet_security(struct rxrpc_connection *conn,\n \t\t\t\t\tconst struct fcrypt_key *cipher);\n \n-/*\n- * Parse the information from a server key\n- *\n- * The data should be the 8-byte secret key.\n- */\n-static int rxkad_preparse_server_key(struct key_preparsed_payload *prep)\n-{\n-\tstruct des_ctx *des_key;\n-\tint err;\n-\n-\tif (prep-\u003edatalen != 8)\n-\t\treturn -EINVAL;\n-\n-\tmemcpy(\u0026prep-\u003epayload.data[2], prep-\u003edata, 8);\n-\n-\tdes_key = kmalloc_obj(*des_key);\n-\tif (!des_key) {\n-\t\t_leave(\" = -ENOMEM\");\n-\t\treturn -ENOMEM;\n-\t}\n-\n-\terr = des_expand_key(des_key, prep-\u003edata, 8);\n-\tif (err) {\n-\t\tkfree_sensitive(des_key);\n-\t\t_leave(\" = %d\", err);\n-\t\treturn err;\n-\t}\n-\n-\tprep-\u003epayload.data[0] = des_key;\n-\t_leave(\" = 0\");\n-\treturn 0;\n-}\n-\n-static void rxkad_free_preparse_server_key(struct key_preparsed_payload *prep)\n-{\n-\tkfree_sensitive(prep-\u003epayload.data[0]);\n-}\n-\n-static void rxkad_destroy_server_key(struct key *key)\n-{\n-\tkfree_sensitive(key-\u003epayload.data[0]);\n-\tkey-\u003epayload.data[0] = NULL;\n-}\n-\n /*\n  * initialise connection security\n  */\n@@ -1124,9 +1080,6 @@ const struct rxrpc_security rxkad = {\n \t.no_key_abort\t\t\t= RXKADUNKNOWNKEY,\n \t.init\t\t\t\t= rxkad_init,\n \t.exit\t\t\t\t= rxkad_exit,\n-\t.preparse_server_key\t\t= rxkad_preparse_server_key,\n-\t.free_preparse_server_key\t= rxkad_free_preparse_server_key,\n-\t.destroy_server_key\t\t= rxkad_destroy_server_key,\n \t.init_connection_security\t= rxkad_init_connection_security,\n \t.alloc_txbuf\t\t\t= rxkad_alloc_txbuf,\n \t.secure_packet\t\t\t= rxkad_secure_packet,\ndiff --git a/net/rxrpc/security.c b/net/rxrpc/security.c\nindex 2bfbf2b2bb37a9..28883a70c9e85b 100644\n--- a/net/rxrpc/security.c\n+++ b/net/rxrpc/security.c\n@@ -10,6 +10,8 @@\n #include \u003clinux/skbuff.h\u003e\n #include \u003clinux/udp.h\u003e\n #include \u003clinux/crypto.h\u003e\n+#include \u003clinux/key-type.h\u003e\n+#include \u003clinux/slab.h\u003e\n #include \u003cnet/sock.h\u003e\n #include \u003cnet/af_rxrpc.h\u003e\n #include \u003ckeys/rxrpc-type.h\u003e\n@@ -208,3 +210,185 @@ struct key *rxrpc_look_up_server_security(struct rxrpc_connection *conn,\n \tread_unlock(\u0026conn-\u003elocal-\u003eservices_lock);\n \treturn key;\n }\n+\n+/*\n+ * grab the security key for a socket\n+ */\n+int rxrpc_request_key(struct rxrpc_sock *rx, sockptr_t optval, int optlen)\n+{\n+\tstruct key *key;\n+\tchar *description;\n+\n+\t_enter(\"\");\n+\n+\tif (optlen \u003c= 0 || optlen \u003e PAGE_SIZE - 1 || rx-\u003ekey)\n+\t\treturn -EINVAL;\n+\n+\tdescription = memdup_sockptr_nul(optval, optlen);\n+\tif (IS_ERR(description))\n+\t\treturn PTR_ERR(description);\n+\n+\tkey = request_key_net(\u0026key_type_rxrpc, description, sock_net(\u0026rx-\u003esk), NULL);\n+\tif (IS_ERR(key)) {\n+\t\tkfree(description);\n+\t\t_leave(\" = %ld\", PTR_ERR(key));\n+\t\treturn PTR_ERR(key);\n+\t}\n+\n+\trx-\u003ekey = key;\n+\tkfree(description);\n+\t_leave(\" = 0 [key %x]\", key-\u003eserial);\n+\treturn 0;\n+}\n+\n+/*\n+ * generate a server data key\n+ */\n+int rxrpc_get_server_data_key(struct rxrpc_connection *conn,\n+\t\t\t      const void *session_key,\n+\t\t\t      time64_t expiry,\n+\t\t\t      u32 kvno)\n+{\n+\tconst struct cred *cred = current_cred();\n+\tstruct {\n+\t\tu32 kver;\n+\t\tstruct rxrpc_key_data_v1 v1;\n+\t} data;\n+\tstruct key *key;\n+\tint ret;\n+\n+\t_enter(\"\");\n+\n+\tkey = key_alloc(\u0026key_type_rxrpc, \"x\",\n+\t\t\tGLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred, 0,\n+\t\t\tKEY_ALLOC_NOT_IN_QUOTA, NULL);\n+\tif (IS_ERR(key)) {\n+\t\t_leave(\" = -ENOMEM [alloc %ld]\", PTR_ERR(key));\n+\t\treturn -ENOMEM;\n+\t}\n+\n+\t_debug(\"key %d\", key_serial(key));\n+\n+\tdata.kver = 1;\n+\tdata.v1.security_index = RXRPC_SECURITY_RXKAD;\n+\tdata.v1.ticket_length = 0;\n+\tdata.v1.expiry = rxrpc_time64_to_u32(expiry);\n+\tdata.v1.kvno = 0;\n+\n+\tmemcpy(\u0026data.v1.session_key, session_key, sizeof(data.v1.session_key));\n+\n+\tret = key_instantiate_and_link(key, \u0026data, sizeof(data), NULL, NULL);\n+\tif (ret \u003c 0)\n+\t\tgoto error;\n+\n+\tconn-\u003ekey = key;\n+\t_leave(\" = 0 [%d]\", key_serial(key));\n+\treturn 0;\n+\n+error:\n+\tkey_revoke(key);\n+\tkey_put(key);\n+\t_leave(\" = -ENOMEM [ins %d]\", ret);\n+\treturn -ENOMEM;\n+}\n+EXPORT_SYMBOL(rxrpc_get_server_data_key);\n+\n+/*\n+ * grab the security keyring for a server socket\n+ */\n+int rxrpc_server_keyring(struct rxrpc_sock *rx, sockptr_t optval, int optlen)\n+{\n+\tstruct key *key;\n+\tchar *description;\n+\n+\t_enter(\"\");\n+\n+\tif (rx-\u003esecurities)\n+\t\treturn -EINVAL;\n+\n+\tif (optlen \u003c= 0 || optlen \u003e PAGE_SIZE - 1)\n+\t\treturn -EINVAL;\n+\n+\tdescription = memdup_sockptr_nul(optval, optlen);\n+\tif (IS_ERR(description))\n+\t\treturn PTR_ERR(description);\n+\n+\tkey = request_key(\u0026key_type_keyring, description, NULL);\n+\tif (IS_ERR(key)) {\n+\t\tkfree(description);\n+\t\t_leave(\" = %ld\", PTR_ERR(key));\n+\t\treturn PTR_ERR(key);\n+\t}\n+\n+\trx-\u003esecurities = key;\n+\tkfree(description);\n+\t_leave(\" = 0 [key %x]\", key-\u003eserial);\n+\treturn 0;\n+}\n+\n+/**\n+ * rxrpc_sock_set_security_keyring - Set the security keyring for a kernel service\n+ * @sk: The socket to set the keyring on\n+ * @keyring: The keyring to set\n+ *\n+ * Set the server security keyring on an rxrpc socket.  This is used to provide\n+ * the encryption keys for a kernel service.\n+ *\n+ * Return: %0 if successful and a negative error code otherwise.\n+ */\n+int rxrpc_sock_set_security_keyring(struct sock *sk, struct key *keyring)\n+{\n+\tstruct rxrpc_sock *rx = rxrpc_sk(sk);\n+\tint ret = 0;\n+\n+\tlock_sock(sk);\n+\tif (rx-\u003esecurities)\n+\t\tret = -EINVAL;\n+\telse if (rx-\u003esk.sk_state != RXRPC_UNBOUND)\n+\t\tret = -EISCONN;\n+\telse\n+\t\trx-\u003esecurities = key_get(keyring);\n+\trelease_sock(sk);\n+\treturn ret;\n+}\n+EXPORT_SYMBOL(rxrpc_sock_set_security_keyring);\n+\n+/**\n+ * rxrpc_sock_set_manage_response - Set the manage-response flag for a kernel service\n+ * @sk: The socket to set the keyring on\n+ * @set: True to set, false to clear the flag\n+ *\n+ * Set the flag on an rxrpc socket to say that the caller wants to manage the\n+ * RESPONSE packet and the user-defined data it may contain.  Setting this\n+ * means that recvmsg() will return messages with RXRPC_CHALLENGED in the\n+ * control message buffer containing information about the challenge.\n+ *\n+ * The user should respond to the challenge by passing RXRPC_RESPOND or\n+ * RXRPC_RESPOND_ABORT control messages with sendmsg() to the same call.\n+ * Supplementary control messages, such as RXRPC_RESP_RXGK_APPDATA, may be\n+ * included to indicate the parts the user wants to supply.\n+ *\n+ * The server will be passed the response data with a RXRPC_RESPONDED control\n+ * message when it gets the first data from each call.\n+ *\n+ * Note that this is only honoured by security classes that need auxiliary data\n+ * (e.g. RxGK).  Those that don't offer the facility (e.g. RxKAD) respond\n+ * without consulting userspace.\n+ *\n+ * Return: The previous setting.\n+ */\n+int rxrpc_sock_set_manage_response(struct sock *sk, bool set)\n+{\n+\tstruct rxrpc_sock *rx = rxrpc_sk(sk);\n+\tint ret;\n+\n+\tlock_sock(sk);\n+\tret = !!test_bit(RXRPC_SOCK_MANAGE_RESPONSE, \u0026rx-\u003eflags);\n+\tif (set)\n+\t\tset_bit(RXRPC_SOCK_MANAGE_RESPONSE, \u0026rx-\u003eflags);\n+\telse\n+\t\tclear_bit(RXRPC_SOCK_MANAGE_RESPONSE, \u0026rx-\u003eflags);\n+\trelease_sock(sk);\n+\treturn ret;\n+}\n+EXPORT_SYMBOL(rxrpc_sock_set_manage_response);\ndiff --git a/net/rxrpc/server_key.c b/net/rxrpc/server_key.c\nindex 3efe104b1930cb..0be259dd0df029 100644\n--- a/net/rxrpc/server_key.c\n+++ b/net/rxrpc/server_key.c\n@@ -9,6 +9,11 @@\n  */\n \n #define pr_fmt(fmt) KBUILD_MODNAME \": \" fmt\n+#define RXRPC_KEY_PROVIDER\n+\n+#include \u003ccrypto/des.h\u003e\n+#include \u003ccrypto/krb5.h\u003e\n+#include \u003clinux/fips.h\u003e\n \n #include \u003clinux/module.h\u003e\n #include \u003clinux/net.h\u003e\n@@ -42,6 +47,7 @@ struct key_type key_type_rxrpc_s = {\n \t.destroy\t= rxrpc_destroy_s,\n \t.describe\t= rxrpc_describe_s,\n };\n+EXPORT_SYMBOL(key_type_rxrpc_s);\n \n /*\n  * Vet the description for an RxRPC server key.\n@@ -60,156 +66,198 @@ static int rxrpc_vet_description_s(const char *desc)\n \treturn 0;\n }\n \n+#ifdef CONFIG_RXKAD\n /*\n- * Preparse a server secret key.\n+ * Parse the information from a server key\n+ *\n+ * The data should be the 8-byte secret key.\n  */\n-static int rxrpc_preparse_s(struct key_preparsed_payload *prep)\n+static int rxkad_preparse_server_key(struct key_preparsed_payload *prep)\n {\n-\tconst struct rxrpc_security *sec;\n-\tunsigned int service, sec_class;\n-\tint n;\n+\tstruct des_ctx *des_key;\n+\tint err;\n+\n+\tif (fips_enabled)\n+\t\treturn -ENOPKG;\n+\n+\tif (prep-\u003edatalen != 8)\n+\t\treturn -EINVAL;\n+\n+\tmemcpy(\u0026prep-\u003epayload.data[2], prep-\u003edata, 8);\n+\n+\tdes_key = kmalloc_obj(*des_key);\n+\tif (!des_key) {\n+\t\t_leave(\" = -ENOMEM\");\n+\t\treturn -ENOMEM;\n+\t}\n+\n+\terr = des_expand_key(des_key, prep-\u003edata, 8);\n+\tif (err) {\n+\t\tkfree_sensitive(des_key);\n+\t\t_leave(\" = %d\", err);\n+\t\treturn err;\n+\t}\n+\n+\tprep-\u003epayload.data[0] = des_key;\n+\t_leave(\" = 0\");\n+\treturn 0;\n+}\n+\n+static void rxkad_free_preparse_server_key(struct key_preparsed_payload *prep)\n+{\n+\tkfree_sensitive(prep-\u003epayload.data[0]);\n+}\n+\n+static void rxkad_destroy_server_key(struct key *key)\n+{\n+\tkfree_sensitive(key-\u003epayload.data[0]);\n+\tkey-\u003epayload.data[0] = NULL;\n+}\n+#endif\n+\n+#ifdef CONFIG_RXGK\n+/*\n+ * Parse the information from a server key\n+ */\n+static int rxgk_preparse_server_key(struct key_preparsed_payload *prep)\n+{\n+\tconst struct krb5_enctype *krb5;\n+\tstruct krb5_buffer *server_key = (void *)\u0026prep-\u003epayload.data[2];\n+\tunsigned int service, sec_class, kvno, enctype;\n+\tint n = 0;\n \n \t_enter(\"%zu\", prep-\u003edatalen);\n \n-\tif (!prep-\u003eorig_description)\n+\tif (sscanf(prep-\u003eorig_description, \"%u:%u:%u:%u%n\",\n+\t\t   \u0026service, \u0026sec_class, \u0026kvno, \u0026enctype, \u0026n) != 4)\n \t\treturn -EINVAL;\n \n-\tif (sscanf(prep-\u003eorig_description, \"%u:%u%n\", \u0026service, \u0026sec_class, \u0026n) != 2)\n+\tif (prep-\u003eorig_description[n])\n \t\treturn -EINVAL;\n \n-\tsec = rxrpc_security_lookup(sec_class);\n-\tif (!sec)\n+\tkrb5 = crypto_krb5_find_enctype(enctype);\n+\tif (!krb5)\n \t\treturn -ENOPKG;\n \n-\tprep-\u003epayload.data[1] = (struct rxrpc_security *)sec;\n+\tprep-\u003epayload.data[0] = (struct krb5_enctype *)krb5;\n \n-\tif (!sec-\u003epreparse_server_key)\n-\t\treturn -EINVAL;\n+\tif (prep-\u003edatalen != krb5-\u003ekey_len)\n+\t\treturn -EKEYREJECTED;\n+\n+\tserver_key-\u003elen = prep-\u003edatalen;\n+\tserver_key-\u003edata = kmemdup(prep-\u003edata, prep-\u003edatalen, GFP_KERNEL);\n+\tif (!server_key-\u003edata)\n+\t\treturn -ENOMEM;\n \n-\treturn sec-\u003epreparse_server_key(prep);\n+\t_leave(\" = 0\");\n+\treturn 0;\n }\n \n-static void rxrpc_free_preparse_s(struct key_preparsed_payload *prep)\n+static void rxgk_free_server_key(union key_payload *payload)\n {\n-\tconst struct rxrpc_security *sec = prep-\u003epayload.data[1];\n+\tstruct krb5_buffer *server_key = (void *)\u0026payload-\u003edata[2];\n \n-\tif (sec \u0026\u0026 sec-\u003efree_preparse_server_key)\n-\t\tsec-\u003efree_preparse_server_key(prep);\n+\tkfree_sensitive(server_key-\u003edata);\n }\n \n-static void rxrpc_destroy_s(struct key *key)\n+static void rxgk_free_preparse_server_key(struct key_preparsed_payload *prep)\n {\n-\tconst struct rxrpc_security *sec = key-\u003epayload.data[1];\n+\trxgk_free_server_key(\u0026prep-\u003epayload);\n+}\n \n-\tif (sec \u0026\u0026 sec-\u003edestroy_server_key)\n-\t\tsec-\u003edestroy_server_key(key);\n+static void rxgk_destroy_server_key(struct key *key)\n+{\n+\trxgk_free_server_key(\u0026key-\u003epayload);\n }\n \n-static void rxrpc_describe_s(const struct key *key, struct seq_file *m)\n+static void rxgk_describe_server_key(const struct key *key, struct seq_file *m)\n {\n-\tconst struct rxrpc_security *sec = key-\u003epayload.data[1];\n+\tconst struct krb5_enctype *krb5 = key-\u003epayload.data[0];\n \n-\tseq_puts(m, key-\u003edescription);\n-\tif (sec \u0026\u0026 sec-\u003edescribe_server_key)\n-\t\tsec-\u003edescribe_server_key(key, m);\n+\tif (krb5)\n+\t\tseq_printf(m, \": %s\", krb5-\u003ename);\n }\n+#endif\n \n /*\n- * grab the security keyring for a server socket\n+ * Preparse a server secret key.\n  */\n-int rxrpc_server_keyring(struct rxrpc_sock *rx, sockptr_t optval, int optlen)\n+static int rxrpc_preparse_s(struct key_preparsed_payload *prep)\n {\n-\tstruct key *key;\n-\tchar *description;\n+\tunsigned int service, sec_class;\n+\tint n;\n \n-\t_enter(\"\");\n+\t_enter(\"%zu\", prep-\u003edatalen);\n \n-\tif (rx-\u003esecurities)\n+\tif (!prep-\u003eorig_description)\n \t\treturn -EINVAL;\n \n-\tif (optlen \u003c= 0 || optlen \u003e PAGE_SIZE - 1)\n+\tif (sscanf(prep-\u003eorig_description, \"%u:%u%n\", \u0026service, \u0026sec_class, \u0026n) != 2)\n \t\treturn -EINVAL;\n \n-\tdescription = memdup_sockptr_nul(optval, optlen);\n-\tif (IS_ERR(description))\n-\t\treturn PTR_ERR(description);\n+\tprep-\u003epayload.data[1] = (void *)(uintptr_t)sec_class;\n \n-\tkey = request_key(\u0026key_type_keyring, description, NULL);\n-\tif (IS_ERR(key)) {\n-\t\tkfree(description);\n-\t\t_leave(\" = %ld\", PTR_ERR(key));\n-\t\treturn PTR_ERR(key);\n+\tswitch (sec_class) {\n+#ifdef CONFIG_RXKAD\n+\tcase RXRPC_SECURITY_RXKAD:\n+\t\treturn rxkad_preparse_server_key(prep);\n+#endif\n+#ifdef CONFIG_RXGK\n+\tcase RXRPC_SECURITY_YFS_RXGK:\n+\t\treturn rxgk_preparse_server_key(prep);\n+#endif\n+\tdefault:\n+\t\treturn -ENOPKG;\n \t}\n+}\n \n-\trx-\u003esecurities = key;\n-\tkfree(description);\n-\t_leave(\" = 0 [key %x]\", key-\u003eserial);\n-\treturn 0;\n+static void rxrpc_free_preparse_s(struct key_preparsed_payload *prep)\n+{\n+\tswitch ((uintptr_t)prep-\u003epayload.data[1]) {\n+#ifdef CONFIG_RXKAD\n+\tcase RXRPC_SECURITY_RXKAD:\n+\t\trxkad_free_preparse_server_key(prep);\n+\t\tbreak;\n+#endif\n+#ifdef CONFIG_RXGK\n+\tcase RXRPC_SECURITY_YFS_RXGK:\n+\t\trxgk_free_preparse_server_key(prep);\n+\t\tbreak;\n+#endif\n+\tdefault:\n+\t\tbreak;\n+\t}\n }\n \n-/**\n- * rxrpc_sock_set_security_keyring - Set the security keyring for a kernel service\n- * @sk: The socket to set the keyring on\n- * @keyring: The keyring to set\n- *\n- * Set the server security keyring on an rxrpc socket.  This is used to provide\n- * the encryption keys for a kernel service.\n- *\n- * Return: %0 if successful and a negative error code otherwise.\n- */\n-int rxrpc_sock_set_security_keyring(struct sock *sk, struct key *keyring)\n+static void rxrpc_destroy_s(struct key *key)\n {\n-\tstruct rxrpc_sock *rx = rxrpc_sk(sk);\n-\tint ret = 0;\n-\n-\tlock_sock(sk);\n-\tif (rx-\u003esecurities)\n-\t\tret = -EINVAL;\n-\telse if (rx-\u003esk.sk_state != RXRPC_UNBOUND)\n-\t\tret = -EISCONN;\n-\telse\n-\t\trx-\u003esecurities = key_get(keyring);\n-\trelease_sock(sk);\n-\treturn ret;\n+\tswitch ((uintptr_t)key-\u003epayload.data[1]) {\n+#ifdef CONFIG_RXKAD\n+\tcase RXRPC_SECURITY_RXKAD:\n+\t\trxkad_destroy_server_key(key);\n+\t\tbreak;\n+#endif\n+#ifdef CONFIG_RXGK\n+\tcase RXRPC_SECURITY_YFS_RXGK:\n+\t\trxgk_destroy_server_key(key);\n+\t\tbreak;\n+#endif\n+\tdefault:\n+\t\tbreak;\n+\t}\n }\n-EXPORT_SYMBOL(rxrpc_sock_set_security_keyring);\n \n-/**\n- * rxrpc_sock_set_manage_response - Set the manage-response flag for a kernel service\n- * @sk: The socket to set the keyring on\n- * @set: True to set, false to clear the flag\n- *\n- * Set the flag on an rxrpc socket to say that the caller wants to manage the\n- * RESPONSE packet and the user-defined data it may contain.  Setting this\n- * means that recvmsg() will return messages with RXRPC_CHALLENGED in the\n- * control message buffer containing information about the challenge.\n- *\n- * The user should respond to the challenge by passing RXRPC_RESPOND or\n- * RXRPC_RESPOND_ABORT control messages with sendmsg() to the same call.\n- * Supplementary control messages, such as RXRPC_RESP_RXGK_APPDATA, may be\n- * included to indicate the parts the user wants to supply.\n- *\n- * The server will be passed the response data with a RXRPC_RESPONDED control\n- * message when it gets the first data from each call.\n- *\n- * Note that this is only honoured by security classes that need auxiliary data\n- * (e.g. RxGK).  Those that don't offer the facility (e.g. RxKAD) respond\n- * without consulting userspace.\n- *\n- * Return: The previous setting.\n- */\n-int rxrpc_sock_set_manage_response(struct sock *sk, bool set)\n+static void rxrpc_describe_s(const struct key *key, struct seq_file *m)\n {\n-\tstruct rxrpc_sock *rx = rxrpc_sk(sk);\n-\tint ret;\n-\n-\tlock_sock(sk);\n-\tret = !!test_bit(RXRPC_SOCK_MANAGE_RESPONSE, \u0026rx-\u003eflags);\n-\tif (set)\n-\t\tset_bit(RXRPC_SOCK_MANAGE_RESPONSE, \u0026rx-\u003eflags);\n-\telse\n-\t\tclear_bit(RXRPC_SOCK_MANAGE_RESPONSE, \u0026rx-\u003eflags);\n-\trelease_sock(sk);\n-\treturn ret;\n+\tseq_puts(m, key-\u003edescription);\n+\n+\tswitch ((uintptr_t)key-\u003epayload.data[1]) {\n+#ifdef CONFIG_RXGK\n+\tcase RXRPC_SECURITY_YFS_RXGK:\n+\t\trxgk_describe_server_key(key, m);\n+\t\tbreak;\n+#endif\n+\tdefault:\n+\t\tbreak;\n+\t}\n }\n-EXPORT_SYMBOL(rxrpc_sock_set_manage_response);\ndiff --git a/security/keys/gc.c b/security/keys/gc.c\nindex eda445f815d47b..704dcc40198360 100644\n--- a/security/keys/gc.c\n+++ b/security/keys/gc.c\n@@ -6,20 +6,35 @@\n  */\n \n #include \u003clinux/slab.h\u003e\n+#include \u003clinux/module.h\u003e\n #include \u003clinux/security.h\u003e\n #include \u003ckeys/keyring-type.h\u003e\n #include \"internal.h\"\n \n-/*\n- * Delay between key revocation/expiry in seconds\n- */\n-unsigned key_gc_delay = 5 * 60;\n+#define KEY_GC_CHUNK_SIZE 64\n \n /*\n  * Reaper for unused keys.\n  */\n static void key_garbage_collector(struct work_struct *work);\n-DECLARE_WORK(key_gc_work, key_garbage_collector);\n+\n+struct workqueue_struct *key_gc_wq __ro_after_init;\n+\n+static struct {\n+\ttime64_t start;\t\t\t/* expiry range start */\n+\ttime64_t end;\t\t\t/* expiry range end */\n+\tstruct rb_node *cursor;\t\t/* serial tree position */\n+\tu8 state;\t\t\t/* state flags */\n+\tatomic_t seq;\n+\tstruct work_struct work;\t/* work item */\n+} key_gc_work = {\n+\t.work = __WORK_INITIALIZER(key_gc_work.work, key_garbage_collector),\n+};\n+\n+/*\n+ * Delay between key revocation/expiry in seconds\n+ */\n+unsigned int key_gc_delay = 5 * 60;\n \n /*\n  * Reaper for links from keyrings to dead keys.\n@@ -28,21 +43,43 @@ static void key_gc_timer_func(struct timer_list *);\n static DEFINE_TIMER(key_gc_timer, key_gc_timer_func);\n \n static time64_t key_gc_next_run = TIME64_MAX;\n-static struct key_type *key_gc_dead_keytype;\n-\n static unsigned long key_gc_flags;\n #define KEY_GC_KEY_EXPIRED\t0\t/* A key expired and needs unlinking */\n-#define KEY_GC_REAP_KEYTYPE\t1\t/* A keytype is being unregistered */\n-#define KEY_GC_REAPING_KEYTYPE\t2\t/* Cleared when keytype reaped */\n-\n+#define KEY_GC_REAP_REQUESTED\t1\t/* Another complete pass was requested */\n \n /*\n- * Any key whose type gets unregistered will be re-typed to this if it can't be\n- * immediately unlinked.\n+ * Schedule a new GC pass or re-schedule an ongoing GC pass.\n  */\n-struct key_type key_type_dead = {\n-\t.name = \".dead\",\n-};\n+void key_schedule_gc_work(bool expired)\n+{\n+\tunsigned long flags = BIT(KEY_GC_REAP_REQUESTED);\n+\n+\tif (expired)\n+\t\tflags |= BIT(KEY_GC_KEY_EXPIRED);\n+\n+\t/* Publish all request flags together, after the caller's updates. */\n+\tset_mask_bits(\u0026key_gc_flags, 0, flags);\n+\tqueue_work(key_gc_wq, \u0026key_gc_work.work);\n+}\n+\n+/**\n+ * key_gc_flush - Drain the garbage collector RCU callbacks\n+ */\n+void key_gc_flush(void)\n+{\n+\tint seq;\n+\n+\tdo {\n+\t\twhile (flush_work(\u0026key_gc_work.work) ||\n+\t\t       work_pending(\u0026key_gc_work.work))\n+\t\t\tcpu_relax();\n+\t\tseq = atomic_read_acquire(\u0026key_gc_work.seq);\n+\t\trcu_barrier();\n+\t} while (flush_work(\u0026key_gc_work.work) ||\n+\t\t work_pending(\u0026key_gc_work.work) ||\n+\t\t atomic_read_acquire(\u0026key_gc_work.seq) != seq);\n+}\n+EXPORT_SYMBOL_GPL(key_gc_flush);\n \n /*\n  * Schedule a garbage collection run.\n@@ -55,9 +92,10 @@ void key_schedule_gc(time64_t gc_at)\n \n \tkenter(\"%lld\", gc_at - now);\n \n-\tif (gc_at \u003c= now || test_bit(KEY_GC_REAP_KEYTYPE, \u0026key_gc_flags)) {\n+\tif (gc_at \u003c= now) {\n \t\tkdebug(\"IMMEDIATE\");\n-\t\tschedule_work(\u0026key_gc_work);\n+\t\t/* Catch expirations that became due during the scan. */\n+\t\tkey_schedule_gc_work(true);\n \t} else if (gc_at \u003c key_gc_next_run) {\n \t\tkdebug(\"DEFERRED\");\n \t\tkey_gc_next_run = gc_at;\n@@ -79,15 +117,6 @@ void key_set_expiry(struct key *key, time64_t expiry)\n \t}\n }\n \n-/*\n- * Schedule a dead links collection run.\n- */\n-void key_schedule_gc_links(void)\n-{\n-\tset_bit(KEY_GC_KEY_EXPIRED, \u0026key_gc_flags);\n-\tschedule_work(\u0026key_gc_work);\n-}\n-\n /*\n  * Some key's cleanup time was met after it expired, so we need to get the\n  * reaper to go through a cycle finding expired keys.\n@@ -96,37 +125,7 @@ static void key_gc_timer_func(struct timer_list *unused)\n {\n \tkenter(\"\");\n \tkey_gc_next_run = TIME64_MAX;\n-\tkey_schedule_gc_links();\n-}\n-\n-/*\n- * Reap keys of dead type.\n- *\n- * We use three flags to make sure we see three complete cycles of the garbage\n- * collector: the first to mark keys of that type as being dead, the second to\n- * collect dead links and the third to clean up the dead keys.  We have to be\n- * careful as there may already be a cycle in progress.\n- *\n- * The caller must be holding key_types_sem.\n- */\n-void key_gc_keytype(struct key_type *ktype)\n-{\n-\tkenter(\"%s\", ktype-\u003ename);\n-\n-\tkey_gc_dead_keytype = ktype;\n-\tset_bit(KEY_GC_REAPING_KEYTYPE, \u0026key_gc_flags);\n-\tsmp_mb();\n-\tset_bit(KEY_GC_REAP_KEYTYPE, \u0026key_gc_flags);\n-\n-\tkdebug(\"schedule\");\n-\tschedule_work(\u0026key_gc_work);\n-\n-\tkdebug(\"sleep\");\n-\twait_on_bit(\u0026key_gc_flags, KEY_GC_REAPING_KEYTYPE,\n-\t\t    TASK_UNINTERRUPTIBLE);\n-\n-\tkey_gc_dead_keytype = NULL;\n-\tkleave(\"\");\n+\tkey_schedule_gc_work(true);\n }\n \n /*\n@@ -134,9 +133,12 @@ void key_gc_keytype(struct key_type *ktype)\n  */\n static noinline void key_gc_unused_keys(struct list_head *keys)\n {\n-\twhile (!list_empty(keys)) {\n+\tunsigned int chunk = KEY_GC_CHUNK_SIZE;\n+\n+\twhile (!list_empty(keys) \u0026\u0026 chunk--) {\n \t\tstruct key *key =\n \t\t\tlist_entry(keys-\u003enext, struct key, graveyard_link);\n+\t\tstruct module *owner = key-\u003etype-\u003eowner;\n \t\tshort state = key-\u003estate;\n \n \t\tlist_del(\u0026key-\u003egraveyard_link);\n@@ -150,8 +152,15 @@ static noinline void key_gc_unused_keys(struct list_head *keys)\n #endif\n \n \t\t/* Throw away the key data if the key is instantiated */\n-\t\tif (state == KEY_IS_POSITIVE \u0026\u0026 key-\u003etype-\u003edestroy)\n-\t\t\tkey-\u003etype-\u003edestroy(key);\n+\t\tif (state == KEY_IS_POSITIVE) {\n+\t\t\tif (key-\u003etype-\u003edestroy)\n+\t\t\t\tkey-\u003etype-\u003edestroy(key);\n+\t\t} else if (key-\u003erestrict_link) {\n+\t\t\tif (key-\u003erestrict_link-\u003ekeytype)\n+\t\t\t\tmodule_put(key-\u003erestrict_link-\u003ekeytype-\u003eowner);\n+\t\t\tkey_put(key-\u003erestrict_link-\u003ekey);\n+\t\t\tkfree(key-\u003erestrict_link);\n+\t\t}\n \n \t\tsecurity_key_free(key);\n \n@@ -165,6 +174,7 @@ static noinline void key_gc_unused_keys(struct list_head *keys)\n \n \t\tmemzero_explicit(key, sizeof(*key));\n \t\tkmem_cache_free(key_jar, key);\n+\t\tmodule_put(owner);\n \t}\n }\n \n@@ -178,89 +188,67 @@ static noinline void key_gc_unused_keys(struct list_head *keys)\n static void key_garbage_collector(struct work_struct *work)\n {\n \tstatic LIST_HEAD(graveyard);\n-\tstatic u8 gc_state;\t\t/* Internal persistent state */\n+\ttypeof(key_gc_work) *gc = \u0026key_gc_work;\n #define KEY_GC_REAP_AGAIN\t0x01\t/* - Need another cycle */\n #define KEY_GC_REAPING_LINKS\t0x02\t/* - We need to reap links */\n-#define KEY_GC_REAPING_DEAD_1\t0x10\t/* - We need to mark dead keys */\n-#define KEY_GC_REAPING_DEAD_2\t0x20\t/* - We need to reap dead key links */\n-#define KEY_GC_REAPING_DEAD_3\t0x40\t/* - We need to reap dead keys */\n-#define KEY_GC_FOUND_DEAD_KEY\t0x80\t/* - We found at least one dead key */\n+#define KEY_GC_DESTROYING\t0x04\t/* - We need to destroy keys */\n \n-\tstruct rb_node *cursor;\n+\tunsigned int chunk = KEY_GC_CHUNK_SIZE;\n+\tunsigned long flags;\n \tstruct key *key;\n-\ttime64_t new_timer, limit, expiry;\n-\n-\tkenter(\"[%lx,%x]\", key_gc_flags, gc_state);\n+\ttime64_t expiry;\n \n-\tlimit = ktime_get_real_seconds();\n+\tkenter(\"[%lx,%x]\", key_gc_flags, gc-\u003estate);\n \n-\t/* Work out what we're going to be doing in this pass */\n-\tgc_state \u0026= KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2;\n-\tgc_state \u003c\u003c= 1;\n-\tif (test_and_clear_bit(KEY_GC_KEY_EXPIRED, \u0026key_gc_flags))\n-\t\tgc_state |= KEY_GC_REAPING_LINKS;\n+\tif (gc-\u003estate \u0026 KEY_GC_DESTROYING)\n+\t\tgoto destroy_keys;\n+\tif (gc-\u003ecursor) {\n+\t\tspin_lock(\u0026key_serial_lock);\n+\t\tgoto continue_scanning;\n+\t}\n \n-\tif (test_and_clear_bit(KEY_GC_REAP_KEYTYPE, \u0026key_gc_flags))\n-\t\tgc_state |= KEY_GC_REAPING_DEAD_1;\n-\tkdebug(\"new pass %x\", gc_state);\n+\tflags = xchg(\u0026key_gc_flags, 0);\n+\tgc-\u003estart = ktime_get_real_seconds();\n+\tgc-\u003estate = 0;\n+\tif (flags \u0026 BIT(KEY_GC_KEY_EXPIRED))\n+\t\tgc-\u003estate |= KEY_GC_REAPING_LINKS;\n+\tkdebug(\"new pass %x\", gc-\u003estate);\n \n-\tnew_timer = TIME64_MAX;\n+\tgc-\u003eend = TIME64_MAX;\n \n \t/* As only this function is permitted to remove things from the key\n \t * serial tree, if cursor is non-NULL then it will always point to a\n \t * valid node in the tree - even if lock got dropped.\n \t */\n \tspin_lock(\u0026key_serial_lock);\n-\tcursor = rb_first(\u0026key_serial_tree);\n+\tgc-\u003ecursor = rb_first(\u0026key_serial_tree);\n \n continue_scanning:\n-\twhile (cursor) {\n-\t\tkey = rb_entry(cursor, struct key, serial_node);\n-\t\tcursor = rb_next(cursor);\n+\twhile (gc-\u003ecursor \u0026\u0026 chunk) {\n+\t\tkey = rb_entry(gc-\u003ecursor, struct key, serial_node);\n+\t\tgc-\u003ecursor = rb_next(gc-\u003ecursor);\n+\t\tchunk--;\n \n \t\tif (!test_bit_acquire(KEY_FLAG_USER_ALIVE, \u0026key-\u003eflags)) {\n \t\t\t/* Clobber key-\u003euser after final put seen. */\n \t\t\tgoto found_unreferenced_key;\n \t\t}\n \n-\t\tif (unlikely(gc_state \u0026 KEY_GC_REAPING_DEAD_1)) {\n-\t\t\tif (key-\u003etype == key_gc_dead_keytype) {\n-\t\t\t\tgc_state |= KEY_GC_FOUND_DEAD_KEY;\n-\t\t\t\tset_bit(KEY_FLAG_DEAD, \u0026key-\u003eflags);\n-\t\t\t\tkey-\u003eperm = 0;\n-\t\t\t\tgoto skip_dead_key;\n-\t\t\t} else if (key-\u003etype == \u0026key_type_keyring \u0026\u0026\n-\t\t\t\t   key-\u003erestrict_link) {\n-\t\t\t\tgoto found_restricted_keyring;\n-\t\t\t}\n-\t\t}\n-\n \t\texpiry = key-\u003eexpiry;\n \t\tif (expiry != TIME64_MAX) {\n \t\t\tif (!(key-\u003etype-\u003eflags \u0026 KEY_TYPE_INSTANT_REAP))\n \t\t\t\texpiry += key_gc_delay;\n-\t\t\tif (expiry \u003e limit \u0026\u0026 expiry \u003c new_timer) {\n+\t\t\tif (expiry \u003e gc-\u003estart \u0026\u0026 expiry \u003c gc-\u003eend) {\n \t\t\t\tkdebug(\"will expire %x in %lld\",\n-\t\t\t\t       key_serial(key), key-\u003eexpiry - limit);\n-\t\t\t\tnew_timer = key-\u003eexpiry;\n+\t\t\t\t       key_serial(key), expiry - gc-\u003estart);\n+\t\t\t\tgc-\u003eend = expiry;\n \t\t\t}\n \t\t}\n \n-\t\tif (unlikely(gc_state \u0026 KEY_GC_REAPING_DEAD_2))\n-\t\t\tif (key-\u003etype == key_gc_dead_keytype)\n-\t\t\t\tgc_state |= KEY_GC_FOUND_DEAD_KEY;\n+\t\tif ((gc-\u003estate \u0026 KEY_GC_REAPING_LINKS) \u0026\u0026\n+\t\t    key-\u003etype == \u0026key_type_keyring)\n+\t\t\tgoto found_keyring;\n \n-\t\tif ((gc_state \u0026 KEY_GC_REAPING_LINKS) ||\n-\t\t    unlikely(gc_state \u0026 KEY_GC_REAPING_DEAD_2)) {\n-\t\t\tif (key-\u003etype == \u0026key_type_keyring)\n-\t\t\t\tgoto found_keyring;\n-\t\t}\n-\n-\t\tif (unlikely(gc_state \u0026 KEY_GC_REAPING_DEAD_3))\n-\t\t\tif (key-\u003etype == key_gc_dead_keytype)\n-\t\t\t\tgoto destroy_dead_key;\n-\n-\tskip_dead_key:\n \t\tif (spin_is_contended(\u0026key_serial_lock) || need_resched())\n \t\t\tgoto contended;\n \t}\n@@ -269,7 +257,11 @@ static void key_garbage_collector(struct work_struct *work)\n \tspin_unlock(\u0026key_serial_lock);\n \n maybe_resched:\n-\tif (cursor) {\n+\tif (gc-\u003ecursor) {\n+\t\tif (!chunk) {\n+\t\t\tqueue_work(key_gc_wq, \u0026key_gc_work.work);\n+\t\t\tgoto out;\n+\t\t}\n \t\tcond_resched();\n \t\tspin_lock(\u0026key_serial_lock);\n \t\tgoto continue_scanning;\n@@ -281,13 +273,10 @@ static void key_garbage_collector(struct work_struct *work)\n \t */\n \tkdebug(\"pass complete\");\n \n-\tif (new_timer != TIME64_MAX) {\n-\t\tnew_timer += key_gc_delay;\n-\t\tkey_schedule_gc(new_timer);\n-\t}\n+\tif (gc-\u003eend != TIME64_MAX)\n+\t\tkey_schedule_gc(gc-\u003eend);\n \n-\tif (unlikely(gc_state \u0026 KEY_GC_REAPING_DEAD_2) ||\n-\t    !list_empty(\u0026graveyard)) {\n+\tif (!list_empty(\u0026graveyard)) {\n \t\t/* Make sure that all pending keyring payload destructions are\n \t\t * fulfilled and that people aren't now looking at dead or\n \t\t * dying keys that they don't have a reference upon or a link\n@@ -297,33 +286,25 @@ static void key_garbage_collector(struct work_struct *work)\n \t\tsynchronize_rcu();\n \t}\n \n+\tgc-\u003estate |= KEY_GC_DESTROYING;\n+\n+destroy_keys:\n \tif (!list_empty(\u0026graveyard)) {\n \t\tkdebug(\"gc keys\");\n \t\tkey_gc_unused_keys(\u0026graveyard);\n-\t}\n-\n-\tif (unlikely(gc_state \u0026 (KEY_GC_REAPING_DEAD_1 |\n-\t\t\t\t KEY_GC_REAPING_DEAD_2))) {\n-\t\tif (!(gc_state \u0026 KEY_GC_FOUND_DEAD_KEY)) {\n-\t\t\t/* No remaining dead keys: short circuit the remaining\n-\t\t\t * keytype reap cycles.\n-\t\t\t */\n-\t\t\tkdebug(\"dead short\");\n-\t\t\tgc_state \u0026= ~(KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2);\n-\t\t\tgc_state |= KEY_GC_REAPING_DEAD_3;\n-\t\t} else {\n-\t\t\tgc_state |= KEY_GC_REAP_AGAIN;\n+\t\tif (!list_empty(\u0026graveyard)) {\n+\t\t\tqueue_work(key_gc_wq, \u0026key_gc_work.work);\n+\t\t\tgoto out;\n \t\t}\n \t}\n-\n-\tif (unlikely(gc_state \u0026 KEY_GC_REAPING_DEAD_3)) {\n-\t\tkdebug(\"dead wake\");\n-\t\tclear_and_wake_up_bit(KEY_GC_REAPING_KEYTYPE, \u0026key_gc_flags);\n-\t}\n-\n-\tif (gc_state \u0026 KEY_GC_REAP_AGAIN)\n-\t\tschedule_work(\u0026key_gc_work);\n-\tkleave(\" [end %x]\", gc_state);\n+\tgc-\u003estate \u0026= ~KEY_GC_DESTROYING;\n+\n+\tif ((gc-\u003estate \u0026 KEY_GC_REAP_AGAIN) ||\n+\t    test_bit(KEY_GC_REAP_REQUESTED, \u0026key_gc_flags))\n+\t\tqueue_work(key_gc_wq, \u0026key_gc_work.work);\n+out:\n+\tatomic_inc_return(\u0026gc-\u003eseq);\n+\tkleave(\" [end %x]\", gc-\u003estate);\n \treturn;\n \n \t/* We found an unreferenced key - once we've removed it from the tree,\n@@ -335,15 +316,7 @@ static void key_garbage_collector(struct work_struct *work)\n \tspin_unlock(\u0026key_serial_lock);\n \n \tlist_add_tail(\u0026key-\u003egraveyard_link, \u0026graveyard);\n-\tgc_state |= KEY_GC_REAP_AGAIN;\n-\tgoto maybe_resched;\n-\n-\t/* We found a restricted keyring and need to update the restriction if\n-\t * it is associated with the dead key type.\n-\t */\n-found_restricted_keyring:\n-\tspin_unlock(\u0026key_serial_lock);\n-\tkeyring_restriction_gc(key, key_gc_dead_keytype);\n+\tgc-\u003estate |= KEY_GC_REAP_AGAIN;\n \tgoto maybe_resched;\n \n \t/* We found a keyring and we need to check the payload for links to\n@@ -353,20 +326,6 @@ static void key_garbage_collector(struct work_struct *work)\n \t */\n found_keyring:\n \tspin_unlock(\u0026key_serial_lock);\n-\tkeyring_gc(key, limit);\n-\tgoto maybe_resched;\n-\n-\t/* We found a dead key that is still referenced.  Reset its type and\n-\t * destroy its payload with its semaphore held.\n-\t */\n-destroy_dead_key:\n-\tspin_unlock(\u0026key_serial_lock);\n-\tkdebug(\"destroy key %d\", key-\u003eserial);\n-\tdown_write(\u0026key-\u003esem);\n-\tkey-\u003etype = \u0026key_type_dead;\n-\tif (key_gc_dead_keytype-\u003edestroy)\n-\t\tkey_gc_dead_keytype-\u003edestroy(key);\n-\tmemset(\u0026key-\u003epayload, KEY_DESTROY, sizeof(key-\u003epayload));\n-\tup_write(\u0026key-\u003esem);\n+\tkeyring_gc(key, gc-\u003estart);\n \tgoto maybe_resched;\n }\ndiff --git a/security/keys/internal.h b/security/keys/internal.h\nindex b7b622bc36a137..6b5bb63b0e9e12 100644\n--- a/security/keys/internal.h\n+++ b/security/keys/internal.h\n@@ -38,7 +38,6 @@ struct iovec;\n \tno_printk(KERN_DEBUG FMT\"\\n\", ##__VA_ARGS__)\n #endif\n \n-extern struct key_type key_type_dead;\n extern struct key_type key_type_user;\n extern struct key_type key_type_logon;\n \n@@ -162,15 +161,12 @@ extern bool lookup_user_key_possessed(const struct key *key,\n extern long join_session_keyring(const char *name);\n extern void key_change_session_keyring(struct callback_head *twork);\n \n-extern struct work_struct key_gc_work;\n extern unsigned key_gc_delay;\n+extern struct workqueue_struct *key_gc_wq;\n extern void keyring_gc(struct key *keyring, time64_t limit);\n-extern void keyring_restriction_gc(struct key *keyring,\n-\t\t\t\t   struct key_type *dead_type);\n void key_set_expiry(struct key *key, time64_t expiry);\n extern void key_schedule_gc(time64_t gc_at);\n-extern void key_schedule_gc_links(void);\n-extern void key_gc_keytype(struct key_type *ktype);\n+void key_schedule_gc_work(bool expired);\n \n extern int key_task_permission(const key_ref_t key_ref,\n \t\t\t       const struct cred *cred,\ndiff --git a/security/keys/key.c b/security/keys/key.c\nindex 3f1f0fc137109a..53106bee2d27cb 100644\n--- a/security/keys/key.c\n+++ b/security/keys/key.c\n@@ -7,6 +7,7 @@\n \n #include \u003clinux/export.h\u003e\n #include \u003clinux/init.h\u003e\n+#include \u003clinux/module.h\u003e\n #include \u003clinux/poison.h\u003e\n #include \u003clinux/sched.h\u003e\n #include \u003clinux/slab.h\u003e\n@@ -234,19 +235,34 @@ struct key *key_alloc(struct key_type *type, const char *desc,\n \n \tkey = ERR_PTR(-EINVAL);\n \tif (!desc || !*desc)\n-\t\tgoto error;\n+\t\tgoto out;\n+\n+\t/* Failed module initialization ignores outstanding module references. */\n+\tif ((type-\u003eowner \u0026\u0026 module_is_coming(type-\u003eowner)) ||\n+\t    !try_module_get(type-\u003eowner)) {\n+\t\tkey = ERR_PTR(-ENOENT);\n+\t\tgoto out;\n+\t}\n+\n+\tif (restrict_link \u0026\u0026 restrict_link-\u003ekeytype \u0026\u0026\n+\t    ((restrict_link-\u003ekeytype-\u003eowner \u0026\u0026\n+\t      module_is_coming(restrict_link-\u003ekeytype-\u003eowner)) ||\n+\t     !try_module_get(restrict_link-\u003ekeytype-\u003eowner))) {\n+\t\tkey = ERR_PTR(-ENOENT);\n+\t\tgoto out_put_module;\n+\t}\n \n \tif (type-\u003evet_description) {\n \t\tret = type-\u003evet_description(desc);\n \t\tif (ret \u003c 0) {\n \t\t\tkey = ERR_PTR(ret);\n-\t\t\tgoto error;\n+\t\t\tgoto out_put_restrict_module;\n \t\t}\n \t}\n \n \tdesclen = strlen(desc);\n \tif (desclen \u003e= KEY_MAX_DESC_SIZE)\n-\t\tgoto error;\n+\t\tgoto out_put_restrict_module;\n \tquotalen = desclen + 1 + type-\u003edef_datalen;\n \n \t/* get hold of the key tracking for this user */\n@@ -323,8 +339,6 @@ struct key *key_alloc(struct key_type *type, const char *desc,\n \trefcount_inc(\u0026key-\u003edomain_tag-\u003eusage);\n \tatomic_inc(\u0026user-\u003enkeys);\n \tkey_alloc_serial(key);\n-\n-error:\n \treturn key;\n \n security_error:\n@@ -338,7 +352,7 @@ struct key *key_alloc(struct key_type *type, const char *desc,\n \t}\n \tkey_user_put(user);\n \tkey = ERR_PTR(ret);\n-\tgoto error;\n+\tgoto out_put_restrict_module;\n \n no_memory_3:\n \tkmem_cache_free(key_jar, key);\n@@ -352,13 +366,22 @@ struct key *key_alloc(struct key_type *type, const char *desc,\n \tkey_user_put(user);\n no_memory_1:\n \tkey = ERR_PTR(-ENOMEM);\n-\tgoto error;\n+\tgoto out_put_restrict_module;\n \n no_quota:\n \tspin_unlock_irqrestore(\u0026user-\u003elock, irqflags);\n \tkey_user_put(user);\n \tkey = ERR_PTR(-EDQUOT);\n-\tgoto error;\n+\n+out_put_restrict_module:\n+\tif (restrict_link \u0026\u0026 restrict_link-\u003ekeytype)\n+\t\tmodule_put(restrict_link-\u003ekeytype-\u003eowner);\n+\n+out_put_module:\n+\tmodule_put(type-\u003eowner);\n+\n+out:\n+\treturn key;\n }\n EXPORT_SYMBOL(key_alloc);\n \n@@ -670,7 +693,7 @@ void key_put(struct key *key)\n \t\t\t}\n \t\t\t/* Mark key as safe for GC after key-\u003euser done. */\n \t\t\tclear_bit_unlock(KEY_FLAG_USER_ALIVE, \u0026key-\u003eflags);\n-\t\t\tschedule_work(\u0026key_gc_work);\n+\t\t\tkey_schedule_gc_work(false);\n \t\t}\n \t}\n }\n@@ -1191,7 +1214,7 @@ void key_invalidate(struct key *key)\n \t\tdown_write_nested(\u0026key-\u003esem, 1);\n \t\tif (!test_and_set_bit(KEY_FLAG_INVALIDATED, \u0026key-\u003eflags)) {\n \t\t\tnotify_key(key, NOTIFY_KEY_INVALIDATED, 0);\n-\t\t\tkey_schedule_gc_links();\n+\t\t\tkey_schedule_gc_work(true);\n \t\t}\n \t\tup_write(\u0026key-\u003esem);\n \t}\n@@ -1231,19 +1254,20 @@ int generic_key_instantiate(struct key *key, struct key_preparsed_payload *prep)\n EXPORT_SYMBOL(generic_key_instantiate);\n \n /**\n- * register_key_type - Register a type of key.\n+ * __register_key_type - Register a type of key.\n  * @ktype: The new key type.\n+ * @owner: Module owning the key type.\n  *\n  * Register a new key type.\n  *\n  * Returns 0 on success or -EEXIST if a type of this name already exists.\n  */\n-int register_key_type(struct key_type *ktype)\n+int __register_key_type(struct key_type *ktype, struct module *owner)\n {\n \tstruct key_type *p;\n \tint ret;\n \n-\tmemset(\u0026ktype-\u003elock_class, 0, sizeof(ktype-\u003elock_class));\n+\tktype-\u003eowner = owner;\n \n \tret = -EEXIST;\n \tdown_write(\u0026key_types_sem);\n@@ -1264,24 +1288,20 @@ int register_key_type(struct key_type *ktype)\n \tup_write(\u0026key_types_sem);\n \treturn ret;\n }\n-EXPORT_SYMBOL(register_key_type);\n+EXPORT_SYMBOL(__register_key_type);\n \n /**\n  * unregister_key_type - Unregister a type of key.\n  * @ktype: The key type.\n  *\n- * Unregister a key type and mark all the extant keys of this type as dead.\n- * Those keys of this type are then destroyed to get rid of their payloads and\n- * they and their links will be garbage collected as soon as possible.\n+ * Unregister a key type.\n  */\n void unregister_key_type(struct key_type *ktype)\n {\n \tdown_write(\u0026key_types_sem);\n \tlist_del_init(\u0026ktype-\u003elink);\n-\tdowngrade_write(\u0026key_types_sem);\n-\tkey_gc_keytype(ktype);\n \tpr_notice(\"Key type %s unregistered\\n\", ktype-\u003ename);\n-\tup_read(\u0026key_types_sem);\n+\tup_write(\u0026key_types_sem);\n }\n EXPORT_SYMBOL(unregister_key_type);\n \n@@ -1294,9 +1314,12 @@ void __init key_init(void)\n \tkey_jar = kmem_cache_create(\"key_jar\", sizeof(struct key),\n \t\t\t0, SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_NO_MERGE, NULL);\n \n+\tkey_gc_wq = alloc_workqueue(\"key_gc\", WQ_MEM_RECLAIM | WQ_PERCPU, 0);\n+\tif (!key_gc_wq)\n+\t\tpanic(\"Cannot create key_gc workqueue\\n\");\n+\n \t/* add the special key types */\n \tlist_add_tail(\u0026key_type_keyring.link, \u0026key_types_list);\n-\tlist_add_tail(\u0026key_type_dead.link, \u0026key_types_list);\n \tlist_add_tail(\u0026key_type_user.link, \u0026key_types_list);\n \tlist_add_tail(\u0026key_type_logon.link, \u0026key_types_list);\n \ndiff --git a/security/keys/keyring.c b/security/keys/keyring.c\nindex 357f5636081055..7776983c3fdac7 100644\n--- a/security/keys/keyring.c\n+++ b/security/keys/keyring.c\n@@ -7,6 +7,7 @@\n \n #include \u003clinux/export.h\u003e\n #include \u003clinux/init.h\u003e\n+#include \u003clinux/module.h\u003e\n #include \u003clinux/sched.h\u003e\n #include \u003clinux/slab.h\u003e\n #include \u003clinux/security.h\u003e\n@@ -265,7 +266,7 @@ void key_remove_domain(struct key_tag *domain_tag)\n {\n \tdomain_tag-\u003eremoved = true;\n \tif (!key_put_tag(domain_tag))\n-\t\tkey_schedule_gc_links();\n+\t\tkey_schedule_gc_work(true);\n }\n \n /*\n@@ -436,6 +437,9 @@ static void keyring_destroy(struct key *keyring)\n \tif (keyring-\u003erestrict_link) {\n \t\tstruct key_restriction *keyres = keyring-\u003erestrict_link;\n \n+\t\tif (keyres-\u003ekeytype)\n+\t\t\tmodule_put(keyres-\u003ekeytype-\u003eowner);\n+\n \t\tkey_put(keyres-\u003ekey);\n \t\tkfree(keyres);\n \t}\n@@ -540,6 +544,9 @@ struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,\n \tif (!IS_ERR(keyring)) {\n \t\tret = key_instantiate_and_link(keyring, NULL, 0, dest, NULL);\n \t\tif (ret \u003c 0) {\n+\t\t\tif (restrict_link \u0026\u0026 restrict_link-\u003ekeytype)\n+\t\t\t\tmodule_put(restrict_link-\u003ekeytype-\u003eowner);\n+\t\t\tkeyring-\u003erestrict_link = NULL;\n \t\t\tkey_put(keyring);\n \t\t\tkeyring = ERR_PTR(ret);\n \t\t}\n@@ -1062,7 +1069,7 @@ int keyring_restrict(key_ref_t keyring_ref, const char *type,\n \n \t\tif (!restrict_type-\u003elookup_restriction) {\n \t\t\tret = -ENOENT;\n-\t\t\tgoto error;\n+\t\t\tgoto out;\n \t\t}\n \n \t\trestrict_link = restrict_type-\u003elookup_restriction(restriction);\n@@ -1070,7 +1077,15 @@ int keyring_restrict(key_ref_t keyring_ref, const char *type,\n \n \tif (IS_ERR(restrict_link)) {\n \t\tret = PTR_ERR(restrict_link);\n-\t\tgoto error;\n+\t\tgoto out;\n+\t}\n+\n+\tif (restrict_link \u0026\u0026 restrict_link-\u003ekeytype \u0026\u0026\n+\t    ((restrict_link-\u003ekeytype-\u003eowner \u0026\u0026\n+\t      module_is_coming(restrict_link-\u003ekeytype-\u003eowner)) ||\n+\t     !try_module_get(restrict_link-\u003ekeytype-\u003eowner))) {\n+\t\tret = -ENOENT;\n+\t\tgoto out_free_restriction;\n \t}\n \n \tdown_write(\u0026keyring-\u003esem);\n@@ -1088,12 +1103,21 @@ int keyring_restrict(key_ref_t keyring_ref, const char *type,\n \tup_write(\u0026keyring_serialise_restrict_sem);\n \tup_write(\u0026keyring-\u003esem);\n \n-\tif (ret \u003c 0) {\n+\tif (ret \u003c 0)\n+\t\tgoto out_put_module;\n+\n+\tgoto out;\n+\n+out_put_module:\n+\tif (restrict_link \u0026\u0026 restrict_link-\u003ekeytype)\n+\t\tmodule_put(restrict_link-\u003ekeytype-\u003eowner);\n+\n+out_free_restriction:\n+\tif (restrict_link)\n \t\tkey_put(restrict_link-\u003ekey);\n-\t\tkfree(restrict_link);\n-\t}\n+\tkfree(restrict_link);\n \n-error:\n+out:\n \tif (restrict_type)\n \t\tkey_type_put(restrict_type);\n \n@@ -1769,53 +1793,3 @@ void keyring_gc(struct key *keyring, time64_t limit)\n \tup_write(\u0026keyring-\u003esem);\n \tkleave(\" [gc]\");\n }\n-\n-/*\n- * Garbage collect restriction pointers from a keyring.\n- *\n- * Keyring restrictions are associated with a key type, and must be cleaned\n- * up if the key type is unregistered. The restriction is altered to always\n- * reject additional keys so a keyring cannot be opened up by unregistering\n- * a key type.\n- *\n- * Not called with any keyring locks held. The keyring's key struct will not\n- * be deallocated under us as only our caller may deallocate it.\n- *\n- * The caller is required to hold key_types_sem and dead_type-\u003esem. This is\n- * fulfilled by key_gc_keytype() holding the locks on behalf of\n- * key_garbage_collector(), which it invokes on a workqueue.\n- */\n-void keyring_restriction_gc(struct key *keyring, struct key_type *dead_type)\n-{\n-\tstruct key_restriction *keyres;\n-\n-\tkenter(\"%x{%s}\", keyring-\u003eserial, keyring-\u003edescription ?: \"\");\n-\n-\t/*\n-\t * keyring-\u003erestrict_link is only assigned at key allocation time\n-\t * or with the key type locked, so the only values that could be\n-\t * concurrently assigned to keyring-\u003erestrict_link are for key\n-\t * types other than dead_type. Given this, it's ok to check\n-\t * the key type before acquiring keyring-\u003esem.\n-\t */\n-\tif (!dead_type || !keyring-\u003erestrict_link ||\n-\t    keyring-\u003erestrict_link-\u003ekeytype != dead_type) {\n-\t\tkleave(\" [no restriction gc]\");\n-\t\treturn;\n-\t}\n-\n-\t/* Lock the keyring to ensure that a link is not in progress */\n-\tdown_write(\u0026keyring-\u003esem);\n-\n-\tkeyres = keyring-\u003erestrict_link;\n-\n-\tkeyres-\u003echeck = restrict_link_reject;\n-\n-\tkey_put(keyres-\u003ekey);\n-\tkeyres-\u003ekey = NULL;\n-\tkeyres-\u003ekeytype = NULL;\n-\n-\tup_write(\u0026keyring-\u003esem);\n-\n-\tkleave(\" [restriction gc]\");\n-}\ndiff --git a/security/keys/trusted-keys/trusted_core.c b/security/keys/trusted-keys/trusted_core.c\nindex 0509d9955f2a6f..11d7d296d063c2 100644\n--- a/security/keys/trusted-keys/trusted_core.c\n+++ b/security/keys/trusted-keys/trusted_core.c\n@@ -373,14 +373,19 @@ static int __init init_trusted(void)\n \t\tif (!get_random)\n \t\t\tget_random = kernel_get_random;\n \n+\t\tstatic_call_update(trusted_key_seal, trusted_key_sources[i].ops-\u003eseal);\n+\t\tstatic_call_update(trusted_key_unseal, trusted_key_sources[i].ops-\u003eunseal);\n+\t\tstatic_call_update(trusted_key_get_random, get_random);\n+\t\tmigratable = trusted_key_sources[i].ops-\u003emigratable;\n+\n \t\tret = trusted_key_sources[i].ops-\u003einit();\n \t\tif (!ret) {\n-\t\t\tstatic_call_update(trusted_key_seal, trusted_key_sources[i].ops-\u003eseal);\n-\t\t\tstatic_call_update(trusted_key_unseal, trusted_key_sources[i].ops-\u003eunseal);\n-\t\t\tstatic_call_update(trusted_key_get_random, get_random);\n-\n \t\t\ttrusted_key_exit = trusted_key_sources[i].ops-\u003eexit;\n-\t\t\tmigratable = trusted_key_sources[i].ops-\u003emigratable;\n+\t\t} else {\n+\t\t\tstatic_call_update(trusted_key_seal, NULL);\n+\t\t\tstatic_call_update(trusted_key_unseal, NULL);\n+\t\t\tstatic_call_update(trusted_key_get_random, NULL);\n+\t\t\tmigratable = 0;\n \t\t}\n \n \t\tif (!ret || ret != -ENODEV)\ndiff --git a/security/keys/trusted-keys/trusted_tee.c b/security/keys/trusted-keys/trusted_tee.c\nindex 6e465c8bef5e5b..87ea549f7f0b97 100644\n--- a/security/keys/trusted-keys/trusted_tee.c\n+++ b/security/keys/trusted-keys/trusted_tee.c\n@@ -9,6 +9,7 @@\n #include \u003clinux/err.h\u003e\n #include \u003clinux/key-type.h\u003e\n #include \u003clinux/module.h\u003e\n+#include \u003clinux/mutex.h\u003e\n #include \u003clinux/slab.h\u003e\n #include \u003clinux/string.h\u003e\n #include \u003clinux/tee_drv.h\u003e\n@@ -56,6 +57,8 @@ struct trusted_key_tee_private {\n };\n \n static struct trusted_key_tee_private pvt_data;\n+/* Do not hold this mutex across key type registration or unregistration. */\n+static DEFINE_MUTEX(trusted_key_tee_mutex);\n \n /*\n  * Have the TEE seal(encrypt) the symmetric key\n@@ -67,6 +70,12 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob)\n \tstruct tee_param param[4];\n \tstruct tee_shm *reg_shm = NULL;\n \n+\tmutex_lock(\u0026trusted_key_tee_mutex);\n+\tif (!pvt_data.ctx) {\n+\t\tret = -ENODEV;\n+\t\tgoto out_unlock;\n+\t}\n+\n \tmemset(\u0026inv_arg, 0, sizeof(inv_arg));\n \tmemset(\u0026param, 0, sizeof(param));\n \n@@ -74,7 +83,8 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob)\n \t\t\t\t\t      sizeof(p-\u003ekey) + sizeof(p-\u003eblob));\n \tif (IS_ERR(reg_shm)) {\n \t\tdev_err(pvt_data.dev, \"shm register failed\\n\");\n-\t\treturn PTR_ERR(reg_shm);\n+\t\tret = PTR_ERR(reg_shm);\n+\t\tgoto out_unlock;\n \t}\n \n \tinv_arg.func = TA_CMD_SEAL;\n@@ -100,7 +110,8 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob)\n \t}\n \n \ttee_shm_free(reg_shm);\n-\n+out_unlock:\n+\tmutex_unlock(\u0026trusted_key_tee_mutex);\n \treturn ret;\n }\n \n@@ -114,6 +125,12 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob)\n \tstruct tee_param param[4];\n \tstruct tee_shm *reg_shm = NULL;\n \n+\tmutex_lock(\u0026trusted_key_tee_mutex);\n+\tif (!pvt_data.ctx) {\n+\t\tret = -ENODEV;\n+\t\tgoto out_unlock;\n+\t}\n+\n \tmemset(\u0026inv_arg, 0, sizeof(inv_arg));\n \tmemset(\u0026param, 0, sizeof(param));\n \n@@ -121,7 +138,8 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob)\n \t\t\t\t\t      sizeof(p-\u003ekey) + sizeof(p-\u003eblob));\n \tif (IS_ERR(reg_shm)) {\n \t\tdev_err(pvt_data.dev, \"shm register failed\\n\");\n-\t\treturn PTR_ERR(reg_shm);\n+\t\tret = PTR_ERR(reg_shm);\n+\t\tgoto out_unlock;\n \t}\n \n \tinv_arg.func = TA_CMD_UNSEAL;\n@@ -147,7 +165,8 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob)\n \t}\n \n \ttee_shm_free(reg_shm);\n-\n+out_unlock:\n+\tmutex_unlock(\u0026trusted_key_tee_mutex);\n \treturn ret;\n }\n \n@@ -161,13 +180,20 @@ static int trusted_tee_get_random(unsigned char *key, size_t key_len)\n \tstruct tee_param param[4];\n \tstruct tee_shm *reg_shm = NULL;\n \n+\tmutex_lock(\u0026trusted_key_tee_mutex);\n+\tif (!pvt_data.ctx) {\n+\t\tret = -ENODEV;\n+\t\tgoto out_unlock;\n+\t}\n+\n \tmemset(\u0026inv_arg, 0, sizeof(inv_arg));\n \tmemset(\u0026param, 0, sizeof(param));\n \n \treg_shm = tee_shm_register_kernel_buf(pvt_data.ctx, key, key_len);\n \tif (IS_ERR(reg_shm)) {\n \t\tdev_err(pvt_data.dev, \"key shm register failed\\n\");\n-\t\treturn PTR_ERR(reg_shm);\n+\t\tret = PTR_ERR(reg_shm);\n+\t\tgoto out_unlock;\n \t}\n \n \tinv_arg.func = TA_CMD_GET_RANDOM;\n@@ -189,7 +215,8 @@ static int trusted_tee_get_random(unsigned char *key, size_t key_len)\n \t}\n \n \ttee_shm_free(reg_shm);\n-\n+out_unlock:\n+\tmutex_unlock(\u0026trusted_key_tee_mutex);\n \treturn ret;\n }\n \n@@ -205,50 +232,67 @@ static int optee_ctx_match(struct tee_ioctl_version_data *ver, const void *data)\n static int trusted_key_probe(struct tee_client_device *rng_device)\n {\n \tstruct device *dev = \u0026rng_device-\u003edev;\n+\tstruct tee_context *ctx;\n \tint ret;\n \tstruct tee_ioctl_open_session_arg sess_arg;\n \n+\tmutex_lock(\u0026trusted_key_tee_mutex);\n+\tif (pvt_data.ctx) {\n+\t\tret = -EBUSY;\n+\t\tgoto out_unlock;\n+\t}\n+\n \tmemset(\u0026sess_arg, 0, sizeof(sess_arg));\n \n-\tpvt_data.ctx = tee_client_open_context(NULL, optee_ctx_match, NULL,\n-\t\t\t\t\t       NULL);\n-\tif (IS_ERR(pvt_data.ctx))\n-\t\treturn -ENODEV;\n+\tctx = tee_client_open_context(NULL, optee_ctx_match, NULL, NULL);\n+\tif (IS_ERR(ctx)) {\n+\t\tret = -ENODEV;\n+\t\tgoto out_unlock;\n+\t}\n \n \tmemcpy(sess_arg.uuid, rng_device-\u003eid.uuid.b, TEE_IOCTL_UUID_LEN);\n \tsess_arg.clnt_login = TEE_IOCTL_LOGIN_REE_KERNEL;\n \tsess_arg.num_params = 0;\n \n-\tret = tee_client_open_session(pvt_data.ctx, \u0026sess_arg, NULL);\n+\tret = tee_client_open_session(ctx, \u0026sess_arg, NULL);\n \tif ((ret \u003c 0) || (sess_arg.ret != 0)) {\n \t\tdev_err(dev, \"tee_client_open_session failed, err: %x\\n\",\n \t\t\tsess_arg.ret);\n \t\tret = -EINVAL;\n \t\tgoto out_ctx;\n \t}\n+\tpvt_data.ctx = ctx;\n \tpvt_data.session_id = sess_arg.session;\n-\n-\tret = register_key_type(\u0026key_type_trusted);\n-\tif (ret \u003c 0)\n-\t\tgoto out_sess;\n-\n \tpvt_data.dev = dev;\n+\tmutex_unlock(\u0026trusted_key_tee_mutex);\n \n-\treturn 0;\n+\tret = register_key_type(\u0026key_type_trusted);\n+\tif (!ret)\n+\t\treturn 0;\n \n-out_sess:\n-\ttee_client_close_session(pvt_data.ctx, pvt_data.session_id);\n+\tmutex_lock(\u0026trusted_key_tee_mutex);\n+\ttee_client_close_session(ctx, pvt_data.session_id);\n out_ctx:\n-\ttee_client_close_context(pvt_data.ctx);\n-\n+\ttee_client_close_context(ctx);\n+\tpvt_data.ctx = NULL;\n+\tpvt_data.dev = NULL;\n+\tpvt_data.session_id = 0;\n+out_unlock:\n+\tmutex_unlock(\u0026trusted_key_tee_mutex);\n \treturn ret;\n }\n \n static void trusted_key_remove(struct tee_client_device *dev)\n {\n \tunregister_key_type(\u0026key_type_trusted);\n+\n+\tmutex_lock(\u0026trusted_key_tee_mutex);\n \ttee_client_close_session(pvt_data.ctx, pvt_data.session_id);\n \ttee_client_close_context(pvt_data.ctx);\n+\tpvt_data.ctx = NULL;\n+\tpvt_data.dev = NULL;\n+\tpvt_data.session_id = 0;\n+\tmutex_unlock(\u0026trusted_key_tee_mutex);\n }\n \n static const struct tee_client_device_id trusted_key_id_table[] = {\n@@ -263,7 +307,8 @@ static struct tee_client_driver trusted_key_driver = {\n \t.remove\t\t= trusted_key_remove,\n \t.id_table\t= trusted_key_id_table,\n \t.driver\t\t= {\n-\t\t.name\t\t= DRIVER_NAME,\n+\t\t.name\t\t\t= DRIVER_NAME,\n+\t\t.suppress_bind_attrs\t= true,\n \t},\n };\n \n"
}

2/1 2026/11/16 00:55 agent patch-evaluator
3m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "KEYS",
    "RXRPC_KEYS",
    "AF_RXRPC",
    "RXKAD",
    "RXGK",
    "DNS_KEY",
    "DNS_RESOLVER",
    "CIFS",
    "CIFS_UPCALL",
    "NFS_FS",
    "NFS_V4"
  ],
  "FocusSymbols": [
    "key_garbage_collector",
    "key_gc_unused_keys",
    "key_schedule_gc_work",
    "key_gc_flush",
    "key_alloc",
    "keyring_restrict",
    "__register_key_type",
    "unregister_key_type",
    "rxrpc_preparse_s",
    "rxrpc_request_key",
    "rxrpc_server_keyring"
  ],
  "Reasoning": "The patch series introduces significant architectural refactorings to the kernel keys subsystem, specifically key garbage collection and key type lifetime management. It eliminates the 3-pass dead-keytype GC cycle in favor of module refcounting (try_module_get/module_put) on key allocation and destruction, reworks the key garbage collector to scan the serial rb_tree in chunks with an explicit cursor, and introduces key_gc_flush() to synchronize deferred key and credential destruction. In addition, RxRPC and DNS resolver key types are split into separate modules, with RxRPC server key preparsing restructured and key flushing integrated into NFSv4 idmap and CIFS session teardowns. These paths are in core subsystems and directly reachable via keyctl(), add_key(), request_key(), and RxRPC socket options, warranting fuzzing.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit bfe32f9841a590f04284c65f8e4157bba77792b8
Author: syz-cluster <triage@syzkaller.com>
Date:   Mon Nov 16 00:55:37 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/networking/rxrpc.rst b/Documentation/networking/rxrpc.rst
index eca055a536aa1b..394190c40d6ee9 100644
--- a/Documentation/networking/rxrpc.rst
+++ b/Documentation/networking/rxrpc.rst
@@ -1165,5 +1165,5 @@ API Function Reference
 .. kernel-doc:: net/rxrpc/recvmsg.c
 .. kernel-doc:: net/rxrpc/rxgk.c
 .. kernel-doc:: net/rxrpc/rxkad.c
+.. kernel-doc:: net/rxrpc/security.c
 .. kernel-doc:: net/rxrpc/sendmsg.c
-.. kernel-doc:: net/rxrpc/server_key.c
diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c
index 998f2da5617500..ab1a78cdfd4ceb 100644
--- a/arch/s390/kernel/cert_store.c
+++ b/arch/s390/kernel/cert_store.c
@@ -17,6 +17,7 @@
 #include <linux/key.h>
 #include <linux/keyctl.h>
 #include <linux/kobject.h>
+#include <linux/list.h>
 #include <linux/module.h>
 #include <linux/seq_file.h>
 #include <linux/slab.h>
@@ -296,6 +297,18 @@ static int check_certificate_valid(const struct vce *vce)
 	return check_certificate_hash(vce);
 }
 
+struct cert_store_key {
+	struct list_head list;
+	struct key *key;
+};
+
+static DEFINE_MUTEX(cs_refresh_lock);
+/* Owned references, protected by cs_refresh_lock. */
+static LIST_HEAD(cs_keys);
+static struct key *active_cs_keyring;
+static struct key *cs_keyring_parent;
+
+/* Return an owned reference to the user session keyring. */
 static struct key *get_user_session_keyring(void)
 {
 	key_ref_t us_keyring_ref;
@@ -305,118 +318,66 @@ static struct key *get_user_session_keyring(void)
 	if (IS_ERR(us_keyring_ref)) {
 		pr_dbf_msg("Couldn't get user session keyring: %ld",
 			   PTR_ERR(us_keyring_ref));
-		return ERR_PTR(-ENOKEY);
+		return ERR_CAST(us_keyring_ref);
 	}
-	key_ref_put(us_keyring_ref);
 	return key_ref_to_ptr(us_keyring_ref);
 }
 
-/* Invalidate all keys from cert_store keyring. */
-static int invalidate_keyring_keys(struct key *keyring)
-{
-	unsigned long num_keys, key_index;
-	size_t keyring_payload_len;
-	key_serial_t *key_array;
-	struct key *current_key;
-	int rc;
-
-	keyring_payload_len = key_type_keyring.read(keyring, NULL, 0);
-	num_keys = keyring_payload_len / sizeof(key_serial_t);
-	key_array = kzalloc_objs(key_serial_t, num_keys);
-	if (!key_array)
-		return -ENOMEM;
-
-	rc = key_type_keyring.read(keyring, (char *)key_array, keyring_payload_len);
-	if (rc != keyring_payload_len) {
-		pr_dbf_msg("Couldn't read keyring payload");
-		goto out;
-	}
-
-	for (key_index = 0; key_index < num_keys; key_index++) {
-		current_key = key_lookup(key_array[key_index]);
-		pr_dbf_msg("Invalidating key %08x", current_key->serial);
-
-		key_invalidate(current_key);
-		key_put(current_key);
-		rc = key_unlink(keyring, current_key);
-		if (rc) {
-			pr_dbf_msg("Couldn't unlink key %08x: %d", current_key->serial, rc);
-			break;
-		}
-	}
-out:
-	kfree(key_array);
-	return rc;
-}
-
-static struct key *find_cs_keyring(void)
-{
-	key_ref_t cs_keyring_ref;
-	struct key *cs_keyring;
-
-	cs_keyring_ref = keyring_search(make_key_ref(get_user_session_keyring(), true),
-					&key_type_keyring, CERT_STORE_KEYRING_NAME,
-					false);
-	if (!IS_ERR(cs_keyring_ref)) {
-		cs_keyring = key_ref_to_ptr(cs_keyring_ref);
-		key_ref_put(cs_keyring_ref);
-		goto found;
-	}
-	/* Search default locations: thread, process, session keyrings */
-	cs_keyring = request_key(&key_type_keyring, CERT_STORE_KEYRING_NAME, NULL);
-	if (IS_ERR(cs_keyring))
-		return NULL;
-	key_put(cs_keyring);
-found:
-	return cs_keyring;
-}
-
 static void cleanup_cs_keys(void)
 {
-	struct key *cs_keyring;
+	struct cert_store_key *entry, *tmp;
+	int rc;
 
-	cs_keyring = find_cs_keyring();
-	if (!cs_keyring)
+	if (!active_cs_keyring)
 		return;
 
-	pr_dbf_msg("Found cert_store keyring. Purging...");
-	/*
-	 * Remove cert_store_key_type in case invalidation
-	 * of old cert_store keys failed (= severe error).
-	 */
-	if (invalidate_keyring_keys(cs_keyring))
-		unregister_key_type(&key_type_cert_store_key);
+	/* Invalidate even certificates unlinked or linked into other keyrings. */
+	list_for_each_entry_safe(entry, tmp, &cs_keys, list) {
+		key_invalidate(entry->key);
+		key_put(entry->key);
+		list_del(&entry->list);
+		kfree(entry);
+	}
 
-	keyring_clear(cs_keyring);
-	key_invalidate(cs_keyring);
-	key_put(cs_keyring);
-	key_unlink(get_user_session_keyring(), cs_keyring);
+	rc = keyring_clear(active_cs_keyring);
+	if (rc)
+		pr_dbf_msg("Couldn't clear cert_store keyring: %d", rc);
+	key_invalidate(active_cs_keyring);
+	rc = key_unlink(cs_keyring_parent, active_cs_keyring);
+	if (rc)
+		pr_dbf_msg("Couldn't unlink cert_store keyring: %d", rc);
+	key_put(active_cs_keyring);
+	key_put(cs_keyring_parent);
+	active_cs_keyring = NULL;
+	cs_keyring_parent = NULL;
 }
 
+/* Return a borrowed reference; cleanup_cs_keys() owns the keyring. */
 static struct key *create_cs_keyring(void)
 {
-	static struct key *cs_keyring;
+	struct key *cs_keyring, *parent;
 
 	/* Cleanup previous cs_keyring and all associated keys if any. */
 	cleanup_cs_keys();
+	parent = get_user_session_keyring();
+	if (IS_ERR(parent))
+		return parent;
+
 	cs_keyring = keyring_alloc(CERT_STORE_KEYRING_NAME, GLOBAL_ROOT_UID,
 				   GLOBAL_ROOT_GID, current_cred(),
 				   (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ,
 				   KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_SET_KEEP,
-				   NULL, get_user_session_keyring());
+				   NULL, parent);
 	if (IS_ERR(cs_keyring)) {
 		pr_dbf_msg("Can't allocate cert_store keyring");
-		return NULL;
+		key_put(parent);
+		return cs_keyring;
 	}
 
+	active_cs_keyring = cs_keyring;
+	cs_keyring_parent = parent;
 	pr_dbf_msg("Successfully allocated cert_store keyring: %08x", cs_keyring->serial);
 
-	/*
-	 * In case a previous clean-up ran into an
-	 * error and unregistered key type.
-	 */
-	register_key_type(&key_type_cert_store_key);
-
 	return cs_keyring;
 }
 
@@ -454,6 +415,7 @@ static char *get_key_description(struct vcssb *vcssb, const struct vce *vce)
 static int create_key_from_vce(struct vcssb *vcssb, struct vce *vce,
 			       struct key *keyring)
 {
+	struct cert_store_key *entry;
 	key_ref_t newkey;
 	char *desc;
 	int rc;
@@ -462,6 +424,13 @@ static int create_key_from_vce(struct vcssb *vcssb, struct vce *vce,
 	if (!desc)
 		return -ENOMEM;
 
+	/* Reserve cleanup tracking before the key can be linked elsewhere. */
+	entry = kmalloc_obj(*entry);
+	if (!entry) {
+		rc = -ENOMEM;
+		goto out;
+	}
+
 	newkey = key_create_or_update(
 		make_key_ref(keyring, true), CERT_STORE_KEY_TYPE_NAME,
 		desc, (u8 *)vce + vce->vce_hdr.vc_offset,
@@ -473,10 +442,12 @@ static int create_key_from_vce(struct vcssb *vcssb, struct vce *vce,
 	if (rc) {
 		pr_dbf_msg("Couldn't create a key from Certificate Entry (%d)", rc);
 		rc = -ENOKEY;
+		kfree(entry);
 		goto out;
 	}
 
-	key_ref_put(newkey);
+	entry->key = key_ref_to_ptr(newkey);
+	list_add_tail(&entry->list, &cs_keys);
 out:
 	kfree(desc);
 	return rc;
@@ -704,19 +675,18 @@ static int fill_cs_keyring(void)
 	if (rc)
 		goto cleanup_keys;
 
-	rc = -ENOMEM;
 	cs_keyring = create_cs_keyring();
-	if (!cs_keyring)
+	if (IS_ERR(cs_keyring)) {
+		rc = PTR_ERR(cs_keyring);
 		goto cleanup_keys;
+	}
 
 	rc = add_certificates_to_keyring(vcssb, cs_keyring);
 	if (rc)
-		goto cleanup_cs_keyring;
+		goto cleanup_keys;
 
 	goto out;
 
-cleanup_cs_keyring:
-	key_put(cs_keyring);
 cleanup_keys:
 	cleanup_cs_keys();
 out:
@@ -724,7 +694,6 @@ static int fill_cs_keyring(void)
 	return rc;
 }
 
-static DEFINE_MUTEX(cs_refresh_lock);
 static int cs_status_val = -1;
 
 static ssize_t cs_status_show(struct kobject *kobj,
@@ -794,14 +763,18 @@ static int __init cert_store_init(void)
 	if (!cert_store_kobj)
 		goto cleanup_dbf;
 
-	rc = sysfs_create_files(cert_store_kobj, cert_store_attrs);
+	rc = register_key_type(&key_type_cert_store_key);
 	if (rc)
 		goto cleanup_kobj;
 
-	register_key_type(&key_type_cert_store_key);
+	rc = sysfs_create_files(cert_store_kobj, cert_store_attrs);
+	if (rc)
+		goto cleanup_key_type;
 
 	return rc;
 
+cleanup_key_type:
+	unregister_key_type(&key_type_cert_store_key);
 cleanup_kobj:
 	kobject_put(cert_store_kobj);
 cleanup_dbf:
diff --git a/fs/nfs/nfs4idmap.c b/fs/nfs/nfs4idmap.c
index bc397110d977f5..c88444cc6bf682 100644
--- a/fs/nfs/nfs4idmap.c
+++ b/fs/nfs/nfs4idmap.c
@@ -47,6 +47,8 @@
 #include <keys/request_key_auth-type.h>
 #include <linux/module.h>
 #include <linux/user_namespace.h>
+#include <linux/mutex.h>
+#include <linux/ratelimit.h>
 
 #include "internal.h"
 #include "netns.h"
@@ -58,6 +60,10 @@
 static const struct cred *id_resolver_cache;
 static struct key_type key_type_id_resolver_legacy;
 
+/* Serializes the idmap cache. */
+static DEFINE_MUTEX(nfs_idmap_cache_mutex);
+static unsigned int nfs_idmap_users;
+
 struct idmap_legacy_upcalldata {
 	struct rpc_pipe_msg pipe_msg;
 	struct idmap_msg idmap_msg;
@@ -469,7 +475,10 @@ nfs_idmap_new(struct nfs_client *clp)
 	if (error)
 		goto err_destroy_pipe;
 
+	mutex_lock(&nfs_idmap_cache_mutex);
+	nfs_idmap_users++;
 	clp->cl_idmap = idmap;
+	mutex_unlock(&nfs_idmap_cache_mutex);
 	return 0;
 err_destroy_pipe:
 	rpc_destroy_pipe_data(idmap->idmap_pipe);
@@ -483,6 +492,7 @@ void
 nfs_idmap_delete(struct nfs_client *clp)
 {
 	struct idmap *idmap = clp->cl_idmap;
+	int ret;
 
 	if (!idmap)
 		return;
@@ -493,6 +503,17 @@ nfs_idmap_delete(struct nfs_client *clp)
 	rpc_destroy_pipe_data(idmap->idmap_pipe);
 	put_user_ns(idmap->user_ns);
 	kfree(idmap);
+
+	mutex_lock(&nfs_idmap_cache_mutex);
+	if (--nfs_idmap_users == 0) {
+		ret = keyring_clear(id_resolver_cache->thread_keyring);
+		if (ret)
+			pr_warn_ratelimited("NFS: Failed to clear idmap cache: %d; cache pins remain\n",
+					    ret);
+		else
+			key_gc_flush();
+	}
+	mutex_unlock(&nfs_idmap_cache_mutex);
 }
 
 static int nfs_idmap_prepare_message(char *desc, struct idmap *idmap,
diff --git a/fs/smb/client/cifs_spnego.c b/fs/smb/client/cifs_spnego.c
index 44c40727568042..e974f396e07f62 100644
--- a/fs/smb/client/cifs_spnego.c
+++ b/fs/smb/client/cifs_spnego.c
@@ -15,6 +15,7 @@
 #include <linux/key-type.h>
 #include <linux/keyctl.h>
 #include <linux/inet.h>
+#include <linux/ratelimit.h>
 #include "cifsglob.h"
 #include "cifs_spnego.h"
 #include "cifs_debug.h"
@@ -190,6 +191,17 @@ cifs_get_spnego_key(struct cifs_ses *sesInfo,
 	return spnego_key;
 }
 
+void
+cifs_spnego_clear_cache(void)
+{
+	int ret;
+
+	ret = keyring_clear(spnego_cred->thread_keyring);
+	if (ret)
+		pr_warn_ratelimited("Failed to clear SPNEGO cache: %d; cache pins remain\n",
+				    ret);
+}
+
 int
 init_cifs_spnego(void)
 {
diff --git a/fs/smb/client/cifsacl.c b/fs/smb/client/cifsacl.c
index 346899da91eb21..60c60c23dd34e2 100644
--- a/fs/smb/client/cifsacl.c
+++ b/fs/smb/client/cifsacl.c
@@ -13,6 +13,7 @@
 #include <linux/string.h>
 #include <linux/keyctl.h>
 #include <linux/key-type.h>
+#include <linux/ratelimit.h>
 #include <uapi/linux/posix_acl.h>
 #include <linux/posix_acl.h>
 #include <linux/posix_acl_xattr.h>
@@ -539,6 +540,17 @@ sid_to_id(struct cifs_sb_info *cifs_sb, struct smb_sid *psid,
 	return 0;
 }
 
+void
+cifs_idmap_clear_cache(void)
+{
+	int ret;
+
+	ret = keyring_clear(root_cred->thread_keyring);
+	if (ret)
+		pr_warn_ratelimited("Failed to clear idmap cache: %d; cache pins remain\n",
+				    ret);
+}
+
 int
 init_cifs_idmap(void)
 {
diff --git a/fs/smb/client/cifsproto.h b/fs/smb/client/cifsproto.h
index f9ea35597bc27f..2930a40d1b673a 100644
--- a/fs/smb/client/cifsproto.h
+++ b/fs/smb/client/cifsproto.h
@@ -58,8 +58,16 @@ do {									\
 } while (0)
 int init_cifs_idmap(void);
 void exit_cifs_idmap(void);
+void cifs_idmap_clear_cache(void);
 int init_cifs_spnego(void);
 void exit_cifs_spnego(void);
+#ifdef CONFIG_CIFS_UPCALL
+void cifs_spnego_clear_cache(void);
+#else
+static inline void cifs_spnego_clear_cache(void)
+{
+}
+#endif
 const char *build_path_from_dentry(struct dentry *direntry, void *page);
 char *__build_path_from_dentry_optional_prefix(struct dentry *direntry,
 					       void *page, const char *tree,
diff --git a/fs/smb/client/misc.c b/fs/smb/client/misc.c
index ec28f102ea08a1..11c0330be489bd 100644
--- a/fs/smb/client/misc.c
+++ b/fs/smb/client/misc.c
@@ -9,6 +9,8 @@
 #include <linux/slab.h>
 #include <linux/ctype.h>
 #include <linux/mempool.h>
+#include <linux/key.h>
+#include <linux/mutex.h>
 #include <linux/vmalloc.h>
 #include "cifsglob.h"
 #include "cifsproto.h"
@@ -33,6 +35,9 @@ struct tcon_list {
 	struct cifs_tcon *tcon;
 };
 
+/* Serialize session admission with the last session's cache clear. */
+static DEFINE_MUTEX(cifs_session_mutex);
+
 /* The xid serves as a useful identifier for each incoming vfs request,
    in a similar way to the mid which is useful to track each sent smb,
    and CurrentXid can also provide a running counter (although it
@@ -74,7 +79,6 @@ sesInfoAlloc(void)
 
 	ret_buf = kzalloc_obj(struct cifs_ses);
 	if (ret_buf) {
-		atomic_inc(&sesInfoAllocCount);
 		spin_lock_init(&ret_buf->ses_lock);
 		ret_buf->ses_status = SES_NEW;
 		++ret_buf->ses_count;
@@ -84,6 +88,10 @@ sesInfoAlloc(void)
 		spin_lock_init(&ret_buf->iface_lock);
 		INIT_LIST_HEAD(&ret_buf->iface_list);
 		spin_lock_init(&ret_buf->chan_lock);
+
+		mutex_lock(&cifs_session_mutex);
+		atomic_inc(&sesInfoAllocCount);
+		mutex_unlock(&cifs_session_mutex);
 	}
 	return ret_buf;
 }
@@ -99,7 +107,6 @@ sesInfoFree(struct cifs_ses *buf_to_free)
 	}
 
 	unload_nls(buf_to_free->local_nls);
-	atomic_dec(&sesInfoAllocCount);
 	kfree(buf_to_free->serverOS);
 	kfree(buf_to_free->serverDomain);
 	kfree(buf_to_free->serverNOS);
@@ -115,6 +122,14 @@ sesInfoFree(struct cifs_ses *buf_to_free)
 		kref_put(&iface->refcount, release_iface);
 	spin_unlock(&buf_to_free->iface_lock);
 	kfree_sensitive(buf_to_free);
+
+	mutex_lock(&cifs_session_mutex);
+	if (atomic_dec_and_test(&sesInfoAllocCount)) {
+		cifs_idmap_clear_cache();
+		cifs_spnego_clear_cache();
+		key_gc_flush();
+	}
+	mutex_unlock(&cifs_session_mutex);
 }
 
 struct cifs_tcon *
diff --git a/include/linux/key-type.h b/include/linux/key-type.h
index c4f329b6ae3fed..9ecec31ad57162 100644
--- a/include/linux/key-type.h
+++ b/include/linux/key-type.h
@@ -10,9 +10,11 @@
 
 #include <linux/key.h>
 #include <linux/errno.h>
+#include <linux/init.h>
 
 #ifdef CONFIG_KEYS
 
+struct module;
 struct kernel_pkey_query;
 struct kernel_pkey_params;
 
@@ -161,6 +163,7 @@ struct key_type {
 				     const void *in, const void *in2);
 
 	/* internal fields */
+	struct module		*owner;
 	atomic64_t		index_id;	/* Opaque keyring index ID */
 	struct list_head	link;		/* link in types list */
 	struct lock_class_key	lock_class;	/* key->sem lock class */
@@ -168,7 +171,8 @@ struct key_type {
 
 extern struct key_type key_type_keyring;
 
-extern int register_key_type(struct key_type *ktype);
+int __register_key_type(struct key_type *ktype, struct module *owner);
+#define register_key_type(ktype) __register_key_type(ktype, THIS_MODULE)
 extern void unregister_key_type(struct key_type *ktype);
 
 extern int key_payload_reserve(struct key *key, size_t datalen);
diff --git a/include/linux/key.h b/include/linux/key.h
index 420412aab9263a..0f408255f7406a 100644
--- a/include/linux/key.h
+++ b/include/linux/key.h
@@ -439,6 +439,7 @@ extern int restrict_link_reject(struct key *keyring,
 				struct key *restriction_key);
 
 extern int keyring_clear(struct key *keyring);
+void key_gc_flush(void);
 
 extern key_ref_t keyring_search(key_ref_t keyring,
 				struct key_type *type,
@@ -526,6 +527,7 @@ extern void key_init(void);
 #define key_free_user_ns(ns)		do { } while(0)
 #define key_remove_domain(d)		do { } while(0)
 #define key_lookup(k)			NULL
+#define key_gc_flush()			do { } while (0)
 
 #endif /* CONFIG_KEYS */
 #endif /* __KERNEL__ */
diff --git a/net/Makefile b/net/Makefile
index 5b2dd7f07a85e9..97b2bd2ace7b5a 100644
--- a/net/Makefile
+++ b/net/Makefile
@@ -30,7 +30,7 @@ obj-$(CONFIG_LAPB)		+= lapb/
 obj-$(CONFIG_CAN)		+= can/
 obj-$(CONFIG_BT)		+= bluetooth/
 obj-$(CONFIG_SUNRPC)		+= sunrpc/
-obj-$(CONFIG_AF_RXRPC)		+= rxrpc/
+obj-$(CONFIG_RXRPC_KEYS)	+= rxrpc/
 obj-$(CONFIG_AF_KCM)		+= kcm/
 obj-$(CONFIG_STREAM_PARSER)	+= strparser/
 obj-$(CONFIG_ATM)		+= atm/
@@ -55,7 +55,7 @@ obj-$(CONFIG_IEEE802154)	+= ieee802154/
 obj-$(CONFIG_MAC802154)		+= mac802154/
 
 obj-$(CONFIG_SYSCTL)		+= sysctl_net.o
-obj-$(CONFIG_DNS_RESOLVER)	+= dns_resolver/
+obj-$(CONFIG_DNS_KEY)		+= dns_resolver/
 obj-$(CONFIG_CEPH_LIB)		+= ceph/
 obj-$(CONFIG_BATMAN_ADV)	+= batman-adv/
 obj-$(CONFIG_NFC)		+= nfc/
diff --git a/net/dns_resolver/Kconfig b/net/dns_resolver/Kconfig
index 7c2dba273e358c..2618bad2e771e9 100644
--- a/net/dns_resolver/Kconfig
+++ b/net/dns_resolver/Kconfig
@@ -1,10 +1,25 @@
 # SPDX-License-Identifier: GPL-2.0-only
+
+#
+# Configuration for DNS Resolver key type
+#
+config DNS_KEY
+	tristate "DNS Resolver key type"
+	depends on KEYS
+	help
+	  Support the key type used to cache DNS lookups independently of
+	  the in-kernel DNS query service.
+
+	  To compile this as a module, choose M here: the module is called
+	  dns_resolver_key.
+
 #
 # Configuration for DNS Resolver
 #
 config DNS_RESOLVER
 	tristate "DNS Resolver support"
 	depends on KEYS
+	select DNS_KEY
 	help
 	  Saying Y here will include support for the DNS Resolver key type
 	  which can be used to make upcalls to perform DNS lookups in
diff --git a/net/dns_resolver/Makefile b/net/dns_resolver/Makefile
index 877532d662d05d..586e4c6514de81 100644
--- a/net/dns_resolver/Makefile
+++ b/net/dns_resolver/Makefile
@@ -3,6 +3,8 @@
 # Makefile for the Linux DNS Resolver.
 #
 
+obj-$(CONFIG_DNS_KEY) += dns_resolver_key.o
 obj-$(CONFIG_DNS_RESOLVER) += dns_resolver.o
 
-dns_resolver-y :=  dns_key.o dns_query.o
+dns_resolver-y := dns_query.o
+dns_resolver_key-y := dns_key.o
diff --git a/net/dns_resolver/dns_key.c b/net/dns_resolver/dns_key.c
index 451247864a638b..fecbdc1d6beb10 100644
--- a/net/dns_resolver/dns_key.c
+++ b/net/dns_resolver/dns_key.c
@@ -9,8 +9,8 @@
  *              Wang Lei (wang840925@gmail.com)
  *		David Howells (dhowells@redhat.com)
  */
+
 #include <linux/module.h>
-#include <linux/moduleparam.h>
 #include <linux/slab.h>
 #include <linux/string.h>
 #include <linux/kernel.h>
@@ -22,15 +22,12 @@
 #include <keys/user-type.h>
 #include "internal.h"
 
-MODULE_DESCRIPTION("DNS Resolver");
+MODULE_DESCRIPTION("DNS Resolver key type");
 MODULE_AUTHOR("Wang Lei");
 MODULE_LICENSE("GPL");
 
 unsigned int dns_resolver_debug;
-module_param_named(debug, dns_resolver_debug, uint, 0644);
-MODULE_PARM_DESC(debug, "DNS Resolver debugging mask");
-
-const struct cred *dns_resolver_cache;
+EXPORT_SYMBOL_GPL(dns_resolver_debug);
 
 #define	DNS_ERRORNO_OPTION	"dnserror"
 
@@ -318,61 +315,17 @@ struct key_type key_type_dns_resolver = {
 	.describe	= dns_resolver_describe,
 	.read		= dns_resolver_read,
 };
+EXPORT_SYMBOL_GPL(key_type_dns_resolver);
 
-static int __init init_dns_resolver(void)
+static int __init init_dns_key(void)
 {
-	struct cred *cred;
-	struct key *keyring;
-	int ret;
-
-	/* create an override credential set with a special thread keyring in
-	 * which DNS requests are cached
-	 *
-	 * this is used to prevent malicious redirections from being installed
-	 * with add_key().
-	 */
-	cred = prepare_kernel_cred(&init_task);
-	if (!cred)
-		return -ENOMEM;
-
-	keyring = keyring_alloc(".dns_resolver",
-				GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,
-				(KEY_POS_ALL & ~KEY_POS_SETATTR) |
-				KEY_USR_VIEW | KEY_USR_READ,
-				KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
-	if (IS_ERR(keyring)) {
-		ret = PTR_ERR(keyring);
-		goto failed_put_cred;
-	}
-
-	ret = register_key_type(&key_type_dns_resolver);
-	if (ret < 0)
-		goto failed_put_key;
-
-	/* instruct request_key() to use this special keyring as a cache for
-	 * the results it looks up */
-	set_bit(KEY_FLAG_ROOT_CAN_CLEAR, &keyring->flags);
-	cred->thread_keyring = keyring;
-	cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
-	dns_resolver_cache = cred;
-
-	kdebug("DNS resolver keyring: %d\n", key_serial(keyring));
-	return 0;
-
-failed_put_key:
-	key_put(keyring);
-failed_put_cred:
-	put_cred(cred);
-	return ret;
+	return register_key_type(&key_type_dns_resolver);
 }
 
-static void __exit exit_dns_resolver(void)
+static void __exit exit_dns_key(void)
 {
-	key_revoke(dns_resolver_cache->thread_keyring);
 	unregister_key_type(&key_type_dns_resolver);
-	put_cred(dns_resolver_cache);
 }
 
-module_init(init_dns_resolver)
-module_exit(exit_dns_resolver)
-MODULE_LICENSE("GPL");
+module_init(init_dns_key);
+module_exit(exit_dns_key);
diff --git a/net/dns_resolver/dns_query.c b/net/dns_resolver/dns_query.c
index b8fb9a1245bf3a..ae4dde190101d7 100644
--- a/net/dns_resolver/dns_query.c
+++ b/net/dns_resolver/dns_query.c
@@ -24,8 +24,10 @@
  */
 
 #include <linux/module.h>
+#include <linux/moduleparam.h>
 #include <linux/slab.h>
 #include <linux/cred.h>
+#include <linux/keyctl.h>
 #include <linux/dns_resolver.h>
 #include <linux/err.h>
 #include <net/net_namespace.h>
@@ -35,6 +37,8 @@
 
 #include "internal.h"
 
+static const struct cred *dns_resolver_cache;
+
 /**
  * dns_query - Query the DNS
  * @net: The network namespace to operate in.
@@ -137,3 +141,63 @@ int dns_query(struct net *net,
 	return ret;
 }
 EXPORT_SYMBOL(dns_query);
+
+static int __init init_dns_resolver(void)
+{
+	struct cred *cred;
+	struct key *keyring;
+	int ret;
+
+	/*
+	 * Create an override credential set with a special thread keyring in
+	 * which DNS requests are cached.  This prevents malicious redirections
+	 * from being installed with add_key().
+	 */
+	cred = prepare_kernel_cred(&init_task);
+	if (!cred)
+		return -ENOMEM;
+
+	keyring = keyring_alloc(".dns_resolver",
+				GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,
+				(KEY_POS_ALL & ~KEY_POS_SETATTR) |
+				KEY_USR_VIEW | KEY_USR_READ,
+				KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
+	if (IS_ERR(keyring)) {
+		ret = PTR_ERR(keyring);
+		goto failed_put_cred;
+	}
+
+	/*
+	 * Instruct request_key() to use this special keyring as a cache for
+	 * the results it looks up.
+	 */
+	set_bit(KEY_FLAG_ROOT_CAN_CLEAR, &keyring->flags);
+	cred->thread_keyring = keyring;
+	cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
+	dns_resolver_cache = cred;
+
+	kdebug("DNS resolver keyring: %d\n", key_serial(keyring));
+	return 0;
+
+failed_put_cred:
+	put_cred(cred);
+	return ret;
+}
+
+static void __exit exit_dns_resolver(void)
+{
+	key_revoke(dns_resolver_cache->thread_keyring);
+	put_cred(dns_resolver_cache);
+	/* Drain deferred credential and keyring destruction. */
+	key_gc_flush();
+}
+
+module_init(init_dns_resolver);
+module_exit(exit_dns_resolver);
+
+MODULE_DESCRIPTION("DNS Resolver");
+MODULE_AUTHOR("Wang Lei");
+MODULE_LICENSE("GPL");
+
+module_param_named(debug, dns_resolver_debug, uint, 0644);
+MODULE_PARM_DESC(debug, "DNS Resolver debugging mask");
diff --git a/net/dns_resolver/internal.h b/net/dns_resolver/internal.h
index d0d8edcea09227..3478bad78a9a75 100644
--- a/net/dns_resolver/internal.h
+++ b/net/dns_resolver/internal.h
@@ -18,11 +18,6 @@ enum {
 	dns_key_error,
 };
 
-/*
- * dns_key.c
- */
-extern const struct cred *dns_resolver_cache;
-
 /*
  * debug tracing
  */
diff --git a/net/rxrpc/Kconfig b/net/rxrpc/Kconfig
index 2cebb666dc0711..30135ae62bd6ac 100644
--- a/net/rxrpc/Kconfig
+++ b/net/rxrpc/Kconfig
@@ -3,6 +3,18 @@
 # RxRPC session sockets
 #
 
+config RXRPC_KEYS
+	tristate "RxRPC key types"
+	select CRYPTO
+	select CRYPTO_LIB_DES if RXKAD
+	select KEYS
+	help
+	  Say Y or M here to include support for rxrpc and rxrpc_s key types
+	  independently of RxRPC session sockets.
+
+	  To compile this as a module, choose M here: the module will be called
+	  rxrpc_keys.
+
 config AF_RXRPC
 	tristate "RxRPC session sockets"
 	depends on INET
@@ -10,6 +22,7 @@ config AF_RXRPC
 	select CRYPTO_LIB_DES if RXKAD
 	select KEYS
 	select NET_UDP_TUNNEL
+	select RXRPC_KEYS
 	help
 	  Say Y or M here to include support for RxRPC session sockets (just
 	  the transport part, not the presentation part: (un)marshalling is
@@ -54,6 +67,9 @@ config AF_RXRPC_DEBUG
 
 	  See Documentation/networking/rxrpc.rst.
 
+endif
+
+if RXRPC_KEYS
 
 config RXKAD
 	bool "RxRPC Kerberos security"
@@ -86,6 +102,10 @@ config RXGK
 
 	  See Documentation/networking/rxrpc.rst.
 
+endif
+
+if AF_RXRPC
+
 config RXPERF
 	tristate "RxRPC test service"
 	help
diff --git a/net/rxrpc/Makefile b/net/rxrpc/Makefile
index f994f9f30a29d4..196e0ce085bae1 100644
--- a/net/rxrpc/Makefile
+++ b/net/rxrpc/Makefile
@@ -3,6 +3,7 @@
 # Makefile for Linux kernel RxRPC
 #
 
+obj-$(CONFIG_RXRPC_KEYS) += rxrpc_keys.o
 obj-$(CONFIG_AF_RXRPC) += rxrpc.o
 
 rxrpc-y := \
@@ -19,7 +20,6 @@ rxrpc-y := \
 	input_rack.o \
 	insecure.o \
 	io_thread.o \
-	key.o \
 	local_event.o \
 	local_object.o \
 	misc.o \
@@ -32,7 +32,6 @@ rxrpc-y := \
 	rtt.o \
 	security.o \
 	sendmsg.o \
-	server_key.o \
 	skbuff.o \
 	txbuf.o \
 	utils.o
@@ -45,5 +44,9 @@ rxrpc-$(CONFIG_RXGK) += \
 	rxgk_app.o \
 	rxgk_kdf.o
 
+rxrpc_keys-y := \
+	key.o \
+	server_key.o
+
 obj-$(CONFIG_RXPERF) += rxperf.o
 obj-$(CONFIG_KUNIT) += tests/
diff --git a/net/rxrpc/af_rxrpc.c b/net/rxrpc/af_rxrpc.c
index 9ab0f22c881ec5..6ccb99a992b925 100644
--- a/net/rxrpc/af_rxrpc.c
+++ b/net/rxrpc/af_rxrpc.c
@@ -1077,18 +1077,6 @@ static int __init af_rxrpc_init(void)
 		goto error_sock;
 	}
 
-	ret = register_key_type(&key_type_rxrpc);
-	if (ret < 0) {
-		pr_crit("Cannot register client key type\n");
-		goto error_key_type;
-	}
-
-	ret = register_key_type(&key_type_rxrpc_s);
-	if (ret < 0) {
-		pr_crit("Cannot register server key type\n");
-		goto error_key_type_s;
-	}
-
 	ret = rxrpc_sysctl_init();
 	if (ret < 0) {
 		pr_crit("Cannot register sysctls\n");
@@ -1098,10 +1086,6 @@ static int __init af_rxrpc_init(void)
 	return 0;
 
 error_sysctls:
-	unregister_key_type(&key_type_rxrpc_s);
-error_key_type_s:
-	unregister_key_type(&key_type_rxrpc);
-error_key_type:
 	sock_unregister(PF_RXRPC);
 error_sock:
 	proto_unregister(&rxrpc_proto);
@@ -1124,8 +1108,6 @@ static void __exit af_rxrpc_exit(void)
 {
 	_enter("");
 	rxrpc_sysctl_exit();
-	unregister_key_type(&key_type_rxrpc_s);
-	unregister_key_type(&key_type_rxrpc);
 	sock_unregister(PF_RXRPC);
 	proto_unregister(&rxrpc_proto);
 	unregister_pernet_device(&rxrpc_net_ops);
@@ -1139,6 +1121,7 @@ static void __exit af_rxrpc_exit(void)
 	destroy_workqueue(rxrpc_workqueue);
 	rxrpc_exit_security();
 	kmem_cache_destroy(rxrpc_call_jar);
+	key_gc_flush();
 	_leave("");
 }
 
diff --git a/net/rxrpc/ar-internal.h b/net/rxrpc/ar-internal.h
index 865f05fe37ab96..b5deab0e1ed9d1 100644
--- a/net/rxrpc/ar-internal.h
+++ b/net/rxrpc/ar-internal.h
@@ -273,18 +273,6 @@ struct rxrpc_security {
 	/* Clean up a security service */
 	void (*exit)(void);
 
-	/* Parse the information from a server key */
-	int (*preparse_server_key)(struct key_preparsed_payload *);
-
-	/* Clean up the preparse buffer after parsing a server key */
-	void (*free_preparse_server_key)(struct key_preparsed_payload *);
-
-	/* Destroy the payload of a server key */
-	void (*destroy_server_key)(struct key *);
-
-	/* Describe a server key */
-	void (*describe_server_key)(const struct key *, struct seq_file *);
-
 	/* initialise a connection's security */
 	int (*init_connection_security)(struct rxrpc_connection *,
 					struct rxrpc_key_token *);
@@ -1307,10 +1295,6 @@ extern const struct rxrpc_security rxrpc_no_security;
  */
 extern struct key_type key_type_rxrpc;
 
-int rxrpc_request_key(struct rxrpc_sock *, sockptr_t , int);
-int rxrpc_get_server_data_key(struct rxrpc_connection *, const void *, time64_t,
-			      u32);
-
 /*
  * local_event.c
  */
@@ -1492,6 +1476,11 @@ const struct rxrpc_security *rxrpc_get_incoming_security(struct rxrpc_sock *,
 							 struct sk_buff *);
 struct key *rxrpc_look_up_server_security(struct rxrpc_connection *,
 					  struct sk_buff *, u32, u32);
+int rxrpc_request_key(struct rxrpc_sock *rx, sockptr_t optval, int optlen);
+int rxrpc_get_server_data_key(struct rxrpc_connection *conn,
+			      const void *session_key, time64_t expiry,
+			      u32 kvno);
+int rxrpc_server_keyring(struct rxrpc_sock *rx, sockptr_t optval, int optlen);
 
 /*
  * sendmsg.c
@@ -1505,8 +1494,6 @@ int rxrpc_do_sendmsg(struct rxrpc_sock *, struct msghdr *, size_t);
  */
 extern struct key_type key_type_rxrpc_s;
 
-int rxrpc_server_keyring(struct rxrpc_sock *, sockptr_t, int);
-
 /*
  * skbuff.c
  */
@@ -1633,7 +1620,7 @@ extern unsigned int rxrpc_debug;
 #define _leave(FMT,...)	kleave(FMT,##__VA_ARGS__)
 #define _debug(FMT,...)	kdebug(FMT,##__VA_ARGS__)
 
-#elif defined(CONFIG_AF_RXRPC_DEBUG)
+#elif defined(CONFIG_AF_RXRPC_DEBUG) && !defined(RXRPC_KEY_PROVIDER)
 #define RXRPC_DEBUG_KENTER	0x01
 #define RXRPC_DEBUG_KLEAVE	0x02
 #define RXRPC_DEBUG_KDEBUG	0x04
diff --git a/net/rxrpc/conn_event.c b/net/rxrpc/conn_event.c
index 611c790bc6d0ce..096807f133546e 100644
--- a/net/rxrpc/conn_event.c
+++ b/net/rxrpc/conn_event.c
@@ -298,8 +298,13 @@ static int rxrpc_process_event(struct rxrpc_connection *conn,
 
 		ret = conn->security->init_connection_security(
 			conn, conn->key->payload.data[0]);
-		if (ret < 0)
+		if (ret < 0) {
+			struct key *key = conn->key;
+
+			WRITE_ONCE(conn->key, NULL);
+			key_put(key);
 			return ret;
+		}
 
 		spin_lock_irq(&conn->state_lock);
 		if (conn->state == RXRPC_CONN_SERVICE_CHALLENGING) {
diff --git a/net/rxrpc/key.c b/net/rxrpc/key.c
index cbd26da4495107..49d0871beaf9cd 100644
--- a/net/rxrpc/key.c
+++ b/net/rxrpc/key.c
@@ -9,6 +9,7 @@
  */
 
 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+#define RXRPC_KEY_PROVIDER
 
 #include <linux/module.h>
 #include <linux/net.h>
@@ -615,89 +616,6 @@ static void rxrpc_describe(const struct key *key, struct seq_file *m)
 	}
 }
 
-/*
- * grab the security key for a socket
- */
-int rxrpc_request_key(struct rxrpc_sock *rx, sockptr_t optval, int optlen)
-{
-	struct key *key;
-	char *description;
-
-	_enter("");
-
-	if (optlen <= 0 || optlen > PAGE_SIZE - 1 || rx->key)
-		return -EINVAL;
-
-	description = memdup_sockptr_nul(optval, optlen);
-	if (IS_ERR(description))
-		return PTR_ERR(description);
-
-	key = request_key_net(&key_type_rxrpc, description, sock_net(&rx->sk), NULL);
-	if (IS_ERR(key)) {
-		kfree(description);
-		_leave(" = %ld", PTR_ERR(key));
-		return PTR_ERR(key);
-	}
-
-	rx->key = key;
-	kfree(description);
-	_leave(" = 0 [key %x]", key->serial);
-	return 0;
-}
-
-/*
- * generate a server data key
- */
-int rxrpc_get_server_data_key(struct rxrpc_connection *conn,
-			      const void *session_key,
-			      time64_t expiry,
-			      u32 kvno)
-{
-	const struct cred *cred = current_cred();
-	struct key *key;
-	int ret;
-
-	struct {
-		u32 kver;
-		struct rxrpc_key_data_v1 v1;
-	} data;
-
-	_enter("");
-
-	key = key_alloc(&key_type_rxrpc, "x",
-			GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred, 0,
-			KEY_ALLOC_NOT_IN_QUOTA, NULL);
-	if (IS_ERR(key)) {
-		_leave(" = -ENOMEM [alloc %ld]", PTR_ERR(key));
-		return -ENOMEM;
-	}
-
-	_debug("key %d", key_serial(key));
-
-	data.kver = 1;
-	data.v1.security_index = RXRPC_SECURITY_RXKAD;
-	data.v1.ticket_length = 0;
-	data.v1.expiry = rxrpc_time64_to_u32(expiry);
-	data.v1.kvno = 0;
-
-	memcpy(&data.v1.session_key, session_key, sizeof(data.v1.session_key));
-
-	ret = key_instantiate_and_link(key, &data, sizeof(data), NULL, NULL);
-	if (ret < 0)
-		goto error;
-
-	conn->key = key;
-	_leave(" = 0 [%d]", key_serial(key));
-	return 0;
-
-error:
-	key_revoke(key);
-	key_put(key);
-	_leave(" = -ENOMEM [ins %d]", ret);
-	return -ENOMEM;
-}
-EXPORT_SYMBOL(rxrpc_get_server_data_key);
-
 /**
  * rxrpc_get_null_key - Generate a null RxRPC key
  * @keyname: The name to give the key.
@@ -893,3 +811,41 @@ static long rxrpc_read(const struct key *key,
 	_leave(" = %zu", size);
 	return size;
 }
+
+static int __init rxrpc_keys_init(void)
+{
+	int ret;
+
+	ret = register_key_type(&key_type_rxrpc);
+	if (ret < 0) {
+		pr_crit("Cannot register client key type\n");
+		goto error_key_type;
+	}
+
+	ret = register_key_type(&key_type_rxrpc_s);
+	if (ret < 0) {
+		pr_crit("Cannot register server key type\n");
+		goto error_key_type_s;
+	}
+
+	return 0;
+
+error_key_type_s:
+	unregister_key_type(&key_type_rxrpc);
+
+error_key_type:
+	return ret;
+}
+
+static void __exit rxrpc_keys_exit(void)
+{
+	unregister_key_type(&key_type_rxrpc_s);
+	unregister_key_type(&key_type_rxrpc);
+}
+
+module_init(rxrpc_keys_init);
+module_exit(rxrpc_keys_exit);
+
+MODULE_DESCRIPTION("RxRPC key types");
+MODULE_AUTHOR("David Howells <dhowells@redhat.com>");
+MODULE_LICENSE("GPL");
diff --git a/net/rxrpc/proc.c b/net/rxrpc/proc.c
index e9a27fa7b25d8b..2bf34b85c2f990 100644
--- a/net/rxrpc/proc.c
+++ b/net/rxrpc/proc.c
@@ -182,7 +182,7 @@ static int rxrpc_connection_seq_show(struct seq_file *seq, void *v)
 		   refcount_read(&conn->ref),
 		   atomic_read(&conn->active),
 		   state,
-		   key_serial(conn->key),
+		   key_serial(READ_ONCE(conn->key)),
 		   conn->tx_serial,
 		   conn->hi_serial,
 		   conn->channels[0].call_id,
diff --git a/net/rxrpc/rxgk.c b/net/rxrpc/rxgk.c
index 77a67ace1d2481..5fb3ce15cac402 100644
--- a/net/rxrpc/rxgk.c
+++ b/net/rxrpc/rxgk.c
@@ -14,68 +14,6 @@
 #include "ar-internal.h"
 #include "rxgk_common.h"
 
-/*
- * Parse the information from a server key
- */
-static int rxgk_preparse_server_key(struct key_preparsed_payload *prep)
-{
-	const struct krb5_enctype *krb5;
-	struct krb5_buffer *server_key = (void *)&prep->payload.data[2];
-	unsigned int service, sec_class, kvno, enctype;
-	int n = 0;
-
-	_enter("%zu", prep->datalen);
-
-	if (sscanf(prep->orig_description, "%u:%u:%u:%u%n",
-		   &service, &sec_class, &kvno, &enctype, &n) != 4)
-		return -EINVAL;
-
-	if (prep->orig_description[n])
-		return -EINVAL;
-
-	krb5 = crypto_krb5_find_enctype(enctype);
-	if (!krb5)
-		return -ENOPKG;
-
-	prep->payload.data[0] = (struct krb5_enctype *)krb5;
-
-	if (prep->datalen != krb5->key_len)
-		return -EKEYREJECTED;
-
-	server_key->len = prep->datalen;
-	server_key->data = kmemdup(prep->data, prep->datalen, GFP_KERNEL);
-	if (!server_key->data)
-		return -ENOMEM;
-
-	_leave(" = 0");
-	return 0;
-}
-
-static void rxgk_free_server_key(union key_payload *payload)
-{
-	struct krb5_buffer *server_key = (void *)&payload->data[2];
-
-	kfree_sensitive(server_key->data);
-}
-
-static void rxgk_free_preparse_server_key(struct key_preparsed_payload *prep)
-{
-	rxgk_free_server_key(&prep->payload);
-}
-
-static void rxgk_destroy_server_key(struct key *key)
-{
-	rxgk_free_server_key(&key->payload);
-}
-
-static void rxgk_describe_server_key(const struct key *key, struct seq_file *m)
-{
-	const struct krb5_enctype *krb5 = key->payload.data[0];
-
-	if (krb5)
-		seq_printf(m, ": %s", krb5->name);
-}
-
 /*
  * Handle rekeying the connection when we see our limits overrun or when the
  * far side decided to rekey.
@@ -1335,10 +1273,6 @@ const struct rxrpc_security rxgk_yfs = {
 	.no_key_abort			= RXGK_NOTAUTH,
 	.init				= rxgk_init,
 	.exit				= rxgk_exit,
-	.preparse_server_key		= rxgk_preparse_server_key,
-	.free_preparse_server_key	= rxgk_free_preparse_server_key,
-	.destroy_server_key		= rxgk_destroy_server_key,
-	.describe_server_key		= rxgk_describe_server_key,
 	.init_connection_security	= rxgk_init_connection_security,
 	.alloc_txbuf			= rxgk_alloc_txbuf,
 	.secure_packet			= rxgk_secure_packet,
diff --git a/net/rxrpc/rxkad.c b/net/rxrpc/rxkad.c
index ca9f0e82cb9ac7..2936c6effae396 100644
--- a/net/rxrpc/rxkad.c
+++ b/net/rxrpc/rxkad.c
@@ -47,50 +47,6 @@ struct rxkad_level2_hdr {
 static void rxkad_prime_packet_security(struct rxrpc_connection *conn,
 					const struct fcrypt_key *cipher);
 
-/*
- * Parse the information from a server key
- *
- * The data should be the 8-byte secret key.
- */
-static int rxkad_preparse_server_key(struct key_preparsed_payload *prep)
-{
-	struct des_ctx *des_key;
-	int err;
-
-	if (prep->datalen != 8)
-		return -EINVAL;
-
-	memcpy(&prep->payload.data[2], prep->data, 8);
-
-	des_key = kmalloc_obj(*des_key);
-	if (!des_key) {
-		_leave(" = -ENOMEM");
-		return -ENOMEM;
-	}
-
-	err = des_expand_key(des_key, prep->data, 8);
-	if (err) {
-		kfree_sensitive(des_key);
-		_leave(" = %d", err);
-		return err;
-	}
-
-	prep->payload.data[0] = des_key;
-	_leave(" = 0");
-	return 0;
-}
-
-static void rxkad_free_preparse_server_key(struct key_preparsed_payload *prep)
-{
-	kfree_sensitive(prep->payload.data[0]);
-}
-
-static void rxkad_destroy_server_key(struct key *key)
-{
-	kfree_sensitive(key->payload.data[0]);
-	key->payload.data[0] = NULL;
-}
-
 /*
  * initialise connection security
  */
@@ -1124,9 +1080,6 @@ const struct rxrpc_security rxkad = {
 	.no_key_abort			= RXKADUNKNOWNKEY,
 	.init				= rxkad_init,
 	.exit				= rxkad_exit,
-	.preparse_server_key		= rxkad_preparse_server_key,
-	.free_preparse_server_key	= rxkad_free_preparse_server_key,
-	.destroy_server_key		= rxkad_destroy_server_key,
 	.init_connection_security	= rxkad_init_connection_security,
 	.alloc_txbuf			= rxkad_alloc_txbuf,
 	.secure_packet			= rxkad_secure_packet,
diff --git a/net/rxrpc/security.c b/net/rxrpc/security.c
index 2bfbf2b2bb37a9..28883a70c9e85b 100644
--- a/net/rxrpc/security.c
+++ b/net/rxrpc/security.c
@@ -10,6 +10,8 @@
 #include <linux/skbuff.h>
 #include <linux/udp.h>
 #include <linux/crypto.h>
+#include <linux/key-type.h>
+#include <linux/slab.h>
 #include <net/sock.h>
 #include <net/af_rxrpc.h>
 #include <keys/rxrpc-type.h>
@@ -208,3 +210,185 @@ struct key *rxrpc_look_up_server_security(struct rxrpc_connection *conn,
 	read_unlock(&conn->local->services_lock);
 	return key;
 }
+
+/*
+ * grab the security key for a socket
+ */
+int rxrpc_request_key(struct rxrpc_sock *rx, sockptr_t optval, int optlen)
+{
+	struct key *key;
+	char *description;
+
+	_enter("");
+
+	if (optlen <= 0 || optlen > PAGE_SIZE - 1 || rx->key)
+		return -EINVAL;
+
+	description = memdup_sockptr_nul(optval, optlen);
+	if (IS_ERR(description))
+		return PTR_ERR(description);
+
+	key = request_key_net(&key_type_rxrpc, description, sock_net(&rx->sk), NULL);
+	if (IS_ERR(key)) {
+		kfree(description);
+		_leave(" = %ld", PTR_ERR(key));
+		return PTR_ERR(key);
+	}
+
+	rx->key = key;
+	kfree(description);
+	_leave(" = 0 [key %x]", key->serial);
+	return 0;
+}
+
+/*
+ * generate a server data key
+ */
+int rxrpc_get_server_data_key(struct rxrpc_connection *conn,
+			      const void *session_key,
+			      time64_t expiry,
+			      u32 kvno)
+{
+	const struct cred *cred = current_cred();
+	struct {
+		u32 kver;
+		struct rxrpc_key_data_v1 v1;
+	} data;
+	struct key *key;
+	int ret;
+
+	_enter("");
+
+	key = key_alloc(&key_type_rxrpc, "x",
+			GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred, 0,
+			KEY_ALLOC_NOT_IN_QUOTA, NULL);
+	if (IS_ERR(key)) {
+		_leave(" = -ENOMEM [alloc %ld]", PTR_ERR(key));
+		return -ENOMEM;
+	}
+
+	_debug("key %d", key_serial(key));
+
+	data.kver = 1;
+	data.v1.security_index = RXRPC_SECURITY_RXKAD;
+	data.v1.ticket_length = 0;
+	data.v1.expiry = rxrpc_time64_to_u32(expiry);
+	data.v1.kvno = 0;
+
+	memcpy(&data.v1.session_key, session_key, sizeof(data.v1.session_key));
+
+	ret = key_instantiate_and_link(key, &data, sizeof(data), NULL, NULL);
+	if (ret < 0)
+		goto error;
+
+	conn->key = key;
+	_leave(" = 0 [%d]", key_serial(key));
+	return 0;
+
+error:
+	key_revoke(key);
+	key_put(key);
+	_leave(" = -ENOMEM [ins %d]", ret);
+	return -ENOMEM;
+}
+EXPORT_SYMBOL(rxrpc_get_server_data_key);
+
+/*
+ * grab the security keyring for a server socket
+ */
+int rxrpc_server_keyring(struct rxrpc_sock *rx, sockptr_t optval, int optlen)
+{
+	struct key *key;
+	char *description;
+
+	_enter("");
+
+	if (rx->securities)
+		return -EINVAL;
+
+	if (optlen <= 0 || optlen > PAGE_SIZE - 1)
+		return -EINVAL;
+
+	description = memdup_sockptr_nul(optval, optlen);
+	if (IS_ERR(description))
+		return PTR_ERR(description);
+
+	key = request_key(&key_type_keyring, description, NULL);
+	if (IS_ERR(key)) {
+		kfree(description);
+		_leave(" = %ld", PTR_ERR(key));
+		return PTR_ERR(key);
+	}
+
+	rx->securities = key;
+	kfree(description);
+	_leave(" = 0 [key %x]", key->serial);
+	return 0;
+}
+
+/**
+ * rxrpc_sock_set_security_keyring - Set the security keyring for a kernel service
+ * @sk: The socket to set the keyring on
+ * @keyring: The keyring to set
+ *
+ * Set the server security keyring on an rxrpc socket.  This is used to provide
+ * the encryption keys for a kernel service.
+ *
+ * Return: %0 if successful and a negative error code otherwise.
+ */
+int rxrpc_sock_set_security_keyring(struct sock *sk, struct key *keyring)
+{
+	struct rxrpc_sock *rx = rxrpc_sk(sk);
+	int ret = 0;
+
+	lock_sock(sk);
+	if (rx->securities)
+		ret = -EINVAL;
+	else if (rx->sk.sk_state != RXRPC_UNBOUND)
+		ret = -EISCONN;
+	else
+		rx->securities = key_get(keyring);
+	release_sock(sk);
+	return ret;
+}
+EXPORT_SYMBOL(rxrpc_sock_set_security_keyring);
+
+/**
+ * rxrpc_sock_set_manage_response - Set the manage-response flag for a kernel service
+ * @sk: The socket to set the keyring on
+ * @set: True to set, false to clear the flag
+ *
+ * Set the flag on an rxrpc socket to say that the caller wants to manage the
+ * RESPONSE packet and the user-defined data it may contain.  Setting this
+ * means that recvmsg() will return messages with RXRPC_CHALLENGED in the
+ * control message buffer containing information about the challenge.
+ *
+ * The user should respond to the challenge by passing RXRPC_RESPOND or
+ * RXRPC_RESPOND_ABORT control messages with sendmsg() to the same call.
+ * Supplementary control messages, such as RXRPC_RESP_RXGK_APPDATA, may be
+ * included to indicate the parts the user wants to supply.
+ *
+ * The server will be passed the response data with a RXRPC_RESPONDED control
+ * message when it gets the first data from each call.
+ *
+ * Note that this is only honoured by security classes that need auxiliary data
+ * (e.g. RxGK).  Those that don't offer the facility (e.g. RxKAD) respond
+ * without consulting userspace.
+ *
+ * Return: The previous setting.
+ */
+int rxrpc_sock_set_manage_response(struct sock *sk, bool set)
+{
+	struct rxrpc_sock *rx = rxrpc_sk(sk);
+	int ret;
+
+	lock_sock(sk);
+	ret = !!test_bit(RXRPC_SOCK_MANAGE_RESPONSE, &rx->flags);
+	if (set)
+		set_bit(RXRPC_SOCK_MANAGE_RESPONSE, &rx->flags);
+	else
+		clear_bit(RXRPC_SOCK_MANAGE_RESPONSE, &rx->flags);
+	release_sock(sk);
+	return ret;
+}
+EXPORT_SYMBOL(rxrpc_sock_set_manage_response);
diff --git a/net/rxrpc/server_key.c b/net/rxrpc/server_key.c
index 3efe104b1930cb..0be259dd0df029 100644
--- a/net/rxrpc/server_key.c
+++ b/net/rxrpc/server_key.c
@@ -9,6 +9,11 @@
  */
 
 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+#define RXRPC_KEY_PROVIDER
+
+#include <crypto/des.h>
+#include <crypto/krb5.h>
+#include <linux/fips.h>
 
 #include <linux/module.h>
 #include <linux/net.h>
@@ -42,6 +47,7 @@ struct key_type key_type_rxrpc_s = {
 	.destroy	= rxrpc_destroy_s,
 	.describe	= rxrpc_describe_s,
 };
+EXPORT_SYMBOL(key_type_rxrpc_s);
 
 /*
  * Vet the description for an RxRPC server key.
@@ -60,156 +66,198 @@ static int rxrpc_vet_description_s(const char *desc)
 	return 0;
 }
 
+#ifdef CONFIG_RXKAD
 /*
- * Preparse a server secret key.
+ * Parse the information from a server key
+ *
+ * The data should be the 8-byte secret key.
  */
-static int rxrpc_preparse_s(struct key_preparsed_payload *prep)
+static int rxkad_preparse_server_key(struct key_preparsed_payload *prep)
 {
-	const struct rxrpc_security *sec;
-	unsigned int service, sec_class;
-	int n;
+	struct des_ctx *des_key;
+	int err;
+
+	if (fips_enabled)
+		return -ENOPKG;
+
+	if (prep->datalen != 8)
+		return -EINVAL;
+
+	memcpy(&prep->payload.data[2], prep->data, 8);
+
+	des_key = kmalloc_obj(*des_key);
+	if (!des_key) {
+		_leave(" = -ENOMEM");
+		return -ENOMEM;
+	}
+
+	err = des_expand_key(des_key, prep->data, 8);
+	if (err) {
+		kfree_sensitive(des_key);
+		_leave(" = %d", err);
+		return err;
+	}
+
+	prep->payload.data[0] = des_key;
+	_leave(" = 0");
+	return 0;
+}
+
+static void rxkad_free_preparse_server_key(struct key_preparsed_payload *prep)
+{
+	kfree_sensitive(prep->payload.data[0]);
+}
+
+static void rxkad_destroy_server_key(struct key *key)
+{
+	kfree_sensitive(key->payload.data[0]);
+	key->payload.data[0] = NULL;
+}
+#endif
+
+#ifdef CONFIG_RXGK
+/*
+ * Parse the information from a server key
+ */
+static int rxgk_preparse_server_key(struct key_preparsed_payload *prep)
+{
+	const struct krb5_enctype *krb5;
+	struct krb5_buffer *server_key = (void *)&prep->payload.data[2];
+	unsigned int service, sec_class, kvno, enctype;
+	int n = 0;
 
 	_enter("%zu", prep->datalen);
 
-	if (!prep->orig_description)
+	if (sscanf(prep->orig_description, "%u:%u:%u:%u%n",
+		   &service, &sec_class, &kvno, &enctype, &n) != 4)
 		return -EINVAL;
 
-	if (sscanf(prep->orig_description, "%u:%u%n", &service, &sec_class, &n) != 2)
+	if (prep->orig_description[n])
 		return -EINVAL;
 
-	sec = rxrpc_security_lookup(sec_class);
-	if (!sec)
+	krb5 = crypto_krb5_find_enctype(enctype);
+	if (!krb5)
 		return -ENOPKG;
 
-	prep->payload.data[1] = (struct rxrpc_security *)sec;
+	prep->payload.data[0] = (struct krb5_enctype *)krb5;
 
-	if (!sec->preparse_server_key)
-		return -EINVAL;
+	if (prep->datalen != krb5->key_len)
+		return -EKEYREJECTED;
+
+	server_key->len = prep->datalen;
+	server_key->data = kmemdup(prep->data, prep->datalen, GFP_KERNEL);
+	if (!server_key->data)
+		return -ENOMEM;
 
-	return sec->preparse_server_key(prep);
+	_leave(" = 0");
+	return 0;
 }
 
-static void rxrpc_free_preparse_s(struct key_preparsed_payload *prep)
+static void rxgk_free_server_key(union key_payload *payload)
 {
-	const struct rxrpc_security *sec = prep->payload.data[1];
+	struct krb5_buffer *server_key = (void *)&payload->data[2];
 
-	if (sec && sec->free_preparse_server_key)
-		sec->free_preparse_server_key(prep);
+	kfree_sensitive(server_key->data);
 }
 
-static void rxrpc_destroy_s(struct key *key)
+static void rxgk_free_preparse_server_key(struct key_preparsed_payload *prep)
 {
-	const struct rxrpc_security *sec = key->payload.data[1];
+	rxgk_free_server_key(&prep->payload);
+}
 
-	if (sec && sec->destroy_server_key)
-		sec->destroy_server_key(key);
+static void rxgk_destroy_server_key(struct key *key)
+{
+	rxgk_free_server_key(&key->payload);
 }
 
-static void rxrpc_describe_s(const struct key *key, struct seq_file *m)
+static void rxgk_describe_server_key(const struct key *key, struct seq_file *m)
 {
-	const struct rxrpc_security *sec = key->payload.data[1];
+	const struct krb5_enctype *krb5 = key->payload.data[0];
 
-	seq_puts(m, key->description);
-	if (sec && sec->describe_server_key)
-		sec->describe_server_key(key, m);
+	if (krb5)
+		seq_printf(m, ": %s", krb5->name);
 }
+#endif
 
 /*
- * grab the security keyring for a server socket
+ * Preparse a server secret key.
  */
-int rxrpc_server_keyring(struct rxrpc_sock *rx, sockptr_t optval, int optlen)
+static int rxrpc_preparse_s(struct key_preparsed_payload *prep)
 {
-	struct key *key;
-	char *description;
+	unsigned int service, sec_class;
+	int n;
 
-	_enter("");
+	_enter("%zu", prep->datalen);
 
-	if (rx->securities)
+	if (!prep->orig_description)
 		return -EINVAL;
 
-	if (optlen <= 0 || optlen > PAGE_SIZE - 1)
+	if (sscanf(prep->orig_description, "%u:%u%n", &service, &sec_class, &n) != 2)
 		return -EINVAL;
 
-	description = memdup_sockptr_nul(optval, optlen);
-	if (IS_ERR(description))
-		return PTR_ERR(description);
+	prep->payload.data[1] = (void *)(uintptr_t)sec_class;
 
-	key = request_key(&key_type_keyring, description, NULL);
-	if (IS_ERR(key)) {
-		kfree(description);
-		_leave(" = %ld", PTR_ERR(key));
-		return PTR_ERR(key);
+	switch (sec_class) {
+#ifdef CONFIG_RXKAD
+	case RXRPC_SECURITY_RXKAD:
+		return rxkad_preparse_server_key(prep);
+#endif
+#ifdef CONFIG_RXGK
+	case RXRPC_SECURITY_YFS_RXGK:
+		return rxgk_preparse_server_key(prep);
+#endif
+	default:
+		return -ENOPKG;
 	}
+}
 
-	rx->securities = key;
-	kfree(description);
-	_leave(" = 0 [key %x]", key->serial);
-	return 0;
+static void rxrpc_free_preparse_s(struct key_preparsed_payload *prep)
+{
+	switch ((uintptr_t)prep->payload.data[1]) {
+#ifdef CONFIG_RXKAD
+	case RXRPC_SECURITY_RXKAD:
+		rxkad_free_preparse_server_key(prep);
+		break;
+#endif
+#ifdef CONFIG_RXGK
+	case RXRPC_SECURITY_YFS_RXGK:
+		rxgk_free_preparse_server_key(prep);
+		break;
+#endif
+	default:
+		break;
+	}
 }
 
-/**
- * rxrpc_sock_set_security_keyring - Set the security keyring for a kernel service
- * @sk: The socket to set the keyring on
- * @keyring: The keyring to set
- *
- * Set the server security keyring on an rxrpc socket.  This is used to provide
- * the encryption keys for a kernel service.
- *
- * Return: %0 if successful and a negative error code otherwise.
- */
-int rxrpc_sock_set_security_keyring(struct sock *sk, struct key *keyring)
+static void rxrpc_destroy_s(struct key *key)
 {
-	struct rxrpc_sock *rx = rxrpc_sk(sk);
-	int ret = 0;
-
-	lock_sock(sk);
-	if (rx->securities)
-		ret = -EINVAL;
-	else if (rx->sk.sk_state != RXRPC_UNBOUND)
-		ret = -EISCONN;
-	else
-		rx->securities = key_get(keyring);
-	release_sock(sk);
-	return ret;
+	switch ((uintptr_t)key->payload.data[1]) {
+#ifdef CONFIG_RXKAD
+	case RXRPC_SECURITY_RXKAD:
+		rxkad_destroy_server_key(key);
+		break;
+#endif
+#ifdef CONFIG_RXGK
+	case RXRPC_SECURITY_YFS_RXGK:
+		rxgk_destroy_server_key(key);
+		break;
+#endif
+	default:
+		break;
+	}
 }
-EXPORT_SYMBOL(rxrpc_sock_set_security_keyring);
 
-/**
- * rxrpc_sock_set_manage_response - Set the manage-response flag for a kernel service
- * @sk: The socket to set the keyring on
- * @set: True to set, false to clear the flag
- *
- * Set the flag on an rxrpc socket to say that the caller wants to manage the
- * RESPONSE packet and the user-defined data it may contain.  Setting this
- * means that recvmsg() will return messages with RXRPC_CHALLENGED in the
- * control message buffer containing information about the challenge.
- *
- * The user should respond to the challenge by passing RXRPC_RESPOND or
- * RXRPC_RESPOND_ABORT control messages with sendmsg() to the same call.
- * Supplementary control messages, such as RXRPC_RESP_RXGK_APPDATA, may be
- * included to indicate the parts the user wants to supply.
- *
- * The server will be passed the response data with a RXRPC_RESPONDED control
- * message when it gets the first data from each call.
- *
- * Note that this is only honoured by security classes that need auxiliary data
- * (e.g. RxGK).  Those that don't offer the facility (e.g. RxKAD) respond
- * without consulting userspace.
- *
- * Return: The previous setting.
- */
-int rxrpc_sock_set_manage_response(struct sock *sk, bool set)
+static void rxrpc_describe_s(const struct key *key, struct seq_file *m)
 {
-	struct rxrpc_sock *rx = rxrpc_sk(sk);
-	int ret;
-
-	lock_sock(sk);
-	ret = !!test_bit(RXRPC_SOCK_MANAGE_RESPONSE, &rx->flags);
-	if (set)
-		set_bit(RXRPC_SOCK_MANAGE_RESPONSE, &rx->flags);
-	else
-		clear_bit(RXRPC_SOCK_MANAGE_RESPONSE, &rx->flags);
-	release_sock(sk);
-	return ret;
+	seq_puts(m, key->description);
+
+	switch ((uintptr_t)key->payload.data[1]) {
+#ifdef CONFIG_RXGK
+	case RXRPC_SECURITY_YFS_RXGK:
+		rxgk_describe_server_key(key, m);
+		break;
+#endif
+	default:
+		break;
+	}
 }
-EXPORT_SYMBOL(rxrpc_sock_set_manage_response);
diff --git a/security/keys/gc.c b/security/keys/gc.c
index eda445f815d47b..704dcc40198360 100644
--- a/security/keys/gc.c
+++ b/security/keys/gc.c
@@ -6,20 +6,35 @@
  */
 
 #include <linux/slab.h>
+#include <linux/module.h>
 #include <linux/security.h>
 #include <keys/keyring-type.h>
 #include "internal.h"
 
-/*
- * Delay between key revocation/expiry in seconds
- */
-unsigned key_gc_delay = 5 * 60;
+#define KEY_GC_CHUNK_SIZE 64
 
 /*
  * Reaper for unused keys.
  */
 static void key_garbage_collector(struct work_struct *work);
-DECLARE_WORK(key_gc_work, key_garbage_collector);
+
+struct workqueue_struct *key_gc_wq __ro_after_init;
+
+static struct {
+	time64_t start;			/* expiry range start */
+	time64_t end;			/* expiry range end */
+	struct rb_node *cursor;		/* serial tree position */
+	u8 state;			/* state flags */
+	atomic_t seq;
+	struct work_struct work;	/* work item */
+} key_gc_work = {
+	.work = __WORK_INITIALIZER(key_gc_work.work, key_garbage_collector),
+};
+
+/*
+ * Delay between key revocation/expiry in seconds
+ */
+unsigned int key_gc_delay = 5 * 60;
 
 /*
  * Reaper for links from keyrings to dead keys.
@@ -28,21 +43,43 @@ static void key_gc_timer_func(struct timer_list *);
 static DEFINE_TIMER(key_gc_timer, key_gc_timer_func);
 
 static time64_t key_gc_next_run = TIME64_MAX;
-static struct key_type *key_gc_dead_keytype;
-
 static unsigned long key_gc_flags;
 #define KEY_GC_KEY_EXPIRED	0	/* A key expired and needs unlinking */
-#define KEY_GC_REAP_KEYTYPE	1	/* A keytype is being unregistered */
-#define KEY_GC_REAPING_KEYTYPE	2	/* Cleared when keytype reaped */
-
+#define KEY_GC_REAP_REQUESTED	1	/* Another complete pass was requested */
 
 /*
- * Any key whose type gets unregistered will be re-typed to this if it can't be
- * immediately unlinked.
+ * Schedule a new GC pass or re-schedule an ongoing GC pass.
  */
-struct key_type key_type_dead = {
-	.name = ".dead",
-};
+void key_schedule_gc_work(bool expired)
+{
+	unsigned long flags = BIT(KEY_GC_REAP_REQUESTED);
+
+	if (expired)
+		flags |= BIT(KEY_GC_KEY_EXPIRED);
+
+	/* Publish all request flags together, after the caller's updates. */
+	set_mask_bits(&key_gc_flags, 0, flags);
+	queue_work(key_gc_wq, &key_gc_work.work);
+}
+
+/**
+ * key_gc_flush - Drain the garbage collector RCU callbacks
+ */
+void key_gc_flush(void)
+{
+	int seq;
+
+	do {
+		while (flush_work(&key_gc_work.work) ||
+		       work_pending(&key_gc_work.work))
+			cpu_relax();
+		seq = atomic_read_acquire(&key_gc_work.seq);
+		rcu_barrier();
+	} while (flush_work(&key_gc_work.work) ||
+		 work_pending(&key_gc_work.work) ||
+		 atomic_read_acquire(&key_gc_work.seq) != seq);
+}
+EXPORT_SYMBOL_GPL(key_gc_flush);
 
 /*
  * Schedule a garbage collection run.
@@ -55,9 +92,10 @@ void key_schedule_gc(time64_t gc_at)
 
 	kenter("%lld", gc_at - now);
 
-	if (gc_at <= now || test_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags)) {
+	if (gc_at <= now) {
 		kdebug("IMMEDIATE");
-		schedule_work(&key_gc_work);
+		/* Catch expirations that became due during the scan. */
+		key_schedule_gc_work(true);
 	} else if (gc_at < key_gc_next_run) {
 		kdebug("DEFERRED");
 		key_gc_next_run = gc_at;
@@ -79,15 +117,6 @@ void key_set_expiry(struct key *key, time64_t expiry)
 	}
 }
 
-/*
- * Schedule a dead links collection run.
- */
-void key_schedule_gc_links(void)
-{
-	set_bit(KEY_GC_KEY_EXPIRED, &key_gc_flags);
-	schedule_work(&key_gc_work);
-}
-
 /*
  * Some key's cleanup time was met after it expired, so we need to get the
  * reaper to go through a cycle finding expired keys.
@@ -96,37 +125,7 @@ static void key_gc_timer_func(struct timer_list *unused)
 {
 	kenter("");
 	key_gc_next_run = TIME64_MAX;
-	key_schedule_gc_links();
-}
-
-/*
- * Reap keys of dead type.
- *
- * We use three flags to make sure we see three complete cycles of the garbage
- * collector: the first to mark keys of that type as being dead, the second to
- * collect dead links and the third to clean up the dead keys.  We have to be
- * careful as there may already be a cycle in progress.
- *
- * The caller must be holding key_types_sem.
- */
-void key_gc_keytype(struct key_type *ktype)
-{
-	kenter("%s", ktype->name);
-
-	key_gc_dead_keytype = ktype;
-	set_bit(KEY_GC_REAPING_KEYTYPE, &key_gc_flags);
-	smp_mb();
-	set_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags);
-
-	kdebug("schedule");
-	schedule_work(&key_gc_work);
-
-	kdebug("sleep");
-	wait_on_bit(&key_gc_flags, KEY_GC_REAPING_KEYTYPE,
-		    TASK_UNINTERRUPTIBLE);
-
-	key_gc_dead_keytype = NULL;
-	kleave("");
+	key_schedule_gc_work(true);
 }
 
 /*
@@ -134,9 +133,12 @@ void key_gc_keytype(struct key_type *ktype)
  */
 static noinline void key_gc_unused_keys(struct list_head *keys)
 {
-	while (!list_empty(keys)) {
+	unsigned int chunk = KEY_GC_CHUNK_SIZE;
+
+	while (!list_empty(keys) && chunk--) {
 		struct key *key =
 			list_entry(keys->next, struct key, graveyard_link);
+		struct module *owner = key->type->owner;
 		short state = key->state;
 
 		list_del(&key->graveyard_link);
@@ -150,8 +152,15 @@ 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) {
+			if (key->type->destroy)
+				key->type->destroy(key);
+		} else if (key->restrict_link) {
+			if (key->restrict_link->keytype)
+				module_put(key->restrict_link->keytype->owner);
+			key_put(key->restrict_link->key);
+			kfree(key->restrict_link);
+		}
 
 		security_key_free(key);
 
@@ -165,6 +174,7 @@ static noinline void key_gc_unused_keys(struct list_head *keys)
 
 		memzero_explicit(key, sizeof(*key));
 		kmem_cache_free(key_jar, key);
+		module_put(owner);
 	}
 }
 
@@ -178,89 +188,67 @@ static noinline void key_gc_unused_keys(struct list_head *keys)
 static void key_garbage_collector(struct work_struct *work)
 {
 	static LIST_HEAD(graveyard);
-	static u8 gc_state;		/* Internal persistent state */
+	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_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 */
-#define KEY_GC_FOUND_DEAD_KEY	0x80	/* - We found at least one dead key */
+#define KEY_GC_DESTROYING	0x04	/* - We need to destroy keys */
 
-	struct rb_node *cursor;
+	unsigned int chunk = KEY_GC_CHUNK_SIZE;
+	unsigned long flags;
 	struct key *key;
-	time64_t new_timer, limit, expiry;
-
-	kenter("[%lx,%x]", key_gc_flags, gc_state);
+	time64_t expiry;
 
-	limit = ktime_get_real_seconds();
+	kenter("[%lx,%x]", key_gc_flags, gc->state);
 
-	/* Work out what we're going to be doing in this pass */
-	gc_state &= KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2;
-	gc_state <<= 1;
-	if (test_and_clear_bit(KEY_GC_KEY_EXPIRED, &key_gc_flags))
-		gc_state |= KEY_GC_REAPING_LINKS;
+	if (gc->state & KEY_GC_DESTROYING)
+		goto destroy_keys;
+	if (gc->cursor) {
+		spin_lock(&key_serial_lock);
+		goto continue_scanning;
+	}
 
-	if (test_and_clear_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags))
-		gc_state |= KEY_GC_REAPING_DEAD_1;
-	kdebug("new pass %x", gc_state);
+	flags = xchg(&key_gc_flags, 0);
+	gc->start = ktime_get_real_seconds();
+	gc->state = 0;
+	if (flags & BIT(KEY_GC_KEY_EXPIRED))
+		gc->state |= KEY_GC_REAPING_LINKS;
+	kdebug("new pass %x", gc->state);
 
-	new_timer = TIME64_MAX;
+	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.
 	 */
 	spin_lock(&key_serial_lock);
-	cursor = rb_first(&key_serial_tree);
+	gc->cursor = rb_first(&key_serial_tree);
 
 continue_scanning:
-	while (cursor) {
-		key = rb_entry(cursor, struct key, serial_node);
-		cursor = rb_next(cursor);
+	while (gc->cursor && chunk) {
+		key = rb_entry(gc->cursor, struct key, serial_node);
+		gc->cursor = rb_next(gc->cursor);
+		chunk--;
 
 		if (!test_bit_acquire(KEY_FLAG_USER_ALIVE, &key->flags)) {
 			/* Clobber key->user after final put seen. */
 			goto found_unreferenced_key;
 		}
 
-		if (unlikely(gc_state & KEY_GC_REAPING_DEAD_1)) {
-			if (key->type == key_gc_dead_keytype) {
-				gc_state |= KEY_GC_FOUND_DEAD_KEY;
-				set_bit(KEY_FLAG_DEAD, &key->flags);
-				key->perm = 0;
-				goto skip_dead_key;
-			} else if (key->type == &key_type_keyring &&
-				   key->restrict_link) {
-				goto found_restricted_keyring;
-			}
-		}
-
 		expiry = key->expiry;
 		if (expiry != TIME64_MAX) {
 			if (!(key->type->flags & KEY_TYPE_INSTANT_REAP))
 				expiry += key_gc_delay;
-			if (expiry > limit && expiry < new_timer) {
+			if (expiry > gc->start && expiry < gc->end) {
 				kdebug("will expire %x in %lld",
-				       key_serial(key), key->expiry - limit);
-				new_timer = key->expiry;
+				       key_serial(key), expiry - gc->start);
+				gc->end = expiry;
 			}
 		}
 
-		if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2))
-			if (key->type == key_gc_dead_keytype)
-				gc_state |= KEY_GC_FOUND_DEAD_KEY;
+		if ((gc->state & KEY_GC_REAPING_LINKS) &&
+		    key->type == &key_type_keyring)
+			goto found_keyring;
 
-		if ((gc_state & KEY_GC_REAPING_LINKS) ||
-		    unlikely(gc_state & KEY_GC_REAPING_DEAD_2)) {
-			if (key->type == &key_type_keyring)
-				goto found_keyring;
-		}
-
-		if (unlikely(gc_state & KEY_GC_REAPING_DEAD_3))
-			if (key->type == key_gc_dead_keytype)
-				goto destroy_dead_key;
-
-	skip_dead_key:
 		if (spin_is_contended(&key_serial_lock) || need_resched())
 			goto contended;
 	}
@@ -269,7 +257,11 @@ static void key_garbage_collector(struct work_struct *work)
 	spin_unlock(&key_serial_lock);
 
 maybe_resched:
-	if (cursor) {
+	if (gc->cursor) {
+		if (!chunk) {
+			queue_work(key_gc_wq, &key_gc_work.work);
+			goto out;
+		}
 		cond_resched();
 		spin_lock(&key_serial_lock);
 		goto continue_scanning;
@@ -281,13 +273,10 @@ static void key_garbage_collector(struct work_struct *work)
 	 */
 	kdebug("pass complete");
 
-	if (new_timer != TIME64_MAX) {
-		new_timer += key_gc_delay;
-		key_schedule_gc(new_timer);
-	}
+	if (gc->end != TIME64_MAX)
+		key_schedule_gc(gc->end);
 
-	if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2) ||
-	    !list_empty(&graveyard)) {
+	if (!list_empty(&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
@@ -297,33 +286,25 @@ static void key_garbage_collector(struct work_struct *work)
 		synchronize_rcu();
 	}
 
+	gc->state |= KEY_GC_DESTROYING;
+
+destroy_keys:
 	if (!list_empty(&graveyard)) {
 		kdebug("gc keys");
 		key_gc_unused_keys(&graveyard);
-	}
-
-	if (unlikely(gc_state & (KEY_GC_REAPING_DEAD_1 |
-				 KEY_GC_REAPING_DEAD_2))) {
-		if (!(gc_state & KEY_GC_FOUND_DEAD_KEY)) {
-			/* No remaining dead keys: short circuit the remaining
-			 * keytype reap cycles.
-			 */
-			kdebug("dead short");
-			gc_state &= ~(KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2);
-			gc_state |= KEY_GC_REAPING_DEAD_3;
-		} else {
-			gc_state |= KEY_GC_REAP_AGAIN;
+		if (!list_empty(&graveyard)) {
+			queue_work(key_gc_wq, &key_gc_work.work);
+			goto out;
 		}
 	}
-
-	if (unlikely(gc_state & KEY_GC_REAPING_DEAD_3)) {
-		kdebug("dead wake");
-		clear_and_wake_up_bit(KEY_GC_REAPING_KEYTYPE, &key_gc_flags);
-	}
-
-	if (gc_state & KEY_GC_REAP_AGAIN)
-		schedule_work(&key_gc_work);
-	kleave(" [end %x]", gc_state);
+	gc->state &= ~KEY_GC_DESTROYING;
+
+	if ((gc->state & KEY_GC_REAP_AGAIN) ||
+	    test_bit(KEY_GC_REAP_REQUESTED, &key_gc_flags))
+		queue_work(key_gc_wq, &key_gc_work.work);
+out:
+	atomic_inc_return(&gc->seq);
+	kleave(" [end %x]", gc->state);
 	return;
 
 	/* We found an unreferenced key - once we've removed it from the tree,
@@ -335,15 +316,7 @@ static void key_garbage_collector(struct work_struct *work)
 	spin_unlock(&key_serial_lock);
 
 	list_add_tail(&key->graveyard_link, &graveyard);
-	gc_state |= KEY_GC_REAP_AGAIN;
-	goto maybe_resched;
-
-	/* We found a restricted keyring and need to update the restriction if
-	 * it is associated with the dead key type.
-	 */
-found_restricted_keyring:
-	spin_unlock(&key_serial_lock);
-	keyring_restriction_gc(key, key_gc_dead_keytype);
+	gc->state |= KEY_GC_REAP_AGAIN;
 	goto maybe_resched;
 
 	/* We found a keyring and we need to check the payload for links to
@@ -353,20 +326,6 @@ static void key_garbage_collector(struct work_struct *work)
 	 */
 found_keyring:
 	spin_unlock(&key_serial_lock);
-	keyring_gc(key, limit);
-	goto maybe_resched;
-
-	/* We found a dead key that is still referenced.  Reset its type and
-	 * destroy its payload with its semaphore held.
-	 */
-destroy_dead_key:
-	spin_unlock(&key_serial_lock);
-	kdebug("destroy key %d", key->serial);
-	down_write(&key->sem);
-	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);
+	keyring_gc(key, gc->start);
 	goto maybe_resched;
 }
diff --git a/security/keys/internal.h b/security/keys/internal.h
index b7b622bc36a137..6b5bb63b0e9e12 100644
--- a/security/keys/internal.h
+++ b/security/keys/internal.h
@@ -38,7 +38,6 @@ struct iovec;
 	no_printk(KERN_DEBUG FMT"\n", ##__VA_ARGS__)
 #endif
 
-extern struct key_type key_type_dead;
 extern struct key_type key_type_user;
 extern struct key_type key_type_logon;
 
@@ -162,15 +161,12 @@ extern bool lookup_user_key_possessed(const struct key *key,
 extern long join_session_keyring(const char *name);
 extern void key_change_session_keyring(struct callback_head *twork);
 
-extern struct work_struct key_gc_work;
 extern unsigned key_gc_delay;
+extern struct workqueue_struct *key_gc_wq;
 extern void keyring_gc(struct key *keyring, time64_t limit);
-extern void keyring_restriction_gc(struct key *keyring,
-				   struct key_type *dead_type);
 void key_set_expiry(struct key *key, time64_t expiry);
 extern void key_schedule_gc(time64_t gc_at);
-extern void key_schedule_gc_links(void);
-extern void key_gc_keytype(struct key_type *ktype);
+void key_schedule_gc_work(bool expired);
 
 extern int key_task_permission(const key_ref_t key_ref,
 			       const struct cred *cred,
diff --git a/security/keys/key.c b/security/keys/key.c
index 3f1f0fc137109a..53106bee2d27cb 100644
--- a/security/keys/key.c
+++ b/security/keys/key.c
@@ -7,6 +7,7 @@
 
 #include <linux/export.h>
 #include <linux/init.h>
+#include <linux/module.h>
 #include <linux/poison.h>
 #include <linux/sched.h>
 #include <linux/slab.h>
@@ -234,19 +235,34 @@ struct key *key_alloc(struct key_type *type, const char *desc,
 
 	key = ERR_PTR(-EINVAL);
 	if (!desc || !*desc)
-		goto error;
+		goto out;
+
+	/* Failed module initialization ignores outstanding module references. */
+	if ((type->owner && module_is_coming(type->owner)) ||
+	    !try_module_get(type->owner)) {
+		key = ERR_PTR(-ENOENT);
+		goto out;
+	}
+
+	if (restrict_link && restrict_link->keytype &&
+	    ((restrict_link->keytype->owner &&
+	      module_is_coming(restrict_link->keytype->owner)) ||
+	     !try_module_get(restrict_link->keytype->owner))) {
+		key = ERR_PTR(-ENOENT);
+		goto out_put_module;
+	}
 
 	if (type->vet_description) {
 		ret = type->vet_description(desc);
 		if (ret < 0) {
 			key = ERR_PTR(ret);
-			goto error;
+			goto out_put_restrict_module;
 		}
 	}
 
 	desclen = strlen(desc);
 	if (desclen >= KEY_MAX_DESC_SIZE)
-		goto error;
+		goto out_put_restrict_module;
 	quotalen = desclen + 1 + type->def_datalen;
 
 	/* get hold of the key tracking for this user */
@@ -323,8 +339,6 @@ struct key *key_alloc(struct key_type *type, const char *desc,
 	refcount_inc(&key->domain_tag->usage);
 	atomic_inc(&user->nkeys);
 	key_alloc_serial(key);
-
-error:
 	return key;
 
 security_error:
@@ -338,7 +352,7 @@ struct key *key_alloc(struct key_type *type, const char *desc,
 	}
 	key_user_put(user);
 	key = ERR_PTR(ret);
-	goto error;
+	goto out_put_restrict_module;
 
 no_memory_3:
 	kmem_cache_free(key_jar, key);
@@ -352,13 +366,22 @@ struct key *key_alloc(struct key_type *type, const char *desc,
 	key_user_put(user);
 no_memory_1:
 	key = ERR_PTR(-ENOMEM);
-	goto error;
+	goto out_put_restrict_module;
 
 no_quota:
 	spin_unlock_irqrestore(&user->lock, irqflags);
 	key_user_put(user);
 	key = ERR_PTR(-EDQUOT);
-	goto error;
+
+out_put_restrict_module:
+	if (restrict_link && restrict_link->keytype)
+		module_put(restrict_link->keytype->owner);
+
+out_put_module:
+	module_put(type->owner);
+
+out:
+	return key;
 }
 EXPORT_SYMBOL(key_alloc);
 
@@ -670,7 +693,7 @@ void key_put(struct key *key)
 			}
 			/* Mark key as safe for GC after key->user done. */
 			clear_bit_unlock(KEY_FLAG_USER_ALIVE, &key->flags);
-			schedule_work(&key_gc_work);
+			key_schedule_gc_work(false);
 		}
 	}
 }
@@ -1191,7 +1214,7 @@ void key_invalidate(struct key *key)
 		down_write_nested(&key->sem, 1);
 		if (!test_and_set_bit(KEY_FLAG_INVALIDATED, &key->flags)) {
 			notify_key(key, NOTIFY_KEY_INVALIDATED, 0);
-			key_schedule_gc_links();
+			key_schedule_gc_work(true);
 		}
 		up_write(&key->sem);
 	}
@@ -1231,19 +1254,20 @@ int generic_key_instantiate(struct key *key, struct key_preparsed_payload *prep)
 EXPORT_SYMBOL(generic_key_instantiate);
 
 /**
- * register_key_type - Register a type of key.
+ * __register_key_type - Register a type of key.
  * @ktype: The new key type.
+ * @owner: Module owning the key type.
  *
  * Register a new key type.
  *
  * Returns 0 on success or -EEXIST if a type of this name already exists.
  */
-int register_key_type(struct key_type *ktype)
+int __register_key_type(struct key_type *ktype, struct module *owner)
 {
 	struct key_type *p;
 	int ret;
 
-	memset(&ktype->lock_class, 0, sizeof(ktype->lock_class));
+	ktype->owner = owner;
 
 	ret = -EEXIST;
 	down_write(&key_types_sem);
@@ -1264,24 +1288,20 @@ int register_key_type(struct key_type *ktype)
 	up_write(&key_types_sem);
 	return ret;
 }
-EXPORT_SYMBOL(register_key_type);
+EXPORT_SYMBOL(__register_key_type);
 
 /**
  * unregister_key_type - Unregister a type of key.
  * @ktype: The key type.
  *
- * Unregister a key type and mark all the extant keys of this type as dead.
- * Those keys of this type are then destroyed to get rid of their payloads and
- * they and their links will be garbage collected as soon as possible.
+ * Unregister a key type.
  */
 void unregister_key_type(struct key_type *ktype)
 {
 	down_write(&key_types_sem);
 	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);
 }
 EXPORT_SYMBOL(unregister_key_type);
 
@@ -1294,9 +1314,12 @@ void __init key_init(void)
 	key_jar = kmem_cache_create("key_jar", sizeof(struct key),
 			0, SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_NO_MERGE, NULL);
 
+	key_gc_wq = alloc_workqueue("key_gc", WQ_MEM_RECLAIM | WQ_PERCPU, 0);
+	if (!key_gc_wq)
+		panic("Cannot create key_gc workqueue\n");
+
 	/* add the special key types */
 	list_add_tail(&key_type_keyring.link, &key_types_list);
-	list_add_tail(&key_type_dead.link, &key_types_list);
 	list_add_tail(&key_type_user.link, &key_types_list);
 	list_add_tail(&key_type_logon.link, &key_types_list);
 
diff --git a/security/keys/keyring.c b/security/keys/keyring.c
index 357f5636081055..7776983c3fdac7 100644
--- a/security/keys/keyring.c
+++ b/security/keys/keyring.c
@@ -7,6 +7,7 @@
 
 #include <linux/export.h>
 #include <linux/init.h>
+#include <linux/module.h>
 #include <linux/sched.h>
 #include <linux/slab.h>
 #include <linux/security.h>
@@ -265,7 +266,7 @@ void key_remove_domain(struct key_tag *domain_tag)
 {
 	domain_tag->removed = true;
 	if (!key_put_tag(domain_tag))
-		key_schedule_gc_links();
+		key_schedule_gc_work(true);
 }
 
 /*
@@ -436,6 +437,9 @@ static void keyring_destroy(struct key *keyring)
 	if (keyring->restrict_link) {
 		struct key_restriction *keyres = keyring->restrict_link;
 
+		if (keyres->keytype)
+			module_put(keyres->keytype->owner);
+
 		key_put(keyres->key);
 		kfree(keyres);
 	}
@@ -540,6 +544,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)
+				module_put(restrict_link->keytype->owner);
+			keyring->restrict_link = NULL;
 			key_put(keyring);
 			keyring = ERR_PTR(ret);
 		}
@@ -1062,7 +1069,7 @@ int keyring_restrict(key_ref_t keyring_ref, const char *type,
 
 		if (!restrict_type->lookup_restriction) {
 			ret = -ENOENT;
-			goto error;
+			goto out;
 		}
 
 		restrict_link = restrict_type->lookup_restriction(restriction);
@@ -1070,7 +1077,15 @@ int keyring_restrict(key_ref_t keyring_ref, const char *type,
 
 	if (IS_ERR(restrict_link)) {
 		ret = PTR_ERR(restrict_link);
-		goto error;
+		goto out;
+	}
+
+	if (restrict_link && restrict_link->keytype &&
+	    ((restrict_link->keytype->owner &&
+	      module_is_coming(restrict_link->keytype->owner)) ||
+	     !try_module_get(restrict_link->keytype->owner))) {
+		ret = -ENOENT;
+		goto out_free_restriction;
 	}
 
 	down_write(&keyring->sem);
@@ -1088,12 +1103,21 @@ int keyring_restrict(key_ref_t keyring_ref, const char *type,
 	up_write(&keyring_serialise_restrict_sem);
 	up_write(&keyring->sem);
 
-	if (ret < 0) {
+	if (ret < 0)
+		goto out_put_module;
+
+	goto out;
+
+out_put_module:
+	if (restrict_link && restrict_link->keytype)
+		module_put(restrict_link->keytype->owner);
+
+out_free_restriction:
+	if (restrict_link)
 		key_put(restrict_link->key);
-		kfree(restrict_link);
-	}
+	kfree(restrict_link);
 
-error:
+out:
 	if (restrict_type)
 		key_type_put(restrict_type);
 
@@ -1769,53 +1793,3 @@ void keyring_gc(struct key *keyring, time64_t limit)
 	up_write(&keyring->sem);
 	kleave(" [gc]");
 }
-
-/*
- * Garbage collect restriction pointers from a keyring.
- *
- * Keyring restrictions are associated with a key type, and must be cleaned
- * up if the key type is unregistered. The restriction is altered to always
- * reject additional keys so a keyring cannot be opened up by unregistering
- * a key type.
- *
- * Not called with any keyring locks held. The keyring's key struct will not
- * be deallocated under us as only our caller may deallocate it.
- *
- * The caller is required to hold key_types_sem and dead_type->sem. This is
- * fulfilled by key_gc_keytype() holding the locks on behalf of
- * key_garbage_collector(), which it invokes on a workqueue.
- */
-void keyring_restriction_gc(struct key *keyring, struct key_type *dead_type)
-{
-	struct key_restriction *keyres;
-
-	kenter("%x{%s}", keyring->serial, keyring->description ?: "");
-
-	/*
-	 * keyring->restrict_link is only assigned at key allocation time
-	 * or with the key type locked, so the only values that could be
-	 * concurrently assigned to keyring->restrict_link are for key
-	 * types other than dead_type. Given this, it's ok to check
-	 * the key type before acquiring keyring->sem.
-	 */
-	if (!dead_type || !keyring->restrict_link ||
-	    keyring->restrict_link->keytype != dead_type) {
-		kleave(" [no restriction gc]");
-		return;
-	}
-
-	/* Lock the keyring to ensure that a link is not in progress */
-	down_write(&keyring->sem);
-
-	keyres = keyring->restrict_link;
-
-	keyres->check = restrict_link_reject;
-
-	key_put(keyres->key);
-	keyres->key = NULL;
-	keyres->keytype = NULL;
-
-	up_write(&keyring->sem);
-
-	kleave(" [restriction gc]");
-}
diff --git a/security/keys/trusted-keys/trusted_core.c b/security/keys/trusted-keys/trusted_core.c
index 0509d9955f2a6f..11d7d296d063c2 100644
--- a/security/keys/trusted-keys/trusted_core.c
+++ b/security/keys/trusted-keys/trusted_core.c
@@ -373,14 +373,19 @@ static int __init init_trusted(void)
 		if (!get_random)
 			get_random = kernel_get_random;
 
+		static_call_update(trusted_key_seal, trusted_key_sources[i].ops->seal);
+		static_call_update(trusted_key_unseal, trusted_key_sources[i].ops->unseal);
+		static_call_update(trusted_key_get_random, get_random);
+		migratable = trusted_key_sources[i].ops->migratable;
+
 		ret = trusted_key_sources[i].ops->init();
 		if (!ret) {
-			static_call_update(trusted_key_seal, trusted_key_sources[i].ops->seal);
-			static_call_update(trusted_key_unseal, trusted_key_sources[i].ops->unseal);
-			static_call_update(trusted_key_get_random, get_random);
-
 			trusted_key_exit = trusted_key_sources[i].ops->exit;
-			migratable = trusted_key_sources[i].ops->migratable;
+		} else {
+			static_call_update(trusted_key_seal, NULL);
+			static_call_update(trusted_key_unseal, NULL);
+			static_call_update(trusted_key_get_random, NULL);
+			migratable = 0;
 		}
 
 		if (!ret || ret != -ENODEV)
diff --git a/security/keys/trusted-keys/trusted_tee.c b/security/keys/trusted-keys/trusted_tee.c
index 6e465c8bef5e5b..87ea549f7f0b97 100644
--- a/security/keys/trusted-keys/trusted_tee.c
+++ b/security/keys/trusted-keys/trusted_tee.c
@@ -9,6 +9,7 @@
 #include <linux/err.h>
 #include <linux/key-type.h>
 #include <linux/module.h>
+#include <linux/mutex.h>
 #include <linux/slab.h>
 #include <linux/string.h>
 #include <linux/tee_drv.h>
@@ -56,6 +57,8 @@ struct trusted_key_tee_private {
 };
 
 static struct trusted_key_tee_private pvt_data;
+/* Do not hold this mutex across key type registration or unregistration. */
+static DEFINE_MUTEX(trusted_key_tee_mutex);
 
 /*
  * Have the TEE seal(encrypt) the symmetric key
@@ -67,6 +70,12 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob)
 	struct tee_param param[4];
 	struct tee_shm *reg_shm = NULL;
 
+	mutex_lock(&trusted_key_tee_mutex);
+	if (!pvt_data.ctx) {
+		ret = -ENODEV;
+		goto out_unlock;
+	}
+
 	memset(&inv_arg, 0, sizeof(inv_arg));
 	memset(&param, 0, sizeof(param));
 
@@ -74,7 +83,8 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob)
 					      sizeof(p->key) + sizeof(p->blob));
 	if (IS_ERR(reg_shm)) {
 		dev_err(pvt_data.dev, "shm register failed\n");
-		return PTR_ERR(reg_shm);
+		ret = PTR_ERR(reg_shm);
+		goto out_unlock;
 	}
 
 	inv_arg.func = TA_CMD_SEAL;
@@ -100,7 +110,8 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob)
 	}
 
 	tee_shm_free(reg_shm);
-
+out_unlock:
+	mutex_unlock(&trusted_key_tee_mutex);
 	return ret;
 }
 
@@ -114,6 +125,12 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob)
 	struct tee_param param[4];
 	struct tee_shm *reg_shm = NULL;
 
+	mutex_lock(&trusted_key_tee_mutex);
+	if (!pvt_data.ctx) {
+		ret = -ENODEV;
+		goto out_unlock;
+	}
+
 	memset(&inv_arg, 0, sizeof(inv_arg));
 	memset(&param, 0, sizeof(param));
 
@@ -121,7 +138,8 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob)
 					      sizeof(p->key) + sizeof(p->blob));
 	if (IS_ERR(reg_shm)) {
 		dev_err(pvt_data.dev, "shm register failed\n");
-		return PTR_ERR(reg_shm);
+		ret = PTR_ERR(reg_shm);
+		goto out_unlock;
 	}
 
 	inv_arg.func = TA_CMD_UNSEAL;
@@ -147,7 +165,8 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob)
 	}
 
 	tee_shm_free(reg_shm);
-
+out_unlock:
+	mutex_unlock(&trusted_key_tee_mutex);
 	return ret;
 }
 
@@ -161,13 +180,20 @@ static int trusted_tee_get_random(unsigned char *key, size_t key_len)
 	struct tee_param param[4];
 	struct tee_shm *reg_shm = NULL;
 
+	mutex_lock(&trusted_key_tee_mutex);
+	if (!pvt_data.ctx) {
+		ret = -ENODEV;
+		goto out_unlock;
+	}
+
 	memset(&inv_arg, 0, sizeof(inv_arg));
 	memset(&param, 0, sizeof(param));
 
 	reg_shm = tee_shm_register_kernel_buf(pvt_data.ctx, key, key_len);
 	if (IS_ERR(reg_shm)) {
 		dev_err(pvt_data.dev, "key shm register failed\n");
-		return PTR_ERR(reg_shm);
+		ret = PTR_ERR(reg_shm);
+		goto out_unlock;
 	}
 
 	inv_arg.func = TA_CMD_GET_RANDOM;
@@ -189,7 +215,8 @@ static int trusted_tee_get_random(unsigned char *key, size_t key_len)
 	}
 
 	tee_shm_free(reg_shm);
-
+out_unlock:
+	mutex_unlock(&trusted_key_tee_mutex);
 	return ret;
 }
 
@@ -205,50 +232,67 @@ static int optee_ctx_match(struct tee_ioctl_version_data *ver, const void *data)
 static int trusted_key_probe(struct tee_client_device *rng_device)
 {
 	struct device *dev = &rng_device->dev;
+	struct tee_context *ctx;
 	int ret;
 	struct tee_ioctl_open_session_arg sess_arg;
 
+	mutex_lock(&trusted_key_tee_mutex);
+	if (pvt_data.ctx) {
+		ret = -EBUSY;
+		goto out_unlock;
+	}
+
 	memset(&sess_arg, 0, sizeof(sess_arg));
 
-	pvt_data.ctx = tee_client_open_context(NULL, optee_ctx_match, NULL,
-					       NULL);
-	if (IS_ERR(pvt_data.ctx))
-		return -ENODEV;
+	ctx = tee_client_open_context(NULL, optee_ctx_match, NULL, NULL);
+	if (IS_ERR(ctx)) {
+		ret = -ENODEV;
+		goto out_unlock;
+	}
 
 	memcpy(sess_arg.uuid, rng_device->id.uuid.b, TEE_IOCTL_UUID_LEN);
 	sess_arg.clnt_login = TEE_IOCTL_LOGIN_REE_KERNEL;
 	sess_arg.num_params = 0;
 
-	ret = tee_client_open_session(pvt_data.ctx, &sess_arg, NULL);
+	ret = tee_client_open_session(ctx, &sess_arg, NULL);
 	if ((ret < 0) || (sess_arg.ret != 0)) {
 		dev_err(dev, "tee_client_open_session failed, err: %x\n",
 			sess_arg.ret);
 		ret = -EINVAL;
 		goto out_ctx;
 	}
+	pvt_data.ctx = ctx;
 	pvt_data.session_id = sess_arg.session;
-
-	ret = register_key_type(&key_type_trusted);
-	if (ret < 0)
-		goto out_sess;
-
 	pvt_data.dev = dev;
+	mutex_unlock(&trusted_key_tee_mutex);
 
-	return 0;
+	ret = register_key_type(&key_type_trusted);
+	if (!ret)
+		return 0;
 
-out_sess:
-	tee_client_close_session(pvt_data.ctx, pvt_data.session_id);
+	mutex_lock(&trusted_key_tee_mutex);
+	tee_client_close_session(ctx, pvt_data.session_id);
 out_ctx:
-	tee_client_close_context(pvt_data.ctx);
-
+	tee_client_close_context(ctx);
+	pvt_data.ctx = NULL;
+	pvt_data.dev = NULL;
+	pvt_data.session_id = 0;
+out_unlock:
+	mutex_unlock(&trusted_key_tee_mutex);
 	return ret;
 }
 
 static void trusted_key_remove(struct tee_client_device *dev)
 {
 	unregister_key_type(&key_type_trusted);
+
+	mutex_lock(&trusted_key_tee_mutex);
 	tee_client_close_session(pvt_data.ctx, pvt_data.session_id);
 	tee_client_close_context(pvt_data.ctx);
+	pvt_data.ctx = NULL;
+	pvt_data.dev = NULL;
+	pvt_data.session_id = 0;
+	mutex_unlock(&trusted_key_tee_mutex);
 }
 
 static const struct tee_client_device_id trusted_key_id_table[] = {
@@ -263,7 +307,8 @@ static struct tee_client_driver trusted_key_driver = {
 	.remove		= trusted_key_remove,
 	.id_table	= trusted_key_id_table,
 	.driver		= {
-		.name		= DRIVER_NAME,
+		.name			= DRIVER_NAME,
+		.suppress_bind_attrs	= true,
 	},
 };
 

3/2 2026/11/16 00:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36646
							output: 27
							thoughts: 1541
						

Thoughts:
**Patch Series Analysis: Key Subsystem Deep Dive**

Okay, so this patch series has my attention. It's touching quite a few files, spanning networking (rxrpc, DNS, NFS, SMB), architecture-specific code (s390), and most importantly, the core `security/keys/` subsystem. That's a big red flag, in a good way!

First, let's establish some ground rules. This is for amd64, that's fine. And this _definitely_ hits core subsystems. `security/keys/` is critical, and the network components are also important. The s390 parts are specific, but that's not the focus here.

My initial reaction is **WorthFuzzing=true** because of the sweeping changes to the key subsystem. We're talking about fundamental changes to key lifecycle, garbage collection, module refcounting, and keyring restrictions. This stuff is directly exposed to userspace via the `add_key`, `keyctl`, and `request_key` syscalls - which means it's a prime target for fuzzing. This is excellent!

Now, according to the triaging guidelines, we need to focus the fuzzer. No generic stuff. Specific function calls in .c, not .h, because the .h files use inline functions. Specifically, we need to focus symbols, so we don't end up fuzzing everywhere. Let's see...

I'll start dissecting the `security/keys/` changes. Looks like `security/keys/gc.c` got the biggest overhaul: We have `key_schedule_gc_work`, `key_gc_flush`, `key_gc_unused_keys` (which sounds interesting for chunked scanning), plus additions and modifications to functions like `key_alloc`, `__register_key_type`, `unregister_key_type` and `keyring_restrict`. And finally, we have `key_garbage_collector`, which looks like the work handler. I should check if that can be a symbol, or whether it's called somewhere else.

Let's not forget the `net/` side.  `net/rxrpc/server_key.c` is being split into module and config, with server key logic being moved, and `fs/nfs/nfs4idmap.c` and `fs/smb/client/misc.c` are also utilizing the new garbage collection.

Next, I'll dive into the Kconfig files, starting with `security/keys/Kconfig` to see what configuration options are involved.  We'll need to figure out the minimal set of configurations to get this code compiled and active.



4/2 2026/11/16 00:55 tool grepper
0m Args:
{
  "Expression": "config KEYS",
  "PathPrefixes": [
    "security/keys/"
  ]
}

Results:
{
  "Output": "security/keys/Kconfig-5-\nsecurity/keys/Kconfig:6:menuconfig KEYS\nsecurity/keys/Kconfig-7-\tbool \"Enable access key retention support\"\n--\nsecurity/keys/Kconfig=24=if KEYS\nsecurity/keys/Kconfig-25-\nsecurity/keys/Kconfig:26:config KEYS_REQUEST_CACHE\nsecurity/keys/Kconfig-27-\tbool \"Enable temporary caching of the last request_key() result\"\n"
}

5/2 2026/11/16 00:55 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38911
							output: 30
							thoughts: 102
						

Thoughts:
Okay, here's my quick rundown of what I'm thinking, keeping it concise and focusing on the important configurations I need to check.

**Configuration Investigation: Key Systems & Network Protocols**

Alright, time to dig in. I need to make sure I've got a comprehensive understanding of how the configuration is set up. First, I'm going to quickly check the configuration options for various key components. Specifically, I'm interested in the settings for:

*   **KEYS**: The core key management system.
*   **RXRPC-related options**: This includes `RXRPC_KEYS`, `AF_RXRPC`, `RXKAD`, and `RXGK`. I need to ensure the configuration related to Remote Execution RPC is correct and integrated properly.
*   **DNS configurations**: I'll review both `DNS_KEY` and `DNS_RESOLVER` settings.
*   **File sharing configs**: I'm going to verify settings related to `CIFS` and `CIFS_UPCALL`.
*   **NFS**: I need to check `NFS_V4` options.
*   **TRUSTED_KEYS**: This is probably the most critical part, given it's under security. I'll need to go to `security/keys/trusted-keys/Kconfig` to see the details on that.

To do this efficiently, I'll need to review a couple of key Kconfig files, starting with `security/keys/trusted-keys/Kconfig` for the trusted keys setup, and also `net/rxrpc/Kconfig` to understand the RxRPC configuration in more detail. That's a good place to start.



6/2 2026/11/16 00:56 tool grepper
0m Args:
{
  "Expression": "config TRUSTED_KEYS",
  "PathPrefixes": [
    "security/keys/"
  ]
}

Results:
{
  "Output": "security/keys/Kconfig=59=config BIG_KEYS\n--\nsecurity/keys/Kconfig-69-\nsecurity/keys/Kconfig:70:config TRUSTED_KEYS\nsecurity/keys/Kconfig-71-\ttristate \"TRUSTED KEYS\"\n--\nsecurity/keys/trusted-keys/Kconfig=4=config HAVE_TRUSTED_KEYS_DEBUG\n--\nsecurity/keys/trusted-keys/Kconfig-6-\nsecurity/keys/trusted-keys/Kconfig:7:config TRUSTED_KEYS_DEBUG\nsecurity/keys/trusted-keys/Kconfig-8-\tbool \"Debug trusted keys\"\n--\nsecurity/keys/trusted-keys/Kconfig-21-\nsecurity/keys/trusted-keys/Kconfig:22:config TRUSTED_KEYS_TPM\nsecurity/keys/trusted-keys/Kconfig-23-\tbool \"TPM-based trusted keys\"\n--\nsecurity/keys/trusted-keys/Kconfig-40-\nsecurity/keys/trusted-keys/Kconfig:41:config TRUSTED_KEYS_TEE\nsecurity/keys/trusted-keys/Kconfig-42-\tbool \"TEE-based trusted keys\"\n--\nsecurity/keys/trusted-keys/Kconfig-50-\nsecurity/keys/trusted-keys/Kconfig:51:config TRUSTED_KEYS_CAAM\nsecurity/keys/trusted-keys/Kconfig-52-\tbool \"CAAM-based trusted keys\"\n--\nsecurity/keys/trusted-keys/Kconfig-61-\nsecurity/keys/trusted-keys/Kconfig:62:config TRUSTED_KEYS_DCP\nsecurity/keys/trusted-keys/Kconfig-63-\tbool \"DCP-based trusted keys\"\n--\nsecurity/keys/trusted-keys/Kconfig-70-\nsecurity/keys/trusted-keys/Kconfig:71:config TRUSTED_KEYS_PKWM\nsecurity/keys/trusted-keys/Kconfig-72-\tbool \"PKWM-based trusted keys\"\n"
}

7/2 2026/11/16 00:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39883
							output: 43
							thoughts: 24
						

Thoughts:
Here's a summary of my immediate thought process:

**Kconfig File Dive: RxRPC and DNS Resolver**

Okay, so I need to get a handle on the current configuration landscape. My initial thought is to zero in on two specific Kconfig files: `net/rxrpc/Kconfig` and `net/dns_resolver/Kconfig`. These are likely to be critical in understanding how these particular network features are being managed and what dependencies they might have. I want to quickly grasp the relevant configuration options available for RxRPC and the DNS resolver, how they relate to each other, and if there are any immediate configuration constraints I need to be aware of. Let's see what these Kconfig files reveal.



8/2 2026/11/16 00:56 tool grepper
0m Args:
{
  "Expression": "config (RXRPC|DNS)",
  "PathPrefixes": [
    "net/rxrpc/",
    "net/dns_resolver/"
  ]
}

Results:
{
  "Output": "net/dns_resolver/Kconfig-5-#\nnet/dns_resolver/Kconfig:6:config DNS_KEY\nnet/dns_resolver/Kconfig-7-\ttristate \"DNS Resolver key type\"\n--\nnet/dns_resolver/Kconfig-18-#\nnet/dns_resolver/Kconfig:19:config DNS_RESOLVER\nnet/dns_resolver/Kconfig-20-\ttristate \"DNS Resolver support\"\n--\nnet/rxrpc/Kconfig-5-\nnet/rxrpc/Kconfig:6:config RXRPC_KEYS\nnet/rxrpc/Kconfig-7-\ttristate \"RxRPC key types\"\n"
}

9/2 2026/11/16 00:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 40266
							output: 34
							thoughts: 22
						

Thoughts:
Here's my analysis of the provided text, structured as a first-person expert summary:

**Digging into the Dependencies of `net/dns_resolver/Kconfig`**

Okay, so I need to get a really good handle on the DNS resolver configuration. Time to dive into `net/dns_resolver/Kconfig` and see what's actually driving its behavior. I know Kconfig is the key to understanding the conditional compilation and dependencies within the build system, so let's start there. I'll need to meticulously examine each `depends on` statement to fully grasp what needs to be enabled or present in order for the DNS resolver options to even become available. It's about figuring out the prerequisites – the building blocks that make the DNS resolver functionality possible, and what other subsystems or configurations hinge on it. This deep dive is crucial for understanding how to best tailor the system configuration and prevent conflicts. Time to get my hands dirty.



10/2 2026/11/16 00:56 tool read-file
0m Args:
{
  "File": "net/dns_resolver/Kconfig",
  "FirstLine": 1,
  "LineCount": 40
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0-only\n   2:\t\n   3:\t#\n   4:\t# Configuration for DNS Resolver key type\n   5:\t#\n   6:\tconfig DNS_KEY\n   7:\t\ttristate \"DNS Resolver key type\"\n   8:\t\tdepends on KEYS\n   9:\t\thelp\n  10:\t\t  Support the key type used to cache DNS lookups independently of\n  11:\t\t  the in-kernel DNS query service.\n  12:\t\n  13:\t\t  To compile this as a module, choose M here: the module is called\n  14:\t\t  dns_resolver_key.\n  15:\t\n  16:\t#\n  17:\t# Configuration for DNS Resolver\n  18:\t#\n  19:\tconfig DNS_RESOLVER\n  20:\t\ttristate \"DNS Resolver support\"\n  21:\t\tdepends on KEYS\n  22:\t\tselect DNS_KEY\n  23:\t\thelp\n  24:\t\t  Saying Y here will include support for the DNS Resolver key type\n  25:\t\t  which can be used to make upcalls to perform DNS lookups in\n  26:\t\t  userspace.\n  27:\t\n  28:\t\t  DNS Resolver is used to query DNS server for information.  Examples\n  29:\t\t  being resolving a UNC hostname element to an IP address for CIFS or\n  30:\t\t  performing a DNS query for AFSDB records so that AFS can locate a\n  31:\t\t  cell's volume location database servers.\n  32:\t\n  33:\t\t  DNS Resolver is used by the CIFS and AFS modules, and would support\n  34:\t\t  SMB2 later.  DNS Resolver is supported by the userspace upcall\n  35:\t\t  helper \"/sbin/dns.resolver\" via /etc/request-key.conf.\n  36:\t\n  37:\t\t  See \u003cfile:Documentation/networking/dns_resolver.rst\u003e for further\n  38:\t\t  information.\n  39:\t\n  40:\t\t  To compile this as a module, choose M here: the module will be called\n"
}

11/2 2026/11/16 00:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41053
							output: 33
							thoughts: 21
						

Thoughts:
Here's a summary of my thought process, focusing on what I'd be thinking as I tackled this:

**Initial Assessment: Kconfig Dive**

Okay, time to dive into `net/rxrpc/Kconfig`. Based on the context, I'm likely debugging, configuring, or reviewing something related to the RxRPC protocol within the Linux kernel. The focus on lines 1-60 suggests a specific section, likely the top-level configuration options, defaults, or dependencies for the RxRPC subsystem. I need to understand what's defined in that initial chunk, because it likely sets the stage for the rest of the configuration. Let's see what the base config options are, if there are any prerequisites, and if the config is structured well. I'll be looking for any immediate red flags or gotchas, like circular dependencies or confusing defaults. This section usually contains the core controls for enabling or disabling the whole feature and maybe selecting key variants, so it is a good starting point.



12/2 2026/11/16 00:56 tool read-file
0m Args:
{
  "File": "net/rxrpc/Kconfig",
  "FirstLine": 1,
  "LineCount": 60
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0-only\n   2:\t#\n   3:\t# RxRPC session sockets\n   4:\t#\n   5:\t\n   6:\tconfig RXRPC_KEYS\n   7:\t\ttristate \"RxRPC key types\"\n   8:\t\tselect CRYPTO\n   9:\t\tselect CRYPTO_LIB_DES if RXKAD\n  10:\t\tselect KEYS\n  11:\t\thelp\n  12:\t\t  Say Y or M here to include support for rxrpc and rxrpc_s key types\n  13:\t\t  independently of RxRPC session sockets.\n  14:\t\n  15:\t\t  To compile this as a module, choose M here: the module will be called\n  16:\t\t  rxrpc_keys.\n  17:\t\n  18:\tconfig AF_RXRPC\n  19:\t\ttristate \"RxRPC session sockets\"\n  20:\t\tdepends on INET\n  21:\t\tselect CRYPTO\n  22:\t\tselect CRYPTO_LIB_DES if RXKAD\n  23:\t\tselect KEYS\n  24:\t\tselect NET_UDP_TUNNEL\n  25:\t\tselect RXRPC_KEYS\n  26:\t\thelp\n  27:\t\t  Say Y or M here to include support for RxRPC session sockets (just\n  28:\t\t  the transport part, not the presentation part: (un)marshalling is\n  29:\t\t  left to the application).\n  30:\t\n  31:\t\t  These are used for AFS kernel filesystem and userspace utilities.\n  32:\t\n  33:\t\t  This module at the moment only supports client operations and is\n  34:\t\t  currently incomplete.\n  35:\t\n  36:\t\t  See Documentation/networking/rxrpc.rst.\n  37:\t\n  38:\tif AF_RXRPC\n  39:\t\n  40:\tconfig AF_RXRPC_IPV6\n  41:\t\tbool \"IPv6 support for RxRPC\"\n  42:\t\tdepends on IPV6\n  43:\t\thelp\n  44:\t\t  Say Y here to allow AF_RXRPC to use IPV6 UDP as well as IPV4 UDP as\n  45:\t\t  its network transport.\n  46:\t\n  47:\tconfig AF_RXRPC_INJECT_LOSS\n  48:\t\tbool \"Inject packet loss into RxRPC packet stream\"\n  49:\t\thelp\n  50:\t\t  Say Y here to inject packet loss by discarding some received and some\n  51:\t\t  transmitted packets.\n  52:\t\n  53:\tconfig AF_RXRPC_INJECT_RX_DELAY\n  54:\t\tbool \"Inject delay into packet reception\"\n  55:\t\tdepends on SYSCTL\n  56:\t\thelp\n  57:\t\t  Say Y here to inject a delay into packet reception, allowing an\n  58:\t\t  extended RTT time to be modelled.  The delay can be configured using\n  59:\t\t  /proc/sys/net/rxrpc/rxrpc_inject_rx_delay, setting a number of\n  60:\t\t  milliseconds up to 0.5s (note that the granularity is actually in\n"
}

13/2 2026/11/16 00:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 42107
							output: 34
							thoughts: 22
						

Thoughts:
Here's my take on those lines of the Kconfig file:

**Checking the RXRPC Configuration Options**

Okay, so I need to dive into lines 61-110 of the `net/rxrpc/Kconfig` file. This is where the core configuration options for RXRPC should be defined. I'm expecting to see the dependencies, descriptions, and default values for the features that control RXRPC functionality.

I'm thinking this section will cover things like the RPC protocol version support, any related security features (authentication, encryption), different transport layer options (UDP, TCP), maybe some options related to flow control, and perhaps debugging or tracing flags. Based on the file location, I also expect to see some options pertaining to connection management, such as keep-alive mechanisms or timeout settings. I also anticipate it will probably include enabling and disabling various RXRPC subsystems. The aim here, is to identify if there are any new or changed options that I need to be aware of. I need to understand whether there are any dependencies that have been added or removed, or if any features have been made mandatory. This will inform my work, and potentially impact other areas of the system.



14/2 2026/11/16 00:56 tool read-file
0m Args:
{
  "File": "net/rxrpc/Kconfig",
  "FirstLine": 61,
  "LineCount": 55
}

Results:
{
  "Contents": "  61:\t\t  jiffies).\n  62:\t\n  63:\tconfig AF_RXRPC_DEBUG\n  64:\t\tbool \"RxRPC dynamic debugging\"\n  65:\t\thelp\n  66:\t\t  Say Y here to make runtime controllable debugging messages appear.\n  67:\t\n  68:\t\t  See Documentation/networking/rxrpc.rst.\n  69:\t\n  70:\tendif\n  71:\t\n  72:\tif RXRPC_KEYS\n  73:\t\n  74:\tconfig RXKAD\n  75:\t\tbool \"RxRPC Kerberos security\"\n  76:\t\thelp\n  77:\t\t  Provide kerberos 4 and AFS kaserver security handling for AF_RXRPC\n  78:\t\t  through the use of the key retention service.\n  79:\t\n  80:\t\t  See Documentation/networking/rxrpc.rst.\n  81:\t\n  82:\tconfig RXGK\n  83:\t\tbool \"RxRPC GSSAPI security\"\n  84:\t\tselect CRYPTO_KRB5\n  85:\t\tselect CRYPTO_MANAGER\n  86:\t\tselect CRYPTO_KRB5ENC\n  87:\t\tselect CRYPTO_AUTHENC\n  88:\t\tselect CRYPTO_SKCIPHER\n  89:\t\tselect CRYPTO_HASH_INFO\n  90:\t\tselect CRYPTO_HMAC\n  91:\t\tselect CRYPTO_CMAC\n  92:\t\tselect CRYPTO_SHA1\n  93:\t\tselect CRYPTO_SHA256\n  94:\t\tselect CRYPTO_SHA512\n  95:\t\tselect CRYPTO_CBC\n  96:\t\tselect CRYPTO_CTS\n  97:\t\tselect CRYPTO_AES\n  98:\t\tselect CRYPTO_CAMELLIA\n  99:\t\thelp\n 100:\t\t  Provide the GSSAPI-based RxGK security class for AFS.  Keys are added\n 101:\t\t  with add_key().\n 102:\t\n 103:\t\t  See Documentation/networking/rxrpc.rst.\n 104:\t\n 105:\tendif\n 106:\t\n 107:\tif AF_RXRPC\n 108:\t\n 109:\tconfig RXPERF\n 110:\t\ttristate \"RxRPC test service\"\n 111:\t\thelp\n 112:\t\t  Provide an rxperf service tester.  This listens on UDP port 7009 for\n 113:\t\t  incoming calls from the rxperf program (an example of which can be\n 114:\t\t  found in OpenAFS).\n 115:\t\n"
}

15/2 2026/11/16 00:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43081
							output: 28
							thoughts: 18
						

Thoughts:
Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:

**Analyzing the Commit History**

Alright, let's dive into this patch series or, if we're looking at the current state, `HEAD`. My initial instinct is to use `git log`. I want a granular view of those commit messages – the *why* behind each change. Understanding the evolution of the code, the reasoning that drove each commit, is crucial. It gives me context. A simple diff isn't going to cut it. I need the narrative. I need to see if the commit messages are well-written, if they follow the conventions we've established, and if they adequately explain the problem addressed and the solution implemented. Ultimately, I need to see if the history tells a clear and consistent story, or if there are any red flags. I’ll be using `git log` to ascertain the relevant commit messages.



16/2 2026/11/16 00:56 tool grepper
0m Args:
{
  "Expression": ".*",
  "PathPrefixes": [
    ".git/logs/HEAD"
  ]
}

Results:
{
  "Output": "no matches"
}

17/2 2026/11/16 00:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43342
							output: 40
							thoughts: 3532
						

Thoughts:
**Analysis of Security/Keys and net/rxrpc Changes for Fuzzing Focus**

Alright, let's break this down. From the git commit, we're looking at a significant refactoring of the key garbage collector and some related changes in `net/rxrpc`. My initial thought is that this has definite fuzzing potential, especially since it touches core subsystems like `security/keys` and `net/rxrpc` – which are absolutely reachable via syscalls.

The `security/keys/gc.c` changes look particularly interesting. They've ripped out the old dead key type mechanism and are now refcounting modules. The `key_garbage_collector` itself is restructured with a cursor, chunking, and locking. The `key_gc_flush` function with its `flush_work` loop immediately raises a flag. That loop could be a recipe for hangs or livelocks – a fuzzer's dream! The cursor manipulation in `key_garbage_collector`, especially with potential removals/additions during lock drops, is another spot I want to explore. The `graveyard` list being *static* within `key_garbage_collector` is also something to keep an eye on. And the fact that `key_gc_unused_keys` processes chunks of keys also raises questions. This is a big state machine change!

Then there's `net/rxrpc`. The key types have been split into a separate module, and various functions like `rxrpc_preparse_s`, `rxkad_preparse_server_key`, and `rxrpc_request_key` are modified. The `conn->security->init_connection_security` call in `conn_event.c` also looks like a good spot to probe for vulnerabilities.

Changes in `net/dns_resolver` including the addition of `key_gc_flush()` are very interesting. The inclusion of `key_gc_flush()` in `nfs4idmap.c` and in multiple `fs/smb/client/*` files indicates that the changes are far-reaching.

Now, let's identify the specific functions. I need to avoid the "ubiquitous lifecycle hot-paths" and focus on feature-specific logic. So, from `security/keys/gc.c`, I'd prioritize `key_garbage_collector`, `key_schedule_gc_work`, `key_gc_flush`, `key_gc_unused_keys` and `key_set_expiry`, `key_alloc`, `__register_key_type`, `unregister_key_type`, and `keyring_restrict`. From `net/rxrpc`, I'm looking at `rxrpc_preparse_s`, `rxkad_preparse_server_key`, `rxrpc_request_key`, `rxrpc_get_server_data_key`, and so on. Additionally, `nfs_idmap_new` and `nfs_idmap_delete` from `fs/nfs/nfs4idmap.c`, as well as `sesInfoAlloc` and `sesInfoFree` from `fs/smb/client/misc.c` look interesting. I'll need to double-check which of these functions are static to ensure they are accessible.

The overarching feeling is that this represents a major shift in how key management is handled, with a lot of potential edge cases that a fuzzer could definitely expose.



18/2 2026/11/16 00:56 tool grepper
0m Args:
{
  "Expression": "^(static )?int rx.*preparse",
  "PathPrefixes": [
    "net/rxrpc/server_key.c"
  ]
}

Results:
{
  "Output": "net/rxrpc/server_key.c=30=static int rxrpc_vet_description_s(const char *);\nnet/rxrpc/server_key.c:31:static int rxrpc_preparse_s(struct key_preparsed_payload *);\nnet/rxrpc/server_key.c-32-static void rxrpc_free_preparse_s(struct key_preparsed_payload *);\n--\nnet/rxrpc/server_key.c=55=static int rxrpc_vet_description_s(const char *desc)\n--\nnet/rxrpc/server_key.c-74- */\nnet/rxrpc/server_key.c:75:static int rxkad_preparse_server_key(struct key_preparsed_payload *prep)\nnet/rxrpc/server_key.c-76-{\n--\nnet/rxrpc/server_key.c=111=static void rxkad_destroy_server_key(struct key *key)\n--\nnet/rxrpc/server_key.c-121- */\nnet/rxrpc/server_key.c:122:static int rxgk_preparse_server_key(struct key_preparsed_payload *prep)\nnet/rxrpc/server_key.c-123-{\n--\nnet/rxrpc/server_key.c=173=static void rxgk_describe_server_key(const struct key *key, struct seq_file *m)\n--\nnet/rxrpc/server_key.c-184- */\nnet/rxrpc/server_key.c:185:static int rxrpc_preparse_s(struct key_preparsed_payload *prep)\nnet/rxrpc/server_key.c-186-{\n"
}

19/2 2026/11/16 00:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 48080
							output: 37
							thoughts: 27
						

Thoughts:
Here's my take on the thought process, as requested:

**Diving into `rxrpc` Key Handling**

Okay, so I need to get a handle on how `rxrpc` manages its key types. Let's start with the server side. My initial thought is to examine the `key_type_rxrpc_s` structure. That sounds like a good starting point, and I know it's defined in the `net/rxrpc/server_key.c` file. I'll need to understand how this specific key type is handled by the server. This should reveal information about server key management. Let's see what's in there.



20/2 2026/11/16 00:56 tool read-file
0m Args:
{
  "File": "net/rxrpc/server_key.c",
  "FirstLine": 30,
  "LineCount": 25
}

Results:
{
  "Contents": "  30:\tstatic int rxrpc_vet_description_s(const char *);\n  31:\tstatic int rxrpc_preparse_s(struct key_preparsed_payload *);\n  32:\tstatic void rxrpc_free_preparse_s(struct key_preparsed_payload *);\n  33:\tstatic void rxrpc_destroy_s(struct key *);\n  34:\tstatic void rxrpc_describe_s(const struct key *, struct seq_file *);\n  35:\t\n  36:\t/*\n  37:\t * rxrpc server keys take \"\u003cserviceId\u003e:\u003csecurityIndex\u003e[:\u003csec-specific\u003e]\" as the\n  38:\t * description and the key material as the payload.\n  39:\t */\n  40:\tstruct key_type key_type_rxrpc_s = {\n  41:\t\t.name\t\t= \"rxrpc_s\",\n  42:\t\t.flags\t\t= KEY_TYPE_NET_DOMAIN,\n  43:\t\t.vet_description = rxrpc_vet_description_s,\n  44:\t\t.preparse\t= rxrpc_preparse_s,\n  45:\t\t.free_preparse\t= rxrpc_free_preparse_s,\n  46:\t\t.instantiate\t= generic_key_instantiate,\n  47:\t\t.destroy\t= rxrpc_destroy_s,\n  48:\t\t.describe\t= rxrpc_describe_s,\n  49:\t};\n  50:\tEXPORT_SYMBOL(key_type_rxrpc_s);\n  51:\t\n  52:\t/*\n  53:\t * Vet the description for an RxRPC server key.\n  54:\t */\n"
}

21/2 2026/11/16 00:56 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 48707
							output: 34
							thoughts: 210
						

Thoughts:
Here's a breakdown of my thought process:

**Diving into the RxRPC Key Management**

Okay, so I'm looking at these methods, `rxrpc_preparse_s`, `rxrpc_destroy_s`, and `rxrpc_describe_s`. They're all part of `key_type_rxrpc_s`, which means they're specific to the "rxrpc_s" key type. Got it. Now, I'm tracing the key addition process. When we use `add_key("rxrpc_s", ...)` with its description, payload, plen, and ring arguments, `key_create_or_update` gets involved and it calls `rxrpc_preparse_s`.

Hold on... I see that `rxrpc_preparse_s` then calls either `rxkad_preparse_server_key` or `rxgk_preparse_server_key`. That's in `server_key.c`. Right, so this is all about parsing and preparing the key data, and I'm guessing "server" implies security.

Now, a broader question is forming: how are these "rxrpc" keys actually used? I need to understand the full picture. Can userspace code add *both* "rxrpc" and "rxrpc_s" key types? The naming is subtly different. Looks like the answer is yes, they can: `add_key("rxrpc", ...)` and `add_key("rxrpc_s", ...)` both exist. Okay, this confirms they're distinct but related key types. I should probably check `net/rxrpc/key.c` to see how the generic key functionality interacts with the RxRPC-specific logic. I need to understand how the RxRPC key management works at a lower level now.



22/2 2026/11/16 00:57 tool grepper
0m Args:
{
  "Expression": "key_type_rxrpc\\b",
  "PathPrefixes": [
    "net/rxrpc/"
  ]
}

Results:
{
  "Output": "net/rxrpc/ar-internal.h=1291=extern const struct rxrpc_security rxrpc_no_security;\n--\nnet/rxrpc/ar-internal.h-1295- */\nnet/rxrpc/ar-internal.h:1296:extern struct key_type key_type_rxrpc;\nnet/rxrpc/ar-internal.h-1297-\n--\nnet/rxrpc/key.c=31=static long rxrpc_read(const struct key *, char *, size_t);\n--\nnet/rxrpc/key.c-36- */\nnet/rxrpc/key.c:37:struct key_type key_type_rxrpc = {\nnet/rxrpc/key.c-38-\t.name\t\t= \"rxrpc\",\n--\nnet/rxrpc/key.c-46-};\nnet/rxrpc/key.c:47:EXPORT_SYMBOL(key_type_rxrpc);\nnet/rxrpc/key.c-48-\n--\nnet/rxrpc/key.c=628=struct key *rxrpc_get_null_key(const char *keyname)\n--\nnet/rxrpc/key.c-633-\nnet/rxrpc/key.c:634:\tkey = key_alloc(\u0026key_type_rxrpc, keyname,\nnet/rxrpc/key.c-635-\t\t\tGLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,\n--\nnet/rxrpc/key.c=815=static int __init rxrpc_keys_init(void)\n--\nnet/rxrpc/key.c-818-\nnet/rxrpc/key.c:819:\tret = register_key_type(\u0026key_type_rxrpc);\nnet/rxrpc/key.c-820-\tif (ret \u003c 0) {\n--\nnet/rxrpc/key.c-833-error_key_type_s:\nnet/rxrpc/key.c:834:\tunregister_key_type(\u0026key_type_rxrpc);\nnet/rxrpc/key.c-835-\n--\nnet/rxrpc/key.c=840=static void __exit rxrpc_keys_exit(void)\n--\nnet/rxrpc/key.c-842-\tunregister_key_type(\u0026key_type_rxrpc_s);\nnet/rxrpc/key.c:843:\tunregister_key_type(\u0026key_type_rxrpc);\nnet/rxrpc/key.c-844-}\n--\nnet/rxrpc/rxgk_app.c=42=int rxgk_yfs_decode_ticket(struct rxrpc_connection *conn, struct sk_buff *skb,\n--\nnet/rxrpc/rxgk_app.c-133-\t/* Now turn that into a key. */\nnet/rxrpc/rxgk_app.c:134:\tkey = key_alloc(\u0026key_type_rxrpc, \"x\",\nnet/rxrpc/rxgk_app.c-135-\t\t\tGLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred, // TODO: Use socket owner\n--\nnet/rxrpc/security.c=217=int rxrpc_request_key(struct rxrpc_sock *rx, sockptr_t optval, int optlen)\n--\nnet/rxrpc/security.c-230-\nnet/rxrpc/security.c:231:\tkey = request_key_net(\u0026key_type_rxrpc, description, sock_net(\u0026rx-\u003esk), NULL);\nnet/rxrpc/security.c-232-\tif (IS_ERR(key)) {\n--\nnet/rxrpc/security.c=247=int rxrpc_get_server_data_key(struct rxrpc_connection *conn,\n--\nnet/rxrpc/security.c-261-\nnet/rxrpc/security.c:262:\tkey = key_alloc(\u0026key_type_rxrpc, \"x\",\nnet/rxrpc/security.c-263-\t\t\tGLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred, 0,\n"
}

23/2 2026/11/16 00:57 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 50364
							output: 34
							thoughts: 20
						

Thoughts:
Okay, here's the summary, rendered as a first-person thought process, keeping in mind the user is an expert:

**Investigating DNS Resolution: Expanding the Scope**

Alright, I'm already deep into this DNS resolution issue, but a nagging feeling tells me we should widen the net a bit. We've likely touched upon the obvious areas, but let's not leave any stone unturned, particularly when dealing with core infrastructure components. *Crucially*, I think we should turn our attention to `net/dns_resolver/dns_key.c`. This file... well, it's where key handling and security aspects related to DNS are likely implemented. Even if it seems tangential at first, the devil is often in the details, and a subtle key management bug could be the root cause of the observed behavior. It's a fundamental part of the DNS system, so examining `dns_key.c` is the logical next step. Let's see if we missed anything critical there.



24/2 2026/11/16 00:57 tool grepper
0m Args:
{
  "Expression": "key_type_dns_resolver",
  "PathPrefixes": [
    "net/dns_resolver/"
  ]
}

Results:
{
  "Output": "net/dns_resolver/dns_key.c=295=static long dns_resolver_read(const struct key *key,\n--\nnet/dns_resolver/dns_key.c-305-\nnet/dns_resolver/dns_key.c:306:struct key_type key_type_dns_resolver = {\nnet/dns_resolver/dns_key.c-307-\t.name\t\t= \"dns_resolver\",\n--\nnet/dns_resolver/dns_key.c-317-};\nnet/dns_resolver/dns_key.c:318:EXPORT_SYMBOL_GPL(key_type_dns_resolver);\nnet/dns_resolver/dns_key.c-319-\nnet/dns_resolver/dns_key.c=320=static int __init init_dns_key(void)\nnet/dns_resolver/dns_key.c-321-{\nnet/dns_resolver/dns_key.c:322:\treturn register_key_type(\u0026key_type_dns_resolver);\nnet/dns_resolver/dns_key.c-323-}\n--\nnet/dns_resolver/dns_key.c=325=static void __exit exit_dns_key(void)\nnet/dns_resolver/dns_key.c-326-{\nnet/dns_resolver/dns_key.c:327:\tunregister_key_type(\u0026key_type_dns_resolver);\nnet/dns_resolver/dns_key.c-328-}\n--\nnet/dns_resolver/dns_query.c=66=int dns_query(struct net *net,\n--\nnet/dns_resolver/dns_query.c-99-\tscoped_with_creds(dns_resolver_cache)\nnet/dns_resolver/dns_query.c:100:\t\trkey = request_key_net(\u0026key_type_dns_resolver, desc, net, options);\nnet/dns_resolver/dns_query.c-101-\tkfree(desc);\n"
}

25/2 2026/11/16 00:57 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 51133
							output: 39
							thoughts: 2289
						

Thoughts:
**Focusing on Key Garbage Collection and Module Ownership**

Okay, so I'm diving into this key management code, specifically looking at how garbage collection and flushing are triggered, and how module ownership is handled. My initial focus is on the `security/keys/gc.c` file. I see the `key_garbage_collector` function, which is the workqueue callback, running through `key_gc_wq`. Then, there’s `key_schedule_gc_work`, which is called from several places: the scheduled garbage collection, a timer function, and from operations like key putting, invalidating, and domain removal. The function `key_gc_flush` is called from network file system operations on exit.

My first thought is, is `key_gc_flush` callable from user space syscalls? It appears to be indirectly triggered through functions like `sesInfoFree` (in `fs/smb/client/misc.c`), `nfs_idmap_delete` (in `fs/nfs/nfs4idmap.c`), and `af_rxrpc_exit` (in `net/rxrpc/af_rxrpc.c`) and `exit_dns_resolver` (in `net/dns_resolver/dns_query.c`). These network filesystem operations call the flush function.

Okay, let's step back and look at the bigger picture of key garbage collection. We have the core garbage collector functions: `key_garbage_collector`, `key_schedule_gc_work`, `key_gc_unused_keys`, and `key_gc_flush`. I also need to keep key allocation and restriction in mind: `key_alloc`, `__register_key_type`, `unregister_key_type`, and `keyring_restrict`.

I'm also seeing some interesting things in `net/rxrpc/server_key.c` (`rxrpc_preparse_s`, etc) and `net/rxrpc/security.c` (`rxrpc_request_key`, `rxrpc_get_server_data_key`, etc). This looks like another important area.

Now, I'm thinking about the fuzzing strategy here. Specifically, I'm reminded of Section 4 of our fuzzing guidelines: "EXTRACTING FocusSymbols (PREVENTING DILUTION)". The key is to *not* focus on ubiquitous functions, those called by almost everything, but rather to target specific features and entrypoints.

So, is `key_alloc` ubiquitous? It’s not a general memory allocator, page fault handler, or core synchronization primitive, but it *is* the central allocator for keys. Is it called by *every* program? No, only programs doing key operations or network filesystems. However, it *is* the central allocator for keys.

Given that `key_alloc` *was* directly modified in the patch (with additions like `try_module_get(type->owner)` and `try_module_get(restrict_link->keytype->owner)`), as was `keyring_restrict` (with `module_is_coming` and `try_module_get`), and the garbage collection functions (`key_garbage_collector`, `key_gc_unused_keys`, `key_schedule_gc_work`, `key_gc_flush`), and also functions in RXRPC, I think it's vital. This means we are dealing with a more feature-specific logic.

Okay, I need to verify which symbols are actually exposed in the symbol table. Remember, static functions in .c files *can* have symbols unless inlined. So let’s check if `key_garbage_collector`, `key_gc_unused_keys`, `rxrpc_preparse_s` are static. I can see from this quick check that the garbage collection related functions are not static, or have been declared `noinline`, which means they have ksym symbols. This is important for coverage filters.

In summary, the key non-static functions include: `key_alloc`, `__register_key_type`, `unregister_key_type`, `keyring_restrict`, and also `key_garbage_collector`, `key_schedule_gc_work`, `key_gc_unused_keys`, `key_gc_flush` and also these rxrpc functions: `rxrpc_request_key`, `rxrpc_get_server_data_key`, `rxrpc_server_keyring`, `rxrpc_sock_set_security_keyring`, `rxrpc_sock_set_manage_response`.

A quick check confirms some interesting entries in other areas like `net/dns_resolver` which call `request_key_net` and the filesystem code for network filesystems (`fs/nfs/nfs4idmap


26/2 2026/11/16 00:57 tool grepper
0m Args:
{
  "Expression": "rxrpc_(request_key|server_keyring)\\b",
  "PathPrefixes": [
    "net/rxrpc/"
  ]
}

Results:
{
  "Output": "net/rxrpc/af_rxrpc.c=632=static int rxrpc_setsockopt(struct socket *sock, int level, int optname,\n--\nnet/rxrpc/af_rxrpc.c-660-\t\t\t\tgoto error;\nnet/rxrpc/af_rxrpc.c:661:\t\t\tret = rxrpc_request_key(rx, optval, optlen);\nnet/rxrpc/af_rxrpc.c-662-\t\t\tgoto error;\n--\nnet/rxrpc/af_rxrpc.c-667-\t\t\t\tgoto error;\nnet/rxrpc/af_rxrpc.c:668:\t\t\tret = rxrpc_server_keyring(rx, optval, optlen);\nnet/rxrpc/af_rxrpc.c-669-\t\t\tgoto error;\n--\nnet/rxrpc/ar-internal.h=1477=struct key *rxrpc_look_up_server_security(struct rxrpc_connection *,\nnet/rxrpc/ar-internal.h-1478-\t\t\t\t\t  struct sk_buff *, u32, u32);\nnet/rxrpc/ar-internal.h:1479:int rxrpc_request_key(struct rxrpc_sock *rx, sockptr_t optval, int optlen);\nnet/rxrpc/ar-internal.h-1480-int rxrpc_get_server_data_key(struct rxrpc_connection *conn,\n--\nnet/rxrpc/ar-internal.h-1482-\t\t\t      u32 kvno);\nnet/rxrpc/ar-internal.h:1483:int rxrpc_server_keyring(struct rxrpc_sock *rx, sockptr_t optval, int optlen);\nnet/rxrpc/ar-internal.h-1484-\n--\nnet/rxrpc/security.c=163=struct key *rxrpc_look_up_server_security(struct rxrpc_connection *conn,\n--\nnet/rxrpc/security.c-216- */\nnet/rxrpc/security.c:217:int rxrpc_request_key(struct rxrpc_sock *rx, sockptr_t optval, int optlen)\nnet/rxrpc/security.c-218-{\n--\nnet/rxrpc/security.c=294=EXPORT_SYMBOL(rxrpc_get_server_data_key);\n--\nnet/rxrpc/security.c-298- */\nnet/rxrpc/security.c:299:int rxrpc_server_keyring(struct rxrpc_sock *rx, sockptr_t optval, int optlen)\nnet/rxrpc/security.c-300-{\n"
}

27/2 2026/11/16 00:57 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 55150
							output: 37
							thoughts: 572
						

Thoughts:
**My Analysis of Key Subsystem Interactions**

Okay, let's break this down. My initial observation is focused on how the RxRPC subsystem interacts with the key management system. Specifically, these calls are crucial: `setsockopt(..., SOL_RXRPC, RXRPC_SECURITY_KEY, ...)` directly invokes `rxrpc_request_key`, and `setsockopt(..., SOL_RXRPC, RXRPC_SECURITY_KEYRING, ...)` goes straight to `rxrpc_server_keyring`. Furthermore, creating keys via `add_key("rxrpc_s", ...)` uses `rxrpc_preparse_s`, and `add_key("rxrpc", ...)` calls `rxrpc_preparse`, both defined within `net/rxrpc/key.c`. I need to remember these interactions as these are how security is established in that subsystem. The `keyctl_restrict_keyring` calls `keyring_restrict`.

Now, pivoting to garbage collection, I need to revisit `security/keys/gc.c`. I'm checking for calls to `key_schedule_gc_work`. This is key (pun intended!) because it is called in response to events like key expiration, invalidation, and most importantly `key_put` when the last user reference drops. This triggers the GC. The actual work happens within `key_garbage_collector`, which scans and cleans up. Importantly, `key_gc_unused_keys` handles the freeing of truly unused keys, and `key_gc_flush` forces a flush of the GC.

Next, I'm shifting my focus to `fs/smb/client/misc.c`. `sesInfoAlloc` and `sesInfoFree`, the CIFS session allocation and deallocation functions, specifically call `key_gc_flush`. This indicates a direct integration between CIFS session management and key garbage collection which I will need to be very aware of.

Finally, I need to verify all the Kconfig options that are required to compile and reach this modified code. This is very important.

1.  `KEYS`: This is the base requirement.  `security/keys/Kconfig` and `menuconfig KEYS`. All of these changes require this to be enabled.

2.  `AF_RXRPC` and `RXRPC_KEYS`: Looking at `net/rxrpc/Kconfig`, I need to make sure `config RXRPC_KEYS` is enabled. `config AF_RXRPC` depends on INET and selects KEYS, NET_UDP_TUNNEL, and RXRPC_KEYS. I need to be aware of the dependencies on INET, etc. I also note that `config RXKAD` and `config RXGK` (Kerberos and GSSAPI security) both depend on `RXRPC_KEYS`.

3.  `DNS_RESOLVER` and `DNS_KEY`: In `net/dns_resolver/Kconfig`, I see that `config DNS_KEY` depends on `KEYS`. `config DNS_RESOLVER` depends on `KEYS` and selects `DNS_KEY`.

4.  `CIFS` and `CIFS_UPCALL`: I need `CONFIG_CIFS` and `CONFIG_CIFS_UPCALL` enabled in `fs/smb/client/`. I'll cross-reference the exact names with `fs/smb/client/Kconfig`.

Okay, that's the full picture as I see it now. I've mapped the key interactions within RxRPC, the GC triggering mechanisms, the CIFS integration and the required Kconfig options. I need to keep this in mind as I continue to examine the security architecture.



28/2 2026/11/16 00:57 tool grepper
0m Args:
{
  "Expression": "config (CIFS|SMB_CLIENT)",
  "PathPrefixes": [
    "fs/smb/client/"
  ]
}

Results:
{
  "Output": "fs/smb/client/Kconfig-1-# SPDX-License-Identifier: GPL-2.0-only\nfs/smb/client/Kconfig:2:config CIFS\nfs/smb/client/Kconfig-3-\ttristate \"SMB3 and CIFS support (advanced network filesystem)\"\n--\nfs/smb/client/Kconfig-53-\nfs/smb/client/Kconfig:54:config CIFS_STATS2\nfs/smb/client/Kconfig-55-\tbool \"Extended statistics\"\n--\nfs/smb/client/Kconfig-67-\nfs/smb/client/Kconfig:68:config CIFS_ALLOW_INSECURE_LEGACY\nfs/smb/client/Kconfig-69-\tbool \"Support legacy servers which use less secure dialects\"\n--\nfs/smb/client/Kconfig-82-\nfs/smb/client/Kconfig:83:config CIFS_UPCALL\nfs/smb/client/Kconfig-84-\tbool \"Kerberos/SPNEGO advanced session setup\"\n--\nfs/smb/client/Kconfig-91-\nfs/smb/client/Kconfig:92:config CIFS_XATTR\nfs/smb/client/Kconfig-93-\tbool \"CIFS extended attributes\"\n--\nfs/smb/client/Kconfig-106-\nfs/smb/client/Kconfig:107:config CIFS_POSIX\nfs/smb/client/Kconfig-108-\tbool \"CIFS POSIX Extensions\"\n--\nfs/smb/client/Kconfig-118-\nfs/smb/client/Kconfig:119:config CIFS_DEBUG\nfs/smb/client/Kconfig-120-\tbool \"Enable CIFS debugging routines\"\n--\nfs/smb/client/Kconfig-127-\nfs/smb/client/Kconfig:128:config CIFS_DEBUG2\nfs/smb/client/Kconfig-129-\tbool \"Enable additional CIFS debugging routines\"\n--\nfs/smb/client/Kconfig-138-\nfs/smb/client/Kconfig:139:config CIFS_DEBUG_DUMP_KEYS\nfs/smb/client/Kconfig-140-\tbool \"Dump encryption keys for offline decryption (Unsafe)\"\n--\nfs/smb/client/Kconfig-148-\nfs/smb/client/Kconfig:149:config CIFS_DFS_UPCALL\nfs/smb/client/Kconfig-150-\tbool \"DFS feature support\"\n--\nfs/smb/client/Kconfig-161-\nfs/smb/client/Kconfig:162:config CIFS_SWN_UPCALL\nfs/smb/client/Kconfig-163-\tbool \"SWN feature support\"\n--\nfs/smb/client/Kconfig-172-\nfs/smb/client/Kconfig:173:config CIFS_NFSD_EXPORT\nfs/smb/client/Kconfig-174-\tbool \"Allow nfsd to export CIFS file system\"\n--\nfs/smb/client/Kconfig=179=if CIFS\nfs/smb/client/Kconfig-180-\nfs/smb/client/Kconfig:181:config CIFS_SMB_DIRECT\nfs/smb/client/Kconfig-182-\tbool \"SMB Direct support\"\n--\nfs/smb/client/Kconfig-190-\nfs/smb/client/Kconfig:191:config CIFS_FSCACHE\nfs/smb/client/Kconfig-192-\tbool \"Provide CIFS client caching support\"\n--\nfs/smb/client/Kconfig-198-\nfs/smb/client/Kconfig:199:config CIFS_ROOT\nfs/smb/client/Kconfig-200-\tbool \"SMB root file system (Experimental)\"\n--\nfs/smb/client/Kconfig-206-\nfs/smb/client/Kconfig:207:config CIFS_COMPRESSION\nfs/smb/client/Kconfig-208-\tbool \"SMB message compression (Experimental)\"\n"
}

29/2 2026/11/16 00:57 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 57587
							output: 31
							thoughts: 43
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Investigating the NFSv4 ID Mapping Configuration**

Right, let's dive into this NFSv4 ID mapping situation. My first instinct is to zero in on the kernel source to understand how the relevant components are built. Specifically, I need to figure out which Kconfig option actually pulls in the `nfs4idmap.o` object file. That's usually the best place to start when tracking down the build dependencies and configuration switches for a module like this. The file I'm targeting, of course, is `fs/nfs/nfs4idmap.c`. From there, I'll need to work backward to see what Kconfig options trigger its compilation.



30/2 2026/11/16 00:57 tool grepper
0m Args:
{
  "Expression": "nfs4idmap",
  "PathPrefixes": [
    "fs/nfs/"
  ]
}

Results:
{
  "Output": "fs/nfs/Makefile=27=nfsv4-y := nfs4proc.o nfs4xdr.o nfs4state.o nfs4renewd.o nfs4super.o nfs4file.o \\\nfs/nfs/Makefile:28:\t  delegation.o nfs4idmap.o callback.o callback_xdr.o callback_proc.o \\\nfs/nfs/Makefile-29-\t  nfs4namespace.o nfs4getroot.o nfs4client.o nfs4session.o \\\n--\nfs/nfs/flexfilelayout/flexfilelayout.c-20-#include \"../nfs4session.h\"\nfs/nfs/flexfilelayout/flexfilelayout.c:21:#include \"../nfs4idmap.h\"\nfs/nfs/flexfilelayout/flexfilelayout.c-22-#include \"../internal.h\"\n--\nfs/nfs/nfs4client.c-18-#include \"nfs4session.h\"\nfs/nfs/nfs4client.c:19:#include \"nfs4idmap.h\"\nfs/nfs/nfs4client.c-20-#include \"pnfs.h\"\n--\nfs/nfs/nfs4idmap.c-54-#include \"netns.h\"\nfs/nfs/nfs4idmap.c:55:#include \"nfs4idmap.h\"\nfs/nfs/nfs4idmap.c-56-#include \"nfs4trace.h\"\n--\nfs/nfs/nfs4idmap.h-1-/*\nfs/nfs/nfs4idmap.h:2: * fs/nfs/nfs4idmap.h\nfs/nfs/nfs4idmap.h-3- *\n--\nfs/nfs/nfs4proc.c-66-#include \"sysfs.h\"\nfs/nfs/nfs4proc.c:67:#include \"nfs4idmap.h\"\nfs/nfs/nfs4proc.c-68-#include \"nfs4session.h\"\n--\nfs/nfs/nfs4state.c-60-#include \"internal.h\"\nfs/nfs/nfs4state.c:61:#include \"nfs4idmap.h\"\nfs/nfs/nfs4state.c-62-#include \"nfs4session.h\"\n--\nfs/nfs/nfs4super.c-13-#include \"nfs4_fs.h\"\nfs/nfs/nfs4super.c:14:#include \"nfs4idmap.h\"\nfs/nfs/nfs4super.c-15-#include \"dns_resolve.h\"\n--\nfs/nfs/nfs4sysctl.c-12-#include \"nfs4_fs.h\"\nfs/nfs/nfs4sysctl.c:13:#include \"nfs4idmap.h\"\nfs/nfs/nfs4sysctl.c-14-#include \"callback.h\"\n--\nfs/nfs/nfs4xdr.c-59-#include \"internal.h\"\nfs/nfs/nfs4xdr.c:60:#include \"nfs4idmap.h\"\nfs/nfs/nfs4xdr.c-61-#include \"nfs4session.h\"\n--\nfs/nfs/super.c-74-#include \"sysfs.h\"\nfs/nfs/super.c:75:#include \"nfs4idmap.h\"\nfs/nfs/super.c-76-\n"
}

31/2 2026/11/16 00:57 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 58717
							output: 33
							thoughts: 41
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience, presented in the first person:

**Navigating the NFSv4 Configuration Landscape**

Right, so `nfsv4-y` – that's a key piece in the NFSv4 puzzle, specifically indicating it's *built-in* support. Naturally, that's governed by `CONFIG_NFS_V4` in the kernel configuration. I need to quickly confirm the dependencies and understand how this option is controlled. The logical place to start is, of course, `fs/nfs/Kconfig`. That's where all the NFS-related configuration options are defined. I'll take a look in there to double-check that `NFS_V4` is indeed the controlling symbol for `nfsv4-y` – and to refresh my memory on any other associated options. Knowing the exact relationship between these config options is crucial for debugging and customization. I bet there are several other nuances too.



32/2 2026/11/16 00:57 tool grepper
0m Args:
{
  "Expression": "config NFS_V4\\b",
  "PathPrefixes": [
    "fs/nfs/"
  ]
}

Results:
{
  "Output": "fs/nfs/Kconfig=55=config NFS_V3_ACL\n--\nfs/nfs/Kconfig-76-\nfs/nfs/Kconfig:77:config NFS_V4\nfs/nfs/Kconfig-78-\ttristate \"NFS client support for NFS version 4\"\n"
}

33/2 2026/11/16 00:57 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 59090
							output: 28
							thoughts: 182
						

Thoughts:
**Examining Makefile Dependencies**

Okay, let's break down these Makefile dependencies. I'm focusing on how various features and modules are linked together, particularly around key management and DNS/RXRPC, as that seems to be the common thread.

First, I examined `net/dns_resolver/Makefile`. I see the `CONFIG_DNS_KEY` option, which, when enabled, includes `dns_resolver_key.o`. Similarly, `CONFIG_DNS_RESOLVER` enables `dns_resolver.o`.  It looks like `dns_query.o` is always built into `dns_resolver.o`, and, logically, `dns_key.o` gets linked with `dns_resolver_key.o`. Simple enough.

Next, I jumped over to `net/rxrpc/Makefile`. I see a similar pattern:  `CONFIG_RXRPC_KEYS` enables `rxrpc_keys.o`, and `CONFIG_AF_RXRPC` enables `rxrpc.o`. More interestingly, the dependencies within `rxrpc_keys-y` include `key.o` and `server_key.o`.  And, importantly, it's clear that `AF_RXRPC` selects `RXRPC_KEYS`.  This is a critical link; the RXRPC subsystem depends on the key management features.

Now, I'll need to check `security/keys/Makefile` to see how those lower-level key components are defined and to trace the complete chain of dependencies. I need to understand the core key infrastructure to grasp the full picture.



34/2 2026/11/16 00:57 tool grepper
0m Args:
{
  "Expression": "obj-.*",
  "PathPrefixes": [
    "security/keys/"
  ]
}

Results:
{
  "Output": "security/keys/Makefile-8-#\nsecurity/keys/Makefile:9:obj-y := \\\nsecurity/keys/Makefile-10-\tgc.o \\\n--\nsecurity/keys/Makefile-18-\tuser_defined.o\nsecurity/keys/Makefile:19:compat-obj-$(CONFIG_KEY_DH_OPERATIONS) += compat_dh.o\nsecurity/keys/Makefile:20:obj-$(CONFIG_COMPAT) += compat.o $(compat-obj-y)\nsecurity/keys/Makefile:21:obj-$(CONFIG_PROC_FS) += proc.o\nsecurity/keys/Makefile:22:obj-$(CONFIG_SYSCTL) += sysctl.o\nsecurity/keys/Makefile:23:obj-$(CONFIG_PERSISTENT_KEYRINGS) += persistent.o\nsecurity/keys/Makefile:24:obj-$(CONFIG_KEY_DH_OPERATIONS) += dh.o\nsecurity/keys/Makefile:25:obj-$(CONFIG_ASYMMETRIC_KEY_TYPE) += keyctl_pkey.o\nsecurity/keys/Makefile-26-\n--\nsecurity/keys/Makefile-29-#\nsecurity/keys/Makefile:30:obj-$(CONFIG_BIG_KEYS) += big_key.o\nsecurity/keys/Makefile:31:obj-$(CONFIG_TRUSTED_KEYS) += trusted-keys/\nsecurity/keys/Makefile:32:obj-$(CONFIG_ENCRYPTED_KEYS) += encrypted-keys/\n--\nsecurity/keys/encrypted-keys/Makefile-5-\nsecurity/keys/encrypted-keys/Makefile:6:obj-$(CONFIG_ENCRYPTED_KEYS) += encrypted-keys.o\nsecurity/keys/encrypted-keys/Makefile-7-\n--\nsecurity/keys/trusted-keys/Makefile-5-\nsecurity/keys/trusted-keys/Makefile:6:obj-$(CONFIG_TRUSTED_KEYS) += trusted.o\nsecurity/keys/trusted-keys/Makefile-7-trusted-y += trusted_core.o\n"
}

35/2 2026/11/16 00:57 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 60115
							output: 32
							thoughts: 28
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Examining the Trusted TEE Object Build Process**

Alright, let's dive in. My immediate thought is to trace the build process for `trusted_tee.o`. Given my experience, the logical place to start is the `security/keys/trusted-keys/Makefile`. It's the most likely location for the rules that define how that specific object file is constructed, especially considering the file path. I'm assuming that this Makefile governs the compilation, linking, and any necessary dependencies for a crucial component related to trusted keys. Let's see how they've set up the build. I'm expecting to find the compilation flags, any specific include paths, and the linking commands that will generate the `trusted_tee.o` object file. Let's see what interesting techniques they have employed.



36/2 2026/11/16 00:57 tool grepper
0m Args:
{
  "Expression": "trusted_tee",
  "PathPrefixes": [
    "security/keys/trusted-keys/"
  ]
}

Results:
{
  "Output": "security/keys/trusted-keys/Makefile=12=trusted-$(CONFIG_TRUSTED_KEYS_TPM) += tpm2key.asn1.o\nsecurity/keys/trusted-keys/Makefile-13-\nsecurity/keys/trusted-keys/Makefile:14:trusted-$(CONFIG_TRUSTED_KEYS_TEE) += trusted_tee.o\nsecurity/keys/trusted-keys/Makefile-15-\n--\nsecurity/keys/trusted-keys/trusted_core.c-10-#include \u003ckeys/trusted-type.h\u003e\nsecurity/keys/trusted-keys/trusted_core.c:11:#include \u003ckeys/trusted_tee.h\u003e\nsecurity/keys/trusted-keys/trusted_core.c-12-#include \u003ckeys/trusted_caam.h\u003e\n--\nsecurity/keys/trusted-keys/trusted_tee.c-17-\nsecurity/keys/trusted-keys/trusted_tee.c:18:#include \u003ckeys/trusted_tee.h\u003e\nsecurity/keys/trusted-keys/trusted_tee.c-19-\n--\nsecurity/keys/trusted-keys/trusted_tee.c=61=static DEFINE_MUTEX(trusted_key_tee_mutex);\n--\nsecurity/keys/trusted-keys/trusted_tee.c-65- */\nsecurity/keys/trusted-keys/trusted_tee.c:66:static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob)\nsecurity/keys/trusted-keys/trusted_tee.c-67-{\n--\nsecurity/keys/trusted-keys/trusted_tee.c-120- */\nsecurity/keys/trusted-keys/trusted_tee.c:121:static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob)\nsecurity/keys/trusted-keys/trusted_tee.c-122-{\n--\nsecurity/keys/trusted-keys/trusted_tee.c-175- */\nsecurity/keys/trusted-keys/trusted_tee.c:176:static int trusted_tee_get_random(unsigned char *key, size_t key_len)\nsecurity/keys/trusted-keys/trusted_tee.c-177-{\n--\nsecurity/keys/trusted-keys/trusted_tee.c=305=static struct tee_client_driver trusted_key_driver = {\n--\nsecurity/keys/trusted-keys/trusted_tee.c-314-\nsecurity/keys/trusted-keys/trusted_tee.c:315:static int trusted_tee_init(void)\nsecurity/keys/trusted-keys/trusted_tee.c-316-{\n--\nsecurity/keys/trusted-keys/trusted_tee.c-319-\nsecurity/keys/trusted-keys/trusted_tee.c:320:static void trusted_tee_exit(void)\nsecurity/keys/trusted-keys/trusted_tee.c-321-{\n--\nsecurity/keys/trusted-keys/trusted_tee.c=325=struct trusted_key_ops trusted_key_tee_ops = {\nsecurity/keys/trusted-keys/trusted_tee.c-326-\t.migratable = 0, /* non-migratable */\nsecurity/keys/trusted-keys/trusted_tee.c:327:\t.init = trusted_tee_init,\nsecurity/keys/trusted-keys/trusted_tee.c:328:\t.seal = trusted_tee_seal,\nsecurity/keys/trusted-keys/trusted_tee.c:329:\t.unseal = trusted_tee_unseal,\nsecurity/keys/trusted-keys/trusted_tee.c:330:\t.get_random = trusted_tee_get_random,\nsecurity/keys/trusted-keys/trusted_tee.c:331:\t.exit = trusted_tee_exit,\nsecurity/keys/trusted-keys/trusted_tee.c-332-};\n"
}

37/2 2026/11/16 00:57 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 61318
							output: 32
							thoughts: 1740
						

Thoughts:
**Focusing the Fuzzer: Kernel Key Management Restructuring**

Alright, let's break down this substantial commit, because it's *definitely* worth fuzzing. The core change is the widespread adoption of module refcounting for key types. Previously, unregistering a key type involved a complicated three-pass garbage collection cycle. Now, `key_alloc` acquires a reference to the module owner, and `key_gc_unused_keys` releases it. This cleaner approach extends to keyring restrictions, too. We've also got new modules for rxrpc and DNS key types. A new `key_gc_flush` function is there to wait on the garbage collector. The key garbage collector itself has been streamlined and chunked.

Now, where do we start with targeted fuzzing? Let's consult the guidance. The goal is to identify and zero in on code that directly *implements* the changes, not ubiquitous functions. So, let's identify relevant FocusSymbols.

Here's my initial list of candidates:

From `security/keys/gc.c`:
*   `key_garbage_collector`
*   `key_gc_unused_keys`
*   `key_schedule_gc_work`
*   `key_gc_flush`

From `security/keys/key.c`:
*   `key_alloc`
*   `__register_key_type`
*   `unregister_key_type`

From `security/keys/keyring.c`:
*   `keyring_restrict`

From `net/rxrpc/server_key.c`:
*   `rxrpc_preparse_s`

From `net/rxrpc/security.c`:
*   `rxrpc_request_key`
*   `rxrpc_server_keyring`

Let's refine that list by focusing on the logic that was directly modified:
*   `key_garbage_collector`
*   `key_gc_unused_keys`
*   `key_schedule_gc_work`
*   `key_gc_flush`
*   `key_alloc`
*   `keyring_restrict`
*   `__register_key_type`
*   `rxrpc_preparse_s`
*   `rxrpc_request_key`
*   `rxrpc_server_keyring`

I'm confident these symbols will be present in vmlinux.

Now, what about the relevant kernel configs? We'll want to ensure these are enabled:

*   `KEYS` (for `security/keys/*`)
*   `AF_RXRPC` (for `net/rxrpc/*`)
*   `RXRPC_KEYS` (for rxrpc key types)
*   `RXKAD` (for rxrpc kerberos keys)
*   `RXGK` (for rxrpc GSSAPI keys)
*   `DNS_KEY` (for dns\_resolver key type)
*   `DNS_RESOLVER` (for dns\_resolver)
*   `NFS_V4` (for nfs4idmap)
*   `CIFS` (for SMB client)
*   `CIFS_UPCALL` (for cifs spnego/idmap)

We need to make sure to handle config dependencies correctly. We will need `INET` for `AF_RXRPC` and `CIFS`. `KEYS` is needed by `DNS_KEY` and `DNS_RESOLVER`.  `NFS_V4` depends on `NFS_FS`. We will also need `RXRPC_KEYS` for `RXKAD` and `RXGK`.



38/2 2026/11/16 00:58 tool grepper
0m Args:
{
  "Expression": "config NFS_V4$",
  "PathPrefixes": [
    "fs/nfs/"
  ]
}

Results:
{
  "Output": "fs/nfs/Kconfig=55=config NFS_V3_ACL\n--\nfs/nfs/Kconfig-76-\nfs/nfs/Kconfig:77:config NFS_V4\nfs/nfs/Kconfig-78-\ttristate \"NFS client support for NFS version 4\"\n"
}

39/2 2026/11/16 00:58 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 63983
							output: 34
							thoughts: 21
						

Thoughts:
Here's my summary, as though I'm thinking through this myself:

**Delving into the NFS Configuration**

Okay, time to dig into the heart of the NFS configuration. I need to understand how certain NFS features are controlled, so let's zoom in on `fs/nfs/Kconfig`. I'm specifically targeting lines 75 through 95. That section should give me the lowdown on the specific options and dependencies I'm interested in, right? It's where the architectural nuances are usually handled, and I want to confirm what my intuition is telling me. That range typically encompasses settings relating to core functionality, or potentially some critical performance optimizations. Let's see if this hunch is correct.



40/2 2026/11/16 00:58 tool read-file
0m Args:
{
  "File": "fs/nfs/Kconfig",
  "FirstLine": 75,
  "LineCount": 20
}

Results:
{
  "Contents": "  75:\t\t  If unsure, say N.\n  76:\t\n  77:\tconfig NFS_V4\n  78:\t\ttristate \"NFS client support for NFS version 4\"\n  79:\t\tdepends on NFS_FS\n  80:\t\tselect KEYS\n  81:\t\tselect SUNRPC_BACKCHANNEL\n  82:\t\thelp\n  83:\t\t  This option enables support for version 4.1 of the NFS protocol\n  84:\t\t  (RFC 5661) in the kernel's NFS client.\n  85:\t\n  86:\t\t  To mount NFS servers using NFSv4, you also need to install user\n  87:\t\t  space programs which can be found in the Linux nfs-utils package,\n  88:\t\t  available from http://linux-nfs.org/.\n  89:\t\n  90:\t\t  If unsure, say N.\n  91:\t\n  92:\tconfig NFS_SWAP\n  93:\t\tbool \"Provide swap over NFS support\"\n  94:\t\tdefault n\n"
}

41/2 2026/11/16 00:58 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 64462
							output: 35
							thoughts: 44
						

Thoughts:
Okay, here's my understanding, considering I already know a bit about this:

**Digging into File System Dependencies**

Right, so I'm looking at `NFS_V4`. I already know, of course, that it relies on `NFS_FS`. That makes sense. Version 4 builds on the core NFS file system. But what about `CIFS`? I should probably double-check the configuration of the client code, so let's take a look. I'll go straight to `fs/smb/client/Kconfig`, specifically lines 1 through 15. That should give me a good overview of any dependencies or relationships there. I need to refresh my memory on any configuration settings.



42/2 2026/11/16 00:58 tool read-file
0m Args:
{
  "File": "fs/smb/client/Kconfig",
  "FirstLine": 1,
  "LineCount": 15
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0-only\n   2:\tconfig CIFS\n   3:\t\ttristate \"SMB3 and CIFS support (advanced network filesystem)\"\n   4:\t\tdepends on INET\n   5:\t\tselect NLS\n   6:\t\tselect NLS_UCS2_UTILS\n   7:\t\tselect CRYPTO\n   8:\t\tselect CRYPTO_AEAD2\n   9:\t\tselect CRYPTO_CCM\n  10:\t\tselect CRYPTO_GCM\n  11:\t\tselect CRYPTO_AES\n  12:\t\tselect CRYPTO_LIB_AES_CBC_MACS\n  13:\t\tselect CRYPTO_LIB_ARC4\n  14:\t\tselect CRYPTO_LIB_MD5\n  15:\t\tselect CRYPTO_LIB_SHA256\n"
}

43/2 2026/11/16 00:58 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 64902
							output: 34
							thoughts: 11
						

Thoughts:
Okay, here's my interpretation of "Let's check `CIFS_UPCALL`", crafted as if I were considering this in my own thought process, assuming I'm an expert in the field:

**Internal Audit: CIFS_UPCALL**

Right, let's take a look at `CIFS_UPCALL`. Given the context of what I'm working on right now, this seems like a pivotal piece, doesn't it? My intuition tells me this likely represents the mechanism for [insert relevant technical concept from your field, e.g., "handling user-space interactions related to the Common Internet File System," or "dispatching network requests and responses"]. I need to quickly ascertain the state of this component to verify:

*   **Its role:** What tasks are performed by `CIFS_UPCALL`? Is it just for, say, credential delegation, or does it handle more? [My mind quickly checks for the specific processes this manages.]
*   **Its status:** Is it operational or causing errors? [I am scanning for known error patterns.]
*   **The interactions it facilitates:** Which system components call it, and what are their behaviors? Is it properly connected to the necessary infrastructure?
*   **Potential bottlenecks:** Could this be a weak point in the workflow? [I look for areas of congestion or possible resource constraints.]
*   **Security risks:** How are the various security functions handled here? Does this represent any security risks?

I'm mentally running through my mental map of the system architecture, mentally placing `CIFS_UPCALL` into the larger scheme. I can begin by, say, checking the relevant logs, or tracing the execution path of a particular network transaction. I'll need to confirm that this section is in good working order. I am keeping in mind the known vulnerabilities, and potential security issues, especially when working on the server.



44/2 2026/11/16 00:58 tool grepper
0m Args:
{
  "Expression": "config CIFS_UPCALL",
  "PathPrefixes": [
    "fs/smb/client/"
  ]
}

Results:
{
  "Output": "fs/smb/client/Kconfig=68=config CIFS_ALLOW_INSECURE_LEGACY\n--\nfs/smb/client/Kconfig-82-\nfs/smb/client/Kconfig:83:config CIFS_UPCALL\nfs/smb/client/Kconfig-84-\tbool \"Kerberos/SPNEGO advanced session setup\"\n"
}

45/2 2026/11/16 00:58 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 65446
							output: 36
							thoughts: 23
						

Thoughts:
Okay, let's dive into this. Here's my take on those lines from `fs/smb/client/Kconfig`:

**Analyzing Kconfig's SMB Client Configuration**

Alright, I need to get a handle on what's being configured in lines 80-90 of `fs/smb/client/Kconfig`. Based on my understanding, this is the configuration file for the Samba client within the kernel. I can immediately infer that these lines probably deal with a specific feature or option related to the SMB/CIFS protocol implementation. Let's see... looking at the context, this *has* to be related to... ah, got it! It's most likely defining a Kconfig symbol, including dependencies, and perhaps default value for a specific setting. This could be anything from enabling a security feature to fine-tuning caching behaviour. It's the building block of what the user, with their experience, can configure for the kernel module. Understanding this is key to interpreting the module’s functionality.



46/2 2026/11/16 00:58 tool read-file
0m Args:
{
  "File": "fs/smb/client/Kconfig",
  "FirstLine": 80,
  "LineCount": 10
}

Results:
{
  "Contents": "  80:\t\n  81:\t\t  If unsure, say Y.\n  82:\t\n  83:\tconfig CIFS_UPCALL\n  84:\t\tbool \"Kerberos/SPNEGO advanced session setup\"\n  85:\t\tdepends on CIFS\n  86:\t\thelp\n  87:\t\t  Enables an upcall mechanism for CIFS which accesses userspace helper\n  88:\t\t  utilities to provide SPNEGO packaged (RFC 4178) Kerberos tickets\n  89:\t\t  which are needed to mount to certain secure servers (for which more\n"
}

47/2 2026/11/16 00:58 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 65872
							output: 366
							thoughts: 393
						

Thoughts:
**My Assessment of the Keys Subsystem Refactor**

Okay, so I've been reviewing this proposed patch series and my initial thought is: it's a significant refactor of the Linux key management subsystem. Let me break it down from my expert perspective.

Essentially, they're modernizing how key types are managed. Instead of the older three-pass reaper, they're moving to module references, which feels like a much cleaner approach to lifetime management. That addresses a potential point of fragility. The restructuring of the garbage collector to use an `rb_tree` cursor with chunk-wise scanning (`KEY_GC_CHUNK_SIZE`) and the introduction of `key_gc_flush()` for deferred GC passes looks like a performance improvement and should lead to a more predictable cleanup process.

The key separation of RxRPC key types into their own module is a good architectural decision. This helps to modularize the system. They've also updated preparsing and keyring operations within RxRPC, which is directly relevant to my area of expertise. And, the updates to DNS resolver keys, the NFSv4 idmap cache, and CIFS SPNEGO/idmap session cache clearing to flush key GC are crucial. It looks like a good, solid integration of these key types into the garbage collection system.

From a security perspective, this is very interesting. These changes are impacting core key retention and directly involve code that's exposed to user space via system calls like `keyctl()`, `add_key()`, `request_key()`, and the RxRPC `setsockopt()`. This makes it a prime target for fuzzing. The patch touches the core of the system and introduces new features. From my vantage point, the potential for discovering subtle vulnerabilities is quite high.

Everything checks out. I'm ready to move forward and invoke `set-results`. I think this is well done.



48/2 2026/11/16 00:58 tool set-results
0m Args:
{
  "EnableConfigs": [
    "KEYS",
    "RXRPC_KEYS",
    "AF_RXRPC",
    "RXKAD",
    "RXGK",
    "DNS_KEY",
    "DNS_RESOLVER",
    "CIFS",
    "CIFS_UPCALL",
    "NFS_FS",
    "NFS_V4"
  ],
  "FocusSymbols": [
    "key_garbage_collector",
    "key_gc_unused_keys",
    "key_schedule_gc_work",
    "key_gc_flush",
    "key_alloc",
    "keyring_restrict",
    "__register_key_type",
    "unregister_key_type",
    "rxrpc_preparse_s",
    "rxrpc_request_key",
    "rxrpc_server_keyring"
  ],
  "Reasoning": "The patch series introduces significant architectural refactorings to the kernel keys subsystem, specifically key garbage collection and key type lifetime management. It eliminates the 3-pass dead-keytype GC cycle in favor of module refcounting (try_module_get/module_put) on key allocation and destruction, reworks the key garbage collector to scan the serial rb_tree in chunks with an explicit cursor, and introduces key_gc_flush() to synchronize deferred key and credential destruction. In addition, RxRPC and DNS resolver key types are split into separate modules, with RxRPC server key preparsing restructured and key flushing integrated into NFSv4 idmap and CIFS session teardowns. These paths are in core subsystems and directly reachable via keyctl(), add_key(), request_key(), and RxRPC socket options, warranting fuzzing.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "KEYS",
    "RXRPC_KEYS",
    "AF_RXRPC",
    "RXKAD",
    "RXGK",
    "DNS_KEY",
    "DNS_RESOLVER",
    "CIFS",
    "CIFS_UPCALL",
    "NFS_FS",
    "NFS_V4"
  ],
  "FocusSymbols": [
    "key_garbage_collector",
    "key_gc_unused_keys",
    "key_schedule_gc_work",
    "key_gc_flush",
    "key_alloc",
    "keyring_restrict",
    "__register_key_type",
    "unregister_key_type",
    "rxrpc_preparse_s",
    "rxrpc_request_key",
    "rxrpc_server_keyring"
  ],
  "Reasoning": "The patch series introduces significant architectural refactorings to the kernel keys subsystem, specifically key garbage collection and key type lifetime management. It eliminates the 3-pass dead-keytype GC cycle in favor of module refcounting (try_module_get/module_put) on key allocation and destruction, reworks the key garbage collector to scan the serial rb_tree in chunks with an explicit cursor, and introduces key_gc_flush() to synchronize deferred key and credential destruction. In addition, RxRPC and DNS resolver key types are split into separate modules, with RxRPC server key preparsing restructured and key flushing integrated into NFSv4 idmap and CIFS session teardowns. These paths are in core subsystems and directly reachable via keyctl(), add_key(), request_key(), and RxRPC socket options, warranting fuzzing.",
  "WorthFuzzing": true
}

49/1 2026/11/16 00:58 action If
1m Args:
{
  "WorthFuzzing": true
}

Results:
null

50/2 2026/11/16 00:58 agent kmsan-evaluator
1m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series refactors the kernel keys subsystem to manage key type module ownership (adding `struct module *owner` to `struct key_type`), introduces module refcounting on key allocation and restriction, and redesigns the key garbage collector (`security/keys/gc.c`) by removing the old dead-keytype sweep in favor of module pinning and iterative workqueue-based garbage collection with `key_gc_flush()`. It also splits key type registrations into dedicated modules for DNS resolver and RxRPC, adds serialization and keyring clearing on session termination in NFS and CIFS/SMB, and adds mutex protection for trusted TEE keys.\n\nPrimary risks associated with these changes are reference counting errors (leaks or premature puts), module unload use-after-free, synchronization issues, and potential lock ordering deadlocks. These failure modes are reliably caught by KASAN, refcount checks, and LOCKDEP in standard debugging builds.\n\nThe changes do not introduce or modify any kernel structures copied to user space, do not alter buffer length or bounds calculations, do not create paths reading uninitialized heap/stack memory, and all introduced variables and struct instances are fully initialized prior to access. Consequently, KMSAN is not needed.",
  "NeedsKMSAN": false
}

Instruction:
You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.

CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
  a comprehensive suite of debugging tools and sanitizers, including KASAN
  (out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
  (locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
  or page allocations) and kernel-to-user memory info-leaks.

Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.

Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.

Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
   attributes, ioctl output arguments, socket options, or BPF buffers) where fields
   or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
   or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
   could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
   uninitialized bytes of existing buffers.

Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
  dereferences, locking deadlocks, or use-after-free bugs (these are already caught
  by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
  or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.

Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit bfe32f9841a590f04284c65f8e4157bba77792b8
Author: syz-cluster <triage@syzkaller.com>
Date:   Mon Nov 16 00:55:37 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/networking/rxrpc.rst b/Documentation/networking/rxrpc.rst
index eca055a536aa1b..394190c40d6ee9 100644
--- a/Documentation/networking/rxrpc.rst
+++ b/Documentation/networking/rxrpc.rst
@@ -1165,5 +1165,5 @@ API Function Reference
 .. kernel-doc:: net/rxrpc/recvmsg.c
 .. kernel-doc:: net/rxrpc/rxgk.c
 .. kernel-doc:: net/rxrpc/rxkad.c
+.. kernel-doc:: net/rxrpc/security.c
 .. kernel-doc:: net/rxrpc/sendmsg.c
-.. kernel-doc:: net/rxrpc/server_key.c
diff --git a/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c
index 998f2da5617500..ab1a78cdfd4ceb 100644
--- a/arch/s390/kernel/cert_store.c
+++ b/arch/s390/kernel/cert_store.c
@@ -17,6 +17,7 @@
 #include <linux/key.h>
 #include <linux/keyctl.h>
 #include <linux/kobject.h>
+#include <linux/list.h>
 #include <linux/module.h>
 #include <linux/seq_file.h>
 #include <linux/slab.h>
@@ -296,6 +297,18 @@ static int check_certificate_valid(const struct vce *vce)
 	return check_certificate_hash(vce);
 }
 
+struct cert_store_key {
+	struct list_head list;
+	struct key *key;
+};
+
+static DEFINE_MUTEX(cs_refresh_lock);
+/* Owned references, protected by cs_refresh_lock. */
+static LIST_HEAD(cs_keys);
+static struct key *active_cs_keyring;
+static struct key *cs_keyring_parent;
+
+/* Return an owned reference to the user session keyring. */
 static struct key *get_user_session_keyring(void)
 {
 	key_ref_t us_keyring_ref;
@@ -305,118 +318,66 @@ static struct key *get_user_session_keyring(void)
 	if (IS_ERR(us_keyring_ref)) {
 		pr_dbf_msg("Couldn't get user session keyring: %ld",
 			   PTR_ERR(us_keyring_ref));
-		return ERR_PTR(-ENOKEY);
+		return ERR_CAST(us_keyring_ref);
 	}
-	key_ref_put(us_keyring_ref);
 	return key_ref_to_ptr(us_keyring_ref);
 }
 
-/* Invalidate all keys from cert_store keyring. */
-static int invalidate_keyring_keys(struct key *keyring)
-{
-	unsigned long num_keys, key_index;
-	size_t keyring_payload_len;
-	key_serial_t *key_array;
-	struct key *current_key;
-	int rc;
-
-	keyring_payload_len = key_type_keyring.read(keyring, NULL, 0);
-	num_keys = keyring_payload_len / sizeof(key_serial_t);
-	key_array = kzalloc_objs(key_serial_t, num_keys);
-	if (!key_array)
-		return -ENOMEM;
-
-	rc = key_type_keyring.read(keyring, (char *)key_array, keyring_payload_len);
-	if (rc != keyring_payload_len) {
-		pr_dbf_msg("Couldn't read keyring payload");
-		goto out;
-	}
-
-	for (key_index = 0; key_index < num_keys; key_index++) {
-		current_key = key_lookup(key_array[key_index]);
-		pr_dbf_msg("Invalidating key %08x", current_key->serial);
-
-		key_invalidate(current_key);
-		key_put(current_key);
-		rc = key_unlink(keyring, current_key);
-		if (rc) {
-			pr_dbf_msg("Couldn't unlink key %08x: %d", current_key->serial, rc);
-			break;
-		}
-	}
-out:
-	kfree(key_array);
-	return rc;
-}
-
-static struct key *find_cs_keyring(void)
-{
-	key_ref_t cs_keyring_ref;
-	struct key *cs_keyring;
-
-	cs_keyring_ref = keyring_search(make_key_ref(get_user_session_keyring(), true),
-					&key_type_keyring, CERT_STORE_KEYRING_NAME,
-					false);
-	if (!IS_ERR(cs_keyring_ref)) {
-		cs_keyring = key_ref_to_ptr(cs_keyring_ref);
-		key_ref_put(cs_keyring_ref);
-		goto found;
-	}
-	/* Search default locations: thread, process, session keyrings */
-	cs_keyring = request_key(&key_type_keyring, CERT_STORE_KEYRING_NAME, NULL);
-	if (IS_ERR(cs_keyring))
-		return NULL;
-	key_put(cs_keyring);
-found:
-	return cs_keyring;
-}
-
 static void cleanup_cs_keys(void)
 {
-	struct key *cs_keyring;
+	struct cert_store_key *entry, *tmp;
+	int rc;
 
-	cs_keyring = find_cs_keyring();
-	if (!cs_keyring)
+	if (!active_cs_keyring)
 		return;
 
-	pr_dbf_msg("Found cert_store keyring. Purging...");
-	/*
-	 * Remove cert_store_key_type in case invalidation
-	 * of old cert_store keys failed (= severe error).
-	 */
-	if (invalidate_keyring_keys(cs_keyring))
-		unregister_key_type(&key_type_cert_store_key);
+	/* Invalidate even certificates unlinked or linked into other keyrings. */
+	list_for_each_entry_safe(entry, tmp, &cs_keys, list) {
+		key_invalidate(entry->key);
+		key_put(entry->key);
+		list_del(&entry->list);
+		kfree(entry);
+	}
 
-	keyring_clear(cs_keyring);
-	key_invalidate(cs_keyring);
-	key_put(cs_keyring);
-	key_unlink(get_user_session_keyring(), cs_keyring);
+	rc = keyring_clear(active_cs_keyring);
+	if (rc)
+		pr_dbf_msg("Couldn't clear cert_store keyring: %d", rc);
+	key_invalidate(active_cs_keyring);
+	rc = key_unlink(cs_keyring_parent, active_cs_keyring);
+	if (rc)
+		pr_dbf_msg("Couldn't unlink cert_store keyring: %d", rc);
+	key_put(active_cs_keyring);
+	key_put(cs_keyring_parent);
+	active_cs_keyring = NULL;
+	cs_keyring_parent = NULL;
 }
 
+/* Return a borrowed reference; cleanup_cs_keys() owns the keyring. */
 static struct key *create_cs_keyring(void)
 {
-	static struct key *cs_keyring;
+	struct key *cs_keyring, *parent;
 
 	/* Cleanup previous cs_keyring and all associated keys if any. */
 	cleanup_cs_keys();
+	parent = get_user_session_keyring();
+	if (IS_ERR(parent))
+		return parent;
+
 	cs_keyring = keyring_alloc(CERT_STORE_KEYRING_NAME, GLOBAL_ROOT_UID,
 				   GLOBAL_ROOT_GID, current_cred(),
 				   (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ,
 				   KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_SET_KEEP,
-				   NULL, get_user_session_keyring());
+				   NULL, parent);
 	if (IS_ERR(cs_keyring)) {
 		pr_dbf_msg("Can't allocate cert_store keyring");
-		return NULL;
+		key_put(parent);
+		return cs_keyring;
 	}
 
+	active_cs_keyring = cs_keyring;
+	cs_keyring_parent = parent;
 	pr_dbf_msg("Successfully allocated cert_store keyring: %08x", cs_keyring->serial);
 
-	/*
-	 * In case a previous clean-up ran into an
-	 * error and unregistered key type.
-	 */
-	register_key_type(&key_type_cert_store_key);
-
 	return cs_keyring;
 }
 
@@ -454,6 +415,7 @@ static char *get_key_description(struct vcssb *vcssb, const struct vce *vce)
 static int create_key_from_vce(struct vcssb *vcssb, struct vce *vce,
 			       struct key *keyring)
 {
+	struct cert_store_key *entry;
 	key_ref_t newkey;
 	char *desc;
 	int rc;
@@ -462,6 +424,13 @@ static int create_key_from_vce(struct vcssb *vcssb, struct vce *vce,
 	if (!desc)
 		return -ENOMEM;
 
+	/* Reserve cleanup tracking before the key can be linked elsewhere. */
+	entry = kmalloc_obj(*entry);
+	if (!entry) {
+		rc = -ENOMEM;
+		goto out;
+	}
+
 	newkey = key_create_or_update(
 		make_key_ref(keyring, true), CERT_STORE_KEY_TYPE_NAME,
 		desc, (u8 *)vce + vce->vce_hdr.vc_offset,
@@ -473,10 +442,12 @@ static int create_key_from_vce(struct vcssb *vcssb, struct vce *vce,
 	if (rc) {
 		pr_dbf_msg("Couldn't create a key from Certificate Entry (%d)", rc);
 		rc = -ENOKEY;
+		kfree(entry);
 		goto out;
 	}
 
-	key_ref_put(newkey);
+	entry->key = key_ref_to_ptr(newkey);
+	list_add_tail(&entry->list, &cs_keys);
 out:
 	kfree(desc);
 	return rc;
@@ -704,19 +675,18 @@ static int fill_cs_keyring(void)
 	if (rc)
 		goto cleanup_keys;
 
-	rc = -ENOMEM;
 	cs_keyring = create_cs_keyring();
-	if (!cs_keyring)
+	if (IS_ERR(cs_keyring)) {
+		rc = PTR_ERR(cs_keyring);
 		goto cleanup_keys;
+	}
 
 	rc = add_certificates_to_keyring(vcssb, cs_keyring);
 	if (rc)
-		goto cleanup_cs_keyring;
+		goto cleanup_keys;
 
 	goto out;
 
-cleanup_cs_keyring:
-	key_put(cs_keyring);
 cleanup_keys:
 	cleanup_cs_keys();
 out:
@@ -724,7 +694,6 @@ static int fill_cs_keyring(void)
 	return rc;
 }
 
-static DEFINE_MUTEX(cs_refresh_lock);
 static int cs_status_val = -1;
 
 static ssize_t cs_status_show(struct kobject *kobj,
@@ -794,14 +763,18 @@ static int __init cert_store_init(void)
 	if (!cert_store_kobj)
 		goto cleanup_dbf;
 
-	rc = sysfs_create_files(cert_store_kobj, cert_store_attrs);
+	rc = register_key_type(&key_type_cert_store_key);
 	if (rc)
 		goto cleanup_kobj;
 
-	register_key_type(&key_type_cert_store_key);
+	rc = sysfs_create_files(cert_store_kobj, cert_store_attrs);
+	if (rc)
+		goto cleanup_key_type;
 
 	return rc;
 
+cleanup_key_type:
+	unregister_key_type(&key_type_cert_store_key);
 cleanup_kobj:
 	kobject_put(cert_store_kobj);
 cleanup_dbf:
diff --git a/fs/nfs/nfs4idmap.c b/fs/nfs/nfs4idmap.c
index bc397110d977f5..c88444cc6bf682 100644
--- a/fs/nfs/nfs4idmap.c
+++ b/fs/nfs/nfs4idmap.c
@@ -47,6 +47,8 @@
 #include <keys/request_key_auth-type.h>
 #include <linux/module.h>
 #include <linux/user_namespace.h>
+#include <linux/mutex.h>
+#include <linux/ratelimit.h>
 
 #include "internal.h"
 #include "netns.h"
@@ -58,6 +60,10 @@
 static const struct cred *id_resolver_cache;
 static struct key_type key_type_id_resolver_legacy;
 
+/* Serializes the idmap cache. */
+static DEFINE_MUTEX(nfs_idmap_cache_mutex);
+static unsigned int nfs_idmap_users;
+
 struct idmap_legacy_upcalldata {
 	struct rpc_pipe_msg pipe_msg;
 	struct idmap_msg idmap_msg;
@@ -469,7 +475,10 @@ nfs_idmap_new(struct nfs_client *clp)
 	if (error)
 		goto err_destroy_pipe;
 
+	mutex_lock(&nfs_idmap_cache_mutex);
+	nfs_idmap_users++;
 	clp->cl_idmap = idmap;
+	mutex_unlock(&nfs_idmap_cache_mutex);
 	return 0;
 err_destroy_pipe:
 	rpc_destroy_pipe_data(idmap->idmap_pipe);
@@ -483,6 +492,7 @@ void
 nfs_idmap_delete(struct nfs_client *clp)
 {
 	struct idmap *idmap = clp->cl_idmap;
+	int ret;
 
 	if (!idmap)
 		return;
@@ -493,6 +503,17 @@ nfs_idmap_delete(struct nfs_client *clp)
 	rpc_destroy_pipe_data(idmap->idmap_pipe);
 	put_user_ns(idmap->user_ns);
 	kfree(idmap);
+
+	mutex_lock(&nfs_idmap_cache_mutex);
+	if (--nfs_idmap_users == 0) {
+		ret = keyring_clear(id_resolver_cache->thread_keyring);
+		if (ret)
+			pr_warn_ratelimited("NFS: Failed to clear idmap cache: %d; cache pins remain\n",
+					    ret);
+		else
+			key_gc_flush();
+	}
+	mutex_unlock(&nfs_idmap_cache_mutex);
 }
 
 static int nfs_idmap_prepare_message(char *desc, struct idmap *idmap,
diff --git a/fs/smb/client/cifs_spnego.c b/fs/smb/client/cifs_spnego.c
index 44c40727568042..e974f396e07f62 100644
--- a/fs/smb/client/cifs_spnego.c
+++ b/fs/smb/client/cifs_spnego.c
@@ -15,6 +15,7 @@
 #include <linux/key-type.h>
 #include <linux/keyctl.h>
 #include <linux/inet.h>
+#include <linux/ratelimit.h>
 #include "cifsglob.h"
 #include "cifs_spnego.h"
 #include "cifs_debug.h"
@@ -190,6 +191,17 @@ cifs_get_spnego_key(struct cifs_ses *sesInfo,
 	return spnego_key;
 }
 
+void
+cifs_spnego_clear_cache(void)
+{
+	int ret;
+
+	ret = keyring_clear(spnego_cred->thread_keyring);
+	if (ret)
+		pr_warn_ratelimited("Failed to clear SPNEGO cache: %d; cache pins remain\n",
+				    ret);
+}
+
 int
 init_cifs_spnego(void)
 {
diff --git a/fs/smb/client/cifsacl.c b/fs/smb/client/cifsacl.c
index 346899da91eb21..60c60c23dd34e2 100644
--- a/fs/smb/client/cifsacl.c
+++ b/fs/smb/client/cifsacl.c
@@ -13,6 +13,7 @@
 #include <linux/string.h>
 #include <linux/keyctl.h>
 #include <linux/key-type.h>
+#include <linux/ratelimit.h>
 #include <uapi/linux/posix_acl.h>
 #include <linux/posix_acl.h>
 #include <linux/posix_acl_xattr.h>
@@ -539,6 +540,17 @@ sid_to_id(struct cifs_sb_info *cifs_sb, struct smb_sid *psid,
 	return 0;
 }
 
+void
+cifs_idmap_clear_cache(void)
+{
+	int ret;
+
+	ret = keyring_clear(root_cred->thread_keyring);
+	if (ret)
+		pr_warn_ratelimited("Failed to clear idmap cache: %d; cache pins remain\n",
+				    ret);
+}
+
 int
 init_cifs_idmap(void)
 {
diff --git a/fs/smb/client/cifsproto.h b/fs/smb/client/cifsproto.h
index f9ea35597bc27f..2930a40d1b673a 100644
--- a/fs/smb/client/cifsproto.h
+++ b/fs/smb/client/cifsproto.h
@@ -58,8 +58,16 @@ do {									\
 } while (0)
 int init_cifs_idmap(void);
 void exit_cifs_idmap(void);
+void cifs_idmap_clear_cache(void);
 int init_cifs_spnego(void);
 void exit_cifs_spnego(void);
+#ifdef CONFIG_CIFS_UPCALL
+void cifs_spnego_clear_cache(void);
+#else
+static inline void cifs_spnego_clear_cache(void)
+{
+}
+#endif
 const char *build_path_from_dentry(struct dentry *direntry, void *page);
 char *__build_path_from_dentry_optional_prefix(struct dentry *direntry,
 					       void *page, const char *tree,
diff --git a/fs/smb/client/misc.c b/fs/smb/client/misc.c
index ec28f102ea08a1..11c0330be489bd 100644
--- a/fs/smb/client/misc.c
+++ b/fs/smb/client/misc.c
@@ -9,6 +9,8 @@
 #include <linux/slab.h>
 #include <linux/ctype.h>
 #include <linux/mempool.h>
+#include <linux/key.h>
+#include <linux/mutex.h>
 #include <linux/vmalloc.h>
 #include "cifsglob.h"
 #include "cifsproto.h"
@@ -33,6 +35,9 @@ struct tcon_list {
 	struct cifs_tcon *tcon;
 };
 
+/* Serialize session admission with the last session's cache clear. */
+static DEFINE_MUTEX(cifs_session_mutex);
+
 /* The xid serves as a useful identifier for each incoming vfs request,
    in a similar way to the mid which is useful to track each sent smb,
    and CurrentXid can also provide a running counter (although it
@@ -74,7 +79,6 @@ sesInfoAlloc(void)
 
 	ret_buf = kzalloc_obj(struct cifs_ses);
 	if (ret_buf) {
-		atomic_inc(&sesInfoAllocCount);
 		spin_lock_init(&ret_buf->ses_lock);
 		ret_buf->ses_status = SES_NEW;
 		++ret_buf->ses_count;
@@ -84,6 +88,10 @@ sesInfoAlloc(void)
 		spin_lock_init(&ret_buf->iface_lock);
 		INIT_LIST_HEAD(&ret_buf->iface_list);
 		spin_lock_init(&ret_buf->chan_lock);
+
+		mutex_lock(&cifs_session_mutex);
+		atomic_inc(&sesInfoAllocCount);
+		mutex_unlock(&cifs_session_mutex);
 	}
 	return ret_buf;
 }
@@ -99,7 +107,6 @@ sesInfoFree(struct cifs_ses *buf_to_free)
 	}
 
 	unload_nls(buf_to_free->local_nls);
-	atomic_dec(&sesInfoAllocCount);
 	kfree(buf_to_free->serverOS);
 	kfree(buf_to_free->serverDomain);
 	kfree(buf_to_free->serverNOS);
@@ -115,6 +122,14 @@ sesInfoFree(struct cifs_ses *buf_to_free)
 		kref_put(&iface->refcount, release_iface);
 	spin_unlock(&buf_to_free->iface_lock);
 	kfree_sensitive(buf_to_free);
+
+	mutex_lock(&cifs_session_mutex);
+	if (atomic_dec_and_test(&sesInfoAllocCount)) {
+		cifs_idmap_clear_cache();
+		cifs_spnego_clear_cache();
+		key_gc_flush();
+	}
+	mutex_unlock(&cifs_session_mutex);
 }
 
 struct cifs_tcon *
diff --git a/include/linux/key-type.h b/include/linux/key-type.h
index c4f329b6ae3fed..9ecec31ad57162 100644
--- a/include/linux/key-type.h
+++ b/include/linux/key-type.h
@@ -10,9 +10,11 @@
 
 #include <linux/key.h>
 #include <linux/errno.h>
+#include <linux/init.h>
 
 #ifdef CONFIG_KEYS
 
+struct module;
 struct kernel_pkey_query;
 struct kernel_pkey_params;
 
@@ -161,6 +163,7 @@ struct key_type {
 				     const void *in, const void *in2);
 
 	/* internal fields */
+	struct module		*owner;
 	atomic64_t		index_id;	/* Opaque keyring index ID */
 	struct list_head	link;		/* link in types list */
 	struct lock_class_key	lock_class;	/* key->sem lock class */
@@ -168,7 +171,8 @@ struct key_type {
 
 extern struct key_type key_type_keyring;
 
-extern int register_key_type(struct key_type *ktype);
+int __register_key_type(struct key_type *ktype, struct module *owner);
+#define register_key_type(ktype) __register_key_type(ktype, THIS_MODULE)
 extern void unregister_key_type(struct key_type *ktype);
 
 extern int key_payload_reserve(struct key *key, size_t datalen);
diff --git a/include/linux/key.h b/include/linux/key.h
index 420412aab9263a..0f408255f7406a 100644
--- a/include/linux/key.h
+++ b/include/linux/key.h
@@ -439,6 +439,7 @@ extern int restrict_link_reject(struct key *keyring,
 				struct key *restriction_key);
 
 extern int keyring_clear(struct key *keyring);
+void key_gc_flush(void);
 
 extern key_ref_t keyring_search(key_ref_t keyring,
 				struct key_type *type,
@@ -526,6 +527,7 @@ extern void key_init(void);
 #define key_free_user_ns(ns)		do { } while(0)
 #define key_remove_domain(d)		do { } while(0)
 #define key_lookup(k)			NULL
+#define key_gc_flush()			do { } while (0)
 
 #endif /* CONFIG_KEYS */
 #endif /* __KERNEL__ */
diff --git a/net/Makefile b/net/Makefile
index 5b2dd7f07a85e9..97b2bd2ace7b5a 100644
--- a/net/Makefile
+++ b/net/Makefile
@@ -30,7 +30,7 @@ obj-$(CONFIG_LAPB)		+= lapb/
 obj-$(CONFIG_CAN)		+= can/
 obj-$(CONFIG_BT)		+= bluetooth/
 obj-$(CONFIG_SUNRPC)		+= sunrpc/
-obj-$(CONFIG_AF_RXRPC)		+= rxrpc/
+obj-$(CONFIG_RXRPC_KEYS)	+= rxrpc/
 obj-$(CONFIG_AF_KCM)		+= kcm/
 obj-$(CONFIG_STREAM_PARSER)	+= strparser/
 obj-$(CONFIG_ATM)		+= atm/
@@ -55,7 +55,7 @@ obj-$(CONFIG_IEEE802154)	+= ieee802154/
 obj-$(CONFIG_MAC802154)		+= mac802154/
 
 obj-$(CONFIG_SYSCTL)		+= sysctl_net.o
-obj-$(CONFIG_DNS_RESOLVER)	+= dns_resolver/
+obj-$(CONFIG_DNS_KEY)		+= dns_resolver/
 obj-$(CONFIG_CEPH_LIB)		+= ceph/
 obj-$(CONFIG_BATMAN_ADV)	+= batman-adv/
 obj-$(CONFIG_NFC)		+= nfc/
diff --git a/net/dns_resolver/Kconfig b/net/dns_resolver/Kconfig
index 7c2dba273e358c..2618bad2e771e9 100644
--- a/net/dns_resolver/Kconfig
+++ b/net/dns_resolver/Kconfig
@@ -1,10 +1,25 @@
 # SPDX-License-Identifier: GPL-2.0-only
+
+#
+# Configuration for DNS Resolver key type
+#
+config DNS_KEY
+	tristate "DNS Resolver key type"
+	depends on KEYS
+	help
+	  Support the key type used to cache DNS lookups independently of
+	  the in-kernel DNS query service.
+
+	  To compile this as a module, choose M here: the module is called
+	  dns_resolver_key.
+
 #
 # Configuration for DNS Resolver
 #
 config DNS_RESOLVER
 	tristate "DNS Resolver support"
 	depends on KEYS
+	select DNS_KEY
 	help
 	  Saying Y here will include support for the DNS Resolver key type
 	  which can be used to make upcalls to perform DNS lookups in
diff --git a/net/dns_resolver/Makefile b/net/dns_resolver/Makefile
index 877532d662d05d..586e4c6514de81 100644
--- a/net/dns_resolver/Makefile
+++ b/net/dns_resolver/Makefile
@@ -3,6 +3,8 @@
 # Makefile for the Linux DNS Resolver.
 #
 
+obj-$(CONFIG_DNS_KEY) += dns_resolver_key.o
 obj-$(CONFIG_DNS_RESOLVER) += dns_resolver.o
 
-dns_resolver-y :=  dns_key.o dns_query.o
+dns_resolver-y := dns_query.o
+dns_resolver_key-y := dns_key.o
diff --git a/net/dns_resolver/dns_key.c b/net/dns_resolver/dns_key.c
index 451247864a638b..fecbdc1d6beb10 100644
--- a/net/dns_resolver/dns_key.c
+++ b/net/dns_resolver/dns_key.c
@@ -9,8 +9,8 @@
  *              Wang Lei (wang840925@gmail.com)
  *		David Howells (dhowells@redhat.com)
  */
+
 #include <linux/module.h>
-#include <linux/moduleparam.h>
 #include <linux/slab.h>
 #include <linux/string.h>
 #include <linux/kernel.h>
@@ -22,15 +22,12 @@
 #include <keys/user-type.h>
 #include "internal.h"
 
-MODULE_DESCRIPTION("DNS Resolver");
+MODULE_DESCRIPTION("DNS Resolver key type");
 MODULE_AUTHOR("Wang Lei");
 MODULE_LICENSE("GPL");
 
 unsigned int dns_resolver_debug;
-module_param_named(debug, dns_resolver_debug, uint, 0644);
-MODULE_PARM_DESC(debug, "DNS Resolver debugging mask");
-
-const struct cred *dns_resolver_cache;
+EXPORT_SYMBOL_GPL(dns_resolver_debug);
 
 #define	DNS_ERRORNO_OPTION	"dnserror"
 
@@ -318,61 +315,17 @@ struct key_type key_type_dns_resolver = {
 	.describe	= dns_resolver_describe,
 	.read		= dns_resolver_read,
 };
+EXPORT_SYMBOL_GPL(key_type_dns_resolver);
 
-static int __init init_dns_resolver(void)
+static int __init init_dns_key(void)
 {
-	struct cred *cred;
-	struct key *keyring;
-	int ret;
-
-	/* create an override credential set with a special thread keyring in
-	 * which DNS requests are cached
-	 *
-	 * this is used to prevent malicious redirections from being installed
-	 * with add_key().
-	 */
-	cred = prepare_kernel_cred(&init_task);
-	if (!cred)
-		return -ENOMEM;
-
-	keyring = keyring_alloc(".dns_resolver",
-				GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,
-				(KEY_POS_ALL & ~KEY_POS_SETATTR) |
-				KEY_USR_VIEW | KEY_USR_READ,
-				KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
-	if (IS_ERR(keyring)) {
-		ret = PTR_ERR(keyring);
-		goto failed_put_cred;
-	}
-
-	ret = register_key_type(&key_type_dns_resolver);
-	if (ret < 0)
-		goto failed_put_key;
-
-	/* instruct request_key() to use this special keyring as a cache for
-	 * the results it looks up */
-	set_bit(KEY_FLAG_ROOT_CAN_CLEAR, &keyring->flags);
-	cred->thread_keyring = keyring;
-	cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
-	dns_resolver_cache = cred;
-
-	kdebug("DNS resolver keyring: %d\n", key_serial(keyring));
-	return 0;
-
-failed_put_key:
-	key_put(keyring);
-failed_put_cred:
-	put_cred(cred);
-	return ret;
+	return register_key_type(&key_type_dns_resolver);
 }
 
-static void __exit exit_dns_resolver(void)
+static void __exit exit_dns_key(void)
 {
-	key_revoke(dns_resolver_cache->thread_keyring);
 	unregister_key_type(&key_type_dns_resolver);
-	put_cred(dns_resolver_cache);
 }
 
-module_init(init_dns_resolver)
-module_exit(exit_dns_resolver)
-MODULE_LICENSE("GPL");
+module_init(init_dns_key);
+module_exit(exit_dns_key);
diff --git a/net/dns_resolver/dns_query.c b/net/dns_resolver/dns_query.c
index b8fb9a1245bf3a..ae4dde190101d7 100644
--- a/net/dns_resolver/dns_query.c
+++ b/net/dns_resolver/dns_query.c
@@ -24,8 +24,10 @@
  */
 
 #include <linux/module.h>
+#include <linux/moduleparam.h>
 #include <linux/slab.h>
 #include <linux/cred.h>
+#include <linux/keyctl.h>
 #include <linux/dns_resolver.h>
 #include <linux/err.h>
 #include <net/net_namespace.h>
@@ -35,6 +37,8 @@
 
 #include "internal.h"
 
+static const struct cred *dns_resolver_cache;
+
 /**
  * dns_query - Query the DNS
  * @net: The network namespace to operate in.
@@ -137,3 +141,63 @@ int dns_query(struct net *net,
 	return ret;
 }
 EXPORT_SYMBOL(dns_query);
+
+static int __init init_dns_resolver(void)
+{
+	struct cred *cred;
+	struct key *keyring;
+	int ret;
+
+	/*
+	 * Create an override credential set with a special thread keyring in
+	 * which DNS requests are cached.  This prevents malicious redirections
+	 * from being installed with add_key().
+	 */
+	cred = prepare_kernel_cred(&init_task);
+	if (!cred)
+		return -ENOMEM;
+
+	keyring = keyring_alloc(".dns_resolver",
+				GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,
+				(KEY_POS_ALL & ~KEY_POS_SETATTR) |
+				KEY_USR_VIEW | KEY_USR_READ,
+				KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
+	if (IS_ERR(keyring)) {
+		ret = PTR_ERR(keyring);
+		goto failed_put_cred;
+	}
+
+	/*
+	 * Instruct request_key() to use this special keyring as a cache for
+	 * the results it looks up.
+	 */
+	set_bit(KEY_FLAG_ROOT_CAN_CLEAR, &keyring->flags);
+	cred->thread_keyring = keyring;
+	cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
+	dns_resolver_cache = cred;
+
+	kdebug("DNS resolver keyring: %d\n", key_serial(keyring));
+	return 0;
+
+failed_put_cred:
+	put_cred(cred);
+	return ret;
+}
+
+static void __exit exit_dns_resolver(void)
+{
+	key_revoke(dns_resolver_cache->thread_keyring);
+	put_cred(dns_resolver_cache);
+	/* Drain deferred credential and keyring destruction. */
+	key_gc_flush();
+}
+
+module_init(init_dns_resolver);
+module_exit(exit_dns_resolver);
+
+MODULE_DESCRIPTION("DNS Resolver");
+MODULE_AUTHOR("Wang Lei");
+MODULE_LICENSE("GPL");
+
+module_param_named(debug, dns_resolver_debug, uint, 0644);
+MODULE_PARM_DESC(debug, "DNS Resolver debugging mask");
diff --git a/net/dns_resolver/internal.h b/net/dns_resolver/internal.h
index d0d8edcea09227..3478bad78a9a75 100644
--- a/net/dns_resolver/internal.h
+++ b/net/dns_resolver/internal.h
@@ -18,11 +18,6 @@ enum {
 	dns_key_error,
 };
 
-/*
- * dns_key.c
- */
-extern const struct cred *dns_resolver_cache;
-
 /*
  * debug tracing
  */
diff --git a/net/rxrpc/Kconfig b/net/rxrpc/Kconfig
index 2cebb666dc0711..30135ae62bd6ac 100644
--- a/net/rxrpc/Kconfig
+++ b/net/rxrpc/Kconfig
@@ -3,6 +3,18 @@
 # RxRPC session sockets
 #
 
+config RXRPC_KEYS
+	tristate "RxRPC key types"
+	select CRYPTO
+	select CRYPTO_LIB_DES if RXKAD
+	select KEYS
+	help
+	  Say Y or M here to include support for rxrpc and rxrpc_s key types
+	  independently of RxRPC session sockets.
+
+	  To compile this as a module, choose M here: the module will be called
+	  rxrpc_keys.
+
 config AF_RXRPC
 	tristate "RxRPC session sockets"
 	depends on INET
@@ -10,6 +22,7 @@ config AF_RXRPC
 	select CRYPTO_LIB_DES if RXKAD
 	select KEYS
 	select NET_UDP_TUNNEL
+	select RXRPC_KEYS
 	help
 	  Say Y or M here to include support for RxRPC session sockets (just
 	  the transport part, not the presentation part: (un)marshalling is
@@ -54,6 +67,9 @@ config AF_RXRPC_DEBUG
 
 	  See Documentation/networking/rxrpc.rst.
 
+endif
+
+if RXRPC_KEYS
 
 config RXKAD
 	bool "RxRPC Kerberos security"
@@ -86,6 +102,10 @@ config RXGK
 
 	  See Documentation/networking/rxrpc.rst.
 
+endif
+
+if AF_RXRPC
+
 config RXPERF
 	tristate "RxRPC test service"
 	help
diff --git a/net/rxrpc/Makefile b/net/rxrpc/Makefile
index f994f9f30a29d4..196e0ce085bae1 100644
--- a/net/rxrpc/Makefile
+++ b/net/rxrpc/Makefile
@@ -3,6 +3,7 @@
 # Makefile for Linux kernel RxRPC
 #
 
+obj-$(CONFIG_RXRPC_KEYS) += rxrpc_keys.o
 obj-$(CONFIG_AF_RXRPC) += rxrpc.o
 
 rxrpc-y := \
@@ -19,7 +20,6 @@ rxrpc-y := \
 	input_rack.o \
 	insecure.o \
 	io_thread.o \
-	key.o \
 	local_event.o \
 	local_object.o \
 	misc.o \
@@ -32,7 +32,6 @@ rxrpc-y := \
 	rtt.o \
 	security.o \
 	sendmsg.o \
-	server_key.o \
 	skbuff.o \
 	txbuf.o \
 	utils.o
@@ -45,5 +44,9 @@ rxrpc-$(CONFIG_RXGK) += \
 	rxgk_app.o \
 	rxgk_kdf.o
 
+rxrpc_keys-y := \
+	key.o \
+	server_key.o
+
 obj-$(CONFIG_RXPERF) += rxperf.o
 obj-$(CONFIG_KUNIT) += tests/
diff --git a/net/rxrpc/af_rxrpc.c b/net/rxrpc/af_rxrpc.c
index 9ab0f22c881ec5..6ccb99a992b925 100644
--- a/net/rxrpc/af_rxrpc.c
+++ b/net/rxrpc/af_rxrpc.c
@@ -1077,18 +1077,6 @@ static int __init af_rxrpc_init(void)
 		goto error_sock;
 	}
 
-	ret = register_key_type(&key_type_rxrpc);
-	if (ret < 0) {
-		pr_crit("Cannot register client key type\n");
-		goto error_key_type;
-	}
-
-	ret = register_key_type(&key_type_rxrpc_s);
-	if (ret < 0) {
-		pr_crit("Cannot register server key type\n");
-		goto error_key_type_s;
-	}
-
 	ret = rxrpc_sysctl_init();
 	if (ret < 0) {
 		pr_crit("Cannot register sysctls\n");
@@ -1098,10 +1086,6 @@ static int __init af_rxrpc_init(void)
 	return 0;
 
 error_sysctls:
-	unregister_key_type(&key_type_rxrpc_s);
-error_key_type_s:
-	unregister_key_type(&key_type_rxrpc);
-error_key_type:
 	sock_unregister(PF_RXRPC);
 error_sock:
 	proto_unregister(&rxrpc_proto);
@@ -1124,8 +1108,6 @@ static void __exit af_rxrpc_exit(void)
 {
 	_enter("");
 	rxrpc_sysctl_exit();
-	unregister_key_type(&key_type_rxrpc_s);
-	unregister_key_type(&key_type_rxrpc);
 	sock_unregister(PF_RXRPC);
 	proto_unregister(&rxrpc_proto);
 	unregister_pernet_device(&rxrpc_net_ops);
@@ -1139,6 +1121,7 @@ static void __exit af_rxrpc_exit(void)
 	destroy_workqueue(rxrpc_workqueue);
 	rxrpc_exit_security();
 	kmem_cache_destroy(rxrpc_call_jar);
+	key_gc_flush();
 	_leave("");
 }
 
diff --git a/net/rxrpc/ar-internal.h b/net/rxrpc/ar-internal.h
index 865f05fe37ab96..b5deab0e1ed9d1 100644
--- a/net/rxrpc/ar-internal.h
+++ b/net/rxrpc/ar-internal.h
@@ -273,18 +273,6 @@ struct rxrpc_security {
 	/* Clean up a security service */
 	void (*exit)(void);
 
-	/* Parse the information from a server key */
-	int (*preparse_server_key)(struct key_preparsed_payload *);
-
-	/* Clean up the preparse buffer after parsing a server key */
-	void (*free_preparse_server_key)(struct key_preparsed_payload *);
-
-	/* Destroy the payload of a server key */
-	void (*destroy_server_key)(struct key *);
-
-	/* Describe a server key */
-	void (*describe_server_key)(const struct key *, struct seq_file *);
-
 	/* initialise a connection's security */
 	int (*init_connection_security)(struct rxrpc_connection *,
 					struct rxrpc_key_token *);
@@ -1307,10 +1295,6 @@ extern const struct rxrpc_security rxrpc_no_security;
  */
 extern struct key_type key_type_rxrpc;
 
-int rxrpc_request_key(struct rxrpc_sock *, sockptr_t , int);
-int rxrpc_get_server_data_key(struct rxrpc_connection *, const void *, time64_t,
-			      u32);
-
 /*
  * local_event.c
  */
@@ -1492,6 +1476,11 @@ const struct rxrpc_security *rxrpc_get_incoming_security(struct rxrpc_sock *,
 							 struct sk_buff *);
 struct key *rxrpc_look_up_server_security(struct rxrpc_connection *,
 					  struct sk_buff *, u32, u32);
+int rxrpc_request_key(struct rxrpc_sock *rx, sockptr_t optval, int optlen);
+int rxrpc_get_server_data_key(struct rxrpc_connection *conn,
+			      const void *session_key, time64_t expiry,
+			      u32 kvno);
+int rxrpc_server_keyring(struct rxrpc_sock *rx, sockptr_t optval, int optlen);
 
 /*
  * sendmsg.c
@@ -1505,8 +1494,6 @@ int rxrpc_do_sendmsg(struct rxrpc_sock *, struct msghdr *, size_t);
  */
 extern struct key_type key_type_rxrpc_s;
 
-int rxrpc_server_keyring(struct rxrpc_sock *, sockptr_t, int);
-
 /*
  * skbuff.c
  */
@@ -1633,7 +1620,7 @@ extern unsigned int rxrpc_debug;
 #define _leave(FMT,...)	kleave(FMT,##__VA_ARGS__)
 #define _debug(FMT,...)	kdebug(FMT,##__VA_ARGS__)
 
-#elif defined(CONFIG_AF_RXRPC_DEBUG)
+#elif defined(CONFIG_AF_RXRPC_DEBUG) && !defined(RXRPC_KEY_PROVIDER)
 #define RXRPC_DEBUG_KENTER	0x01
 #define RXRPC_DEBUG_KLEAVE	0x02
 #define RXRPC_DEBUG_KDEBUG	0x04
diff --git a/net/rxrpc/conn_event.c b/net/rxrpc/conn_event.c
index 611c790bc6d0ce..096807f133546e 100644
--- a/net/rxrpc/conn_event.c
+++ b/net/rxrpc/conn_event.c
@@ -298,8 +298,13 @@ static int rxrpc_process_event(struct rxrpc_connection *conn,
 
 		ret = conn->security->init_connection_security(
 			conn, conn->key->payload.data[0]);
-		if (ret < 0)
+		if (ret < 0) {
+			struct key *key = conn->key;
+
+			WRITE_ONCE(conn->key, NULL);
+			key_put(key);
 			return ret;
+		}
 
 		spin_lock_irq(&conn->state_lock);
 		if (conn->state == RXRPC_CONN_SERVICE_CHALLENGING) {
diff --git a/net/rxrpc/key.c b/net/rxrpc/key.c
index cbd26da4495107..49d0871beaf9cd 100644
--- a/net/rxrpc/key.c
+++ b/net/rxrpc/key.c
@@ -9,6 +9,7 @@
  */
 
 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+#define RXRPC_KEY_PROVIDER
 
 #include <linux/module.h>
 #include <linux/net.h>
@@ -615,89 +616,6 @@ static void rxrpc_describe(const struct key *key, struct seq_file *m)
 	}
 }
 
-/*
- * grab the security key for a socket
- */
-int rxrpc_request_key(struct rxrpc_sock *rx, sockptr_t optval, int optlen)
-{
-	struct key *key;
-	char *description;
-
-	_enter("");
-
-	if (optlen <= 0 || optlen > PAGE_SIZE - 1 || rx->key)
-		return -EINVAL;
-
-	description = memdup_sockptr_nul(optval, optlen);
-	if (IS_ERR(description))
-		return PTR_ERR(description);
-
-	key = request_key_net(&key_type_rxrpc, description, sock_net(&rx->sk), NULL);
-	if (IS_ERR(key)) {
-		kfree(description);
-		_leave(" = %ld", PTR_ERR(key));
-		return PTR_ERR(key);
-	}
-
-	rx->key = key;
-	kfree(description);
-	_leave(" = 0 [key %x]", key->serial);
-	return 0;
-}
-
-/*
- * generate a server data key
- */
-int rxrpc_get_server_data_key(struct rxrpc_connection *conn,
-			      const void *session_key,
-			      time64_t expiry,
-			      u32 kvno)
-{
-	const struct cred *cred = current_cred();
-	struct key *key;
-	int ret;
-
-	struct {
-		u32 kver;
-		struct rxrpc_key_data_v1 v1;
-	} data;
-
-	_enter("");
-
-	key = key_alloc(&key_type_rxrpc, "x",
-			GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred, 0,
-			KEY_ALLOC_NOT_IN_QUOTA, NULL);
-	if (IS_ERR(key)) {
-		_leave(" = -ENOMEM [alloc %ld]", PTR_ERR(key));
-		return -ENOMEM;
-	}
-
-	_debug("key %d", key_serial(key));
-
-	data.kver = 1;
-	data.v1.security_index = RXRPC_SECURITY_RXKAD;
-	data.v1.ticket_length = 0;
-	data.v1.expiry = rxrpc_time64_to_u32(expiry);
-	data.v1.kvno = 0;
-
-	memcpy(&data.v1.session_key, session_key, sizeof(data.v1.session_key));
-
-	ret = key_instantiate_and_link(key, &data, sizeof(data), NULL, NULL);
-	if (ret < 0)
-		goto error;
-
-	conn->key = key;
-	_leave(" = 0 [%d]", key_serial(key));
-	return 0;
-
-error:
-	key_revoke(key);
-	key_put(key);
-	_leave(" = -ENOMEM [ins %d]", ret);
-	return -ENOMEM;
-}
-EXPORT_SYMBOL(rxrpc_get_server_data_key);
-
 /**
  * rxrpc_get_null_key - Generate a null RxRPC key
  * @keyname: The name to give the key.
@@ -893,3 +811,41 @@ static long rxrpc_read(const struct key *key,
 	_leave(" = %zu", size);
 	return size;
 }
+
+static int __init rxrpc_keys_init(void)
+{
+	int ret;
+
+	ret = register_key_type(&key_type_rxrpc);
+	if (ret < 0) {
+		pr_crit("Cannot register client key type\n");
+		goto error_key_type;
+	}
+
+	ret = register_key_type(&key_type_rxrpc_s);
+	if (ret < 0) {
+		pr_crit("Cannot register server key type\n");
+		goto error_key_type_s;
+	}
+
+	return 0;
+
+error_key_type_s:
+	unregister_key_type(&key_type_rxrpc);
+
+error_key_type:
+	return ret;
+}
+
+static void __exit rxrpc_keys_exit(void)
+{
+	unregister_key_type(&key_type_rxrpc_s);
+	unregister_key_type(&key_type_rxrpc);
+}
+
+module_init(rxrpc_keys_init);
+module_exit(rxrpc_keys_exit);
+
+MODULE_DESCRIPTION("RxRPC key types");
+MODULE_AUTHOR("David Howells <dhowells@redhat.com>");
+MODULE_LICENSE("GPL");
diff --git a/net/rxrpc/proc.c b/net/rxrpc/proc.c
index e9a27fa7b25d8b..2bf34b85c2f990 100644
--- a/net/rxrpc/proc.c
+++ b/net/rxrpc/proc.c
@@ -182,7 +182,7 @@ static int rxrpc_connection_seq_show(struct seq_file *seq, void *v)
 		   refcount_read(&conn->ref),
 		   atomic_read(&conn->active),
 		   state,
-		   key_serial(conn->key),
+		   key_serial(READ_ONCE(conn->key)),
 		   conn->tx_serial,
 		   conn->hi_serial,
 		   conn->channels[0].call_id,
diff --git a/net/rxrpc/rxgk.c b/net/rxrpc/rxgk.c
index 77a67ace1d2481..5fb3ce15cac402 100644
--- a/net/rxrpc/rxgk.c
+++ b/net/rxrpc/rxgk.c
@@ -14,68 +14,6 @@
 #include "ar-internal.h"
 #include "rxgk_common.h"
 
-/*
- * Parse the information from a server key
- */
-static int rxgk_preparse_server_key(struct key_preparsed_payload *prep)
-{
-	const struct krb5_enctype *krb5;
-	struct krb5_buffer *server_key = (void *)&prep->payload.data[2];
-	unsigned int service, sec_class, kvno, enctype;
-	int n = 0;
-
-	_enter("%zu", prep->datalen);
-
-	if (sscanf(prep->orig_description, "%u:%u:%u:%u%n",
-		   &service, &sec_class, &kvno, &enctype, &n) != 4)
-		return -EINVAL;
-
-	if (prep->orig_description[n])
-		return -EINVAL;
-
-	krb5 = crypto_krb5_find_enctype(enctype);
-	if (!krb5)
-		return -ENOPKG;
-
-	prep->payload.data[0] = (struct krb5_enctype *)krb5;
-
-	if (prep->datalen != krb5->key_len)
-		return -EKEYREJECTED;
-
-	server_key->len = prep->datalen;
-	server_key->data = kmemdup(prep->data, prep->datalen, GFP_KERNEL);
-	if (!server_key->data)
-		return -ENOMEM;
-
-	_leave(" = 0");
-	return 0;
-}
-
-static void rxgk_free_server_key(union key_payload *payload)
-{
-	struct krb5_buffer *server_key = (void *)&payload->data[2];
-
-	kfree_sensitive(server_key->data);
-}
-
-static void rxgk_free_preparse_server_key(struct key_preparsed_payload *prep)
-{
-	rxgk_free_server_key(&prep->payload);
-}
-
-static void rxgk_destroy_server_key(struct key *key)
-{
-	rxgk_free_server_key(&key->payload);
-}
-
-static void rxgk_describe_server_key(const struct key *key, struct seq_file *m)
-{
-	const struct krb5_enctype *krb5 = key->payload.data[0];
-
-	if (krb5)
-		seq_printf(m, ": %s", krb5->name);
-}
-
 /*
  * Handle rekeying the connection when we see our limits overrun or when the
  * far side decided to rekey.
@@ -1335,10 +1273,6 @@ const struct rxrpc_security rxgk_yfs = {
 	.no_key_abort			= RXGK_NOTAUTH,
 	.init				= rxgk_init,
 	.exit				= rxgk_exit,
-	.preparse_server_key		= rxgk_preparse_server_key,
-	.free_preparse_server_key	= rxgk_free_preparse_server_key,
-	.destroy_server_key		= rxgk_destroy_server_key,
-	.describe_server_key		= rxgk_describe_server_key,
 	.init_connection_security	= rxgk_init_connection_security,
 	.alloc_txbuf			= rxgk_alloc_txbuf,
 	.secure_packet			= rxgk_secure_packet,
diff --git a/net/rxrpc/rxkad.c b/net/rxrpc/rxkad.c
index ca9f0e82cb9ac7..2936c6effae396 100644
--- a/net/rxrpc/rxkad.c
+++ b/net/rxrpc/rxkad.c
@@ -47,50 +47,6 @@ struct rxkad_level2_hdr {
 static void rxkad_prime_packet_security(struct rxrpc_connection *conn,
 					const struct fcrypt_key *cipher);
 
-/*
- * Parse the information from a server key
- *
- * The data should be the 8-byte secret key.
- */
-static int rxkad_preparse_server_key(struct key_preparsed_payload *prep)
-{
-	struct des_ctx *des_key;
-	int err;
-
-	if (prep->datalen != 8)
-		return -EINVAL;
-
-	memcpy(&prep->payload.data[2], prep->data, 8);
-
-	des_key = kmalloc_obj(*des_key);
-	if (!des_key) {
-		_leave(" = -ENOMEM");
-		return -ENOMEM;
-	}
-
-	err = des_expand_key(des_key, prep->data, 8);
-	if (err) {
-		kfree_sensitive(des_key);
-		_leave(" = %d", err);
-		return err;
-	}
-
-	prep->payload.data[0] = des_key;
-	_leave(" = 0");
-	return 0;
-}
-
-static void rxkad_free_preparse_server_key(struct key_preparsed_payload *prep)
-{
-	kfree_sensitive(prep->payload.data[0]);
-}
-
-static void rxkad_destroy_server_key(struct key *key)
-{
-	kfree_sensitive(key->payload.data[0]);
-	key->payload.data[0] = NULL;
-}
-
 /*
  * initialise connection security
  */
@@ -1124,9 +1080,6 @@ const struct rxrpc_security rxkad = {
 	.no_key_abort			= RXKADUNKNOWNKEY,
 	.init				= rxkad_init,
 	.exit				= rxkad_exit,
-	.preparse_server_key		= rxkad_preparse_server_key,
-	.free_preparse_server_key	= rxkad_free_preparse_server_key,
-	.destroy_server_key		= rxkad_destroy_server_key,
 	.init_connection_security	= rxkad_init_connection_security,
 	.alloc_txbuf			= rxkad_alloc_txbuf,
 	.secure_packet			= rxkad_secure_packet,
diff --git a/net/rxrpc/security.c b/net/rxrpc/security.c
index 2bfbf2b2bb37a9..28883a70c9e85b 100644
--- a/net/rxrpc/security.c
+++ b/net/rxrpc/security.c
@@ -10,6 +10,8 @@
 #include <linux/skbuff.h>
 #include <linux/udp.h>
 #include <linux/crypto.h>
+#include <linux/key-type.h>
+#include <linux/slab.h>
 #include <net/sock.h>
 #include <net/af_rxrpc.h>
 #include <keys/rxrpc-type.h>
@@ -208,3 +210,185 @@ struct key *rxrpc_look_up_server_security(struct rxrpc_connection *conn,
 	read_unlock(&conn->local->services_lock);
 	return key;
 }
+
+/*
+ * grab the security key for a socket
+ */
+int rxrpc_request_key(struct rxrpc_sock *rx, sockptr_t optval, int optlen)
+{
+	struct key *key;
+	char *description;
+
+	_enter("");
+
+	if (optlen <= 0 || optlen > PAGE_SIZE - 1 || rx->key)
+		return -EINVAL;
+
+	description = memdup_sockptr_nul(optval, optlen);
+	if (IS_ERR(description))
+		return PTR_ERR(description);
+
+	key = request_key_net(&key_type_rxrpc, description, sock_net(&rx->sk), NULL);
+	if (IS_ERR(key)) {
+		kfree(description);
+		_leave(" = %ld", PTR_ERR(key));
+		return PTR_ERR(key);
+	}
+
+	rx->key = key;
+	kfree(description);
+	_leave(" = 0 [key %x]", key->serial);
+	return 0;
+}
+
+/*
+ * generate a server data key
+ */
+int rxrpc_get_server_data_key(struct rxrpc_connection *conn,
+			      const void *session_key,
+			      time64_t expiry,
+			      u32 kvno)
+{
+	const struct cred *cred = current_cred();
+	struct {
+		u32 kver;
+		struct rxrpc_key_data_v1 v1;
+	} data;
+	struct key *key;
+	int ret;
+
+	_enter("");
+
+	key = key_alloc(&key_type_rxrpc, "x",
+			GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred, 0,
+			KEY_ALLOC_NOT_IN_QUOTA, NULL);
+	if (IS_ERR(key)) {
+		_leave(" = -ENOMEM [alloc %ld]", PTR_ERR(key));
+		return -ENOMEM;
+	}
+
+	_debug("key %d", key_serial(key));
+
+	data.kver = 1;
+	data.v1.security_index = RXRPC_SECURITY_RXKAD;
+	data.v1.ticket_length = 0;
+	data.v1.expiry = rxrpc_time64_to_u32(expiry);
+	data.v1.kvno = 0;
+
+	memcpy(&data.v1.session_key, session_key, sizeof(data.v1.session_key));
+
+	ret = key_instantiate_and_link(key, &data, sizeof(data), NULL, NULL);
+	if (ret < 0)
+		goto error;
+
+	conn->key = key;
+	_leave(" = 0 [%d]", key_serial(key));
+	return 0;
+
+error:
+	key_revoke(key);
+	key_put(key);
+	_leave(" = -ENOMEM [ins %d]", ret);
+	return -ENOMEM;
+}
+EXPORT_SYMBOL(rxrpc_get_server_data_key);
+
+/*
+ * grab the security keyring for a server socket
+ */
+int rxrpc_server_keyring(struct rxrpc_sock *rx, sockptr_t optval, int optlen)
+{
+	struct key *key;
+	char *description;
+
+	_enter("");
+
+	if (rx->securities)
+		return -EINVAL;
+
+	if (optlen <= 0 || optlen > PAGE_SIZE - 1)
+		return -EINVAL;
+
+	description = memdup_sockptr_nul(optval, optlen);
+	if (IS_ERR(description))
+		return PTR_ERR(description);
+
+	key = request_key(&key_type_keyring, description, NULL);
+	if (IS_ERR(key)) {
+		kfree(description);
+		_leave(" = %ld", PTR_ERR(key));
+		return PTR_ERR(key);
+	}
+
+	rx->securities = key;
+	kfree(description);
+	_leave(" = 0 [key %x]", key->serial);
+	return 0;
+}
+
+/**
+ * rxrpc_sock_set_security_keyring - Set the security keyring for a kernel service
+ * @sk: The socket to set the keyring on
+ * @keyring: The keyring to set
+ *
+ * Set the server security keyring on an rxrpc socket.  This is used to provide
+ * the encryption keys for a kernel service.
+ *
+ * Return: %0 if successful and a negative error code otherwise.
+ */
+int rxrpc_sock_set_security_keyring(struct sock *sk, struct key *keyring)
+{
+	struct rxrpc_sock *rx = rxrpc_sk(sk);
+	int ret = 0;
+
+	lock_sock(sk);
+	if (rx->securities)
+		ret = -EINVAL;
+	else if (rx->sk.sk_state != RXRPC_UNBOUND)
+		ret = -EISCONN;
+	else
+		rx->securities = key_get(keyring);
+	release_sock(sk);
+	return ret;
+}
+EXPORT_SYMBOL(rxrpc_sock_set_security_keyring);
+
+/**
+ * rxrpc_sock_set_manage_response - Set the manage-response flag for a kernel service
+ * @sk: The socket to set the keyring on
+ * @set: True to set, false to clear the flag
+ *
+ * Set the flag on an rxrpc socket to say that the caller wants to manage the
+ * RESPONSE packet and the user-defined data it may contain.  Setting this
+ * means that recvmsg() will return messages with RXRPC_CHALLENGED in the
+ * control message buffer containing information about the challenge.
+ *
+ * The user should respond to the challenge by passing RXRPC_RESPOND or
+ * RXRPC_RESPOND_ABORT control messages with sendmsg() to the same call.
+ * Supplementary control messages, such as RXRPC_RESP_RXGK_APPDATA, may be
+ * included to indicate the parts the user wants to supply.
+ *
+ * The server will be passed the response data with a RXRPC_RESPONDED control
+ * message when it gets the first data from each call.
+ *
+ * Note that this is only honoured by security classes that need auxiliary data
+ * (e.g. RxGK).  Those that don't offer the facility (e.g. RxKAD) respond
+ * without consulting userspace.
+ *
+ * Return: The previous setting.
+ */
+int rxrpc_sock_set_manage_response(struct sock *sk, bool set)
+{
+	struct rxrpc_sock *rx = rxrpc_sk(sk);
+	int ret;
+
+	lock_sock(sk);
+	ret = !!test_bit(RXRPC_SOCK_MANAGE_RESPONSE, &rx->flags);
+	if (set)
+		set_bit(RXRPC_SOCK_MANAGE_RESPONSE, &rx->flags);
+	else
+		clear_bit(RXRPC_SOCK_MANAGE_RESPONSE, &rx->flags);
+	release_sock(sk);
+	return ret;
+}
+EXPORT_SYMBOL(rxrpc_sock_set_manage_response);
diff --git a/net/rxrpc/server_key.c b/net/rxrpc/server_key.c
index 3efe104b1930cb..0be259dd0df029 100644
--- a/net/rxrpc/server_key.c
+++ b/net/rxrpc/server_key.c
@@ -9,6 +9,11 @@
  */
 
 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+#define RXRPC_KEY_PROVIDER
+
+#include <crypto/des.h>
+#include <crypto/krb5.h>
+#include <linux/fips.h>
 
 #include <linux/module.h>
 #include <linux/net.h>
@@ -42,6 +47,7 @@ struct key_type key_type_rxrpc_s = {
 	.destroy	= rxrpc_destroy_s,
 	.describe	= rxrpc_describe_s,
 };
+EXPORT_SYMBOL(key_type_rxrpc_s);
 
 /*
  * Vet the description for an RxRPC server key.
@@ -60,156 +66,198 @@ static int rxrpc_vet_description_s(const char *desc)
 	return 0;
 }
 
+#ifdef CONFIG_RXKAD
 /*
- * Preparse a server secret key.
+ * Parse the information from a server key
+ *
+ * The data should be the 8-byte secret key.
  */
-static int rxrpc_preparse_s(struct key_preparsed_payload *prep)
+static int rxkad_preparse_server_key(struct key_preparsed_payload *prep)
 {
-	const struct rxrpc_security *sec;
-	unsigned int service, sec_class;
-	int n;
+	struct des_ctx *des_key;
+	int err;
+
+	if (fips_enabled)
+		return -ENOPKG;
+
+	if (prep->datalen != 8)
+		return -EINVAL;
+
+	memcpy(&prep->payload.data[2], prep->data, 8);
+
+	des_key = kmalloc_obj(*des_key);
+	if (!des_key) {
+		_leave(" = -ENOMEM");
+		return -ENOMEM;
+	}
+
+	err = des_expand_key(des_key, prep->data, 8);
+	if (err) {
+		kfree_sensitive(des_key);
+		_leave(" = %d", err);
+		return err;
+	}
+
+	prep->payload.data[0] = des_key;
+	_leave(" = 0");
+	return 0;
+}
+
+static void rxkad_free_preparse_server_key(struct key_preparsed_payload *prep)
+{
+	kfree_sensitive(prep->payload.data[0]);
+}
+
+static void rxkad_destroy_server_key(struct key *key)
+{
+	kfree_sensitive(key->payload.data[0]);
+	key->payload.data[0] = NULL;
+}
+#endif
+
+#ifdef CONFIG_RXGK
+/*
+ * Parse the information from a server key
+ */
+static int rxgk_preparse_server_key(struct key_preparsed_payload *prep)
+{
+	const struct krb5_enctype *krb5;
+	struct krb5_buffer *server_key = (void *)&prep->payload.data[2];
+	unsigned int service, sec_class, kvno, enctype;
+	int n = 0;
 
 	_enter("%zu", prep->datalen);
 
-	if (!prep->orig_description)
+	if (sscanf(prep->orig_description, "%u:%u:%u:%u%n",
+		   &service, &sec_class, &kvno, &enctype, &n) != 4)
 		return -EINVAL;
 
-	if (sscanf(prep->orig_description, "%u:%u%n", &service, &sec_class, &n) != 2)
+	if (prep->orig_description[n])
 		return -EINVAL;
 
-	sec = rxrpc_security_lookup(sec_class);
-	if (!sec)
+	krb5 = crypto_krb5_find_enctype(enctype);
+	if (!krb5)
 		return -ENOPKG;
 
-	prep->payload.data[1] = (struct rxrpc_security *)sec;
+	prep->payload.data[0] = (struct krb5_enctype *)krb5;
 
-	if (!sec->preparse_server_key)
-		return -EINVAL;
+	if (prep->datalen != krb5->key_len)
+		return -EKEYREJECTED;
+
+	server_key->len = prep->datalen;
+	server_key->data = kmemdup(prep->data, prep->datalen, GFP_KERNEL);
+	if (!server_key->data)
+		return -ENOMEM;
 
-	return sec->preparse_server_key(prep);
+	_leave(" = 0");
+	return 0;
 }
 
-static void rxrpc_free_preparse_s(struct key_preparsed_payload *prep)
+static void rxgk_free_server_key(union key_payload *payload)
 {
-	const struct rxrpc_security *sec = prep->payload.data[1];
+	struct krb5_buffer *server_key = (void *)&payload->data[2];
 
-	if (sec && sec->free_preparse_server_key)
-		sec->free_preparse_server_key(prep);
+	kfree_sensitive(server_key->data);
 }
 
-static void rxrpc_destroy_s(struct key *key)
+static void rxgk_free_preparse_server_key(struct key_preparsed_payload *prep)
 {
-	const struct rxrpc_security *sec = key->payload.data[1];
+	rxgk_free_server_key(&prep->payload);
+}
 
-	if (sec && sec->destroy_server_key)
-		sec->destroy_server_key(key);
+static void rxgk_destroy_server_key(struct key *key)
+{
+	rxgk_free_server_key(&key->payload);
 }
 
-static void rxrpc_describe_s(const struct key *key, struct seq_file *m)
+static void rxgk_describe_server_key(const struct key *key, struct seq_file *m)
 {
-	const struct rxrpc_security *sec = key->payload.data[1];
+	const struct krb5_enctype *krb5 = key->payload.data[0];
 
-	seq_puts(m, key->description);
-	if (sec && sec->describe_server_key)
-		sec->describe_server_key(key, m);
+	if (krb5)
+		seq_printf(m, ": %s", krb5->name);
 }
+#endif
 
 /*
- * grab the security keyring for a server socket
+ * Preparse a server secret key.
  */
-int rxrpc_server_keyring(struct rxrpc_sock *rx, sockptr_t optval, int optlen)
+static int rxrpc_preparse_s(struct key_preparsed_payload *prep)
 {
-	struct key *key;
-	char *description;
+	unsigned int service, sec_class;
+	int n;
 
-	_enter("");
+	_enter("%zu", prep->datalen);
 
-	if (rx->securities)
+	if (!prep->orig_description)
 		return -EINVAL;
 
-	if (optlen <= 0 || optlen > PAGE_SIZE - 1)
+	if (sscanf(prep->orig_description, "%u:%u%n", &service, &sec_class, &n) != 2)
 		return -EINVAL;
 
-	description = memdup_sockptr_nul(optval, optlen);
-	if (IS_ERR(description))
-		return PTR_ERR(description);
+	prep->payload.data[1] = (void *)(uintptr_t)sec_class;
 
-	key = request_key(&key_type_keyring, description, NULL);
-	if (IS_ERR(key)) {
-		kfree(description);
-		_leave(" = %ld", PTR_ERR(key));
-		return PTR_ERR(key);
+	switch (sec_class) {
+#ifdef CONFIG_RXKAD
+	case RXRPC_SECURITY_RXKAD:
+		return rxkad_preparse_server_key(prep);
+#endif
+#ifdef CONFIG_RXGK
+	case RXRPC_SECURITY_YFS_RXGK:
+		return rxgk_preparse_server_key(prep);
+#endif
+	default:
+		return -ENOPKG;
 	}
+}
 
-	rx->securities = key;
-	kfree(description);
-	_leave(" = 0 [key %x]", key->serial);
-	return 0;
+static void rxrpc_free_preparse_s(struct key_preparsed_payload *prep)
+{
+	switch ((uintptr_t)prep->payload.data[1]) {
+#ifdef CONFIG_RXKAD
+	case RXRPC_SECURITY_RXKAD:
+		rxkad_free_preparse_server_key(prep);
+		break;
+#endif
+#ifdef CONFIG_RXGK
+	case RXRPC_SECURITY_YFS_RXGK:
+		rxgk_free_preparse_server_key(prep);
+		break;
+#endif
+	default:
+		break;
+	}
 }
 
-/**
- * rxrpc_sock_set_security_keyring - Set the security keyring for a kernel service
- * @sk: The socket to set the keyring on
- * @keyring: The keyring to set
- *
- * Set the server security keyring on an rxrpc socket.  This is used to provide
- * the encryption keys for a kernel service.
- *
- * Return: %0 if successful and a negative error code otherwise.
- */
-int rxrpc_sock_set_security_keyring(struct sock *sk, struct key *keyring)
+static void rxrpc_destroy_s(struct key *key)
 {
-	struct rxrpc_sock *rx = rxrpc_sk(sk);
-	int ret = 0;
-
-	lock_sock(sk);
-	if (rx->securities)
-		ret = -EINVAL;
-	else if (rx->sk.sk_state != RXRPC_UNBOUND)
-		ret = -EISCONN;
-	else
-		rx->securities = key_get(keyring);
-	release_sock(sk);
-	return ret;
+	switch ((uintptr_t)key->payload.data[1]) {
+#ifdef CONFIG_RXKAD
+	case RXRPC_SECURITY_RXKAD:
+		rxkad_destroy_server_key(key);
+		break;
+#endif
+#ifdef CONFIG_RXGK
+	case RXRPC_SECURITY_YFS_RXGK:
+		rxgk_destroy_server_key(key);
+		break;
+#endif
+	default:
+		break;
+	}
 }
-EXPORT_SYMBOL(rxrpc_sock_set_security_keyring);
 
-/**
- * rxrpc_sock_set_manage_response - Set the manage-response flag for a kernel service
- * @sk: The socket to set the keyring on
- * @set: True to set, false to clear the flag
- *
- * Set the flag on an rxrpc socket to say that the caller wants to manage the
- * RESPONSE packet and the user-defined data it may contain.  Setting this
- * means that recvmsg() will return messages with RXRPC_CHALLENGED in the
- * control message buffer containing information about the challenge.
- *
- * The user should respond to the challenge by passing RXRPC_RESPOND or
- * RXRPC_RESPOND_ABORT control messages with sendmsg() to the same call.
- * Supplementary control messages, such as RXRPC_RESP_RXGK_APPDATA, may be
- * included to indicate the parts the user wants to supply.
- *
- * The server will be passed the response data with a RXRPC_RESPONDED control
- * message when it gets the first data from each call.
- *
- * Note that this is only honoured by security classes that need auxiliary data
- * (e.g. RxGK).  Those that don't offer the facility (e.g. RxKAD) respond
- * without consulting userspace.
- *
- * Return: The previous setting.
- */
-int rxrpc_sock_set_manage_response(struct sock *sk, bool set)
+static void rxrpc_describe_s(const struct key *key, struct seq_file *m)
 {
-	struct rxrpc_sock *rx = rxrpc_sk(sk);
-	int ret;
-
-	lock_sock(sk);
-	ret = !!test_bit(RXRPC_SOCK_MANAGE_RESPONSE, &rx->flags);
-	if (set)
-		set_bit(RXRPC_SOCK_MANAGE_RESPONSE, &rx->flags);
-	else
-		clear_bit(RXRPC_SOCK_MANAGE_RESPONSE, &rx->flags);
-	release_sock(sk);
-	return ret;
+	seq_puts(m, key->description);
+
+	switch ((uintptr_t)key->payload.data[1]) {
+#ifdef CONFIG_RXGK
+	case RXRPC_SECURITY_YFS_RXGK:
+		rxgk_describe_server_key(key, m);
+		break;
+#endif
+	default:
+		break;
+	}
 }
-EXPORT_SYMBOL(rxrpc_sock_set_manage_response);
diff --git a/security/keys/gc.c b/security/keys/gc.c
index eda445f815d47b..704dcc40198360 100644
--- a/security/keys/gc.c
+++ b/security/keys/gc.c
@@ -6,20 +6,35 @@
  */
 
 #include <linux/slab.h>
+#include <linux/module.h>
 #include <linux/security.h>
 #include <keys/keyring-type.h>
 #include "internal.h"
 
-/*
- * Delay between key revocation/expiry in seconds
- */
-unsigned key_gc_delay = 5 * 60;
+#define KEY_GC_CHUNK_SIZE 64
 
 /*
  * Reaper for unused keys.
  */
 static void key_garbage_collector(struct work_struct *work);
-DECLARE_WORK(key_gc_work, key_garbage_collector);
+
+struct workqueue_struct *key_gc_wq __ro_after_init;
+
+static struct {
+	time64_t start;			/* expiry range start */
+	time64_t end;			/* expiry range end */
+	struct rb_node *cursor;		/* serial tree position */
+	u8 state;			/* state flags */
+	atomic_t seq;
+	struct work_struct work;	/* work item */
+} key_gc_work = {
+	.work = __WORK_INITIALIZER(key_gc_work.work, key_garbage_collector),
+};
+
+/*
+ * Delay between key revocation/expiry in seconds
+ */
+unsigned int key_gc_delay = 5 * 60;
 
 /*
  * Reaper for links from keyrings to dead keys.
@@ -28,21 +43,43 @@ static void key_gc_timer_func(struct timer_list *);
 static DEFINE_TIMER(key_gc_timer, key_gc_timer_func);
 
 static time64_t key_gc_next_run = TIME64_MAX;
-static struct key_type *key_gc_dead_keytype;
-
 static unsigned long key_gc_flags;
 #define KEY_GC_KEY_EXPIRED	0	/* A key expired and needs unlinking */
-#define KEY_GC_REAP_KEYTYPE	1	/* A keytype is being unregistered */
-#define KEY_GC_REAPING_KEYTYPE	2	/* Cleared when keytype reaped */
-
+#define KEY_GC_REAP_REQUESTED	1	/* Another complete pass was requested */
 
 /*
- * Any key whose type gets unregistered will be re-typed to this if it can't be
- * immediately unlinked.
+ * Schedule a new GC pass or re-schedule an ongoing GC pass.
  */
-struct key_type key_type_dead = {
-	.name = ".dead",
-};
+void key_schedule_gc_work(bool expired)
+{
+	unsigned long flags = BIT(KEY_GC_REAP_REQUESTED);
+
+	if (expired)
+		flags |= BIT(KEY_GC_KEY_EXPIRED);
+
+	/* Publish all request flags together, after the caller's updates. */
+	set_mask_bits(&key_gc_flags, 0, flags);
+	queue_work(key_gc_wq, &key_gc_work.work);
+}
+
+/**
+ * key_gc_flush - Drain the garbage collector RCU callbacks
+ */
+void key_gc_flush(void)
+{
+	int seq;
+
+	do {
+		while (flush_work(&key_gc_work.work) ||
+		       work_pending(&key_gc_work.work))
+			cpu_relax();
+		seq = atomic_read_acquire(&key_gc_work.seq);
+		rcu_barrier();
+	} while (flush_work(&key_gc_work.work) ||
+		 work_pending(&key_gc_work.work) ||
+		 atomic_read_acquire(&key_gc_work.seq) != seq);
+}
+EXPORT_SYMBOL_GPL(key_gc_flush);
 
 /*
  * Schedule a garbage collection run.
@@ -55,9 +92,10 @@ void key_schedule_gc(time64_t gc_at)
 
 	kenter("%lld", gc_at - now);
 
-	if (gc_at <= now || test_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags)) {
+	if (gc_at <= now) {
 		kdebug("IMMEDIATE");
-		schedule_work(&key_gc_work);
+		/* Catch expirations that became due during the scan. */
+		key_schedule_gc_work(true);
 	} else if (gc_at < key_gc_next_run) {
 		kdebug("DEFERRED");
 		key_gc_next_run = gc_at;
@@ -79,15 +117,6 @@ void key_set_expiry(struct key *key, time64_t expiry)
 	}
 }
 
-/*
- * Schedule a dead links collection run.
- */
-void key_schedule_gc_links(void)
-{
-	set_bit(KEY_GC_KEY_EXPIRED, &key_gc_flags);
-	schedule_work(&key_gc_work);
-}
-
 /*
  * Some key's cleanup time was met after it expired, so we need to get the
  * reaper to go through a cycle finding expired keys.
@@ -96,37 +125,7 @@ static void key_gc_timer_func(struct timer_list *unused)
 {
 	kenter("");
 	key_gc_next_run = TIME64_MAX;
-	key_schedule_gc_links();
-}
-
-/*
- * Reap keys of dead type.
- *
- * We use three flags to make sure we see three complete cycles of the garbage
- * collector: the first to mark keys of that type as being dead, the second to
- * collect dead links and the third to clean up the dead keys.  We have to be
- * careful as there may already be a cycle in progress.
- *
- * The caller must be holding key_types_sem.
- */
-void key_gc_keytype(struct key_type *ktype)
-{
-	kenter("%s", ktype->name);
-
-	key_gc_dead_keytype = ktype;
-	set_bit(KEY_GC_REAPING_KEYTYPE, &key_gc_flags);
-	smp_mb();
-	set_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags);
-
-	kdebug("schedule");
-	schedule_work(&key_gc_work);
-
-	kdebug("sleep");
-	wait_on_bit(&key_gc_flags, KEY_GC_REAPING_KEYTYPE,
-		    TASK_UNINTERRUPTIBLE);
-
-	key_gc_dead_keytype = NULL;
-	kleave("");
+	key_schedule_gc_work(true);
 }
 
 /*
@@ -134,9 +133,12 @@ void key_gc_keytype(struct key_type *ktype)
  */
 static noinline void key_gc_unused_keys(struct list_head *keys)
 {
-	while (!list_empty(keys)) {
+	unsigned int chunk = KEY_GC_CHUNK_SIZE;
+
+	while (!list_empty(keys) && chunk--) {
 		struct key *key =
 			list_entry(keys->next, struct key, graveyard_link);
+		struct module *owner = key->type->owner;
 		short state = key->state;
 
 		list_del(&key->graveyard_link);
@@ -150,8 +152,15 @@ 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) {
+			if (key->type->destroy)
+				key->type->destroy(key);
+		} else if (key->restrict_link) {
+			if (key->restrict_link->keytype)
+				module_put(key->restrict_link->keytype->owner);
+			key_put(key->restrict_link->key);
+			kfree(key->restrict_link);
+		}
 
 		security_key_free(key);
 
@@ -165,6 +174,7 @@ static noinline void key_gc_unused_keys(struct list_head *keys)
 
 		memzero_explicit(key, sizeof(*key));
 		kmem_cache_free(key_jar, key);
+		module_put(owner);
 	}
 }
 
@@ -178,89 +188,67 @@ static noinline void key_gc_unused_keys(struct list_head *keys)
 static void key_garbage_collector(struct work_struct *work)
 {
 	static LIST_HEAD(graveyard);
-	static u8 gc_state;		/* Internal persistent state */
+	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_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 */
-#define KEY_GC_FOUND_DEAD_KEY	0x80	/* - We found at least one dead key */
+#define KEY_GC_DESTROYING	0x04	/* - We need to destroy keys */
 
-	struct rb_node *cursor;
+	unsigned int chunk = KEY_GC_CHUNK_SIZE;
+	unsigned long flags;
 	struct key *key;
-	time64_t new_timer, limit, expiry;
-
-	kenter("[%lx,%x]", key_gc_flags, gc_state);
+	time64_t expiry;
 
-	limit = ktime_get_real_seconds();
+	kenter("[%lx,%x]", key_gc_flags, gc->state);
 
-	/* Work out what we're going to be doing in this pass */
-	gc_state &= KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2;
-	gc_state <<= 1;
-	if (test_and_clear_bit(KEY_GC_KEY_EXPIRED, &key_gc_flags))
-		gc_state |= KEY_GC_REAPING_LINKS;
+	if (gc->state & KEY_GC_DESTROYING)
+		goto destroy_keys;
+	if (gc->cursor) {
+		spin_lock(&key_serial_lock);
+		goto continue_scanning;
+	}
 
-	if (test_and_clear_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags))
-		gc_state |= KEY_GC_REAPING_DEAD_1;
-	kdebug("new pass %x", gc_state);
+	flags = xchg(&key_gc_flags, 0);
+	gc->start = ktime_get_real_seconds();
+	gc->state = 0;
+	if (flags & BIT(KEY_GC_KEY_EXPIRED))
+		gc->state |= KEY_GC_REAPING_LINKS;
+	kdebug("new pass %x", gc->state);
 
-	new_timer = TIME64_MAX;
+	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.
 	 */
 	spin_lock(&key_serial_lock);
-	cursor = rb_first(&key_serial_tree);
+	gc->cursor = rb_first(&key_serial_tree);
 
 continue_scanning:
-	while (cursor) {
-		key = rb_entry(cursor, struct key, serial_node);
-		cursor = rb_next(cursor);
+	while (gc->cursor && chunk) {
+		key = rb_entry(gc->cursor, struct key, serial_node);
+		gc->cursor = rb_next(gc->cursor);
+		chunk--;
 
 		if (!test_bit_acquire(KEY_FLAG_USER_ALIVE, &key->flags)) {
 			/* Clobber key->user after final put seen. */
 			goto found_unreferenced_key;
 		}
 
-		if (unlikely(gc_state & KEY_GC_REAPING_DEAD_1)) {
-			if (key->type == key_gc_dead_keytype) {
-				gc_state |= KEY_GC_FOUND_DEAD_KEY;
-				set_bit(KEY_FLAG_DEAD, &key->flags);
-				key->perm = 0;
-				goto skip_dead_key;
-			} else if (key->type == &key_type_keyring &&
-				   key->restrict_link) {
-				goto found_restricted_keyring;
-			}
-		}
-
 		expiry = key->expiry;
 		if (expiry != TIME64_MAX) {
 			if (!(key->type->flags & KEY_TYPE_INSTANT_REAP))
 				expiry += key_gc_delay;
-			if (expiry > limit && expiry < new_timer) {
+			if (expiry > gc->start && expiry < gc->end) {
 				kdebug("will expire %x in %lld",
-				       key_serial(key), key->expiry - limit);
-				new_timer = key->expiry;
+				       key_serial(key), expiry - gc->start);
+				gc->end = expiry;
 			}
 		}
 
-		if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2))
-			if (key->type == key_gc_dead_keytype)
-				gc_state |= KEY_GC_FOUND_DEAD_KEY;
+		if ((gc->state & KEY_GC_REAPING_LINKS) &&
+		    key->type == &key_type_keyring)
+			goto found_keyring;
 
-		if ((gc_state & KEY_GC_REAPING_LINKS) ||
-		    unlikely(gc_state & KEY_GC_REAPING_DEAD_2)) {
-			if (key->type == &key_type_keyring)
-				goto found_keyring;
-		}
-
-		if (unlikely(gc_state & KEY_GC_REAPING_DEAD_3))
-			if (key->type == key_gc_dead_keytype)
-				goto destroy_dead_key;
-
-	skip_dead_key:
 		if (spin_is_contended(&key_serial_lock) || need_resched())
 			goto contended;
 	}
@@ -269,7 +257,11 @@ static void key_garbage_collector(struct work_struct *work)
 	spin_unlock(&key_serial_lock);
 
 maybe_resched:
-	if (cursor) {
+	if (gc->cursor) {
+		if (!chunk) {
+			queue_work(key_gc_wq, &key_gc_work.work);
+			goto out;
+		}
 		cond_resched();
 		spin_lock(&key_serial_lock);
 		goto continue_scanning;
@@ -281,13 +273,10 @@ static void key_garbage_collector(struct work_struct *work)
 	 */
 	kdebug("pass complete");
 
-	if (new_timer != TIME64_MAX) {
-		new_timer += key_gc_delay;
-		key_schedule_gc(new_timer);
-	}
+	if (gc->end != TIME64_MAX)
+		key_schedule_gc(gc->end);
 
-	if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2) ||
-	    !list_empty(&graveyard)) {
+	if (!list_empty(&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
@@ -297,33 +286,25 @@ static void key_garbage_collector(struct work_struct *work)
 		synchronize_rcu();
 	}
 
+	gc->state |= KEY_GC_DESTROYING;
+
+destroy_keys:
 	if (!list_empty(&graveyard)) {
 		kdebug("gc keys");
 		key_gc_unused_keys(&graveyard);
-	}
-
-	if (unlikely(gc_state & (KEY_GC_REAPING_DEAD_1 |
-				 KEY_GC_REAPING_DEAD_2))) {
-		if (!(gc_state & KEY_GC_FOUND_DEAD_KEY)) {
-			/* No remaining dead keys: short circuit the remaining
-			 * keytype reap cycles.
-			 */
-			kdebug("dead short");
-			gc_state &= ~(KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2);
-			gc_state |= KEY_GC_REAPING_DEAD_3;
-		} else {
-			gc_state |= KEY_GC_REAP_AGAIN;
+		if (!list_empty(&graveyard)) {
+			queue_work(key_gc_wq, &key_gc_work.work);
+			goto out;
 		}
 	}
-
-	if (unlikely(gc_state & KEY_GC_REAPING_DEAD_3)) {
-		kdebug("dead wake");
-		clear_and_wake_up_bit(KEY_GC_REAPING_KEYTYPE, &key_gc_flags);
-	}
-
-	if (gc_state & KEY_GC_REAP_AGAIN)
-		schedule_work(&key_gc_work);
-	kleave(" [end %x]", gc_state);
+	gc->state &= ~KEY_GC_DESTROYING;
+
+	if ((gc->state & KEY_GC_REAP_AGAIN) ||
+	    test_bit(KEY_GC_REAP_REQUESTED, &key_gc_flags))
+		queue_work(key_gc_wq, &key_gc_work.work);
+out:
+	atomic_inc_return(&gc->seq);
+	kleave(" [end %x]", gc->state);
 	return;
 
 	/* We found an unreferenced key - once we've removed it from the tree,
@@ -335,15 +316,7 @@ static void key_garbage_collector(struct work_struct *work)
 	spin_unlock(&key_serial_lock);
 
 	list_add_tail(&key->graveyard_link, &graveyard);
-	gc_state |= KEY_GC_REAP_AGAIN;
-	goto maybe_resched;
-
-	/* We found a restricted keyring and need to update the restriction if
-	 * it is associated with the dead key type.
-	 */
-found_restricted_keyring:
-	spin_unlock(&key_serial_lock);
-	keyring_restriction_gc(key, key_gc_dead_keytype);
+	gc->state |= KEY_GC_REAP_AGAIN;
 	goto maybe_resched;
 
 	/* We found a keyring and we need to check the payload for links to
@@ -353,20 +326,6 @@ static void key_garbage_collector(struct work_struct *work)
 	 */
 found_keyring:
 	spin_unlock(&key_serial_lock);
-	keyring_gc(key, limit);
-	goto maybe_resched;
-
-	/* We found a dead key that is still referenced.  Reset its type and
-	 * destroy its payload with its semaphore held.
-	 */
-destroy_dead_key:
-	spin_unlock(&key_serial_lock);
-	kdebug("destroy key %d", key->serial);
-	down_write(&key->sem);
-	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);
+	keyring_gc(key, gc->start);
 	goto maybe_resched;
 }
diff --git a/security/keys/internal.h b/security/keys/internal.h
index b7b622bc36a137..6b5bb63b0e9e12 100644
--- a/security/keys/internal.h
+++ b/security/keys/internal.h
@@ -38,7 +38,6 @@ struct iovec;
 	no_printk(KERN_DEBUG FMT"\n", ##__VA_ARGS__)
 #endif
 
-extern struct key_type key_type_dead;
 extern struct key_type key_type_user;
 extern struct key_type key_type_logon;
 
@@ -162,15 +161,12 @@ extern bool lookup_user_key_possessed(const struct key *key,
 extern long join_session_keyring(const char *name);
 extern void key_change_session_keyring(struct callback_head *twork);
 
-extern struct work_struct key_gc_work;
 extern unsigned key_gc_delay;
+extern struct workqueue_struct *key_gc_wq;
 extern void keyring_gc(struct key *keyring, time64_t limit);
-extern void keyring_restriction_gc(struct key *keyring,
-				   struct key_type *dead_type);
 void key_set_expiry(struct key *key, time64_t expiry);
 extern void key_schedule_gc(time64_t gc_at);
-extern void key_schedule_gc_links(void);
-extern void key_gc_keytype(struct key_type *ktype);
+void key_schedule_gc_work(bool expired);
 
 extern int key_task_permission(const key_ref_t key_ref,
 			       const struct cred *cred,
diff --git a/security/keys/key.c b/security/keys/key.c
index 3f1f0fc137109a..53106bee2d27cb 100644
--- a/security/keys/key.c
+++ b/security/keys/key.c
@@ -7,6 +7,7 @@
 
 #include <linux/export.h>
 #include <linux/init.h>
+#include <linux/module.h>
 #include <linux/poison.h>
 #include <linux/sched.h>
 #include <linux/slab.h>
@@ -234,19 +235,34 @@ struct key *key_alloc(struct key_type *type, const char *desc,
 
 	key = ERR_PTR(-EINVAL);
 	if (!desc || !*desc)
-		goto error;
+		goto out;
+
+	/* Failed module initialization ignores outstanding module references. */
+	if ((type->owner && module_is_coming(type->owner)) ||
+	    !try_module_get(type->owner)) {
+		key = ERR_PTR(-ENOENT);
+		goto out;
+	}
+
+	if (restrict_link && restrict_link->keytype &&
+	    ((restrict_link->keytype->owner &&
+	      module_is_coming(restrict_link->keytype->owner)) ||
+	     !try_module_get(restrict_link->keytype->owner))) {
+		key = ERR_PTR(-ENOENT);
+		goto out_put_module;
+	}
 
 	if (type->vet_description) {
 		ret = type->vet_description(desc);
 		if (ret < 0) {
 			key = ERR_PTR(ret);
-			goto error;
+			goto out_put_restrict_module;
 		}
 	}
 
 	desclen = strlen(desc);
 	if (desclen >= KEY_MAX_DESC_SIZE)
-		goto error;
+		goto out_put_restrict_module;
 	quotalen = desclen + 1 + type->def_datalen;
 
 	/* get hold of the key tracking for this user */
@@ -323,8 +339,6 @@ struct key *key_alloc(struct key_type *type, const char *desc,
 	refcount_inc(&key->domain_tag->usage);
 	atomic_inc(&user->nkeys);
 	key_alloc_serial(key);
-
-error:
 	return key;
 
 security_error:
@@ -338,7 +352,7 @@ struct key *key_alloc(struct key_type *type, const char *desc,
 	}
 	key_user_put(user);
 	key = ERR_PTR(ret);
-	goto error;
+	goto out_put_restrict_module;
 
 no_memory_3:
 	kmem_cache_free(key_jar, key);
@@ -352,13 +366,22 @@ struct key *key_alloc(struct key_type *type, const char *desc,
 	key_user_put(user);
 no_memory_1:
 	key = ERR_PTR(-ENOMEM);
-	goto error;
+	goto out_put_restrict_module;
 
 no_quota:
 	spin_unlock_irqrestore(&user->lock, irqflags);
 	key_user_put(user);
 	key = ERR_PTR(-EDQUOT);
-	goto error;
+
+out_put_restrict_module:
+	if (restrict_link && restrict_link->keytype)
+		module_put(restrict_link->keytype->owner);
+
+out_put_module:
+	module_put(type->owner);
+
+out:
+	return key;
 }
 EXPORT_SYMBOL(key_alloc);
 
@@ -670,7 +693,7 @@ void key_put(struct key *key)
 			}
 			/* Mark key as safe for GC after key->user done. */
 			clear_bit_unlock(KEY_FLAG_USER_ALIVE, &key->flags);
-			schedule_work(&key_gc_work);
+			key_schedule_gc_work(false);
 		}
 	}
 }
@@ -1191,7 +1214,7 @@ void key_invalidate(struct key *key)
 		down_write_nested(&key->sem, 1);
 		if (!test_and_set_bit(KEY_FLAG_INVALIDATED, &key->flags)) {
 			notify_key(key, NOTIFY_KEY_INVALIDATED, 0);
-			key_schedule_gc_links();
+			key_schedule_gc_work(true);
 		}
 		up_write(&key->sem);
 	}
@@ -1231,19 +1254,20 @@ int generic_key_instantiate(struct key *key, struct key_preparsed_payload *prep)
 EXPORT_SYMBOL(generic_key_instantiate);
 
 /**
- * register_key_type - Register a type of key.
+ * __register_key_type - Register a type of key.
  * @ktype: The new key type.
+ * @owner: Module owning the key type.
  *
  * Register a new key type.
  *
  * Returns 0 on success or -EEXIST if a type of this name already exists.
  */
-int register_key_type(struct key_type *ktype)
+int __register_key_type(struct key_type *ktype, struct module *owner)
 {
 	struct key_type *p;
 	int ret;
 
-	memset(&ktype->lock_class, 0, sizeof(ktype->lock_class));
+	ktype->owner = owner;
 
 	ret = -EEXIST;
 	down_write(&key_types_sem);
@@ -1264,24 +1288,20 @@ int register_key_type(struct key_type *ktype)
 	up_write(&key_types_sem);
 	return ret;
 }
-EXPORT_SYMBOL(register_key_type);
+EXPORT_SYMBOL(__register_key_type);
 
 /**
  * unregister_key_type - Unregister a type of key.
  * @ktype: The key type.
  *
- * Unregister a key type and mark all the extant keys of this type as dead.
- * Those keys of this type are then destroyed to get rid of their payloads and
- * they and their links will be garbage collected as soon as possible.
+ * Unregister a key type.
  */
 void unregister_key_type(struct key_type *ktype)
 {
 	down_write(&key_types_sem);
 	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);
 }
 EXPORT_SYMBOL(unregister_key_type);
 
@@ -1294,9 +1314,12 @@ void __init key_init(void)
 	key_jar = kmem_cache_create("key_jar", sizeof(struct key),
 			0, SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_NO_MERGE, NULL);
 
+	key_gc_wq = alloc_workqueue("key_gc", WQ_MEM_RECLAIM | WQ_PERCPU, 0);
+	if (!key_gc_wq)
+		panic("Cannot create key_gc workqueue\n");
+
 	/* add the special key types */
 	list_add_tail(&key_type_keyring.link, &key_types_list);
-	list_add_tail(&key_type_dead.link, &key_types_list);
 	list_add_tail(&key_type_user.link, &key_types_list);
 	list_add_tail(&key_type_logon.link, &key_types_list);
 
diff --git a/security/keys/keyring.c b/security/keys/keyring.c
index 357f5636081055..7776983c3fdac7 100644
--- a/security/keys/keyring.c
+++ b/security/keys/keyring.c
@@ -7,6 +7,7 @@
 
 #include <linux/export.h>
 #include <linux/init.h>
+#include <linux/module.h>
 #include <linux/sched.h>
 #include <linux/slab.h>
 #include <linux/security.h>
@@ -265,7 +266,7 @@ void key_remove_domain(struct key_tag *domain_tag)
 {
 	domain_tag->removed = true;
 	if (!key_put_tag(domain_tag))
-		key_schedule_gc_links();
+		key_schedule_gc_work(true);
 }
 
 /*
@@ -436,6 +437,9 @@ static void keyring_destroy(struct key *keyring)
 	if (keyring->restrict_link) {
 		struct key_restriction *keyres = keyring->restrict_link;
 
+		if (keyres->keytype)
+			module_put(keyres->keytype->owner);
+
 		key_put(keyres->key);
 		kfree(keyres);
 	}
@@ -540,6 +544,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)
+				module_put(restrict_link->keytype->owner);
+			keyring->restrict_link = NULL;
 			key_put(keyring);
 			keyring = ERR_PTR(ret);
 		}
@@ -1062,7 +1069,7 @@ int keyring_restrict(key_ref_t keyring_ref, const char *type,
 
 		if (!restrict_type->lookup_restriction) {
 			ret = -ENOENT;
-			goto error;
+			goto out;
 		}
 
 		restrict_link = restrict_type->lookup_restriction(restriction);
@@ -1070,7 +1077,15 @@ int keyring_restrict(key_ref_t keyring_ref, const char *type,
 
 	if (IS_ERR(restrict_link)) {
 		ret = PTR_ERR(restrict_link);
-		goto error;
+		goto out;
+	}
+
+	if (restrict_link && restrict_link->keytype &&
+	    ((restrict_link->keytype->owner &&
+	      module_is_coming(restrict_link->keytype->owner)) ||
+	     !try_module_get(restrict_link->keytype->owner))) {
+		ret = -ENOENT;
+		goto out_free_restriction;
 	}
 
 	down_write(&keyring->sem);
@@ -1088,12 +1103,21 @@ int keyring_restrict(key_ref_t keyring_ref, const char *type,
 	up_write(&keyring_serialise_restrict_sem);
 	up_write(&keyring->sem);
 
-	if (ret < 0) {
+	if (ret < 0)
+		goto out_put_module;
+
+	goto out;
+
+out_put_module:
+	if (restrict_link && restrict_link->keytype)
+		module_put(restrict_link->keytype->owner);
+
+out_free_restriction:
+	if (restrict_link)
 		key_put(restrict_link->key);
-		kfree(restrict_link);
-	}
+	kfree(restrict_link);
 
-error:
+out:
 	if (restrict_type)
 		key_type_put(restrict_type);
 
@@ -1769,53 +1793,3 @@ void keyring_gc(struct key *keyring, time64_t limit)
 	up_write(&keyring->sem);
 	kleave(" [gc]");
 }
-
-/*
- * Garbage collect restriction pointers from a keyring.
- *
- * Keyring restrictions are associated with a key type, and must be cleaned
- * up if the key type is unregistered. The restriction is altered to always
- * reject additional keys so a keyring cannot be opened up by unregistering
- * a key type.
- *
- * Not called with any keyring locks held. The keyring's key struct will not
- * be deallocated under us as only our caller may deallocate it.
- *
- * The caller is required to hold key_types_sem and dead_type->sem. This is
- * fulfilled by key_gc_keytype() holding the locks on behalf of
- * key_garbage_collector(), which it invokes on a workqueue.
- */
-void keyring_restriction_gc(struct key *keyring, struct key_type *dead_type)
-{
-	struct key_restriction *keyres;
-
-	kenter("%x{%s}", keyring->serial, keyring->description ?: "");
-
-	/*
-	 * keyring->restrict_link is only assigned at key allocation time
-	 * or with the key type locked, so the only values that could be
-	 * concurrently assigned to keyring->restrict_link are for key
-	 * types other than dead_type. Given this, it's ok to check
-	 * the key type before acquiring keyring->sem.
-	 */
-	if (!dead_type || !keyring->restrict_link ||
-	    keyring->restrict_link->keytype != dead_type) {
-		kleave(" [no restriction gc]");
-		return;
-	}
-
-	/* Lock the keyring to ensure that a link is not in progress */
-	down_write(&keyring->sem);
-
-	keyres = keyring->restrict_link;
-
-	keyres->check = restrict_link_reject;
-
-	key_put(keyres->key);
-	keyres->key = NULL;
-	keyres->keytype = NULL;
-
-	up_write(&keyring->sem);
-
-	kleave(" [restriction gc]");
-}
diff --git a/security/keys/trusted-keys/trusted_core.c b/security/keys/trusted-keys/trusted_core.c
index 0509d9955f2a6f..11d7d296d063c2 100644
--- a/security/keys/trusted-keys/trusted_core.c
+++ b/security/keys/trusted-keys/trusted_core.c
@@ -373,14 +373,19 @@ static int __init init_trusted(void)
 		if (!get_random)
 			get_random = kernel_get_random;
 
+		static_call_update(trusted_key_seal, trusted_key_sources[i].ops->seal);
+		static_call_update(trusted_key_unseal, trusted_key_sources[i].ops->unseal);
+		static_call_update(trusted_key_get_random, get_random);
+		migratable = trusted_key_sources[i].ops->migratable;
+
 		ret = trusted_key_sources[i].ops->init();
 		if (!ret) {
-			static_call_update(trusted_key_seal, trusted_key_sources[i].ops->seal);
-			static_call_update(trusted_key_unseal, trusted_key_sources[i].ops->unseal);
-			static_call_update(trusted_key_get_random, get_random);
-
 			trusted_key_exit = trusted_key_sources[i].ops->exit;
-			migratable = trusted_key_sources[i].ops->migratable;
+		} else {
+			static_call_update(trusted_key_seal, NULL);
+			static_call_update(trusted_key_unseal, NULL);
+			static_call_update(trusted_key_get_random, NULL);
+			migratable = 0;
 		}
 
 		if (!ret || ret != -ENODEV)
diff --git a/security/keys/trusted-keys/trusted_tee.c b/security/keys/trusted-keys/trusted_tee.c
index 6e465c8bef5e5b..87ea549f7f0b97 100644
--- a/security/keys/trusted-keys/trusted_tee.c
+++ b/security/keys/trusted-keys/trusted_tee.c
@@ -9,6 +9,7 @@
 #include <linux/err.h>
 #include <linux/key-type.h>
 #include <linux/module.h>
+#include <linux/mutex.h>
 #include <linux/slab.h>
 #include <linux/string.h>
 #include <linux/tee_drv.h>
@@ -56,6 +57,8 @@ struct trusted_key_tee_private {
 };
 
 static struct trusted_key_tee_private pvt_data;
+/* Do not hold this mutex across key type registration or unregistration. */
+static DEFINE_MUTEX(trusted_key_tee_mutex);
 
 /*
  * Have the TEE seal(encrypt) the symmetric key
@@ -67,6 +70,12 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob)
 	struct tee_param param[4];
 	struct tee_shm *reg_shm = NULL;
 
+	mutex_lock(&trusted_key_tee_mutex);
+	if (!pvt_data.ctx) {
+		ret = -ENODEV;
+		goto out_unlock;
+	}
+
 	memset(&inv_arg, 0, sizeof(inv_arg));
 	memset(&param, 0, sizeof(param));
 
@@ -74,7 +83,8 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob)
 					      sizeof(p->key) + sizeof(p->blob));
 	if (IS_ERR(reg_shm)) {
 		dev_err(pvt_data.dev, "shm register failed\n");
-		return PTR_ERR(reg_shm);
+		ret = PTR_ERR(reg_shm);
+		goto out_unlock;
 	}
 
 	inv_arg.func = TA_CMD_SEAL;
@@ -100,7 +110,8 @@ static int trusted_tee_seal(struct trusted_key_payload *p, char *datablob)
 	}
 
 	tee_shm_free(reg_shm);
-
+out_unlock:
+	mutex_unlock(&trusted_key_tee_mutex);
 	return ret;
 }
 
@@ -114,6 +125,12 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob)
 	struct tee_param param[4];
 	struct tee_shm *reg_shm = NULL;
 
+	mutex_lock(&trusted_key_tee_mutex);
+	if (!pvt_data.ctx) {
+		ret = -ENODEV;
+		goto out_unlock;
+	}
+
 	memset(&inv_arg, 0, sizeof(inv_arg));
 	memset(&param, 0, sizeof(param));
 
@@ -121,7 +138,8 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob)
 					      sizeof(p->key) + sizeof(p->blob));
 	if (IS_ERR(reg_shm)) {
 		dev_err(pvt_data.dev, "shm register failed\n");
-		return PTR_ERR(reg_shm);
+		ret = PTR_ERR(reg_shm);
+		goto out_unlock;
 	}
 
 	inv_arg.func = TA_CMD_UNSEAL;
@@ -147,7 +165,8 @@ static int trusted_tee_unseal(struct trusted_key_payload *p, char *datablob)
 	}
 
 	tee_shm_free(reg_shm);
-
+out_unlock:
+	mutex_unlock(&trusted_key_tee_mutex);
 	return ret;
 }
 
@@ -161,13 +180,20 @@ static int trusted_tee_get_random(unsigned char *key, size_t key_len)
 	struct tee_param param[4];
 	struct tee_shm *reg_shm = NULL;
 
+	mutex_lock(&trusted_key_tee_mutex);
+	if (!pvt_data.ctx) {
+		ret = -ENODEV;
+		goto out_unlock;
+	}
+
 	memset(&inv_arg, 0, sizeof(inv_arg));
 	memset(&param, 0, sizeof(param));
 
 	reg_shm = tee_shm_register_kernel_buf(pvt_data.ctx, key, key_len);
 	if (IS_ERR(reg_shm)) {
 		dev_err(pvt_data.dev, "key shm register failed\n");
-		return PTR_ERR(reg_shm);
+		ret = PTR_ERR(reg_shm);
+		goto out_unlock;
 	}
 
 	inv_arg.func = TA_CMD_GET_RANDOM;
@@ -189,7 +215,8 @@ static int trusted_tee_get_random(unsigned char *key, size_t key_len)
 	}
 
 	tee_shm_free(reg_shm);
-
+out_unlock:
+	mutex_unlock(&trusted_key_tee_mutex);
 	return ret;
 }
 
@@ -205,50 +232,67 @@ static int optee_ctx_match(struct tee_ioctl_version_data *ver, const void *data)
 static int trusted_key_probe(struct tee_client_device *rng_device)
 {
 	struct device *dev = &rng_device->dev;
+	struct tee_context *ctx;
 	int ret;
 	struct tee_ioctl_open_session_arg sess_arg;
 
+	mutex_lock(&trusted_key_tee_mutex);
+	if (pvt_data.ctx) {
+		ret = -EBUSY;
+		goto out_unlock;
+	}
+
 	memset(&sess_arg, 0, sizeof(sess_arg));
 
-	pvt_data.ctx = tee_client_open_context(NULL, optee_ctx_match, NULL,
-					       NULL);
-	if (IS_ERR(pvt_data.ctx))
-		return -ENODEV;
+	ctx = tee_client_open_context(NULL, optee_ctx_match, NULL, NULL);
+	if (IS_ERR(ctx)) {
+		ret = -ENODEV;
+		goto out_unlock;
+	}
 
 	memcpy(sess_arg.uuid, rng_device->id.uuid.b, TEE_IOCTL_UUID_LEN);
 	sess_arg.clnt_login = TEE_IOCTL_LOGIN_REE_KERNEL;
 	sess_arg.num_params = 0;
 
-	ret = tee_client_open_session(pvt_data.ctx, &sess_arg, NULL);
+	ret = tee_client_open_session(ctx, &sess_arg, NULL);
 	if ((ret < 0) || (sess_arg.ret != 0)) {
 		dev_err(dev, "tee_client_open_session failed, err: %x\n",
 			sess_arg.ret);
 		ret = -EINVAL;
 		goto out_ctx;
 	}
+	pvt_data.ctx = ctx;
 	pvt_data.session_id = sess_arg.session;
-
-	ret = register_key_type(&key_type_trusted);
-	if (ret < 0)
-		goto out_sess;
-
 	pvt_data.dev = dev;
+	mutex_unlock(&trusted_key_tee_mutex);
 
-	return 0;
+	ret = register_key_type(&key_type_trusted);
+	if (!ret)
+		return 0;
 
-out_sess:
-	tee_client_close_session(pvt_data.ctx, pvt_data.session_id);
+	mutex_lock(&trusted_key_tee_mutex);
+	tee_client_close_session(ctx, pvt_data.session_id);
 out_ctx:
-	tee_client_close_context(pvt_data.ctx);
-
+	tee_client_close_context(ctx);
+	pvt_data.ctx = NULL;
+	pvt_data.dev = NULL;
+	pvt_data.session_id = 0;
+out_unlock:
+	mutex_unlock(&trusted_key_tee_mutex);
 	return ret;
 }
 
 static void trusted_key_remove(struct tee_client_device *dev)
 {
 	unregister_key_type(&key_type_trusted);
+
+	mutex_lock(&trusted_key_tee_mutex);
 	tee_client_close_session(pvt_data.ctx, pvt_data.session_id);
 	tee_client_close_context(pvt_data.ctx);
+	pvt_data.ctx = NULL;
+	pvt_data.dev = NULL;
+	pvt_data.session_id = 0;
+	mutex_unlock(&trusted_key_tee_mutex);
 }
 
 static const struct tee_client_device_id trusted_key_id_table[] = {
@@ -263,7 +307,8 @@ static struct tee_client_driver trusted_key_driver = {
 	.remove		= trusted_key_remove,
 	.id_table	= trusted_key_id_table,
 	.driver		= {
-		.name		= DRIVER_NAME,
+		.name			= DRIVER_NAME,
+		.suppress_bind_attrs	= true,
 	},
 };
 

51/3 2026/11/16 00:58 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35858
							output: 40
							thoughts: 3053
						

Thoughts:
**KMSAN Evaluation: Patch Series Analysis**

Alright, let's break down this patch series and determine if a KMSAN fuzzing session is warranted. My primary concern here is uninitialized memory reads or information leaks, as that's what KMSAN is designed to catch, and I won't waste resources if KASAN or other tools would do.

First, I see the initial set of patches deal with key management and garbage collection. The key changes are focused on improving the key garbage collection mechanism.  Crucially, the module reference counting (`ktype->owner`) is now integrated, and this looks promising. Specifically, the garbage collection is changed to use `module_put(owner)` after a key is freed. This should improve stability and correctness, and replaces a dangerous dead-type sweep, which is a significant improvement. I also see they've implemented chunking to avoid excessive CPU usage. This change *might* introduce a subtle memory leak, or UAF, but KASAN should easily detect it.

Patch 2 has some potentially interesting areas.  I see `kmalloc_obj` being used, and while the variables within `struct cert_store_key` *should* be initialized, I'm verifying the code flow to be absolutely sure. The initialization looks solid, and I confirm the code is for amd64 architecture, so no problems are found, and this patch doesn't look like a concern for KMSAN.

Patches 3 and 4 deal with NFS and SMB file systems.  I'm scanning for any indications of uninitialized memory, but I see clean-up routines and counters being added, which generally points towards better memory management rather than introducing new risks. They're adding mutexes and counters, clearing caches, and calling `key_gc_flush` as part of these clean-up routines. This is all good housekeeping and doesn't warrant KMSAN.

Patch 5 is adding a `struct module *owner;` to `struct key_type` for the module reference counting, and looks like part of the larger garbage collection improvement. The `register_key_type` function is redefined, but the critical change is setting `ktype->owner = owner;`.

Patch 6 refactors the DNS resolver, splitting it into two parts, and now has an associated key type.  The main changes look to be modularization, and making `key_gc_flush` calls. This change seems straightforward refactoring, and I'm not seeing any red flags for KMSAN.

Patch 7 is where things get interesting.  This splits RXRPC keys from the AF_RXRPC module, and that *could* be a vector for memory safety issues.  I will look closely at this one, and confirm all memory is initialized.  I see a call to `rxkad_preparse_server_key`.  The interesting part is that this function was moved from `rxkad.c` to `server_key.c`.  I will pay close attention to the move of this function, since the key parsing functions could have memory safety issues.  I also see that `memcpy` to the prep->payload.data, and now checking if `fips_enabled`, but it just calls `return -ENOPKG`.  This is a potential issue, however, it is handled in a good way to avoid an uninitialized read.

The key garbage collector improvements in patch 8 are very promising for overall kernel stability, but they *shouldn't* introduce new KMSAN issues. I need to be *sure*, and will re-check all memory paths. The key is now freed with `memzero_explicit(key, sizeof(*key));` and is already safe. I will be sure to confirm that the `module_put(owner)` calls are paired with the allocation calls.

Patch 9 is related to the previous two, with the module refcounts being used in `key_alloc`, `keyring_restrict`, and `keyring_destroy`.  I see the key type is updated to store owner. I will check what `lock_class` in `struct key_type` is used for in the kernel.

After this thorough review, I'm not seeing any clear KMSAN-worthy red flags in this patch series. All the key related areas look to be *improving* memory safety and garbage collection rather than introducing new risks. The move of `rxkad_preparse_server_key` is the most interesting change, but doesn't seem to be a problem based on the code. The patches appear focused on improving module management, garbage collection, and modularity. I will run these patches through KASAN to make sure I don't miss anything subtle, but a KMSAN session doesn't seem necessary here.



52/3 2026/11/16 00:59 tool grepper
0m Args:
{
  "Expression": "lock_class",
  "PathPrefixes": [
    "security/keys/",
    "include/linux/key-type.h"
  ]
}

Results:
{
  "Output": "include/linux/key-type.h=66=struct key_type {\n--\ninclude/linux/key-type.h-168-\tstruct list_head\tlink;\t\t/* link in types list */\ninclude/linux/key-type.h:169:\tstruct lock_class_key\tlock_class;\t/* key-\u003esem lock class */\ninclude/linux/key-type.h-170-} __randomize_layout;\n--\nsecurity/keys/key.c=225=struct key *key_alloc(struct key_type *type, const char *desc,\n--\nsecurity/keys/key.c-307-\tinit_rwsem(\u0026key-\u003esem);\nsecurity/keys/key.c:308:\tlockdep_set_class(\u0026key-\u003esem, \u0026type-\u003elock_class);\nsecurity/keys/key.c-309-\tkey-\u003euser = user;\n"
}

53/3 2026/11/16 00:59 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 40187
							output: 34
							thoughts: 2872
						

Thoughts:
**Detailed Analysis of Kernel Key Management Changes**

Okay, let's break this down. My initial concern was static storage and potential uninitialized memory exposure with `lock_class` in `struct key_type`. The fact that it's static and used within statically defined or dynamically registered `key_types` and that lockdep keys avoid uninitialized memory in user-space operations is reassuring.

Moving on to the `trusted_core.c` and `trusted_tee.c` changes, the ordering fix for static calls in `trusted_key_sources` is important. Ensuring `ops->init()` can correctly call `seal/unseal/get_random` *before* the potential teardown on failure prevents subtle race conditions. The addition of the `trusted_key_tee_mutex` and null context check in `trusted_tee.c` helps protect against race conditions within that subsystem, a crucial consideration for trusted execution environments.

Next, I examined `gc.c`. The `key_gc_work` struct's static initialization is as expected: zeroed BSS/static. The code in `key_garbage_collector` explicitly sets all fields of `gc` before use, which is critical to avoid uninitialized memory reads. This is the correct approach.

Now, I meticulously went through the patch changes. The core question became: Are there any data structures being copied to user space without proper sanitization? The search for `copy_to_user`, `put_user`, `keyctl` read operations, socket options, and netlink activity was key.

The discovery that `rxrpc_get_server_data_key`, `rxrpc_request_key`, `rxrpc_server_keyring`, `rxrpc_sock_set_security_keyring`, and `rxrpc_sock_set_manage_response` were moved verbatim from `net/rxrpc/key.c` and `net/rxrpc/server_key.c` to `net/rxrpc/security.c` caught my attention. This is a refactoring, and not a functional change to the code, so it's good in terms of code structure, but it means no new vulnerabilities introduced by those functions alone.

The real point of interest emerged in `rxrpc_preparse_s` and `rxkad_preparse_server_key`:

The `rxkad_preparse_server_key` function was moved from `rxkad.c` to `server_key.c`, with only a FIPS check (`if (fips_enabled) return -ENOPKG;`) added. This means there is no change in behavior when FIPS isn't enabled.

The change in `rxrpc_preparse_s` is more interesting. It now stores the `sec_class` directly in `prep->payload.data[1]` instead of a pointer to `rxrpc_security`.  This change avoids dereferencing a potentially unsafe pointer. This looks to be a significant improvement and reduces risk from possible vulnerabilities in that area. The switch statement then uses the stored `sec_class` value in the related `*_free_` and `*_describe_` functions, and this is a correct and safe approach.

The crucial next step is to examine the implications of changing `rxrpc_preparse_s` regarding where server keys are read. The ultimate safety check is to determine if any user space reads are changed or introduced. The next thing I'll do is check `key_type_rxrpc_s` in the kernel code.



54/3 2026/11/16 00:59 tool grepper
0m Args:
{
  "Expression": "key_type_rxrpc_s",
  "PathPrefixes": [
    "net/rxrpc/"
  ]
}

Results:
{
  "Output": "net/rxrpc/ar-internal.h=1490=int rxrpc_do_sendmsg(struct rxrpc_sock *, struct msghdr *, size_t);\n--\nnet/rxrpc/ar-internal.h-1494- */\nnet/rxrpc/ar-internal.h:1495:extern struct key_type key_type_rxrpc_s;\nnet/rxrpc/ar-internal.h-1496-\n--\nnet/rxrpc/key.c=815=static int __init rxrpc_keys_init(void)\n--\nnet/rxrpc/key.c-824-\nnet/rxrpc/key.c:825:\tret = register_key_type(\u0026key_type_rxrpc_s);\nnet/rxrpc/key.c-826-\tif (ret \u003c 0) {\n--\nnet/rxrpc/key.c=840=static void __exit rxrpc_keys_exit(void)\nnet/rxrpc/key.c-841-{\nnet/rxrpc/key.c:842:\tunregister_key_type(\u0026key_type_rxrpc_s);\nnet/rxrpc/key.c-843-\tunregister_key_type(\u0026key_type_rxrpc);\n--\nnet/rxrpc/security.c=163=struct key *rxrpc_look_up_server_security(struct rxrpc_connection *conn,\n--\nnet/rxrpc/security.c-193-\tkref = keyring_search(make_key_ref(rx-\u003esecurities, 1UL),\nnet/rxrpc/security.c:194:\t\t\t      \u0026key_type_rxrpc_s, kdesc, true);\nnet/rxrpc/security.c-195-\tif (IS_ERR(kref)) {\n--\nnet/rxrpc/server_key.c=34=static void rxrpc_describe_s(const struct key *, struct seq_file *);\n--\nnet/rxrpc/server_key.c-39- */\nnet/rxrpc/server_key.c:40:struct key_type key_type_rxrpc_s = {\nnet/rxrpc/server_key.c-41-\t.name\t\t= \"rxrpc_s\",\n--\nnet/rxrpc/server_key.c-49-};\nnet/rxrpc/server_key.c:50:EXPORT_SYMBOL(key_type_rxrpc_s);\nnet/rxrpc/server_key.c-51-\n"
}

55/3 2026/11/16 00:59 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 44469
							output: 37
							thoughts: 57
						

Thoughts:
Here's my analysis of what you've presented, thinking through the process as you've outlined it:

**Decoding the `key_type_rxrpc_s` Definition**

Okay, so we're diving into the `rxrpc` kernel code, specifically focusing on the server key management. My immediate thought is to understand the structure of `key_type_rxrpc_s`. To do that, I'll need to go directly to the source. Let's start with the standard location: `net/rxrpc/server_key.c`.

The instruction is to examine the definition by looking at lines 30 through 55. This will give me the declaration of `key_type_rxrpc_s` and the immediate surrounding code, which is probably the important comment describing its role, and possibly a few related definitions. I'll read through that section carefully, paying attention to the members of the struct and any associated macros or typedefs. I'm expecting this structure to contain the essential data needed to identify and manage the RXRPC server keys, their cryptographic parameters, and the associated server identification. It's the foundation of the server-side authentication process.



56/3 2026/11/16 00:59 tool read-file
0m Args:
{
  "File": "net/rxrpc/server_key.c",
  "FirstLine": 30,
  "LineCount": 25
}

Results:
{
  "Contents": "  30:\tstatic int rxrpc_vet_description_s(const char *);\n  31:\tstatic int rxrpc_preparse_s(struct key_preparsed_payload *);\n  32:\tstatic void rxrpc_free_preparse_s(struct key_preparsed_payload *);\n  33:\tstatic void rxrpc_destroy_s(struct key *);\n  34:\tstatic void rxrpc_describe_s(const struct key *, struct seq_file *);\n  35:\t\n  36:\t/*\n  37:\t * rxrpc server keys take \"\u003cserviceId\u003e:\u003csecurityIndex\u003e[:\u003csec-specific\u003e]\" as the\n  38:\t * description and the key material as the payload.\n  39:\t */\n  40:\tstruct key_type key_type_rxrpc_s = {\n  41:\t\t.name\t\t= \"rxrpc_s\",\n  42:\t\t.flags\t\t= KEY_TYPE_NET_DOMAIN,\n  43:\t\t.vet_description = rxrpc_vet_description_s,\n  44:\t\t.preparse\t= rxrpc_preparse_s,\n  45:\t\t.free_preparse\t= rxrpc_free_preparse_s,\n  46:\t\t.instantiate\t= generic_key_instantiate,\n  47:\t\t.destroy\t= rxrpc_destroy_s,\n  48:\t\t.describe\t= rxrpc_describe_s,\n  49:\t};\n  50:\tEXPORT_SYMBOL(key_type_rxrpc_s);\n  51:\t\n  52:\t/*\n  53:\t * Vet the description for an RxRPC server key.\n  54:\t */\n"
}

57/3 2026/11/16 00:59 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 45234
							output: 273
							thoughts: 3160
						

Thoughts:
**KMSAN Applicability Analysis for Key Subsystem Changes**

Okay, so I've gone through this patch set meticulously. My initial thought was, "Hmm, no `.read` for `key_type_rxrpc_s`? Server keys are read-only, makes sense." But then I needed to dive deeper. I started by checking the DNS resolver and quickly found that the changes there were focused on module init/exit and symbol splitting, not touching the read or describe functions, which is good.

The meat of the changes is clearly in the `security/keys` area.  I've noticed the introduction of module reference counting in `key_alloc` and the associated `try_module_get` calls, along with module puts on errors to handle the reference count.  I see a shift towards `key_schedule_gc_work(false)` and `key_schedule_gc_work(true)` in `key_put` and `key_invalidate` respectively, which is part of the garbage collection changes, and `ktype->owner = owner;` set in `__register_key_type`.  Importantly, the removal of `key_gc_keytype(ktype)` in `unregister_key_type` signals a big shift in the garbage collection mechanism.  The `keyring` code also shows module ref counting, and module puts on error.

I had to understand the GC rewrite. It appears the core idea is that module reference counting is now the *primary* mechanism to prevent module unload while keys exist. Therefore the garbage collector is simplified, not needing to find and destroy keys of a dying type, and `key_gc_work` is re-written. This is a very significant change. I checked the `key_garbage_collector` to see what could potentially be wrong here. Nothing jumped out at me as a KMSAN problem. The variables are all properly initialized, and the loop seems safe.

I had to contrast KMSAN and KASAN. KASAN is the comprehensive one here. I need to know where KMSAN is useful, and where it is not. This patch set really seems to focus on object destruction and cleanup. So I need to make sure I've thought about it.

I then went through the four KMSAN criteria. First, there's nothing here that's *newly* sending kernel structures to userspace without zeroing. I looked at the seq file output, session/idmap cleanup, and the security changes; nothing. Second, I checked every local variable. All are initialized before branching or use. Third, complex data structure initialization? The key type changes, including the `owner` field, are all properly handled. Fourth, bounds checks and length alterations, to expose uninitialized memory? No, nothing. This is not about buffer lengths or bounds.

So, realistically, what bugs could arise? Likely, lifetime issues, use-after-free, refcount imbalances, deadlocks, lock hierarchy issues, NULL pointer dereferences. I know that KASAN catches use-after-free, and refcount issues. LOCKDEP would catch deadlocks. The NULL pointer dereferences get caught by standard kernel checks. KMSAN doesn't have a place here.

I re-read the KMSAN instructions. The focus is to avoid running KMSAN if it's not needed. It appears that KMSAN is not needed here. Therefore, I'm comfortable saying that `NeedsKMSAN` is false.



58/3 2026/11/16 00:59 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series refactors the kernel keys subsystem to manage key type module ownership (adding `struct module *owner` to `struct key_type`), introduces module refcounting on key allocation and restriction, and redesigns the key garbage collector (`security/keys/gc.c`) by removing the old dead-keytype sweep in favor of module pinning and iterative workqueue-based garbage collection with `key_gc_flush()`. It also splits key type registrations into dedicated modules for DNS resolver and RxRPC, adds serialization and keyring clearing on session termination in NFS and CIFS/SMB, and adds mutex protection for trusted TEE keys.\n\nPrimary risks associated with these changes are reference counting errors (leaks or premature puts), module unload use-after-free, synchronization issues, and potential lock ordering deadlocks. These failure modes are reliably caught by KASAN, refcount checks, and LOCKDEP in standard debugging builds.\n\nThe changes do not introduce or modify any kernel structures copied to user space, do not alter buffer length or bounds calculations, do not create paths reading uninitialized heap/stack memory, and all introduced variables and struct instances are fully initialized prior to access. Consequently, KMSAN is not needed.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series refactors the kernel keys subsystem to manage key type module ownership (adding `struct module *owner` to `struct key_type`), introduces module refcounting on key allocation and restriction, and redesigns the key garbage collector (`security/keys/gc.c`) by removing the old dead-keytype sweep in favor of module pinning and iterative workqueue-based garbage collection with `key_gc_flush()`. It also splits key type registrations into dedicated modules for DNS resolver and RxRPC, adds serialization and keyring clearing on session termination in NFS and CIFS/SMB, and adds mutex protection for trusted TEE keys.\n\nPrimary risks associated with these changes are reference counting errors (leaks or premature puts), module unload use-after-free, synchronization issues, and potential lock ordering deadlocks. These failure modes are reliably caught by KASAN, refcount checks, and LOCKDEP in standard debugging builds.\n\nThe changes do not introduce or modify any kernel structures copied to user space, do not alter buffer length or bounds calculations, do not create paths reading uninitialized heap/stack memory, and all introduced variables and struct instances are fully initialized prior to access. Consequently, KMSAN is not needed.",
  "NeedsKMSAN": false
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)