KEYS: From assoc_array to rhashtable migration
Subsystems (10)
Jarkko Sakkinen
maintainercover KEYS: From assoc_array to rhashtable migration
As a constant source of LLM attention this must be done.
This patch set started from Claude Opus 5.5 generated code that I got from Linus. I tweaked what I got over one day scoping it into a proper kernel patch, fixing some minor bugs in the core change, improved the use of types and basic stuff like that.
This felt a good chance to try out LLM in the kernel context and I used Gemini Flash 3.8 to seek for out-of-scope bugs intersecting with the core change.
Since this patch set is marked as RFC, I did not yet cut out-of-context bug fixes out, so for most part consider them as white noise. This applies to patches 1-3.
Jarkko Sakkinen (6):
keys: prevent quota overflow and widen quotalen and datalen to 32 bits
keys: reclaim link quota during keyring garbage collection
keys: verify key identity on unlink and move
keys: Add keyring_is_empty() for {fs,dm}-verity
KEYS: Replace assoc_array with struct keyring_index
lib: Remove unused assoc_array
Documentation/core-api/assoc_array.rst | 564 ------ Documentation/core-api/index.rst | 1 - .../zh_CN/core-api/assoc_array.rst | 473 ----- .../translations/zh_CN/core-api/index.rst | 1 - drivers/md/dm-verity-verify-sig.c | 2 +- fs/smb/client/cifsacl.c | 6 +- fs/verity/signature.c | 2 +- include/keys/keyring-type.h | 1 - include/linux/assoc_array.h | 88 - include/linux/assoc_array_priv.h | 178 -- include/linux/key.h | 24 +- lib/Kconfig | 14 - lib/Makefile | 1 - lib/assoc_array.c | 1724 ----------------- security/keys/Kconfig | 1 - security/keys/internal.h | 10 +- security/keys/key.c | 33 +- security/keys/keyctl.c | 9 +- security/keys/keyring.c | 887 ++++----- security/keys/request_key.c | 2 +- .../dm-verity/test-dm-verity-keyring.sh | 2 +- 21 files changed, 478 insertions(+), 3545 deletions(-) delete mode 100644 Documentation/core-api/assoc_array.rst delete mode 100644 Documentation/translations/zh_CN/core-api/assoc_array.rst delete mode 100644 include/linux/assoc_array.h delete mode 100644 include/linux/assoc_array_priv.h delete mode 100644 lib/assoc_array.c
--
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH 1/6 keys: prevent quota overflow and widen quotalen and datalen to 32 bits
In struct key, quotalen and datalen are 16-bit unsigned shorts, limiting payload and quota tracking to 64 KiB. With large descriptions or payload updates, addition and difference calculations can truncate or overflow, corrupting user quota accounting.
Additionally, existing quota checks rely on undefined signed overflow checks (e.g. user->qnbytes + quotalen < user->qnbytes) and do not guard against user->qnkeys or user->qnbytes reaching INT_MAX.
Widen quotalen and datalen to unsigned 32-bit integers in struct key. Validate description lengths against INT_MAX in key_alloc(), and check quota headroom using safe subtraction across key_alloc(), key_payload_reserve(), and keyctl_chown_key().
--- fs/smb/client/cifsacl.c | 6 +++--- include/linux/key.h | 4 ++-- security/keys/key.c | 25 ++++++++++++++++++++----- security/keys/keyctl.c | 9 +++++---- 4 files changed, 30 insertions(+), 14 deletions(-)
fs/smb/client/cifsacl.c +3 -3
@@ -385,7 +385,7 @@ id_to_sid(unsigned int cid, uint sidtype, struct smb_sid *ssid) goto out_revert_creds; }else if (sidkey->datalen <CIFS_SID_BASE_SIZE ) { rc =smb_EIO1 (smb_eio_trace_malformed_sid_key, sidkey->datalen); -cifs_dbg (FYI ,"%s: Downcall contained malformed key (datalen=%hu)\n" , +cifs_dbg (FYI ,"%s: Downcall contained malformed key (datalen=%u)\n" , __func__, sidkey->datalen); goto invalidate_key; }
@@ -403,7 +403,7 @@ id_to_sid(unsigned int cid, uint sidtype, struct smb_sid *ssid)if (ksid_size > sidkey->datalen) { rc =smb_EIO2 (smb_eio_trace_malformed_ksid_key, ksid_size, sidkey->datalen); -cifs_dbg (FYI ,"%s: Downcall contained malformed key (datalen=%hu, ksid_size=%u)\n" , +cifs_dbg (FYI ,"%s: Downcall contained malformed key (datalen=%u, ksid_size=%u)\n" , __func__, sidkey->datalen, ksid_size); goto invalidate_key; }
@@ -498,7 +498,7 @@ sid_to_id(struct cifs_sb_info *cifs_sb, struct smb_sid *psid,*/ BUILD_BUG_ON (sizeof (uid_t) !=sizeof (gid_t));if (sidkey->datalen !=sizeof (uid_t)) { -cifs_dbg (FYI ,"%s: Downcall contained malformed key (datalen=%hu)\n" , +cifs_dbg (FYI ,"%s: Downcall contained malformed key (datalen=%u)\n" , __func__, sidkey->datalen);key_invalidate (sidkey); goto out_key_put;
include/linux/key.h +2 -2
@@ -216,8 +216,8 @@ struct key {kuid_t uid;kgid_t gid;key_perm_t perm;/* access permissions */ -unsigned short quotalen;/* length added to quota */ -unsigned short datalen;/* payload data length +unsigned int quotalen;/* length added to quota */ +unsigned int datalen;/* payload data length * - may not match RCU dereferenced payload * - payload should contain own length */
security/keys/key.c +20 -5
@@ -245,6 +245,10 @@ struct key *key_alloc(struct key_type *type, const char *desc, } desclen =strlen (desc); +if (desclen >=INT_MAX || type->def_datalen >INT_MAX - desclen -1 ) { + key =ERR_PTR (-EINVAL ); + goto error; + } quotalen = desclen +1 + type->def_datalen;/* get hold of the key tracking for this user */
@@ -261,10 +265,14 @@ struct key *key_alloc(struct key_type *type, const char *desc, key_quota_root_maxbytes : key_quota_maxbytes;spin_lock_irqsave (&user->lock, irqflags); +if (user->qnkeys ==INT_MAX || + quotalen >INT_MAX - user->qnbytes) + goto no_quota; +if (!(flags &KEY_ALLOC_QUOTA_OVERRUN )) {if (user->qnkeys +1 > maxkeys || - user->qnbytes + quotalen > maxbytes || - user->qnbytes + quotalen < user->qnbytes) + quotalen > maxbytes || + user->qnbytes > maxbytes - quotalen) goto no_quota; }
@@ -373,11 +381,16 @@ EXPORT_SYMBOL(key_alloc);*/ int key_payload_reserve (struct key *key,size_t datalen) { -int delta = (int )datalen - key->datalen; +int delta;int ret =0 ;key_check (key); +if (datalen >INT_MAX ) +return -EINVAL ; + + delta = (int )datalen - (int )key->datalen; +/* contemplate the quota adjustment */ if (delta !=0 &&test_bit (KEY_FLAG_IN_QUOTA , &key->flags)) { unsigned maxbytes = uid_eq(key->user->uid, GLOBAL_ROOT_UID) ?
@@ -387,8 +400,10 @@ int key_payload_reserve(struct key *key, size_t datalen)spin_lock_irqsave (&key->user->lock, flags);if (delta >0 && - (key->user->qnbytes + delta > maxbytes || - key->user->qnbytes + delta < key->user->qnbytes)) { + (delta >INT_MAX - key->user->qnbytes || + delta >INT_MAX - key->quotalen || + delta > maxbytes || + key->user->qnbytes > maxbytes - delta)) { ret = -EDQUOT ; }else {
security/keys/keyctl.c +5 -4
@@ -1014,10 +1014,11 @@ long keyctl_chown_key(key_serial_t id, uid_t user, gid_t group) key_quota_root_maxbytes : key_quota_maxbytes;spin_lock_irqsave (&newowner->lock, flags); -if (newowner->qnkeys +1 > maxkeys || - newowner->qnbytes + key->quotalen > maxbytes || - newowner->qnbytes + key->quotalen < - newowner->qnbytes) +if (newowner->qnkeys ==INT_MAX || + newowner->qnkeys +1 > maxkeys || + key->quotalen >INT_MAX - newowner->qnbytes || + key->quotalen > maxbytes || + newowner->qnbytes > maxbytes - key->quotalen) goto quota_overrun; newowner->qnkeys++;
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH 2/6 keys: reclaim link quota during keyring garbage collection
In reply to Jarkko SakkinenGarbage collection removes dead key links without releasing their quota. Repeated collection therefore leaves the owner charged for links that no longer exist, eventually preventing further links with -EDQUOT.
Update the payload reservation from the surviving link count while holding the keyring semaphore. If assoc_array_gc() fails, the tree and its count remain unchanged, so the existing reservation is retained.
--- security/keys/keyring.c | 2 ++ 1 file changed, 2 insertions(+)
security/keys/keyring.c +2 -0
@@ -1755,6 +1755,8 @@ void keyring_gc(struct key *keyring, time64_t limit)down_write (&keyring->sem);assoc_array_gc (&keyring->keys, &keyring_assoc_array_ops, keyring_gc_select_iterator, &limit); +key_payload_reserve (keyring, + keyring->keys.nr_leaves_on_tree *KEYQUOTA_LINK_BYTES );up_write (&keyring->sem);kleave (" [gc]" ); }
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH 3/6 keys: verify key identity on unlink and move
In reply to Jarkko Sakkinen__key_unlink_begin() matches keys by index key without checking pointer identity. If distinct keys share type and description, unlinking or moving one can mistakenly unlink the other.
Verify key pointer identity before unlinking, returning -ENOENT on mismatch.
--- security/keys/keyring.c | 6 ++++++ 1 file changed, 6 insertions(+)
security/keys/keyring.c +6 -0
@@ -1501,9 +1501,15 @@ static int __key_unlink_begin(struct key *keyring, struct key *key, struct assoc_array_edit **_edit) {struct assoc_array_edit *edit; +const void *object;BUG_ON (*_edit !=NULL ); + object =assoc_array_find (&keyring->keys, &keyring_assoc_array_ops, + &key->index_key); +if (!object ||keyring_ptr_to_key (object) != key) +return -ENOENT ; + edit =assoc_array_delete (&keyring->keys, &keyring_assoc_array_ops, &key->index_key);if (IS_ERR (edit))
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH 4/6 keys: Add keyring_is_empty() for {fs,dm}-verity
In reply to Jarkko Sakkinenfs-verity and dm-verity read assoc_array's nr_leaves_on_tree directly to check whether a keyring is empty.
Add keyring_is_empty() and use it in the both callers.
--- drivers/md/dm-verity-verify-sig.c | 2 +- fs/verity/signature.c | 2 +- include/linux/key.h | 1 + security/keys/keyring.c | 10 ++++++++++ .../selftests/dm-verity/test-dm-verity-keyring.sh | 2 +- 5 files changed, 14 insertions(+), 3 deletions(-)
drivers/md/dm-verity-verify-sig.c +1 -1
@@ -153,7 +153,7 @@ int verity_verify_root_hash(const void *root_hash, size_t root_hash_len,if (ret != -ENOKEY && ret != -EKEYREJECTED )return ret; -if (dm_verity_keyring->keys.nr_leaves_on_tree && +if (!keyring_is_empty (dm_verity_keyring) && dm_verity_keyring->restrict_link) ret = verify_pkcs7_signature(root_hash, root_hash_len, sig_data, sig_len,
fs/verity/signature.c +1 -1
@@ -67,7 +67,7 @@ int fsverity_verify_signature(const struct fsverity_info *vi,return 0 ; } -if (fsverity_keyring->keys.nr_leaves_on_tree ==0 ) { +if (keyring_is_empty (fsverity_keyring)) {/* * The ".fs-verity" keyring is empty, due to builtin signatures * being supported by the kernel but not actually being used.
include/linux/key.h +1 -0
@@ -436,6 +436,7 @@ extern int restrict_link_reject(struct key *keyring, struct key *restriction_key);extern int keyring_clear (struct key *keyring); +bool keyring_is_empty (const struct key *keyring); extern key_ref_t keyring_search(key_ref_t keyring, struct key_type *type,
security/keys/keyring.c +10 -0
@@ -443,6 +443,16 @@ static void keyring_destroy(struct key *keyring)assoc_array_destroy (&keyring->keys, &keyring_assoc_array_ops); } +/** +* keyring_is_empty - Check whether a keyring contains any links +* @keyring: The keyring to check. +*/ +bool keyring_is_empty (const struct key *keyring) +{ +return READ_ONCE (keyring->keys.nr_leaves_on_tree) ==0 ; +} +EXPORT_SYMBOL (keyring_is_empty); +/* * Describe a keyring for /proc. */
tools/testing/selftests/dm-verity/test-dm-verity-keyring.sh +1 -1
@@ -746,7 +746,7 @@ test_keyring_inactive_when_empty() { log_info "TEST: Verify dm-verity keyring is inactive when sealed empty" # When keyring_unsealed=0, the keyring is sealed immediately while empty - # This means it should NOT be used for verification (nr_leaves_on_tree=0) + # An empty keyring should NOT be used for verification. log_info "Keyring state (should be empty and sealed):" list_keyring_keys
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH 5/6 KEYS: Replace assoc_array with struct keyring_index
In reply to Jarkko SakkinenLinux keyring would be better off without struct assoc_array given the overhead caused by sole ownership of it. Linux has multiple popular choices for key-value store and there is nothing special in lib/assoc_array.c that would make it stand out enough to be ratiaonalize the time spent on maintaining it.
A keyring has a sparse data population, making rhashtable a plausible choice. Multiple subsystems rely on it, and best of all, rhashtable has dedicated maintainers.
Replace assoc_array with struct keyring_index, allocated for a keyring on its first link attempt. Initialize its ht member with rhashtable_init() to store links indexed by key type, domain tag and description.
Maintain two linked lists in the index:
- all: enumerate committed links without retrying hash table walks when the table resizes.
- keyrings: visit nested keyrings during recursive search without scanning links to other key types.
A key can belong to several keyrings. Represent each link with struct keyring_link so it has separate hash table and list nodes and holds its own key reference. Traverse the lists under RCU and defer freeing removed links and dropping their key references until after a grace period.
--- include/keys/keyring-type.h | 1 - include/linux/key.h | 19 +- security/keys/Kconfig | 1 - security/keys/internal.h | 10 +- security/keys/key.c | 8 +- security/keys/keyring.c | 885 +++++++++++++++++------------------- security/keys/request_key.c | 2 +- 7 files changed, 434 insertions(+), 492 deletions(-)
include/keys/keyring-type.h +0 -1
@@ -9,6 +9,5 @@#define _KEYS_KEYRING_TYPE_H#include <linux/key.h> -#include <linux/assoc_array.h> #endif /* _KEYS_KEYRING_TYPE_H */
include/linux/key.h +4 -15
@@ -17,7 +17,6 @@#include <linux/sysctl.h> #include <linux/rwsem.h> #include <linux/atomic.h> -#include <linux/assoc_array.h> #include <linux/refcount.h> #include <linux/time64.h>
@@ -104,6 +103,7 @@ struct key_owner;struct key_tag ;struct keyring_list ;struct keyring_name ; +struct keyring_index ;struct key_tag {struct rcu_head rcu;
@@ -115,18 +115,7 @@ struct key_tag {struct keyring_index_key {/* [!] If this structure is altered, the union in struct key must change too! */ unsigned long hash;/* Hash value */ -union { -struct { -#ifdef __LITTLE_ENDIAN/* Put desc_len at the LSB of x */ -u16 desc_len; -char desc[sizeof (long ) -2 ];/* First few chars of description */ -#else -char desc[sizeof (long ) -2 ];/* First few chars of description */ -u16 desc_len; -#endif - }; -unsigned long x; - }; +unsigned int desc_len;struct key_type *type;struct key_tag *domain_tag;/* Domain of operation */ const char *description;
@@ -250,7 +239,7 @@ struct key {struct keyring_index_key index_key;struct {unsigned long hash; -unsigned long len_desc; +unsigned int desc_len;struct key_type *type;/* type of key */ struct key_tag *domain_tag;/* Domain of operation */ char *description;
@@ -268,7 +257,7 @@ struct key {struct {/* Keyring bits */ struct list_head name_link; -struct assoc_array keys; +struct keyring_index __rcu *links; }; };
security/keys/Kconfig +0 -1
@@ -5,7 +5,6 @@ menuconfig KEYS bool "Enable access key retention support" - select ASSOCIATIVE_ARRAY help This option provides support for retaining authentication tokens and access keys in the kernel.
security/keys/internal.h +6 -4
@@ -96,15 +96,17 @@ extern int __key_link_lock(struct key *keyring, const struct keyring_index_key *index_key);extern int __key_move_lock (struct key *l_keyring,struct key *u_keyring,const struct keyring_index_key *index_key); +struct keyring_link ; +extern int __key_link_begin (struct key *keyring,const struct keyring_index_key *index_key, -struct assoc_array_edit **_edit); +struct keyring_link **_edit);extern int __key_link_check_live_key (struct key *keyring,struct key *key);extern void __key_link (struct key *keyring,struct key *key, -struct assoc_array_edit **_edit); +struct keyring_link **_edit);extern void __key_link_end (struct key *keyring,const struct keyring_index_key *index_key, -struct assoc_array_edit *edit); +struct keyring_link *edit);extern key_ref_t find_key_to_update (key_ref_t keyring_ref,const struct keyring_index_key *index_key);
@@ -122,7 +124,7 @@ struct keyring_search_context {#define KEYRING_SEARCH_SKIP_EXPIRED 0x0020/* Ignore expired keys (intention to replace) */ #define KEYRING_SEARCH_RECURSE 0x0040/* Search child keyrings also */ -int (*iterator)(const void *object,void *iterator_data); +int (*iterator)(const struct key *key,void *iterator_data);/* Internal stuff */ int skipped_ret;
security/keys/key.c +4 -4
@@ -443,7 +443,7 @@ static int __key_instantiate_and_link(struct key *key,struct key_preparsed_payload *prep, struct key *keyring, struct key *authkey, - struct assoc_array_edit **_edit) + struct keyring_link **_edit) { int ret, awaken;
@@ -518,7 +518,7 @@ int key_instantiate_and_link(struct key *key, struct key *authkey) {struct key_preparsed_payload prep; -struct assoc_array_edit *edit =NULL ; +struct keyring_link *edit =NULL ;int ret;memset (&prep,0 ,sizeof (prep));
@@ -593,7 +593,7 @@ int key_reject_and_link(struct key *key,struct key *keyring, struct key *authkey) { - struct assoc_array_edit *edit = NULL; + struct keyring_link *edit = NULL;int ret, awaken, link_ret =0 ;key_check (key);
@@ -838,7 +838,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref, .description = description, };struct key_preparsed_payload prep; -struct assoc_array_edit *edit =NULL ; +struct keyring_link *edit =NULL ;const struct cred *cred =current_cred ();struct key *keyring, *key =NULL ;key_ref_t key_ref;
security/keys/keyring.c +419 -466
1,221 lines not on this page · raw message
security/keys/request_key.c +1 -1
@@ -372,7 +372,7 @@ static int construct_alloc_key(struct keyring_search_context *ctx,struct key_user *user, struct key **_key) { - struct assoc_array_edit *edit = NULL; + struct keyring_link *edit = NULL;struct key *key;key_perm_t perm;key_ref_t key_ref;
Signature · 1 line
2.47.3
Jarkko Sakkinen
maintainerRFC PATCH 6/6 lib: Remove unused assoc_array
In reply to Jarkko SakkinenDrop the obsolete leaf-count reference from a dm-verity test comment.
--- Documentation/core-api/assoc_array.rst | 564 ------ Documentation/core-api/index.rst | 1 - .../zh_CN/core-api/assoc_array.rst | 473 ----- .../translations/zh_CN/core-api/index.rst | 1 - include/linux/assoc_array.h | 88 - include/linux/assoc_array_priv.h | 178 -- lib/Kconfig | 14 - lib/Makefile | 1 - lib/assoc_array.c | 1724 ----------------- 9 files changed, 3044 deletions(-) delete mode 100644 Documentation/core-api/assoc_array.rst delete mode 100644 Documentation/translations/zh_CN/core-api/assoc_array.rst delete mode 100644 include/linux/assoc_array.h delete mode 100644 include/linux/assoc_array_priv.h delete mode 100644 lib/assoc_array.c
Documentation/core-api/assoc_array.rst deleted +0 -564
@@ -1,564 +0,0 @@ -======================================== -Generic Associative Array Implementation -======================================== - -Overview -======== - -This associative array implementation is an object container with the following -properties: - -1. Objects are opaque pointers. The implementation does not care where they - point (if anywhere) or what they point to (if anything). - - .. note:: - - Pointers to objects _must_ be zero in the least significant bit. - -2. Objects do not need to contain linkage blocks for use by the array. This - permits an object to be located in multiple arrays simultaneously. - Rather, the array is made up of metadata blocks that point to objects. - -3. Objects require index keys to locate them within the array. - -4. Index keys must be unique. Inserting an object with the same key as one - already in the array will replace the old object. - -5. Index keys can be of any length and can be of different lengths. - -6. Index keys should encode the length early on, before any variation due to - length is seen. - -7. Index keys can include a hash to scatter objects throughout the array. - -8. The array can iterated over. The objects will not necessarily come out in - key order. - -9. The array can be iterated over while it is being modified, provided the - RCU readlock is being held by the iterator. Note, however, under these - circumstances, some objects may be seen more than once. If this is a - problem, the iterator should lock against modification. Objects will not - be missed, however, unless deleted. - -10. Objects in the array can be looked up by means of their index key. - -11. Objects can be looked up while the array is being modified, provided the - RCU readlock is being held by the thread doing the look up. - -The implementation uses a tree of 16-pointer nodes internally that are indexed -on each level by nibbles from the index key in the same manner as in a radix -tree. To improve memory efficiency, shortcuts can be emplaced to skip over -what would otherwise be a series of single-occupancy nodes. Further, nodes -pack leaf object pointers into spare space in the node rather than making an -extra branch until as such time an object needs to be added to a full node. - - -The Public API -============== - -The public API can be found in ``<linux/assoc_array.h>``. The associative -array is rooted on the following structure:: - - struct assoc_array { - ... - }; - -The code is selected by enabling ``CONFIG_ASSOCIATIVE_ARRAY`` with:: - - ./script/config -e ASSOCIATIVE_ARRAY - - -Edit Script ------------ - -The insertion and deletion functions produce an 'edit script' that can later be -applied to effect the changes without risking ``ENOMEM``. This retains the -preallocated metadata blocks that will be installed in the internal tree and -keeps track of the metadata blocks that will be removed from the tree when the -script is applied. - -This is also used to keep track of dead blocks and dead objects after the -script has been applied so that they can be freed later. The freeing is done -after an RCU grace period has passed - thus allowing access functions to -proceed under the RCU read lock. - -The script appears as outside of the API as a pointer of the type:: - - struct assoc_array_edit; - -There are two functions for dealing with the script: - -1. Apply an edit script:: - - void assoc_array_apply_edit(struct assoc_array_edit *edit); - - This will perform the edit functions, interpolating various write barriers - to permit accesses under the RCU read lock to continue. The edit script - will then be passed to ``call_rcu()`` to free it and any dead stuff it - points to. - -2. Cancel an edit script:: - - void assoc_array_cancel_edit(struct assoc_array_edit *edit); - - This frees the edit script and all preallocated memory immediately. If - this was for insertion, the new object is *not* released by this function, - but must rather be released by the caller. - -These functions are guaranteed not to fail. - - -Operations Table ----------------- - -Various functions take a table of operations:: - - struct assoc_array_ops { - ... - }; - -This points to a number of methods, all of which need to be provided: - -1. Get a chunk of index key from caller data:: - - unsigned long (*get_key_chunk)(const void *index_key, int level); - - This should return a chunk of caller-supplied index key starting at the - *bit* position given by the level argument. The level argument will be a - multiple of ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` and the function should return - ``ASSOC_ARRAY_KEY_CHUNK_SIZE bits``. No error is possible. - - -2. Get a chunk of an object's index key:: - - unsigned long (*get_object_key_chunk)(const void *object, int level); - - As the previous function, but gets its data from an object in the array - rather than from a caller-supplied index key. - - -3. See if this is the object we're looking for:: - - bool (*compare_object)(const void *object, const void *index_key); - - Compare the object against an index key and return ``true`` if it matches - and ``false`` if it doesn't. - - -4. Diff the index keys of two objects:: - - int (*diff_objects)(const void *object, const void *index_key); - - Return the bit position at which the index key of the specified object - differs from the given index key or -1 if they are the same. - - -5. Free an object:: - - void (*free_object)(void *object); - - Free the specified object. Note that this may be called an RCU grace period - after ``assoc_array_apply_edit()`` was called, so ``synchronize_rcu()`` may - be necessary on module unloading. - - -Manipulation Functions ----------------------- - -There are a number of functions for manipulating an associative array: - -1. Initialise an associative array:: - - void assoc_array_init(struct assoc_array *array); - - This initialises the base structure for an associative array. It can't fail. - - -2. Insert/replace an object in an associative array:: - - struct assoc_array_edit * - assoc_array_insert(struct assoc_array *array, - const struct assoc_array_ops *ops, - const void *index_key, - void *object); - - This inserts the given object into the array. Note that the least - significant bit of the pointer must be zero as it's used to type-mark - pointers internally. - - If an object already exists for that key then it will be replaced with the - new object and the old one will be freed automatically. - - The ``index_key`` argument should hold index key information and is - passed to the methods in the ops table when they are called. - - This function makes no alteration to the array itself, but rather returns - an edit script that must be applied. ``-ENOMEM`` is returned in the case of - an out-of-memory error. - - The caller should lock exclusively against other modifiers of the array. - - -3. Delete an object from an associative array:: - - struct assoc_array_edit * - assoc_array_delete(struct assoc_array *array, - const struct assoc_array_ops *ops, - const void *index_key); - - This deletes an object that matches the specified data from the array. - - The ``index_key`` argument should hold index key information and is - passed to the methods in the ops table when they are called. - - This function makes no alteration to the array itself, but rather returns - an edit script that must be applied. ``-ENOMEM`` is returned in the case of - an out-of-memory error. ``NULL`` will be returned if the specified object - is not found within the array. - -The caller should lock exclusively against other modifiers of the array. - - -4. Delete all objects from an associative array:: - - struct assoc_array_edit * - assoc_array_clear(struct assoc_array *array, - const struct assoc_array_ops *ops); - - This deletes all the objects from an associative array and leaves it - completely empty. - - This function makes no alteration to the array itself, but rather returns - an edit script that must be applied. ``-ENOMEM`` is returned in the case of - an out-of-memory error. - - The caller should lock exclusively against other modifiers of the array. - - -5. Destroy an associative array, deleting all objects:: - - void assoc_array_destroy(struct assoc_array *array, - const struct assoc_array_ops *ops); - - This destroys the contents of the associative array and leaves it - completely empty. It is not permitted for another thread to be traversing - the array under the RCU read lock at the same time as this function is - destroying it as no RCU deferral is performed on memory release - - something that would require memory to be allocated. - - The caller should lock exclusively against other modifiers and accessors - of the array. - - -6. Garbage collect an associative array:: - - int assoc_array_gc(struct assoc_array *array, - const struct assoc_array_ops *ops, - bool (*iterator)(void *object, void *iterator_data), - void *iterator_data); - - This iterates over the objects in an associative array and passes each one - to ``iterator()``. If ``iterator()`` returns ``true``, the object is kept. - If it returns ``false``, the object will be freed. If the ``iterator()`` - function returns ``true``, it must perform any appropriate refcount - incrementing on the object before returning. - - The internal tree will be packed down if possible as part of the iteration - to reduce the number of nodes in it. - - The ``iterator_data`` is passed directly to ``iterator()`` and is otherwise - ignored by the function. - - The function will return ``0`` if successful and ``-ENOMEM`` if there wasn't - enough memory. - - It is possible for other threads to iterate over or search the array under - the RCU read lock while this function is in progress. The caller should - lock exclusively against other modifiers of the array. - - -Access Functions ----------------- - -There are two functions for accessing an associative array: - -1. Iterate over all the objects in an associative array:: - - int assoc_array_iterate(const struct assoc_array *array, - int (*iterator)(const void *object, - void *iterator_data), - void *iterator_data); - - This passes each object in the array to the iterator callback function. - ``iterator_data`` is private data for that function. - - This may be used on an array at the same time as the array is being - modified, provided the RCU read lock is held. Under such circumstances, - it is possible for the iteration function to see some objects twice. If - this is a problem, then modification should be locked against. The - iteration algorithm should not, however, miss any objects. - - The function will return ``0`` if no objects were in the array or else it - will return the result of the last iterator function called. Iteration - stops immediately if any call to the iteration function results in a - non-zero return. - - -2. Find an object in an associative array:: - - void *assoc_array_find(const struct assoc_array *array, - const struct assoc_array_ops *ops, - const void *index_key); - - This walks through the array's internal tree directly to the object - specified by the index key. - - This may be used on an array at the same time as the array is being - modified, provided the RCU read lock is held. - - The function will return the object if found (and set ``*_type`` to the - object type) or will return ``NULL`` if the object was not found. - - -Index Key Form --------------- - -The index key can be of any form, but since the algorithms aren't told how long -the key is, it is strongly recommended that the index key includes its length -very early on before any variation due to the length would have an effect on -comparisons. - -This will cause leaves with different length keys to scatter away from each -other - and those with the same length keys to cluster together. - -It is also recommended that the index key begin with a hash of the rest of the -key to maximise scattering throughout keyspace. - -The better the scattering, the wider and lower the internal tree will be. - -Poor scattering isn't too much of a problem as there are shortcuts and nodes -can contain mixtures of leaves and metadata pointers. - -The index key is read in chunks of machine word. Each chunk is subdivided into -one nibble (4 bits) per level, so on a 32-bit CPU this is good for 8 levels and -on a 64-bit CPU, 16 levels. Unless the scattering is really poor, it is -unlikely that more than one word of any particular index key will have to be -used. - - -Internal Workings -================= - -The associative array data structure has an internal tree. This tree is -constructed of two types of metadata blocks: nodes and shortcuts. - -A node is an array of slots. Each slot can contain one of four things: - -* A NULL pointer, indicating that the slot is empty. -* A pointer to an object (a leaf). -* A pointer to a node at the next level. -* A pointer to a shortcut. - - -Basic Internal Tree Layout --------------------------- - -Ignoring shortcuts for the moment, the nodes form a multilevel tree. The index -key space is strictly subdivided by the nodes in the tree and nodes occur on -fixed levels. For example:: - - Level: 0 1 2 3 - =============== =============== =============== =============== - NODE D - NODE B NODE C +------>+---+ - +------>+---+ +------>+---+ | | 0 | - NODE A | | 0 | | | 0 | | +---+ - +---+ | +---+ | +---+ | : : - | 0 | | : : | : : | +---+ - +---+ | +---+ | +---+ | | f | - | 1 |---+ | 3 |---+ | 7 |---+ +---+ - +---+ +---+ +---+ - : : : : | 8 |---+ - +---+ +---+ +---+ | NODE E - | e |---+ | f | : : +------>+---+ - +---+ | +---+ +---+ | 0 | - | f | | | f | +---+ - +---+ | +---+ : : - | NODE F +---+ - +------>+---+ | f | - | 0 | NODE G +---+ - +---+ +------>+---+ - : : | | 0 | - +---+ | +---+ - | 6 |---+ : : - +---+ +---+ - : : | f | - +---+ +---+ - | f | - +---+ - -In the above example, there are 7 nodes (A-G), each with 16 slots (0-f). -Assuming no other meta data nodes in the tree, the key space is divided -thusly: - - =========== ==== - KEY PREFIX NODE - =========== ==== - 137* D - 138* E - 13[0-69-f]* C - 1[0-24-f]* B - e6* G - e[0-57-f]* F - [02-df]* A - =========== ==== - -So, for instance, keys with the following example index keys will be found in -the appropriate nodes: - - =============== ======= ==== - INDEX KEY PREFIX NODE - =============== ======= ==== - 13694892892489 13 C - 13795289025897 137 D - 13889dde88793 138 E - 138bbb89003093 138 E - 1394879524789 12 C - 1458952489 1 B - 9431809de993ba \- A - b4542910809cd \- A - e5284310def98 e F - e68428974237 e6 G - e7fffcbd443 e F - f3842239082 \- A - =============== ======= ==== - -To save memory, if a node can hold all the leaves in its portion of keyspace, -then the node will have all those leaves in it and will not have any metadata -pointers - even if some of those leaves would like to be in the same slot. - -A node can contain a heterogeneous mix of leaves and metadata pointers. -Metadata pointers must be in the slots that match their subdivisions of key -space. The leaves can be in any slot not occupied by a metadata pointer. It -is guaranteed that none of the leaves in a node will match a slot occupied by a -metadata pointer. If the metadata pointer is there, any leaf whose key matches -the metadata key prefix must be in the subtree that the metadata pointer points -to. - -In the above example list of index keys, node A will contain: - - ==== =============== ================== - SLOT CONTENT INDEX KEY (PREFIX) - ==== =============== ================== - 1 PTR TO NODE B 1* - any LEAF 9431809de993ba - any LEAF b4542910809cd - e PTR TO NODE F e* - any LEAF f3842239082 - ==== =============== ================== - -and node B: - - ==== =============== ================== - SLOT CONTENT INDEX KEY (PREFIX) - ==== =============== ================== - 3 PTR TO NODE C 13* - any LEAF 1458952489 - ==== =============== ================== - - -Shortcuts ---------- - -Shortcuts are metadata records that jump over a piece of keyspace. A shortcut -is a replacement for a series of single-occupancy nodes ascending through the -levels. Shortcuts exist to save memory and to speed up traversal. - -It is possible for the root of the tree to be a shortcut - say, for example, -the tree contains at least 17 nodes all with key prefix ``1111``. The -insertion algorithm will insert a shortcut to skip over the ``1111`` keyspace -in a single bound and get to the fourth level where these actually become -different. - - -Splitting And Collapsing Nodes ------------------------------- - -Each node has a maximum capacity of 16 leaves and metadata pointers. If the -insertion algorithm finds that it is trying to insert a 17th object into a -node, that node will be split such that at least two leaves that have a common -key segment at that level end up in a separate node rooted on that slot for -that common key segment. - -If the leaves in a full node and the leaf that is being inserted are -sufficiently similar, then a shortcut will be inserted into the tree. - -When the number of objects in the subtree rooted at a node falls to 16 or -fewer, then the subtree will be collapsed down to a single node - and this will -ripple towards the root if possible. - - -Non-Recursive Iteration ------------------------ - -Each node and shortcut contains a back pointer to its parent and the number of -slot in that parent that points to it. None-recursive iteration uses these to -proceed rootwards through the tree, going to the parent node, slot N + 1 to -make sure progress is made without the need for a stack. - -The backpointers, however, make simultaneous alteration and iteration tricky. - - -Simultaneous Alteration And Iteration -------------------------------------- - -There are a number of cases to consider: - -1. Simple insert/replace. This involves simply replacing a NULL or old - matching leaf pointer with the pointer to the new leaf after a barrier. - The metadata blocks don't change otherwise. An old leaf won't be freed - until after the RCU grace period. - -2. Simple delete. This involves just clearing an old matching leaf. The - metadata blocks don't change otherwise. The old leaf won't be freed until - after the RCU grace period. - -3. Insertion replacing part of a subtree that we haven't yet entered. This - may involve replacement of part of that subtree - but that won't affect - the iteration as we won't have reached the pointer to it yet and the - ancestry blocks are not replaced (the layout of those does not change). - -4. Insertion replacing nodes that we're actively processing. This isn't a - problem as we've passed the anchoring pointer and won't switch onto the - new layout until we follow the back pointers - at which point we've - already examined the leaves in the replaced node (we iterate over all the - leaves in a node before following any of its metadata pointers). - - We might, however, re-see some leaves that have been split out into a new - branch that's in a slot further along than we were at. - -5. Insertion replacing nodes that we're processing a dependent branch of. - This won't affect us until we follow the back pointers. Similar to (4). - -6. Deletion collapsing a branch under us. This doesn't affect us because the - back pointers will get us back to the parent of the new node before we - could see the new node. The entire collapsed subtree is thrown away - unchanged - and will still be rooted on the same slot, so we shouldn't - process it a second time as we'll go back to slot + 1. - -.. note:: - - Under some circumstances, we need to simultaneously change the parent - pointer and the parent slot pointer on a node (say, for example, we - inserted another node before it and moved it up a level). We cannot do - this without locking against a read - so we have to replace that node too. - - However, when we're changing a shortcut into a node this isn't a problem - as shortcuts only have one slot and so the parent slot number isn't used - when traversing backwards over one. This means that it's okay to change - the slot number first - provided suitable barriers are used to make sure - the parent slot number is read after the back pointer. - -Obsolete blocks and leaves are freed up after an RCU grace period has passed, -so as long as anyone doing walking or iteration holds the RCU read lock, the -old superstructure should not go away on them.
Documentation/core-api/index.rst +0 -1
@@ -38,7 +38,6 @@ Library functionality that is used throughout the kernel. kobject kref cleanup - assoc_array folio_queue xarray maple_tree
Documentation/translations/zh_CN/core-api/assoc_array.rst deleted +0 -473
473 lines not on this page · raw message
Documentation/translations/zh_CN/core-api/index.rst +0 -1
@@ -41,7 +41,6 @@ kobject kref - assoc_array xarray rbtree idr
include/linux/assoc_array.h deleted +0 -88
88 lines not on this page · raw message
include/linux/assoc_array_priv.h deleted +0 -178
178 lines not on this page · raw message
lib/Kconfig +0 -14
@@ -349,20 +349,6 @@ config XARRAY_MULTI Support entries which occupy multiple consecutive indices in the XArray. -config ASSOCIATIVE_ARRAY - bool - help - Generic associative array. Can be searched and iterated over whilst - it is being modified. It is also reasonably quick to search and - modify. The algorithms are non-recursive, and the trees are highly - capacious. - - See: - - Documentation/core-api/assoc_array.rst - - for more information. - config CLOSURES bool
lib/Makefile +0 -1
@@ -141,7 +141,6 @@ obj-$(CONFIG_GENERIC_HWEIGHT) += hweight.o obj-$(CONFIG_BTREE) += btree.o obj-$(CONFIG_INTERVAL_TREE) += interval_tree.o -obj-$(CONFIG_ASSOCIATIVE_ARRAY) += assoc_array.o obj-$(CONFIG_DEBUG_PREEMPT) += smp_processor_id.o obj-$(CONFIG_LIST_HARDENED) += list_debug.o obj-$(CONFIG_DEBUG_OBJECTS) += debugobjects.o
lib/assoc_array.c deleted +0 -1724
1,656 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.47.3
Part of the diff is not shown here. View the raw message.
Jarkko Sakkinen
maintainerRe: [RFC PATCH 5/6] KEYS: Replace assoc_array with struct keyring_index
In reply to Jarkko Sakkinensecurity/keys/keyring.c static int __key_unlink_begin(struct key *keyring, struct key *key, · line 1559
Quoted 13 lines · Jarkko Sakkinen
security/keys/keyring.c +0
-13-/* -* Finish unlinking a key from to a keyring. -*/ -static void __key_unlink_end (struct key *keyring, -struct key *key, -struct assoc_array_edit *edit) - __releases(&keyring->sem) -{ -if (edit) -assoc_array_cancel_edit (edit); -up_write (&keyring->sem); -} -
This is the part that I'm particularly happy about because it would be nice if teardown type of operations would not allocate new resources. And it is also incompatible with OOM handler expectations, if not formal, at least intuitive.
Br, Jarkko
Eric Biggers
maintainerRe: [RFC PATCH 1/6] keys: prevent quota overflow and widen quotalen and datalen to 32 bits
In reply to Jarkko Sakkinensecurity/keys/key.c struct key *key_alloc(struct key_type *type, const char *desc, · line 252
Quoted 9 lines · Jarkko Sakkinen
security/keys/key.c +4
-0@@ -245,6 +245,10 @@ struct key *key_alloc(struct key_type *type, const char *desc, } desclen =strlen (desc); +if (desclen >=INT_MAX || type->def_datalen >INT_MAX - desclen -1 ) { + key =ERR_PTR (-EINVAL ); + goto error; + } quotalen = desclen +1 + type->def_datalen;
This should be tightened further to 'desclen > U16_MAX', since desclen is assigned to a u16 later in the function.
- Eric
Eric Biggers
maintainerRe: [RFC PATCH 2/6] keys: reclaim link quota during keyring garbage collection
In reply to Jarkko SakkinenQuoted 20 lines · Jarkko Sakkinen
Garbage collection removes dead key links without releasing their quota. Repeated collection therefore leaves the owner charged for links that no longer exist, eventually preventing further links with
-EDQUOT.Update the payload reservation from the surviving link count while holding the keyring semaphore. If
assoc_array_gc()fails, the tree and its count remain unchanged, so the existing reservation is retained.Fixes b2a4df200d57 ("KEYS: Expand the capacity of a keyring")Assisted-by LLMSigned-off-by Jarkko Sakkinen <[email protected]>--- security/keys/keyring.c | 2 ++ 1 file changed, 2 insertions(+)security/keys/keyring.c +0
-0
security/keys/keyring.c void keyring_gc(struct key *keyring, time64_t limit) · line 1761
Quoted 7 lines
security/keys/keyring.c +2
-0@@ -1755,6 +1755,8 @@ void keyring_gc(struct key *keyring, time64_t limit)down_write (&keyring->sem);assoc_array_gc (&keyring->keys, &keyring_assoc_array_ops, keyring_gc_select_iterator, &limit); +key_payload_reserve (keyring, + keyring->keys.nr_leaves_on_tree *KEYQUOTA_LINK_BYTES );up_write (&keyring->sem);kleave (" [gc]" );
This doesn't actually hold a reference to the keyring, so can't it race with key_put() which released the quota already? Then the quota for a link can be released multiple times.
- Eric
Jarkko Sakkinen
maintainerRe: [RFC PATCH 1/6] keys: prevent quota overflow and widen quotalen and datalen to 32 bits
In reply to Eric BiggersQuoted 4 lines · Eric Biggers
Quoted 3 lines · Jarkko Sakkinen
(quoted diff) +0
-0@@ -245,6 +245,10 @@ struct key *key_alloc(struct key_type *type, const char *desc, }
Quoted 9 lines
security/keys/key.c struct key *key_alloc(struct key_type *type, const char *desc, · line 252
Quoted 6 lines
security/keys/key.c +4
-0desclen =strlen (desc); +if (desclen >=INT_MAX || type->def_datalen >INT_MAX - desclen -1 ) { + key =ERR_PTR (-EINVAL ); + goto error; + } quotalen = desclen +1 + type->def_datalen;This should be tightened further to 'desclen >
U16_MAX', since desclen is assigned to a u16 later in the function.
Thanks for the remark. I think you are right and fits to what I've been working on today.
Cutting hairs perhaps but I have really hard time to comprehend this as a scoped bug fix.
Today morning I tried different things and what made sense to me is instead think the bug scope as three separate integer overflows and and one truncation bug.
The net result is here already:
https://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd.git/log/?h=keys-rhashtable
I decided that I retain all fixes as part of the series but eagerly apply and drop them series of course. Split series would be a mess. And they are any way part of the staircase from "now" to "then".
Quoted 2 lines
- Eric
Br, Jarkko
Jarkko Sakkinen
maintainerRe: [RFC PATCH 2/6] keys: reclaim link quota during keyring garbage collection
In reply to Eric BiggersQuoted 16 lines · Eric Biggers
Quoted 15 lines · Jarkko Sakkinen
Garbage collection removes dead key links without releasing their quota. Repeated collection therefore leaves the owner charged for links that no longer exist, eventually preventing further links with
-EDQUOT.Update the payload reservation from the surviving link count while holding the keyring semaphore. If
assoc_array_gc()fails, the tree and its count remain unchanged, so the existing reservation is retained.Fixes b2a4df200d57 ("KEYS: Expand the capacity of a keyring")Assisted-by LLMSigned-off-by Jarkko Sakkinen <[email protected]>--- security/keys/keyring.c | 2 ++ 1 file changed, 2 insertions(+)
Quoted 16 lines
security/keys/keyring.c void keyring_gc(struct key *keyring, time64_t limit) · line 1761
Quoted 12 lines
security/keys/keyring.c +2
-0@@ -1755,6 +1755,8 @@ void keyring_gc(struct key *keyring, time64_t limit)down_write (&keyring->sem);assoc_array_gc (&keyring->keys, &keyring_assoc_array_ops, keyring_gc_select_iterator, &limit); +key_payload_reserve (keyring, + keyring->keys.nr_leaves_on_tree *KEYQUOTA_LINK_BYTES );up_write (&keyring->sem);kleave (" [gc]" );This doesn't actually hold a reference to the keyring, so can't it race with
key_put()which released the quota already? Then the quota for a link can be released multiple times.
I agree. Thanks for checking this. I only got through the first today but plan to inventory them all in detail. This can be dropped without any further consideration.
The head is the LLM assisted part from my side and I go through them with presumption that the changes are not applicable.
Quoted 2 lines
- Eric
Br, Jarkko
Eric Biggers
maintainerRe: [RFC PATCH 5/6] KEYS: Replace assoc_array with struct keyring_index
In reply to Jarkko SakkinenThanks, this generally looks good.
I was tempted to recommend a custom hashtable, instead of rhashtable plus the two lists alongside it, to save memory and avoid the rhashtable dependency. Especially given that the keyrings subsystem already uses its own lock for writes, so the rhashtable bucket locks are wasted.
But ultimately I think I lean towards the rhashtable plus the two lists, as this patch does. It's slightly less code, it allows the hash table to be shrunk (whereas custom solution would likely be grow-only), and it continues to allow iterating over just the keyrings in a keyring without traversing every key in that keyring.
Quoted 5 lines · Jarkko Sakkinen
Linux keyring would be better off without struct
assoc_arraygiven the overhead caused by sole ownership of it. Linux has multiple popular choices for key-value store and there is nothing special inlib/assoc_array.cthat would make it stand out enough to be ratiaonalize the time spent on maintaining it.
"to be ratiaonalize" => "to rationalize"
Quoted 11 lines
/*
- * We mark pointers we pass to the associative array with bit 1 set if
- * they're keyrings and clear otherwise.
+ * The contents of a keyring, allocated when the first link is made.
+ *
+ * Modified only withkeyring->semwrite-locked; read under RCU. @ht indexes
+ * the links by index key, for direct lookup. @all holds every committed link
+ * and @keyrings the committed links to keyrings, for iteration: an RCU walk of
+ * a list sees every entry that stays on it for the duration of the walk, which
+ * a walk of @ht racing with a resize does not.
+ */
"which a walk of @ht" => "while a walk of ht"
Quoted 4 lines
+ * ->hash is copied from the index key at
__key_link_begin()and never changes,
+ * so the hash table can rehash the link without looking at the key, whose
+ * type the garbage collector may change (key_type_dead).
+structkeyring_link{
This explanation seems inaccurate. The actual reason ->hash is needed is because reserved links can be inserted while ->key is still NULL.
security/keys/keyring.c line 68
Quoted 7 lines
security/keys/keyring.c +7
-0+struct rhash_head node; +struct key __rcu *key;/* NULL while reserved */ +unsigned long hash; +struct list_head all_link;/* in keyring_index::all */ +struct list_head keyrings_link;/* in keyring_index::keyrings */ +struct keyring_link *replaces;/* Link this one replaces, or NULL */ +bool is_keyring;
Make 'hash' u32 and make it adjacent to 'is_keyring' to get rid of the hole?
Or at least make it u64, given that it's a SipHash value.
But it ultimately just gets combined with the rhashtable seed to produce a 32-bit hash anyway, so u32 is enough. (Then in keyring_hashfn() and keyring_obj_hashfn(), use jhash_1word() instead of jhash_2word().)
'unsigned long' doesn't make much sense and seems to just be a holdover from the assoc_array based code.
Quoted 5 lines
security/keys/keyring.c +5
-0+/* +* Pass each key linked from a keyring to @iterator until it returns non-zero. +* Returns the last value @iterator returned, or 0 if the keyring is empty. +* Concurrent links and unlinks may be seen or not; a key that stays linked +* throughout is passed to @iterator.
security/keys/keyring.c line 156
Quoted 10 lines
security/keys/keyring.c +10
-0+*/ +static int keyring_iterate (const struct key *keyring, +int (*iterator)(const struct key *key,void *data), +void *data) +{ +struct keyring_index *links; +struct keyring_link *link; +int ret =0 ; + +rcu_read_lock ();
guard(rcu)()
security/keys/keyring.c line 166
Quoted 10 lines
security/keys/keyring.c +10
-0+ links =rcu_dereference (keyring->links); +if (links) { +list_for_each_entry_rcu (link, &links->all, all_link) { + ret =iterator (keyring_link_key (link), data); +if (ret) +break ; + } + } +rcu_read_unlock (); +return ret;
... then 'return ret' in the loop, and 'return 0' at the end
Quoted 26 lines
security/keys/keyring.c +0
-26-/* -* Build the next index key chunk. -* -* The hash and inline description are followed by the 64-bit type and domain -* IDs, low word first, and then by the rest of the description. -* We return it one word-sized chunk at a time. -*/ -static unsigned long keyring_get_key_chunk (const void *data,int level) -{ -const unsigned int id_chunks =sizeof (u64) /sizeof (unsigned long ); -const struct keyring_index_key *index_key = data; -int desc_len = index_key->desc_len; -unsigned long chunk =0 ; -int n =sizeof (chunk); -unsigned int offset; -const u8 *d; - - level /=ASSOC_ARRAY_KEY_CHUNK_SIZE ; -switch (level) { -case 0 : -return index_key->hash; -case 1 : -return index_key->x; - } - - level -=2 ;
security/keys/keyring.c void key_remove_domain(struct key_tag *domain_tag) · line 306
Quoted 10 lines
security/keys/keyring.c +0
-10-if (level < id_chunks) -return index_key->type_id >> (level *ASSOC_ARRAY_KEY_CHUNK_SIZE ); - level -= id_chunks; -if (level < id_chunks) -return index_key->domain_id >> (level *ASSOC_ARRAY_KEY_CHUNK_SIZE ); - level -= id_chunks; - - offset =sizeof (index_key->desc) + level *sizeof (long ); -if (desc_len <= offset) -return 0 ;
With type_id and domain_id no longer being used directly as part of a radix tree key, they're no longer actually needed at all. Provided that we continue to use SipHash (or another cryptographically secure PRF) with a random key, using the pointers directly (as was done originally) no longer leaks kernel addresses. E.g., we can just do:
/* Finalize an index key: set the domain tag and calculate the hash. */
void key_set_index_key(struct keyring_index_key *index_key)
{
static struct key_tag default_domain_tag = { .usage = REFCOUNT_INIT(1), };
static siphash_key_t hash_key __read_mostly;
u64 acc;
if (!index_key->domain_tag) {
if (index_key->type->flags & KEY_TYPE_NET_DOMAIN)
index_key->domain_tag = current->nsproxy->net_ns->key_domain;
else
index_key->domain_tag = &default_domain_tag;
}
get_random_once(&hash_key, sizeof(hash_key));
/*
* Compute a SipHash value of the description, type pointer, and domain
* tag pointer using a per-boot random key.
*
* Note that using the pointers as input to the hash is safe, since
* SipHash is a cryptographically secure pseudorandom function. Thus
* the hash values don't leak any information about the pointers.
*
* Similarly, truncating the SipHash values to the required 32 bits is
* also safe. No "folding" step is needed.
*/
acc = siphash(index_key->description, index_key->desc_len, &hash_key);
acc = siphash_3u64((unsigned long)index_key->type,
(unsigned long)index_key->domain_tag, acc,
&hash_key);
index_key->hash = (u32)acc;
}... and remove the type_id and domain_id fields.
Might be worth folding this into "keys: make keyring indexes independent of kernel addresses" actually, since otherwise this just supersedes all of that commit except for the introduction of SipHash. And I guess this commit will end up needing to be backported anyway, since otherwise assoc_array bugs will be unfixed in stable.
Quoted 4 lines
security/keys/keyring.c +4
-0+/* +* The number of links in a keyring. +*/ +static unsigned long keyring_nr_links (const struct key *keyring)
security/keys/keyring.c static void keyring_destroy(struct key *keyring) · line 469
Quoted 10 lines
security/keys/keyring.c +9
-0+{ +const struct keyring_index *links; +unsigned long nr; + +rcu_read_lock (); + links =rcu_dereference (keyring->links); + nr = links ?READ_ONCE (links->nr) :0 ; +rcu_read_unlock (); +return nr; }
Another opportunity for guard(rcu)():
static unsigned long keyring_nr_links(const struct key *keyring)
{
const struct keyring_index *links;
guard(rcu)();
links = rcu_dereference(keyring->links);
return links ? READ_ONCE(links->nr) : 0;
}Quoted 6 lines
/*
* Search inside a keyring for a key. We can search by walking to it
* directly based on its index-key or we can iterate over the entire
* tree looking for it, based on the match function.
*/
static intsearch_keyring(struct key *keyring, struct keyring_search_context *ctx)
"entire tree" => "entire keyring", given that it seemed to be referring to the implementation detail of the assoc_array being a tree.
On the topic of outdated comments, two comments also mention -ENFILE being the error for when the keyring is full. That's been outdated for over a decade: there's no concept of a keyring being "full".
security/keys/keyring.c static int keyring_search_iterator(const void *object, void *iterator_data) · line 704
Quoted 6 lines
security/keys/keyring.c +6
-0+ link =keyring_find_link (rcu_dereference (keyring->links), + &ctx->index_key); +if (!link) +return 0 ; + key =keyring_link_key (link); +return key ? ctx->iterator (key, ctx) :0 ;
Checking 'key' for NULL here is unnecessary, since keyring_find_link() only matches a keyring_link that has a non-NULL key pointer.
Quoted 12 lines
security/keys/keyring.c +1
-1@@ -1123,8 +1055,8 @@ EXPORT_SYMBOL(keyring_restrict);key_ref_t find_key_to_update (key_ref_t keyring_ref,const struct keyring_index_key *index_key) { +struct keyring_link *link;struct key *keyring, *key; -const void *object; keyring =key_ref_to_ptr (keyring_ref);@@ -1132,17 +1064,15 @@ key_ref_t find_key_to_update(key_ref_t keyring_ref, keyring->serial, index_key->type->name, index_key->description);
security/keys/keyring.c key_ref_t find_key_to_update(key_ref_t keyring_ref, · line 1070
Quoted 10 lines
security/keys/keyring.c +3
-4guard (rcu)(); - object =assoc_array_find (&keyring->keys, &keyring_assoc_array_ops, - index_key); - -if (object) + link =keyring_find_link (rcu_dereference (keyring->links), index_key); + key = link ?keyring_link_key (link) :NULL ; +if (key) goto found;
Similarly here. Checking 'key' for NULL is unnecessary and this could be:
if (link) {
key = keyring_link_key(link);
goto found;
}Quoted 7 lines
security/keys/keyring.c +0
-0/** * key_unlink - Unlink the first link to a key from a keyring. * @keyring: The keyring to remove the link from. @@ -1576,7 +1557,7 @@ static void __key_unlink_end(struct key *keyring,* Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if * the key isn't linked to by the keyring or -ENOMEM if there's insufficient * memory.
[..]
Quoted 2 lines
*/
intkey_unlink(struct key *keyring, struct key *key)
-ENOMEM is no longer a possible error from key_unlink(), since this patch fixes the design to no longer need memory allocations for unlinks.
Quoted 8 lines
void
keyring_gc(struct key *keyring, time64_t limit){security/keys/keyring.c +2
-0+struct keyring_index *links; +struct keyring_link *link, *tmp;int result;kenter ("%x{%s}" , keyring->serial, keyring->description ?:"" );
security/keys/keyring.c void keyring_gc(struct key *keyring, time64_t limit) · line 1716
Quoted 10 lines
security/keys/keyring.c +1
-4@@ -1756,10 +1711,7 @@ void keyring_gc(struct key *keyring, time64_t limit) goto dont_gc;/* scan the keyring looking for dead keys */ -rcu_read_lock (); - result =assoc_array_iterate (&keyring->keys, - keyring_gc_check_iterator, &limit); -rcu_read_unlock (); + result =keyring_iterate (keyring, keyring_gc_check_iterator, &limit);if (result == true) goto do_gc;
As long as this line is being changed, probably should remove the weird comparison of an int to 'true':
if (keyring_iterate(keyring, keyring_gc_check_iterator, &limit)) goto do_gc;
security/keys/keyring.c void keyring_gc(struct key *keyring, time64_t limit) · line 1724
Quoted 9 lines
security/keys/keyring.c +1
-4@@ -1769,10 +1721,11 @@ void keyring_gc(struct key *keyring, time64_t limit) do_gc:down_write (&keyring->sem); -assoc_array_gc (&keyring->keys, &keyring_assoc_array_ops, - keyring_gc_select_iterator, &limit); -key_payload_reserve (keyring, - keyring->keys.nr_leaves_on_tree *KEYQUOTA_LINK_BYTES ); + links =keyring_index_locked (keyring);
Would be worth leaving a comment here:
/* links != NULL here, since at least one link was found. */
- Eric
Jarkko Sakkinen
maintainerRe: [RFC PATCH 5/6] KEYS: Replace assoc_array with struct keyring_index
Quoted 6 lines · Eric Biggers
Thanks, this generally looks good.
I was tempted to recommend a custom hashtable, instead of rhashtable plus the two lists alongside it, to save memory and avoid the rhashtable dependency. Especially given that the keyrings subsystem already uses its own lock for writes, so the rhashtable bucket locks are wasted.
I get your point here and actually keep this in mind. Did not cross my mind by I get where this is coming from.
The logic translates easily to some other data structure if this comes up again.
Quoted 30 lines
But ultimately I think I lean towards the rhashtable plus the two lists, as this patch does. It's slightly less code, it allows the hash table to be shrunk (whereas custom solution would likely be grow-only), and it continues to allow iterating over just the keyrings in a keyring without traversing every key in that keyring.
Quoted 5 lines · Jarkko Sakkinen
Linux keyring would be better off without struct
assoc_arraygiven the overhead caused by sole ownership of it. Linux has multiple popular choices for key-value store and there is nothing special inlib/assoc_array.cthat would make it stand out enough to be ratiaonalize the time spent on maintaining it."to be ratiaonalize" => "to rationalize"
Quoted 11 lines
/*
- * We mark pointers we pass to the associative array with bit 1 set if
- * they're keyrings and clear otherwise.
+ * The contents of a keyring, allocated when the first link is made.
+ *
+ * Modified only withkeyring->semwrite-locked; read under RCU. @ht indexes
+ * the links by index key, for direct lookup. @all holds every committed link
+ * and @keyrings the committed links to keyrings, for iteration: an RCU walk of
+ * a list sees every entry that stays on it for the duration of the walk, which
+ * a walk of @ht racing with a resize does not.
+ */"which a walk of @ht" => "while a walk of ht"
Quoted 7 lines
Quoted 4 lines
+ * ->hash is copied from the index key at
__key_link_begin()and never changes,
+ * so the hash table can rehash the link without looking at the key, whose
+ * type the garbage collector may change (key_type_dead).
+structkeyring_link{This explanation seems inaccurate. The actual reason ->hash is needed is because reserved links can be inserted while ->key is still NULL.
I will do a full rewrite. I don't get anything out of that either other than there's a lot of text.
LLMs honestly are incredibly bad documenting anything.
Quoted 12 lines
security/keys/keyring.c line 68
Quoted 8 lines
security/keys/keyring.c +7
-0+struct rhash_head node; +struct key __rcu *key;/* NULL while reserved */ +unsigned long hash; +struct list_head all_link;/* in keyring_index::all */ +struct list_head keyrings_link;/* in keyring_index::keyrings */ +struct keyring_link *replaces;/* Link this one replaces, or NULL */ +bool is_keyring;Make 'hash' u32 and make it adjacent to '
is_keyring' to get rid of the hole?
Quoted 8 lines
Or at least make it u64, given that it's a SipHash value.
But it ultimately just gets combined with the rhashtable seed to produce a 32-bit hash anyway, so u32 is enough. (Then in
keyring_hashfn()andkeyring_obj_hashfn(), usejhash_1word()instead ofjhash_2word().)'unsigned long' doesn't make much sense and seems to just be a holdover from the
assoc_arraybased code.
It does not and yeah I consider the options. I'll also go through structs declared and do at least best effort in ordering as per memory alignment (if possible only tail padding).
Quoted 10 lines
Quoted 10 lines
security/keys/keyring.c +9
-0+/* +* Pass each key linked from a keyring to @iterator until it returns non-zero. +* Returns the last value @iterator returned, or 0 if the keyring is empty. +* Concurrent links and unlinks may be seen or not; a key that stays linked +* throughout is passed to @iterator. +*/ +static int keyring_iterate (const struct key *keyring, +int (*iterator)(const struct key *key,void *data), +void *data)
Quoted 8 lines
security/keys/keyring.c line 156
Quoted 6 lines
security/keys/keyring.c +6
-0+{ +struct keyring_index *links; +struct keyring_link *link; +int ret =0 ; + +rcu_read_lock ();guard(rcu)()
And in general I check where I could use cleanup.h more. I keep this mind :-)
Quoted 13 lines
security/keys/keyring.c line 166
Quoted 11 lines
security/keys/keyring.c +10
-0+ links =rcu_dereference (keyring->links); +if (links) { +list_for_each_entry_rcu (link, &links->all, all_link) { + ret =iterator (keyring_link_key (link), data); +if (ret) +break ; + } + } +rcu_read_unlock (); +return ret;... then 'return ret' in the loop, and 'return 0' at the end
I fully got this and agree.
Quoted 78 lines
Quoted 27 lines
security/keys/keyring.c +0
-26-/* -* Build the next index key chunk. -* -* The hash and inline description are followed by the 64-bit type and domain -* IDs, low word first, and then by the rest of the description. -* We return it one word-sized chunk at a time. -*/ -static unsigned long keyring_get_key_chunk (const void *data,int level) -{ -const unsigned int id_chunks =sizeof (u64) /sizeof (unsigned long ); -const struct keyring_index_key *index_key = data; -int desc_len = index_key->desc_len; -unsigned long chunk =0 ; -int n =sizeof (chunk); -unsigned int offset; -const u8 *d; - - level /=ASSOC_ARRAY_KEY_CHUNK_SIZE ; -switch (level) { -case 0 : -return index_key->hash; -case 1 : -return index_key->x; - } - - level -=2 ;security/keys/keyring.c void key_remove_domain(struct key_tag *domain_tag) · line 306
Quoted 10 lines
security/keys/keyring.c +0
-10-if (level < id_chunks) -return index_key->type_id >> (level *ASSOC_ARRAY_KEY_CHUNK_SIZE ); - level -= id_chunks; -if (level < id_chunks) -return index_key->domain_id >> (level *ASSOC_ARRAY_KEY_CHUNK_SIZE ); - level -= id_chunks; - - offset =sizeof (index_key->desc) + level *sizeof (long ); -if (desc_len <= offset) -return 0 ;With
type_idanddomain_idno longer being used directly as part of a radix tree key, they're no longer actually needed at all. Provided that we continue to use SipHash (or another cryptographically secure PRF) with a random key, using the pointers directly (as was done originally) no longer leaks kernel addresses. E.g., we can just do:/* Finalize an index key: set the domain tag and calculate the hash. */ void key_set_index_key(struct keyring_index_key *index_key) { static struct key_tag default_domain_tag = { .usage = REFCOUNT_INIT(1), }; static siphash_key_t hash_key __read_mostly; u64 acc; if (!index_key->domain_tag) { if (index_key->type->flags & KEY_TYPE_NET_DOMAIN) index_key->domain_tag = current->nsproxy->net_ns->key_domain; else index_key->domain_tag = &default_domain_tag; } get_random_once(&hash_key, sizeof(hash_key)); /* * Compute a SipHash value of the description, type pointer, and domain * tag pointer using a per-boot random key. * * Note that using the pointers as input to the hash is safe, since * SipHash is a cryptographically secure pseudorandom function. Thus * the hash values don't leak any information about the pointers. * * Similarly, truncating the SipHash values to the required 32 bits is * also safe. No "folding" step is needed. */ acc = siphash(index_key->description, index_key->desc_len, &hash_key); acc = siphash_3u64((unsigned long)index_key->type, (unsigned long)index_key->domain_tag, acc, &hash_key); index_key->hash = (u32)acc; }
Quoted 7 lines
... and remove the
type_idanddomain_idfields.Might be worth folding this into "keys: make keyring indexes independent of kernel addresses" actually, since otherwise this just supersedes all of that commit except for the introduction of SipHash. And I guess this commit will end up needing to be backported anyway, since otherwise
assoc_arraybugs will be unfixed in stable.
With quick skim, I agree. Thanks for the snippet!
Quoted 18 lines
Quoted 5 lines
security/keys/keyring.c +4
-0+/* +* The number of links in a keyring. +*/ +static unsigned long keyring_nr_links (const struct key *keyring)security/keys/keyring.c static void keyring_destroy(struct key *keyring) · line 469
Quoted 10 lines
security/keys/keyring.c +9
-0+{ +const struct keyring_index *links; +unsigned long nr; + +rcu_read_lock (); + links =rcu_dereference (keyring->links); + nr = links ?READ_ONCE (links->nr) :0 ; +rcu_read_unlock (); +return nr; }Another opportunity for guard(rcu)():
Quoted 8 lines
static unsigned long keyring_nr_links(const struct key *keyring)
{
const struct keyring_index *links;
guard(rcu)();
links = rcu_dereference(keyring->links);
return links ? READ_ONCE(links->nr) : 0;
}+1
Quoted 8 lines
Quoted 7 lines
/*
* Search inside a keyring for a key. We can search by walking to it
* directly based on its index-key or we can iterate over the entire
* tree looking for it, based on the match function.
*/
static intsearch_keyring(struct key *keyring, struct keyring_search_context *ctx)
Quoted 6 lines
"entire tree" => "entire keyring", given that it seemed to be referring to the implementation detail of the
assoc_arraybeing a tree.On the topic of outdated comments, two comments also mention
-ENFILEbeing the error for when the keyring is full. That's been outdated for over a decade: there's no concept of a keyring being "full".
I mark this also as "rewrite the comment".
Quoted 10 lines
security/keys/keyring.c static int keyring_search_iterator(const void *object, void *iterator_data) · line 704
Quoted 7 lines
security/keys/keyring.c +6
-0+ link =keyring_find_link (rcu_dereference (keyring->links), + &ctx->index_key); +if (!link) +return 0 ; + key =keyring_link_key (link); +return key ? ctx->iterator (key, ctx) :0 ;Checking 'key' for NULL here is unnecessary, since
keyring_find_link()only matches akeyring_linkthat has a non-NULL key pointer.
+1
Quoted 27 lines
Quoted 13 lines
security/keys/keyring.c +1
-1@@ -1123,8 +1055,8 @@ EXPORT_SYMBOL(keyring_restrict);key_ref_t find_key_to_update (key_ref_t keyring_ref,const struct keyring_index_key *index_key) { +struct keyring_link *link;struct key *keyring, *key; -const void *object; keyring =key_ref_to_ptr (keyring_ref);@@ -1132,17 +1064,15 @@ key_ref_t find_key_to_update(key_ref_t keyring_ref, keyring->serial, index_key->type->name, index_key->description);security/keys/keyring.c key_ref_t find_key_to_update(key_ref_t keyring_ref, · line 1070
Quoted 10 lines
security/keys/keyring.c +3
-4guard (rcu)(); - object =assoc_array_find (&keyring->keys, &keyring_assoc_array_ops, - index_key); - -if (object) + link =keyring_find_link (rcu_dereference (keyring->links), index_key); + key = link ?keyring_link_key (link) :NULL ; +if (key) goto found;Similarly here. Checking 'key' for NULL is unnecessary and this could be:
Quoted 4 lines
if (link) {
key = keyring_link_key(link);
goto found;
}+1
Quoted 9 lines
Quoted 8 lines
security/keys/keyring.c +0
-0/** * key_unlink - Unlink the first link to a key from a keyring. * @keyring: The keyring to remove the link from. @@ -1576,7 +1557,7 @@ static void __key_unlink_end(struct key *keyring,* Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if * the key isn't linked to by the keyring or -ENOMEM if there's insufficient * memory. [..]
Quoted 5 lines
Quoted 2 lines
*/
intkey_unlink(struct key *keyring, struct key *key)
-ENOMEMis no longer a possible error fromkey_unlink(), since this patch fixes the design to no longer need memory allocations for unlinks.
+1
And a surgical catch :-)
Quoted 23 lines
Quoted 9 lines
void
keyring_gc(struct key *keyring, time64_t limit){security/keys/keyring.c +2
-0+struct keyring_index *links; +struct keyring_link *link, *tmp;int result;kenter ("%x{%s}" , keyring->serial, keyring->description ?:"" );security/keys/keyring.c void keyring_gc(struct key *keyring, time64_t limit) · line 1716
Quoted 10 lines
security/keys/keyring.c +1
-4@@ -1756,10 +1711,7 @@ void keyring_gc(struct key *keyring, time64_t limit) goto dont_gc;/* scan the keyring looking for dead keys */ -rcu_read_lock (); - result =assoc_array_iterate (&keyring->keys, - keyring_gc_check_iterator, &limit); -rcu_read_unlock (); + result =keyring_iterate (keyring, keyring_gc_check_iterator, &limit);if (result == true) goto do_gc;As long as this line is being changed, probably should remove the weird comparison of an int to 'true':
Quoted 2 lines
if (keyring_iterate(keyring, keyring_gc_check_iterator, &limit)) goto do_gc;
+1
Quoted 13 lines
security/keys/keyring.c void keyring_gc(struct key *keyring, time64_t limit) · line 1724
Quoted 10 lines
security/keys/keyring.c +1
-4@@ -1769,10 +1721,11 @@ void keyring_gc(struct key *keyring, time64_t limit) do_gc:down_write (&keyring->sem); -assoc_array_gc (&keyring->keys, &keyring_assoc_array_ops, - keyring_gc_select_iterator, &limit); -key_payload_reserve (keyring, - keyring->keys.nr_leaves_on_tree *KEYQUOTA_LINK_BYTES ); + links =keyring_index_locked (keyring);Would be worth leaving a comment here:
Quoted 1 line
/* links != NULL here, since at least one link was found. */
+1
Quoted 2 lines
- Eric
Hey, this was very useful, thanks. I've already polished the patch where I see low-hanging fruit. I've split the bug fixes perhaps a bit over the top because I've noticed that unchecked LLM bug fixes are surpsingly often not that great. They are often short circuited to the nearest surface, instead of thinking the overall vector.
I go all comments through that are added or modified. Especially with LLM originated code it is a one place to do a sanity check for yourself whether you are actually reading the code or not.
LLMs feel in kernel development more like a power tool than an assistant. I can make big holes fast but that does not take care of the "precission work".
Br, Jarkko
Jarkko Sakkinen
maintainerRe: [RFC PATCH 5/6] KEYS: Replace assoc_array with struct keyring_index
Quoted 10 lines · Jarkko Sakkinen
Quoted 2 lines
- Eric
Hey, this was very useful, thanks. I've already polished the patch where I see low-hanging fruit. I've split the bug fixes perhaps a bit over the top because I've noticed that unchecked LLM bug fixes are surpsingly often not that great. They are often short circuited to the nearest surface, instead of thinking the overall vector.
Quoted 7 lines
I go all comments through that are added or modified. Especially with LLM originated code it is a one place to do a sanity check for yourself whether you are actually reading the code or not.
LLMs feel in kernel development more like a power tool than an assistant. I can make big holes fast but that does not take care of the "precission work".
Right the patch lacks your suggested-by :-) I'll add it. It was actually unintentionally forgotten.
Br, Jarkko
David Howells
maintainerRe: [RFC PATCH 5/6] KEYS: Replace assoc_array with struct keyring_index
In reply to Jarkko SakkinenQuoted 6 lines · Jarkko Sakkinen
Maintain two linked lists in the index:
- all: enumerate committed links without retrying hash table walks when the table resizes.
- keyrings: visit nested keyrings during recursive search without scanning links to other key types.
Do you actually need two lists? Can you just "sort" the list to put all the keyrings first?
include/linux/key.h struct key { · line 260
Quoted 1 line
include/linux/key.h +1
-0+struct keyring_index __rcu *links;
Does that actually need an __rcu mark? Is it going to get replaced once allocated?
security/keys/internal.h extern int __key_link_lock(struct key *keyring, · line 100
Quoted 2 lines
security/keys/internal.h +2
-0+struct keyring_link ; +
Somewhere near the top of internal.h, please, not sandwiched in the middle of some func declarations.
security/keys/keyring.c line 18
Quoted 8 lines
security/keys/keyring.c +2
-0@@ -14,12 +14,12 @@#include <linux/err.h> #include <linux/user_namespace.h> #include <linux/nsproxy.h> +#include <keys/keyring-type.h> +#include <keys/user-type.h>
Why #include user-type.h here?
security/keys/keyring.c line 46
Quoted 5 lines
security/keys/keyring.c +5
-0+struct keyring_index { +struct rhashtable ht; +struct list_head all; +struct list_head keyrings; +unsigned long nr;/* Number of committed links */
Given key->serial is 1-INT_MAX, nr probably doesn't need to be unsigned long - otoh, it's not likely to leave a hole, I guess.
security/keys/keyring.c line 61
Quoted 1 line
security/keys/keyring.c +1
-0+struct keyring_link {
I wonder if keyring_entry would be a better name, but the docs do mention making and removing links.
security/keys/keyring.c line 69
Quoted 3 lines
security/keys/keyring.c +2
-0+unsigned long hash; +struct rcu_head rcu;
Can they be in a union? And I would put rcu first as I think there are (or maybe used to be) some things that required it to be first.
security/keys/keyring.c line 66
Quoted 1 line
security/keys/keyring.c +1
-0+struct list_head keyrings_link;/* in keyring_index::keyrings */
This may be unnecessary if you can put keyrings at the front of the list.
security/keys/keyring.c line 67
Quoted 1 line
security/keys/keyring.c +1
-0+struct keyring_link *replaces;/* Link this one replaces, or NULL */
Please don't put this in keyring_link. It's only needed by __key_link() and friends and could be passed around in a context struct as the edit script is done now:
struct keyring_link_context {
struct keyring_link *spare; /* Spare link block */
struct keyring_link *replace; /* Link being replaced */
};then:
int __key_link_begin(struct key *keyring,
const struct keyring_index_key *index_key,
- struct assoc_array_edit **_edit)
+ struct keyring_link_context **_edit)
Quoted 10 lines
security/keys/keyring.c +10
-0+/* +* Remove every link from a keyring. The caller holds keyring->sem +* write-locked. A concurrent RCU reader can see some of the links gone and +* others not yet. +*/ +static void keyring_remove_all_links (struct key *keyring) +{ +struct keyring_index *links =keyring_index_locked (keyring); +struct keyring_link *link, *tmp; +
security/keys/keyring.c
Quoted 10 lines
security/keys/keyring.c +5
-0+if (!links) +return ; +list_for_each_entry_safe (link, tmp, &links->all, all_link) +keyring_remove_link (links, link); }int keyring_clear (struct key *keyring) { +keyring_remove_all_links (keyring);
This can be made atomic by replacing the key->links pointer value with NULL (since key->links is marked __rcu), then destroying the content afterwards.
David
Jarkko Sakkinen
maintainerRe: [RFC PATCH 5/6] KEYS: Replace assoc_array with struct keyring_index
Quoted 92 lines · David Howells
Quoted 6 lines · Jarkko Sakkinen
Maintain two linked lists in the index:
- all: enumerate committed links without retrying hash table walks when the table resizes.
- keyrings: visit nested keyrings during recursive search without scanning links to other key types.Do you actually need two lists? Can you just "sort" the list to put all the keyrings first?
include/linux/key.h struct key { · line 260
Quoted 1 line
include/linux/key.h +1
-0+struct keyring_index __rcu *links;Does that actually need an
__rcumark? Is it going to get replaced once allocated?security/keys/internal.h extern int __key_link_lock(struct key *keyring, · line 100
Quoted 2 lines
security/keys/internal.h +2
-0+struct keyring_link ; +Somewhere near the top of
internal.h, please, not sandwiched in the middle of some func declarations.security/keys/keyring.c line 18
Quoted 8 lines
security/keys/keyring.c +2
-0@@ -14,12 +14,12 @@#include <linux/err.h> #include <linux/user_namespace.h> #include <linux/nsproxy.h> +#include <keys/keyring-type.h> +#include <keys/user-type.h> Why #include
user-type.hhere?security/keys/keyring.c line 46
Quoted 5 lines
security/keys/keyring.c +5
-0+struct keyring_index { +struct rhashtable ht; +struct list_head all; +struct list_head keyrings; +unsigned long nr;/* Number of committed links */ Given
key->serialis 1-INT_MAX, nr probably doesn't need to be unsigned long - otoh, it's not likely to leave a hole, I guess.security/keys/keyring.c line 61
Quoted 1 line
security/keys/keyring.c +1
-0+struct keyring_link {I wonder if
keyring_entrywould be a better name, but the docs do mention making and removing links.security/keys/keyring.c line 69
Quoted 3 lines
security/keys/keyring.c +2
-0+unsigned long hash; +struct rcu_head rcu;Can they be in a union? And I would put rcu first as I think there are (or maybe used to be) some things that required it to be first.
security/keys/keyring.c line 66
Quoted 1 line
security/keys/keyring.c +1
-0+struct list_head keyrings_link;/* in keyring_index::keyrings */ This may be unnecessary if you can put keyrings at the front of the list.
security/keys/keyring.c line 67
Quoted 1 line
security/keys/keyring.c +1
-0+struct keyring_link *replaces;/* Link this one replaces, or NULL */ Please don't put this in
keyring_link. It's only needed by__key_link()and friends and could be passed around in a context struct as the edit script is done now:struct keyring_link_context { struct keyring_link *spare; /* Spare link block */ struct keyring_link *replace; /* Link being replaced */ };then:
int __key_link_begin(struct key *keyring,
const structkeyring_index_key*index_key,
- structassoc_array_edit**_edit)
+ structkeyring_link_context**_edit)Quoted 15 lines
security/keys/keyring.c +14
-0+/* +* Remove every link from a keyring. The caller holds keyring->sem +* write-locked. A concurrent RCU reader can see some of the links gone and +* others not yet. +*/ +static void keyring_remove_all_links (struct key *keyring) +{ +struct keyring_index *links =keyring_index_locked (keyring); +struct keyring_link *link, *tmp; + +if (!links) +return ; +list_for_each_entry_safe (link, tmp, &links->all, all_link) +keyring_remove_link (links, link); }
Quoted 8 lines
security/keys/keyring.c
Quoted 5 lines
...
intkeyring_clear(struct key *keyring)
{
...security/keys/keyring.c +1
-0+keyring_remove_all_links (keyring);This can be made atomic by replacing the
key->linkspointer value with NULL (sincekey->linksis marked__rcu), then destroying the content afterwards.
Great remarks. I'll try to address them all together when I address Eric's remarks and there's been a few cleanups I've made. I'll fuse this all together but there's one thing.
I just sent a patch set, which is a result of going through the head of the patch set and hand-crafted bug fixes that make sense and dropped false positives. If we could get those ack'd soon I could then iterate a cleaner version of this patch set.
Quoted 3 lines
David
Br, Jarkko
David Howells
maintainerRe: [RFC PATCH 6/6] lib: Remove unused assoc_array
In reply to Jarkko SakkinenQuoted 1 line · Jarkko Sakkinen
Drop the obsolete leaf-count reference from a dm-verity test comment.
This might need reworking as a commit message...
David
Jarkko Sakkinen
maintainerRe: [RFC PATCH 6/6] lib: Remove unused assoc_array
Quoted 5 lines · David Howells
Quoted 1 line · Jarkko Sakkinen
Drop the obsolete leaf-count reference from a dm-verity test comment.
This might need reworking as a commit message...
Agreed.
Quoted 3 lines
David
Br, Jarkko
Jarkko Sakkinen
maintainerRe: [RFC PATCH 5/6] KEYS: Replace assoc_array with struct keyring_index
In reply to Jarkko SakkinenQuoted 26 lines · Jarkko Sakkinen
Linux keyring would be better off without struct
assoc_arraygiven the overhead caused by sole ownership of it. Linux has multiple popular choices for key-value store and there is nothing special inlib/assoc_array.cthat would make it stand out enough to be ratiaonalize the time spent on maintaining it.A keyring has a sparse data population, making rhashtable a plausible choice. Multiple subsystems rely on it, and best of all, rhashtable has dedicated maintainers.
Replace
assoc_arraywith structkeyring_index, allocated for a keyring on its first link attempt. Initialize its ht member withrhashtable_init()to store links indexed by key type, domain tag and description.Maintain two linked lists in the index:
- all: enumerate committed links without retrying hash table walks when the table resizes.
- keyrings: visit nested keyrings during recursive search without scanning links to other key types.A key can belong to several keyrings. Represent each link with struct
keyring_linkso it has separate hash table and list nodes and holds its own key reference. Traverse the lists under RCU and defer freeing removed links and dropping their key references until after a grace period.
Quoted 4 lines
Assisted-by LLMCo-developed-by Linus Torvalds <[email protected]>Signed-off-by Linus Torvalds <[email protected]>Signed-off-by Jarkko Sakkinen <[email protected]>
In addition to addressing Eric's and David's comments, I'll align the change with Kyle's fix (and rewrite the commit message).
Br, Jarkko
Jarkko Sakkinen
maintainerRe: [RFC PATCH 5/6] KEYS: Replace assoc_array with struct keyring_index
Quoted 27 lines · Jarkko Sakkinen
Quoted 26 lines · Jarkko Sakkinen
Linux keyring would be better off without struct
assoc_arraygiven the overhead caused by sole ownership of it. Linux has multiple popular choices for key-value store and there is nothing special inlib/assoc_array.cthat would make it stand out enough to be ratiaonalize the time spent on maintaining it.A keyring has a sparse data population, making rhashtable a plausible choice. Multiple subsystems rely on it, and best of all, rhashtable has dedicated maintainers.
Replace
assoc_arraywith structkeyring_index, allocated for a keyring on its first link attempt. Initialize its ht member withrhashtable_init()to store links indexed by key type, domain tag and description.Maintain two linked lists in the index:
- all: enumerate committed links without retrying hash table walks when the table resizes.
- keyrings: visit nested keyrings during recursive search without scanning links to other key types.A key can belong to several keyrings. Represent each link with struct
keyring_linkso it has separate hash table and list nodes and holds its own key reference. Traverse the lists under RCU and defer freeing removed links and dropping their key references until after a grace period.
Quoted 7 lines
Quoted 4 lines
Assisted-by LLMCo-developed-by Linus Torvalds <[email protected]>Signed-off-by Linus Torvalds <[email protected]>Signed-off-by Jarkko Sakkinen <[email protected]>In addition to addressing Eric's and David's comments, I'll align the change with Kyle's fix (and rewrite the commit message).
This turned out not to be difficult. I just purposely had retained the original behavior of the this patch when I rebased it yesterday until I had my keyring PR out so could not know :-)
Kyle's fix came at really great spot because if it had came after this feature had landed stable kernels would need a different fix than the mainline (given that they build on top of different data structures).
Br, Jarkko
Jarkko Sakkinen
maintainerRe: [RFC PATCH 5/6] KEYS: Replace assoc_array with struct keyring_index
In reply to David HowellsQuoted 9 lines · David Howells
Please don't put this in
keyring_link. It's only needed by__key_link()and friends and could be passed around in a context struct as the edit script is done now:struct keyring_link_context { struct keyring_link *spare; /* Spare link block */ struct keyring_link *replace; /* Link being replaced */ };
Quoted 6 lines
then:
int __key_link_begin(struct key *keyring,
const structkeyring_index_key*index_key,
- structassoc_array_edit**_edit)
+ structkeyring_link_context**_edit)
Hmm... I think it would be more transparent to pass two element array than declare a struct here. It does not do a lot and makes the code just require more cross-referencing.
I'm not fighting over this detail but even when I look at the patch the struct makes it more confusing to proof-read.
Br, Jarkko
Jarkko Sakkinen
maintainerRe: [RFC PATCH 5/6] KEYS: Replace assoc_array with struct keyring_index
In reply to Eric BiggersQuoted 2 lines · Eric Biggers
Make 'hash' u32 and make it adjacent to '
is_keyring' to get rid of the hole?
The whole 'is_keyring' is completely redundant and more like a glitch in this RFC patch (equal to key->type == &key_type_keyring).
Nothing wrong in the review comment. I just wanted to remark this dead obvious fact that I should noticed immediately (doing updates ATM) :-)
Br, Jarkko
Jarkko Sakkinen
maintainerRe: [RFC PATCH 5/6] KEYS: Replace assoc_array with struct keyring_index
In reply to Jarkko SakkinenQuoted 26 lines · Jarkko Sakkinen
Linux keyring would be better off without struct
assoc_arraygiven the overhead caused by sole ownership of it. Linux has multiple popular choices for key-value store and there is nothing special inlib/assoc_array.cthat would make it stand out enough to be ratiaonalize the time spent on maintaining it.A keyring has a sparse data population, making rhashtable a plausible choice. Multiple subsystems rely on it, and best of all, rhashtable has dedicated maintainers.
Replace
assoc_arraywith structkeyring_index, allocated for a keyring on its first link attempt. Initialize its ht member withrhashtable_init()to store links indexed by key type, domain tag and description.Maintain two linked lists in the index:
- all: enumerate committed links without retrying hash table walks when the table resizes.
- keyrings: visit nested keyrings during recursive search without scanning links to other key types.A key can belong to several keyrings. Represent each link with struct
keyring_linkso it has separate hash table and list nodes and holds its own key reference. Traverse the lists under RCU and defer freeing removed links and dropping their key references until after a grace period.
Quoted 4 lines
Assisted-by LLMCo-developed-by Linus Torvalds <[email protected]>Signed-off-by Linus Torvalds <[email protected]>Signed-off-by Jarkko Sakkinen <[email protected]>
For the functions introduced, I'll also use cleanup.h primitives to cover all fallible initializations. This is something that I don't recall seeing in the review comments, and it is a nice extra safety measure when landing a refactor like this.
Br, Jarkko