Skip to content

Commit

Permalink
keys: Provide a key_try_get() function and use it
Browse files Browse the repository at this point in the history
Add a key_try_get() function to try to get a ref on a key and switch code
that's manipulating the key refcount directly to use it.  This will allow a
tracepoint to be emplaced there later.

Signed-off-by: David Howells <dhowells@redhat.com>
cc: Jarkko Sakkinen <jarkko@kernel.org>
cc: keyrings@vger.kernel.org
cc: linux-security-module@vger.kernel.org
  • Loading branch information
dhowells committed Aug 21, 2024
1 parent 8561d53 commit 5ff8a54
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
1 change: 1 addition & 0 deletions include/linux/key.h
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ extern struct key *key_alloc(struct key_type *type,
extern void key_revoke(struct key *key);
extern void key_invalidate(struct key *key);
struct key *key_get(struct key *key);
struct key *key_try_get(struct key *key);
extern void key_put(struct key *key);
extern bool key_put_tag(struct key_tag *tag);
extern void key_remove_domain(struct key_tag *domain_tag);
Expand Down
16 changes: 15 additions & 1 deletion security/keys/key.c
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,20 @@ struct key *key_get(struct key *key)
}
EXPORT_SYMBOL(key_get);

/**
* key_try_get - Get a ref on a key if its refcount is not non-zero.
* @key: The key to get a reference on.
*
* Get a reference on a key unless it has no references and return true if
* successful. @key must not be NULL.
*/
struct key *key_try_get(struct key *key)
{
if (!refcount_inc_not_zero(&key->usage))
return NULL;
return key;
}

/**
* key_put - Discard a reference to a key.
* @key: The key to discard a reference from.
Expand Down Expand Up @@ -709,7 +723,7 @@ struct key *key_lookup(key_serial_t id)
/* A key is allowed to be looked up only if someone still owns a
* reference to it - otherwise it's awaiting the gc.
*/
if (!refcount_inc_not_zero(&key->usage))
if (!key_try_get(key))
goto not_found;

error:
Expand Down
2 changes: 1 addition & 1 deletion security/keys/keyring.c
Original file line number Diff line number Diff line change
Expand Up @@ -1174,7 +1174,7 @@ struct key *find_keyring_by_name(const char *name, bool uid_keyring)
/* we've got a match but we might end up racing with
* key_cleanup() if the keyring is currently 'dead'
* (ie. it has a zero usage count) */
if (!refcount_inc_not_zero(&keyring->usage))
if (!key_try_get(keyring))
continue;
keyring->last_used_at = ktime_get_real_seconds();
goto out;
Expand Down

0 comments on commit 5ff8a54

Please sign in to comment.