[PATCH v7 12/14] KEYS: trusted: Unregister key type on module exit in TEE backend

From: Jarkko Sakkinen

Date: Sun Nov 29 2026 - 12:07:22 EST


trusted_key_remove() is a TEE client bus .remove() callback that runs
when the underlying TEE device unbinds, whereas key_type_trusted is
owned by trusted.ko.

Once keys pin trusted.ko and unregister_key_type() no longer reaps
extant keys via key_type_dead, unregistering key_type_trusted from
trusted_key_remove() can run while trusted keys still exist.

Keep key_type_trusted registered until trusted_tee_exit(), matching the
other trusted-key backends, while trusted_key_remove() tears down the
TEE session so subsequent TEE operations return -ENODEV.

Signed-off-by: Jarkko Sakkinen <jarkko@xxxxxxxxxx>
---
security/keys/trusted-keys/trusted_tee.c | 16 +++++++++++-----
1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/security/keys/trusted-keys/trusted_tee.c b/security/keys/trusted-keys/trusted_tee.c
index 87ea549f7f0b..4b67f504a54b 100644
--- a/security/keys/trusted-keys/trusted_tee.c
+++ b/security/keys/trusted-keys/trusted_tee.c
@@ -57,6 +57,7 @@ struct trusted_key_tee_private {
};

static struct trusted_key_tee_private pvt_data;
+static bool trusted_key_registered;
/* Do not hold this mutex across key type registration or unregistration. */
static DEFINE_MUTEX(trusted_key_tee_mutex);

@@ -266,10 +267,15 @@ static int trusted_key_probe(struct tee_client_device *rng_device)
pvt_data.dev = dev;
mutex_unlock(&trusted_key_tee_mutex);

- ret = register_key_type(&key_type_trusted);
- if (!ret)
- return 0;
+ if (!trusted_key_registered) {
+ ret = register_key_type(&key_type_trusted);
+ if (ret)
+ goto err_close_session;
+ trusted_key_registered = true;
+ }
+ return 0;

+err_close_session:
mutex_lock(&trusted_key_tee_mutex);
tee_client_close_session(ctx, pvt_data.session_id);
out_ctx:
@@ -284,8 +290,6 @@ static int trusted_key_probe(struct tee_client_device *rng_device)

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);
@@ -320,6 +324,8 @@ static int trusted_tee_init(void)
static void trusted_tee_exit(void)
{
tee_client_driver_unregister(&trusted_key_driver);
+ if (trusted_key_registered)
+ unregister_key_type(&key_type_trusted);
}

struct trusted_key_ops trusted_key_tee_ops = {
--
2.47.3