AI Trajectory


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

Results:
{
  "EnableConfigs": [
    "KEYS"
  ],
  "FocusSymbols": [
    "key_link",
    "key_unlink",
    "key_move",
    "keyring_clear",
    "keyring_gc",
    "keyring_read",
    "search_nested_keyrings",
    "find_key_to_update",
    "keyring_is_empty",
    "__key_link_begin",
    "__key_link",
    "__key_link_end"
  ],
  "KMSANReasoning": "The patch series completely removes the generic associative array (`assoc_array`) data structure and replaces its usage in the keys subsystem (`security/keys/keyring.c`) with a combination of `rhashtable` and `list_head`.\n\nEvaluation of uninitialized memory and info-leak risks:\n1. Memory Allocation: All newly introduced heap structures (`struct keyring_index` and `struct keyring_link`) are allocated using `kzalloc_obj()`, ensuring all fields and padding are zero-initialized before insertion into the hash table or list.\n2. Stack Initialization: All stack variables of `struct keyring_edit` and link pointers introduced across `key.c`, `keyring.c`, and `request_key.c` are explicitly zero-initialized (`= {}` or `= NULL`).\n3. User-space Exposure: Keyring listing (`keyring_read`) iterates through active keys and writes `key_serial_t` scalars into the provided buffer up to `links-\u003enr` entries, leaving no uninitialized buffer bytes or padding copied to user space.\n4. Structure Redesign: The simplified `struct keyring_index_key` removes the previous union containing partial description bytes and replaces ad-hoc index IDs with direct SipHash hashing of initialized pointers and description data.\n\nKASAN vs. KMSAN Applicability:\n- The risks introduced by this change involve concurrent RCU iteration and mutation (`rhashtable_replace_fast`, `list_replace_rcu`, `call_rcu`), rwsem lock synchronization (`keyring-\u003esem`), key reference counting (`key_get`, `key_put`), and pointer dereferences.\n- These issues are comprehensively covered by standard KASAN (use-after-free, double-free), LOCKDEP (locking violations), and general kernel assertions.\n- There are no uninitialized memory reads, uninitialized branch conditions, or kernel-to-user info-leaks that would necessitate a dedicated KMSAN fuzzing session.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch series removes the generic associative array (assoc_array) implementation and replaces the internal keyring indexing mechanism in the keys subsystem with an rhashtable and RCU-protected linked list. This refactors core data structures and concurrency/locking logic in reachable security/keys code, directly accessible via keyctl, add_key, and request_key syscalls. Hence, it is worth fuzzing.",
  "WorthFuzzing": true
}

1/1 2026/11/10 21:40 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 9b677570f5d4a445ef4a8b94fb6e5bf96ecddb01\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Tue Nov 10 21:40:32 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/core-api/assoc_array.rst b/Documentation/core-api/assoc_array.rst\ndeleted file mode 100644\nindex 19d89f92bf8da8..00000000000000\n--- a/Documentation/core-api/assoc_array.rst\n+++ /dev/null\n@@ -1,564 +0,0 @@\n-========================================\n-Generic Associative Array Implementation\n-========================================\n-\n-Overview\n-========\n-\n-This associative array implementation is an object container with the following\n-properties:\n-\n-1. Objects are opaque pointers.  The implementation does not care where they\n-   point (if anywhere) or what they point to (if anything).\n-\n-   .. note::\n-\n-      Pointers to objects _must_ be zero in the least significant bit.\n-\n-2. Objects do not need to contain linkage blocks for use by the array.  This\n-   permits an object to be located in multiple arrays simultaneously.\n-   Rather, the array is made up of metadata blocks that point to objects.\n-\n-3. Objects require index keys to locate them within the array.\n-\n-4. Index keys must be unique.  Inserting an object with the same key as one\n-   already in the array will replace the old object.\n-\n-5. Index keys can be of any length and can be of different lengths.\n-\n-6. Index keys should encode the length early on, before any variation due to\n-   length is seen.\n-\n-7. Index keys can include a hash to scatter objects throughout the array.\n-\n-8. The array can iterated over.  The objects will not necessarily come out in\n-   key order.\n-\n-9. The array can be iterated over while it is being modified, provided the\n-   RCU readlock is being held by the iterator.  Note, however, under these\n-   circumstances, some objects may be seen more than once.  If this is a\n-   problem, the iterator should lock against modification.  Objects will not\n-   be missed, however, unless deleted.\n-\n-10. Objects in the array can be looked up by means of their index key.\n-\n-11. Objects can be looked up while the array is being modified, provided the\n-    RCU readlock is being held by the thread doing the look up.\n-\n-The implementation uses a tree of 16-pointer nodes internally that are indexed\n-on each level by nibbles from the index key in the same manner as in a radix\n-tree.  To improve memory efficiency, shortcuts can be emplaced to skip over\n-what would otherwise be a series of single-occupancy nodes.  Further, nodes\n-pack leaf object pointers into spare space in the node rather than making an\n-extra branch until as such time an object needs to be added to a full node.\n-\n-\n-The Public API\n-==============\n-\n-The public API can be found in ``\u003clinux/assoc_array.h\u003e``.  The associative\n-array is rooted on the following structure::\n-\n-    struct assoc_array {\n-            ...\n-    };\n-\n-The code is selected by enabling ``CONFIG_ASSOCIATIVE_ARRAY`` with::\n-\n-    ./script/config -e ASSOCIATIVE_ARRAY\n-\n-\n-Edit Script\n------------\n-\n-The insertion and deletion functions produce an 'edit script' that can later be\n-applied to effect the changes without risking ``ENOMEM``. This retains the\n-preallocated metadata blocks that will be installed in the internal tree and\n-keeps track of the metadata blocks that will be removed from the tree when the\n-script is applied.\n-\n-This is also used to keep track of dead blocks and dead objects after the\n-script has been applied so that they can be freed later.  The freeing is done\n-after an RCU grace period has passed - thus allowing access functions to\n-proceed under the RCU read lock.\n-\n-The script appears as outside of the API as a pointer of the type::\n-\n-    struct assoc_array_edit;\n-\n-There are two functions for dealing with the script:\n-\n-1. Apply an edit script::\n-\n-    void assoc_array_apply_edit(struct assoc_array_edit *edit);\n-\n-   This will perform the edit functions, interpolating various write barriers\n-   to permit accesses under the RCU read lock to continue.  The edit script\n-   will then be passed to ``call_rcu()`` to free it and any dead stuff it\n-   points to.\n-\n-2. Cancel an edit script::\n-\n-    void assoc_array_cancel_edit(struct assoc_array_edit *edit);\n-\n-   This frees the edit script and all preallocated memory immediately. If\n-   this was for insertion, the new object is *not* released by this function,\n-   but must rather be released by the caller.\n-\n-These functions are guaranteed not to fail.\n-\n-\n-Operations Table\n-----------------\n-\n-Various functions take a table of operations::\n-\n-    struct assoc_array_ops {\n-            ...\n-    };\n-\n-This points to a number of methods, all of which need to be provided:\n-\n-1. Get a chunk of index key from caller data::\n-\n-    unsigned long (*get_key_chunk)(const void *index_key, int level);\n-\n-   This should return a chunk of caller-supplied index key starting at the\n-   *bit* position given by the level argument.  The level argument will be a\n-   multiple of ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` and the function should return\n-   ``ASSOC_ARRAY_KEY_CHUNK_SIZE bits``.  No error is possible.\n-\n-\n-2. Get a chunk of an object's index key::\n-\n-    unsigned long (*get_object_key_chunk)(const void *object, int level);\n-\n-   As the previous function, but gets its data from an object in the array\n-   rather than from a caller-supplied index key.\n-\n-\n-3. See if this is the object we're looking for::\n-\n-    bool (*compare_object)(const void *object, const void *index_key);\n-\n-   Compare the object against an index key and return ``true`` if it matches\n-   and ``false`` if it doesn't.\n-\n-\n-4. Diff the index keys of two objects::\n-\n-    int (*diff_objects)(const void *object, const void *index_key);\n-\n-   Return the bit position at which the index key of the specified object\n-   differs from the given index key or -1 if they are the same.\n-\n-\n-5. Free an object::\n-\n-    void (*free_object)(void *object);\n-\n-   Free the specified object.  Note that this may be called an RCU grace period\n-   after ``assoc_array_apply_edit()`` was called, so ``synchronize_rcu()`` may\n-   be necessary on module unloading.\n-\n-\n-Manipulation Functions\n-----------------------\n-\n-There are a number of functions for manipulating an associative array:\n-\n-1. Initialise an associative array::\n-\n-    void assoc_array_init(struct assoc_array *array);\n-\n-   This initialises the base structure for an associative array.  It can't fail.\n-\n-\n-2. Insert/replace an object in an associative array::\n-\n-    struct assoc_array_edit *\n-    assoc_array_insert(struct assoc_array *array,\n-                       const struct assoc_array_ops *ops,\n-                       const void *index_key,\n-                       void *object);\n-\n-   This inserts the given object into the array.  Note that the least\n-   significant bit of the pointer must be zero as it's used to type-mark\n-   pointers internally.\n-\n-   If an object already exists for that key then it will be replaced with the\n-   new object and the old one will be freed automatically.\n-\n-   The ``index_key`` argument should hold index key information and is\n-   passed to the methods in the ops table when they are called.\n-\n-   This function makes no alteration to the array itself, but rather returns\n-   an edit script that must be applied.  ``-ENOMEM`` is returned in the case of\n-   an out-of-memory error.\n-\n-   The caller should lock exclusively against other modifiers of the array.\n-\n-\n-3. Delete an object from an associative array::\n-\n-    struct assoc_array_edit *\n-    assoc_array_delete(struct assoc_array *array,\n-                       const struct assoc_array_ops *ops,\n-                       const void *index_key);\n-\n-   This deletes an object that matches the specified data from the array.\n-\n-   The ``index_key`` argument should hold index key information and is\n-   passed to the methods in the ops table when they are called.\n-\n-   This function makes no alteration to the array itself, but rather returns\n-   an edit script that must be applied.  ``-ENOMEM`` is returned in the case of\n-   an out-of-memory error.  ``NULL`` will be returned if the specified object\n-   is not found within the array.\n-\n-The caller should lock exclusively against other modifiers of the array.\n-\n-\n-4. Delete all objects from an associative array::\n-\n-    struct assoc_array_edit *\n-    assoc_array_clear(struct assoc_array *array,\n-                      const struct assoc_array_ops *ops);\n-\n-   This deletes all the objects from an associative array and leaves it\n-   completely empty.\n-\n-   This function makes no alteration to the array itself, but rather returns\n-   an edit script that must be applied.  ``-ENOMEM`` is returned in the case of\n-   an out-of-memory error.\n-\n-   The caller should lock exclusively against other modifiers of the array.\n-\n-\n-5. Destroy an associative array, deleting all objects::\n-\n-    void assoc_array_destroy(struct assoc_array *array,\n-                             const struct assoc_array_ops *ops);\n-\n-   This destroys the contents of the associative array and leaves it\n-   completely empty.  It is not permitted for another thread to be traversing\n-   the array under the RCU read lock at the same time as this function is\n-   destroying it as no RCU deferral is performed on memory release -\n-   something that would require memory to be allocated.\n-\n-   The caller should lock exclusively against other modifiers and accessors\n-   of the array.\n-\n-\n-6. Garbage collect an associative array::\n-\n-    int assoc_array_gc(struct assoc_array *array,\n-                       const struct assoc_array_ops *ops,\n-                       bool (*iterator)(void *object, void *iterator_data),\n-                       void *iterator_data);\n-\n-   This iterates over the objects in an associative array and passes each one\n-   to ``iterator()``.  If ``iterator()`` returns ``true``, the object is kept.\n-   If it returns ``false``, the object will be freed.  If the ``iterator()``\n-   function returns ``true``, it must perform any appropriate refcount\n-   incrementing on the object before returning.\n-\n-   The internal tree will be packed down if possible as part of the iteration\n-   to reduce the number of nodes in it.\n-\n-   The ``iterator_data`` is passed directly to ``iterator()`` and is otherwise\n-   ignored by the function.\n-\n-   The function will return ``0`` if successful and ``-ENOMEM`` if there wasn't\n-   enough memory.\n-\n-   It is possible for other threads to iterate over or search the array under\n-   the RCU read lock while this function is in progress.  The caller should\n-   lock exclusively against other modifiers of the array.\n-\n-\n-Access Functions\n-----------------\n-\n-There are two functions for accessing an associative array:\n-\n-1. Iterate over all the objects in an associative array::\n-\n-    int assoc_array_iterate(const struct assoc_array *array,\n-                            int (*iterator)(const void *object,\n-                                            void *iterator_data),\n-                            void *iterator_data);\n-\n-   This passes each object in the array to the iterator callback function.\n-   ``iterator_data`` is private data for that function.\n-\n-   This may be used on an array at the same time as the array is being\n-   modified, provided the RCU read lock is held.  Under such circumstances,\n-   it is possible for the iteration function to see some objects twice.  If\n-   this is a problem, then modification should be locked against.  The\n-   iteration algorithm should not, however, miss any objects.\n-\n-   The function will return ``0`` if no objects were in the array or else it\n-   will return the result of the last iterator function called.  Iteration\n-   stops immediately if any call to the iteration function results in a\n-   non-zero return.\n-\n-\n-2. Find an object in an associative array::\n-\n-    void *assoc_array_find(const struct assoc_array *array,\n-                           const struct assoc_array_ops *ops,\n-                           const void *index_key);\n-\n-   This walks through the array's internal tree directly to the object\n-   specified by the index key.\n-\n-   This may be used on an array at the same time as the array is being\n-   modified, provided the RCU read lock is held.\n-\n-   The function will return the object if found (and set ``*_type`` to the\n-   object type) or will return ``NULL`` if the object was not found.\n-\n-\n-Index Key Form\n---------------\n-\n-The index key can be of any form, but since the algorithms aren't told how long\n-the key is, it is strongly recommended that the index key includes its length\n-very early on before any variation due to the length would have an effect on\n-comparisons.\n-\n-This will cause leaves with different length keys to scatter away from each\n-other - and those with the same length keys to cluster together.\n-\n-It is also recommended that the index key begin with a hash of the rest of the\n-key to maximise scattering throughout keyspace.\n-\n-The better the scattering, the wider and lower the internal tree will be.\n-\n-Poor scattering isn't too much of a problem as there are shortcuts and nodes\n-can contain mixtures of leaves and metadata pointers.\n-\n-The index key is read in chunks of machine word.  Each chunk is subdivided into\n-one nibble (4 bits) per level, so on a 32-bit CPU this is good for 8 levels and\n-on a 64-bit CPU, 16 levels.  Unless the scattering is really poor, it is\n-unlikely that more than one word of any particular index key will have to be\n-used.\n-\n-\n-Internal Workings\n-=================\n-\n-The associative array data structure has an internal tree.  This tree is\n-constructed of two types of metadata blocks: nodes and shortcuts.\n-\n-A node is an array of slots.  Each slot can contain one of four things:\n-\n-* A NULL pointer, indicating that the slot is empty.\n-* A pointer to an object (a leaf).\n-* A pointer to a node at the next level.\n-* A pointer to a shortcut.\n-\n-\n-Basic Internal Tree Layout\n---------------------------\n-\n-Ignoring shortcuts for the moment, the nodes form a multilevel tree.  The index\n-key space is strictly subdivided by the nodes in the tree and nodes occur on\n-fixed levels.  For example::\n-\n- Level: 0               1               2               3\n-        =============== =============== =============== ===============\n-                                                        NODE D\n-                        NODE B          NODE C  +------\u003e+---+\n-                +------\u003e+---+   +------\u003e+---+   |       | 0 |\n-        NODE A  |       | 0 |   |       | 0 |   |       +---+\n-        +---+   |       +---+   |       +---+   |       :   :\n-        | 0 |   |       :   :   |       :   :   |       +---+\n-        +---+   |       +---+   |       +---+   |       | f |\n-        | 1 |---+       | 3 |---+       | 7 |---+       +---+\n-        +---+           +---+           +---+\n-        :   :           :   :           | 8 |---+\n-        +---+           +---+           +---+   |       NODE E\n-        | e |---+       | f |           :   :   +------\u003e+---+\n-        +---+   |       +---+           +---+           | 0 |\n-        | f |   |                       | f |           +---+\n-        +---+   |                       +---+           :   :\n-                |       NODE F                          +---+\n-                +------\u003e+---+                           | f |\n-                        | 0 |           NODE G          +---+\n-                        +---+   +------\u003e+---+\n-                        :   :   |       | 0 |\n-                        +---+   |       +---+\n-                        | 6 |---+       :   :\n-                        +---+           +---+\n-                        :   :           | f |\n-                        +---+           +---+\n-                        | f |\n-                        +---+\n-\n-In the above example, there are 7 nodes (A-G), each with 16 slots (0-f).\n-Assuming no other meta data nodes in the tree, the key space is divided\n-thusly:\n-\n-    ===========     ====\n-    KEY PREFIX      NODE\n-    ===========     ====\n-    137*            D\n-    138*            E\n-    13[0-69-f]*     C\n-    1[0-24-f]*      B\n-    e6*             G\n-    e[0-57-f]*      F\n-    [02-df]*        A\n-    ===========     ====\n-\n-So, for instance, keys with the following example index keys will be found in\n-the appropriate nodes:\n-\n-    =============== ======= ====\n-    INDEX KEY       PREFIX  NODE\n-    =============== ======= ====\n-    13694892892489  13      C\n-    13795289025897  137     D\n-    13889dde88793   138     E\n-    138bbb89003093  138     E\n-    1394879524789   12      C\n-    1458952489      1       B\n-    9431809de993ba  \\-      A\n-    b4542910809cd   \\-      A\n-    e5284310def98   e       F\n-    e68428974237    e6      G\n-    e7fffcbd443     e       F\n-    f3842239082     \\-      A\n-    =============== ======= ====\n-\n-To save memory, if a node can hold all the leaves in its portion of keyspace,\n-then the node will have all those leaves in it and will not have any metadata\n-pointers - even if some of those leaves would like to be in the same slot.\n-\n-A node can contain a heterogeneous mix of leaves and metadata pointers.\n-Metadata pointers must be in the slots that match their subdivisions of key\n-space.  The leaves can be in any slot not occupied by a metadata pointer.  It\n-is guaranteed that none of the leaves in a node will match a slot occupied by a\n-metadata pointer.  If the metadata pointer is there, any leaf whose key matches\n-the metadata key prefix must be in the subtree that the metadata pointer points\n-to.\n-\n-In the above example list of index keys, node A will contain:\n-\n-    ====    =============== ==================\n-    SLOT    CONTENT         INDEX KEY (PREFIX)\n-    ====    =============== ==================\n-    1       PTR TO NODE B   1*\n-    any     LEAF            9431809de993ba\n-    any     LEAF            b4542910809cd\n-    e       PTR TO NODE F   e*\n-    any     LEAF            f3842239082\n-    ====    =============== ==================\n-\n-and node B:\n-\n-    ====    =============== ==================\n-    SLOT    CONTENT         INDEX KEY (PREFIX)\n-    ====    =============== ==================\n-    3       PTR TO NODE C   13*\n-    any     LEAF            1458952489\n-    ====    =============== ==================\n-\n-\n-Shortcuts\n----------\n-\n-Shortcuts are metadata records that jump over a piece of keyspace.  A shortcut\n-is a replacement for a series of single-occupancy nodes ascending through the\n-levels.  Shortcuts exist to save memory and to speed up traversal.\n-\n-It is possible for the root of the tree to be a shortcut - say, for example,\n-the tree contains at least 17 nodes all with key prefix ``1111``.  The\n-insertion algorithm will insert a shortcut to skip over the ``1111`` keyspace\n-in a single bound and get to the fourth level where these actually become\n-different.\n-\n-\n-Splitting And Collapsing Nodes\n-------------------------------\n-\n-Each node has a maximum capacity of 16 leaves and metadata pointers.  If the\n-insertion algorithm finds that it is trying to insert a 17th object into a\n-node, that node will be split such that at least two leaves that have a common\n-key segment at that level end up in a separate node rooted on that slot for\n-that common key segment.\n-\n-If the leaves in a full node and the leaf that is being inserted are\n-sufficiently similar, then a shortcut will be inserted into the tree.\n-\n-When the number of objects in the subtree rooted at a node falls to 16 or\n-fewer, then the subtree will be collapsed down to a single node - and this will\n-ripple towards the root if possible.\n-\n-\n-Non-Recursive Iteration\n------------------------\n-\n-Each node and shortcut contains a back pointer to its parent and the number of\n-slot in that parent that points to it.  None-recursive iteration uses these to\n-proceed rootwards through the tree, going to the parent node, slot N + 1 to\n-make sure progress is made without the need for a stack.\n-\n-The backpointers, however, make simultaneous alteration and iteration tricky.\n-\n-\n-Simultaneous Alteration And Iteration\n--------------------------------------\n-\n-There are a number of cases to consider:\n-\n-1. Simple insert/replace.  This involves simply replacing a NULL or old\n-   matching leaf pointer with the pointer to the new leaf after a barrier.\n-   The metadata blocks don't change otherwise.  An old leaf won't be freed\n-   until after the RCU grace period.\n-\n-2. Simple delete.  This involves just clearing an old matching leaf.  The\n-   metadata blocks don't change otherwise.  The old leaf won't be freed until\n-   after the RCU grace period.\n-\n-3. Insertion replacing part of a subtree that we haven't yet entered.  This\n-   may involve replacement of part of that subtree - but that won't affect\n-   the iteration as we won't have reached the pointer to it yet and the\n-   ancestry blocks are not replaced (the layout of those does not change).\n-\n-4. Insertion replacing nodes that we're actively processing.  This isn't a\n-   problem as we've passed the anchoring pointer and won't switch onto the\n-   new layout until we follow the back pointers - at which point we've\n-   already examined the leaves in the replaced node (we iterate over all the\n-   leaves in a node before following any of its metadata pointers).\n-\n-   We might, however, re-see some leaves that have been split out into a new\n-   branch that's in a slot further along than we were at.\n-\n-5. Insertion replacing nodes that we're processing a dependent branch of.\n-   This won't affect us until we follow the back pointers.  Similar to (4).\n-\n-6. Deletion collapsing a branch under us.  This doesn't affect us because the\n-   back pointers will get us back to the parent of the new node before we\n-   could see the new node.  The entire collapsed subtree is thrown away\n-   unchanged - and will still be rooted on the same slot, so we shouldn't\n-   process it a second time as we'll go back to slot + 1.\n-\n-.. note::\n-\n-   Under some circumstances, we need to simultaneously change the parent\n-   pointer and the parent slot pointer on a node (say, for example, we\n-   inserted another node before it and moved it up a level).  We cannot do\n-   this without locking against a read - so we have to replace that node too.\n-\n-   However, when we're changing a shortcut into a node this isn't a problem\n-   as shortcuts only have one slot and so the parent slot number isn't used\n-   when traversing backwards over one.  This means that it's okay to change\n-   the slot number first - provided suitable barriers are used to make sure\n-   the parent slot number is read after the back pointer.\n-\n-Obsolete blocks and leaves are freed up after an RCU grace period has passed,\n-so as long as anyone doing walking or iteration holds the RCU read lock, the\n-old superstructure should not go away on them.\ndiff --git a/Documentation/core-api/index.rst b/Documentation/core-api/index.rst\nindex 92f91c6a0d79d6..d56c60663b0c40 100644\n--- a/Documentation/core-api/index.rst\n+++ b/Documentation/core-api/index.rst\n@@ -38,7 +38,6 @@ Library functionality that is used throughout the kernel.\n    kobject\n    kref\n    cleanup\n-   assoc_array\n    folio_queue\n    xarray\n    maple_tree\ndiff --git a/Documentation/translations/zh_CN/core-api/assoc_array.rst b/Documentation/translations/zh_CN/core-api/assoc_array.rst\ndeleted file mode 100644\nindex 3649bf0d148807..00000000000000\n--- a/Documentation/translations/zh_CN/core-api/assoc_array.rst\n+++ /dev/null\n@@ -1,473 +0,0 @@\n-.. include:: ../disclaimer-zh_CN.rst\n-\n-:Original: Documentation/core-api/assoc_array.rst\n-\n-:翻译:\n-\n- 司延腾 Yanteng Si \u003csiyanteng@loongson.cn\u003e\n-\n-:校译:\n-\n-\n-\n-.. _cn_core-api_assoc_array:\n-\n-==================\n-通用关联数组的实现\n-==================\n-\n-简介\n-====\n-\n-这个关联数组的实现是一个具有以下属性的对象容器:\n-\n-1. 对象是不透明的指针。该实现不关心它们指向哪里(如果有的话)或它们指向什么(如果有的\n-   话)。\n-\n-   .. note::\n-\n-      指向对象的指针 *必须* 在最小有效位为零。\n-\n-2. 对象不需要包含供数组使用的链接块。这允许一个对象同时位于多个数组中。相反,数组是\n-   由指向对象的元数据块组成的。\n-\n-3. 对象需要索引键来定位它们在阵列中的位置。\n-\n-4. 索引键必须是唯一的。插入一个与已经在数组中的且具有相同键值的对象将取代旧的对象。\n-\n-5. 索引键可以是任何长度,也可以是不同的长度。\n-\n-6. 索引键应该在早期就对长度进行编码,即在任何由于长度引起的变化出现之前。\n-\n-7. 索引键可以包括一个哈希值,以便将对象分散到整个数组中。\n-\n-8. 该数组可以迭代。对象不一定会按索引键的顺序出现。\n-\n-9.  数组可以在被修改的时候进行迭代,只要RCU的读锁被迭代器持有。然而,请注意,在这种情\n-    况下,一些对象可能会被看到不止一次。如果这是个问题,迭代器应该锁定以防止修改。然\n-    而,除非删除,否则对象不会被错过。\n-\n-10. 数组中的对象可以通过其索引键进行查询。\n-\n-11. 当数组被修改时,对象可以被查询,前提是进行查询的线程持有RCU的读锁。\n-\n-该实现在内部使用了一棵由16个指针节点组成的树,这些节点在每一层都由索引键的小数点进行索\n-引,其方式与基数树相同。为了提高内存效率,可以放置快捷键,以跳过本来是一系列单占节点的地\n-方。此外,节点将叶子对象指针打包到节点的空闲空间中,而不是做一个额外的分支,直到有对象\n-需要被添加到一个完整的节点中。\n-\n-公用API\n-=======\n-\n-公用API可以在 ``\u003clinux/assoc_array.h\u003e`` 中找到。关联数组的根是以下结构::\n-\n-    struct assoc_array {\n-            ...\n-    };\n-\n-该代码是通过启用 ``CONFIG_ASSOCIATIVE_ARRAY`` 来选择的,以::\n-\n-    ./script/config -e ASSOCIATIVE_ARRAY\n-\n-\n-编辑脚本\n---------\n-\n-插入和删除功能会产生一个“编辑脚本”,以后可以应用这个脚本来实现更改,而不会造成 ``ENOMEM``\n-风险。这保留了将被安装在内部树中的预分配的元数据块,并跟踪应用脚本时将从树中删除的元数\n-据块。\n-\n-在脚本应用后,这也被用来跟踪死块和死对象,以便以后可以释放它们。释放是在RCU宽限期过后\n-进行的--因此允许访问功能在RCU读锁下进行。\n-\n-脚本在API之外显示为一个类型为::\n-\n-    struct assoc_array_edit;\n-\n-有两个处理脚本的功能:\n-\n-1. 应用一个编辑脚本::\n-\n-    void assoc_array_apply_edit(struct assoc_array_edit *edit);\n-\n-这将执行编辑功能,插值各种写屏障,以允许在RCU读锁下的访问继续进行。然后,编辑脚本将被\n-传递给 ``call_rcu()`` ,以释放它和它所指向的任何死的东西。\n-\n-2. Cancel an edit script::\n-\n-    void assoc_array_cancel_edit(struct assoc_array_edit *edit);\n-\n-这将立即释放编辑脚本和所有预分配的内存。如果这是为了插入,新的对象不会被这个函数释放,\n-而是必须由调用者释放。\n-\n-这些函数保证不会失败。\n-\n-\n-操作表\n-------\n-\n-各种功能采用了一个操作表::\n-\n-    struct assoc_array_ops {\n-            ...\n-    };\n-\n-这指出了一些方法,所有这些方法都需要提供:\n-\n-1. 从调用者数据中获取索引键的一个块::\n-\n-    unsigned long (*get_key_chunk)(const void *index_key, int level);\n-\n-这应该返回一个由调用者提供的索引键的块,从level参数给出的 *比特* 位置开始。level参数将\n-是 ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` 的倍数,该函数应返回 ``ASSOC_ARRAY_KEY_CHUNK_SIZE``\n-位。不可能出现错误。\n-\n-\n-2. 获取一个对象的索引键的一个块::\n-\n-    unsigned long (*get_object_key_chunk)(const void *object, int level);\n-\n-和前面的函数一样,但是从数组中的一个对象而不是从调用者提供的索引键中获取数据。\n-\n-\n-3. 看看这是否是我们要找的对象::\n-\n-    bool (*compare_object)(const void *object, const void *index_key);\n-\n-将对象与一个索引键进行比较,如果匹配则返回 ``true`` ,不匹配则返回 ``false`` 。\n-\n-\n-4. 对两个对象的索引键进行比较::\n-\n-    int (*diff_objects)(const void *object, const void *index_key);\n-\n-返回指定对象的索引键与给定索引键不同的比特位置,如果它们相同,则返回-1。\n-\n-\n-5. 释放一个对象::\n-\n-    void (*free_object)(void *object);\n-\n-释放指定的对象。注意,这可能是在调用 ``assoc_array_apply_edit()`` 后的一个RCU宽限期内\n-调用的,所以在模块卸载时可能需要 ``synchronize_rcu()`` 。\n-\n-\n-操控函数\n---------\n-\n-有一些函数用于操控关联数组:\n-\n-1. 初始化一个关联数组::\n-\n-    void assoc_array_init(struct assoc_array *array);\n-\n-这将初始化一个关联数组的基础结构。它不会失败。\n-\n-\n-2. 在一个关联数组中插入/替换一个对象::\n-\n-    struct assoc_array_edit *\n-    assoc_array_insert(struct assoc_array *array,\n-                       const struct assoc_array_ops *ops,\n-                       const void *index_key,\n-                       void *object);\n-\n-这将把给定的对象插入数组中。注意,指针的最小有效位必须是0,因为它被用来在内部标记指针的类\n-型。\n-\n-如果该键已经存在一个对象,那么它将被新的对象所取代,旧的对象将被自动释放。\n-\n-``index_key`` 参数应持有索引键信息,并在调用OPP表中的方法时传递给它们。\n-\n-这个函数不对数组本身做任何改动,而是返回一个必须应用的编辑脚本。如果出现内存不足的错误,会\n-返回 ``-ENOMEM`` 。\n-\n-调用者应专门锁定数组的其他修改器。\n-\n-\n-3. 从一个关联数组中删除一个对象::\n-\n-    struct assoc_array_edit *\n-    assoc_array_delete(struct assoc_array *array,\n-                       const struct assoc_array_ops *ops,\n-                       const void *index_key);\n-\n-这将从数组中删除一个符合指定数据的对象。\n-\n-``index_key`` 参数应持有索引键信息,并在调用OPP表中的方法时传递给它们。\n-\n-这个函数不对数组本身做任何改动,而是返回一个必须应用的编辑脚本。 ``-ENOMEM`` 在出现内存不足\n-的错误时返回。如果在数组中没有找到指定的对象,将返回 ``NULL`` 。\n-\n-调用者应该对数组的其他修改者进行专门锁定。\n-\n-\n-4. 从一个关联数组中删除所有对象::\n-\n-    struct assoc_array_edit *\n-    assoc_array_clear(struct assoc_array *array,\n-                      const struct assoc_array_ops *ops);\n-\n-这个函数删除了一个关联数组中的所有对象,使其完全为空。\n-\n-这个函数没有对数组本身做任何改动,而是返回一个必须应用的编辑脚本。如果出现内存不足\n-的错误,则返回 ``-ENOMEM`` 。\n-\n-调用者应专门锁定数组的其他修改者。\n-\n-\n-5. 销毁一个关联数组,删除所有对象::\n-\n-    void assoc_array_destroy(struct assoc_array *array,\n-                             const struct assoc_array_ops *ops);\n-\n-这将破坏关联数组的内容,使其完全为空。在这个函数销毁数组的同时,不允许另一个线程在RCU读锁\n-下遍历数组,因为在内存释放时不执行RCU延迟,这需要分配内存。\n-\n-调用者应该专门针对数组的其他修改者和访问者进行锁定。\n-\n-\n-6. 垃圾回收一个关联数组::\n-\n-    int assoc_array_gc(struct assoc_array *array,\n-                       const struct assoc_array_ops *ops,\n-                       bool (*iterator)(void *object, void *iterator_data),\n-                       void *iterator_data);\n-\n-这是对一个关联数组中的对象进行迭代,并将每个对象传递给 ``iterator()`` 。如果 ``iterator()`` 返回\n-true,该对象被保留。如果它返回 ``false`` ,该对象将被释放。如果 ``iterator()`` 函数返回 ``true`` ,它必须\n-在返回之前对该对象进行适当的 ``refcount`` 递增。\n-\n-如果可能的话,内部树将被打包下来,作为迭代的一部分,以减少其中的节点数量。\n-\n-``iterator_data`` 被直接传递给 ``iterator()`` ,否则会被函数忽略。\n-\n-如果成功,该函数将返回 ``0`` ,如果没有足够的内存,则返回 ``-ENOMEM`` 。\n-\n-在这个函数执行过程中,其他线程有可能在RCU读锁下迭代或搜索阵列。调用者应该专门针对数组的其他\n-修改者进行锁定。\n-\n-\n-访问函数\n---------\n-\n-有两个函数用于访问一个关联数组:\n-\n-1. 遍历一个关联数组中的所有对象::\n-\n-    int assoc_array_iterate(const struct assoc_array *array,\n-                            int (*iterator)(const void *object,\n-                                            void *iterator_data),\n-                            void *iterator_data);\n-\n-这将数组中的每个对象传递给迭代器回调函数。 ``iterator_data`` 是该函数的私有数据。\n-\n-在数组被修改的同时,可以在数组上使用这个方法,前提是RCU读锁被持有。在这种情况下,迭代函数有\n-可能两次看到某些对象。如果这是个问题,那么修改应该被锁定。然而,迭代算法不应该错过任何对象。\n-\n-如果数组中没有对象,该函数将返回 ``0`` ,否则将返回最后一次调用的迭代器函数的结果。如果对迭代函数\n-的任何调用导致非零返回,迭代立即停止。\n-\n-\n-2. 在一个关联数组中寻找一个对象::\n-\n-    void *assoc_array_find(const struct assoc_array *array,\n-                           const struct assoc_array_ops *ops,\n-                           const void *index_key);\n-\n-这将直接穿过数组的内部树,到达索引键所指定的对象。\n-\n-这个函数可以在修改数组的同时用在数组上,前提是RCU读锁被持有。\n-\n-如果找到对象,该函数将返回对象(并将 ``*_type`` 设置为对象的类型),如果没有找到对象,将返回 ``NULL`` 。\n-\n-\n-索引键形式\n-----------\n-\n-索引键可以是任何形式的,但是由于算法没有被告知键有多长,所以强烈建议在任何由于长度而产生的变化\n-对比较产生影响之前,索引键应该很早就包括其长度。\n-\n-这将导致具有不同长度键的叶子相互分散,而具有相同长度键的叶子则聚集在一起。\n-\n-我们还建议索引键以键的其余部分的哈希值开始,以最大限度地提高整个键空间的散布情况。\n-\n-分散性越好,内部树就越宽,越低。\n-\n-分散性差并不是一个太大的问题,因为有快捷键,节点可以包含叶子和元数据指针的混合物。\n-\n-索引键是以机器字的块状来读取的。每个块被细分为每层一个nibble(4比特),所以在32位CPU上这适合8层,\n-在64位CPU上适合16层。除非散布情况真的很差,否则不太可能有超过一个字的任何特定索引键需要被使用。\n-\n-\n-内部工作机制\n-============\n-\n-关联数组数据结构有一个内部树。这个树由两种类型的元数据块构成:节点和快捷键。\n-\n-一个节点是一个槽的数组。每个槽可以包含以下四种东西之一:\n-\n-* 一个NULL的指针,表示槽是空的。\n-* 一个指向对象(叶子)的指针。\n-* 一个指向下一级节点的指针。\n-* 一个指向快捷键的指针。\n-\n-\n-基本的内部树形布局\n-------------------\n-\n-暂时不考虑快捷键,节点形成一个多级树。索引键空间被树上的节点严格细分,节点出现在固定的层次上。例如::\n-\n- Level: 0               1               2               3\n-        =============== =============== =============== ===============\n-                                                        NODE D\n-                        NODE B          NODE C  +------\u003e+---+\n-                +------\u003e+---+   +------\u003e+---+   |       | 0 |\n-        NODE A  |       | 0 |   |       | 0 |   |       +---+\n-        +---+   |       +---+   |       +---+   |       :   :\n-        | 0 |   |       :   :   |       :   :   |       +---+\n-        +---+   |       +---+   |       +---+   |       | f |\n-        | 1 |---+       | 3 |---+       | 7 |---+       +---+\n-        +---+           +---+           +---+\n-        :   :           :   :           | 8 |---+\n-        +---+           +---+           +---+   |       NODE E\n-        | e |---+       | f |           :   :   +------\u003e+---+\n-        +---+   |       +---+           +---+           | 0 |\n-        | f |   |                       | f |           +---+\n-        +---+   |                       +---+           :   :\n-                |       NODE F                          +---+\n-                +------\u003e+---+                           | f |\n-                        | 0 |           NODE G          +---+\n-                        +---+   +------\u003e+---+\n-                        :   :   |       | 0 |\n-                        +---+   |       +---+\n-                        | 6 |---+       :   :\n-                        +---+           +---+\n-                        :   :           | f |\n-                        +---+           +---+\n-                        | f |\n-                        +---+\n-\n-在上述例子中,有7个节点(A-G),每个节点有16个槽(0-f)。假设树上没有其他元数据节点,那么密钥空间\n-是这样划分的::\n-\n-    KEY PREFIX      NODE\n-    ==========      ====\n-    137*            D\n-    138*            E\n-    13[0-69-f]*     C\n-    1[0-24-f]*      B\n-    e6*             G\n-    e[0-57-f]*      F\n-    [02-df]*        A\n-\n-因此,例如,具有以下示例索引键的键将在适当的节点中被找到::\n-\n-    INDEX KEY       PREFIX  NODE\n-    =============== ======= ====\n-    13694892892489  13      C\n-    13795289025897  137     D\n-    13889dde88793   138     E\n-    138bbb89003093  138     E\n-    1394879524789   12      C\n-    1458952489      1       B\n-    9431809de993ba  -       A\n-    b4542910809cd   -       A\n-    e5284310def98   e       F\n-    e68428974237    e6      G\n-    e7fffcbd443     e       F\n-    f3842239082     -       A\n-\n-为了节省内存,如果一个节点可以容纳它的那部分键空间中的所有叶子,那么这个节点将有所有这些叶子,而不\n-会有任何元数据指针——即使其中一些叶子想在同一个槽中。\n-\n-一个节点可以包含叶子和元数据指针的异质性混合。元数据指针必须在与它们的关键空间的细分相匹配的槽中。\n-叶子可以在任何没有被元数据指针占据的槽中。保证一个节点中没有一个叶子会与元数据指针占据的槽相匹配。\n-如果元数据指针在那里,任何键与元数据键前缀相匹配的叶必须在元数据指针指向的子树中。\n-\n-在上面的索引键的例子列表中,节点A将包含::\n-\n-    SLOT    CONTENT         INDEX KEY (PREFIX)\n-    ====    =============== ==================\n-    1       PTR TO NODE B   1*\n-    any     LEAF            9431809de993ba\n-    any     LEAF            b4542910809cd\n-    e       PTR TO NODE F   e*\n-    any     LEAF            f3842239082\n-\n-和节点B::\n-\n-    3\tPTR TO NODE C\t13*\n-    any\tLEAF\t\t1458952489\n-\n-\n-快捷键\n----------\n-\n-快捷键是跳过一块键空间的元数据记录。快捷键是一系列通过层次上升的单占节点的替代物。快捷键的存在是\n-为了节省内存和加快遍历速度。\n-\n-树的根部有可能是一个快捷键——比如说,树至少包含17个节点,都有键前缀 ``1111`` 。插入算法将插入一个快捷键,\n-以单次跳过 ``1111`` 的键位,并到达第四层,在这里,这些键位实际上变得不同。\n-\n-\n-拆分和合并节点\n-------------------------------\n-\n-每个节点的最大容量为16个叶子和元数据指针。如果插入算法发现它正试图将一个第17个对象插入到一个节点中,\n-该节点将被拆分,使得至少两个在该层有一个共同的关键段的叶子最终在一个单独的节点中,该共同的关键段的根\n-在该槽上。\n-\n-如果一个完整的节点中的叶子和被插入的叶子足够相似,那么就会在树中插入一个快捷键。\n-\n-当根植于某个节点的子树中的对象数量下降到16个或更少时,那么该子树将被合并成一个单独的节点——如果可能的\n-话,这将向根部扩散。\n-\n-\n-非递归式迭代\n-------------\n-\n-每个节点和快捷键都包含一个指向其父节点的后置指针,以及该父节点中指向它的槽数。非递归迭代使用这些来\n-通过树的根部进行,前往父节点,槽N+1,以确保在没有堆栈的情况下取得进展。\n-\n-然而,反向指针使得同时改变和迭代变得很棘手。\n-\n-\n-同时改变和迭代\n---------------\n-\n-有一些情况需要考虑:\n-\n-1. 简单的插入/替换。这涉及到简单地将一个NULL或旧的匹配叶子的指针替换为屏障后的新叶子的指针。否则元数\n-   据块不会改变。一个旧的叶子直到RCU宽限期过后才会被释放。\n-\n-2. 简单删除。这只是涉及到清除一个旧的匹配叶子。元数据块不会有其他变化。旧的叶子直到RCU宽限期之后才会\n-   被释放。\n-\n-3. 插入,替换我们还没有进入的子树的一部分。这可能涉及到替换该子树的一部分——但这不会影响迭代,因为我们\n-   还没有到达它的指针,而且祖先块也不会被替换(这些块的布局不会改变)。\n-\n-4. 插入替换了我们正在处理的节点。这不是一个问题,因为我们已经通过了锚定指针,直到我们跟随后面的指针才\n-   会切换到新的布局上——这时我们已经检查了被替换节点的叶子(在跟随任何元数据指针之前,我们会迭代一个节\n-   点的所有叶子)。\n-\n-   然而,我们可能会重新看到一些叶子,这些叶子已经被分割成一个新的分支,而这个分支的位置比我们之前的位\n-   置更远。\n-\n-5. 插入替换了我们正在处理的依赖分支的节点。这不会影响到我们,直到我们跟随后面的指针。与(4)类似。\n-\n-6. 删掉我们下面的一个分支。这不会影响我们,因为在我们看到新节点之前,回溯指针会让我们回到新节点的父节\n-   点。整个崩溃的子树被扔掉了,没有任何变化——而且仍然会在同一个槽上生根,所以我们不应该第二次处理它,\n-   因为我们会回到槽+1。\n-\n-.. note::\n-\n-    在某些情况下,我们需要同时改变一个节点的父指针和父槽指针(比如说,我们在它之前插入了另一个节点,\n-    并把它往上移了一层)。我们不能在不锁定读取的情况下这样做——所以我们必须同时替换该节点。\n-\n-    然而,当我们把一个快捷键改成一个节点时,这不是一个问题,因为快捷键只有一个槽,所以当向后遍\n-    历一个槽时,不会使用父槽号。这意味着先改变槽位号是可以的——只要使用适当的屏障来确保父槽位号在后\n-    退指针之后被读取。\n-\n-过时的块和叶子在RCU宽限期过后会被释放,所以只要任何进行遍历或迭代的人持有RCU读锁,旧的上层建筑就不\n-应该在他们身上消失。\ndiff --git a/Documentation/translations/zh_CN/core-api/index.rst b/Documentation/translations/zh_CN/core-api/index.rst\nindex 453a02cd1f4486..ec4b03b2a0a60e 100644\n--- a/Documentation/translations/zh_CN/core-api/index.rst\n+++ b/Documentation/translations/zh_CN/core-api/index.rst\n@@ -41,7 +41,6 @@\n \n    kobject\n    kref\n-   assoc_array\n    xarray\n    rbtree\n    idr\ndiff --git a/drivers/md/dm-verity-verify-sig.c b/drivers/md/dm-verity-verify-sig.c\nindex 0c65c7a31da8bd..bd5143aae4fa96 100644\n--- a/drivers/md/dm-verity-verify-sig.c\n+++ b/drivers/md/dm-verity-verify-sig.c\n@@ -153,7 +153,7 @@ int verity_verify_root_hash(const void *root_hash, size_t root_hash_len,\n \tif (ret != -ENOKEY \u0026\u0026 ret != -EKEYREJECTED)\n \t\treturn ret;\n \n-\tif (dm_verity_keyring-\u003ekeys.nr_leaves_on_tree \u0026\u0026\n+\tif (!keyring_is_empty(dm_verity_keyring) \u0026\u0026\n \t    dm_verity_keyring-\u003erestrict_link)\n \t\tret = verify_pkcs7_signature(root_hash, root_hash_len,\n \t\t\t\t\t     sig_data, sig_len,\ndiff --git a/fs/verity/signature.c b/fs/verity/signature.c\nindex 2f49c5d9d98705..b45b39b829b298 100644\n--- a/fs/verity/signature.c\n+++ b/fs/verity/signature.c\n@@ -70,7 +70,7 @@ int fsverity_verify_signature(const struct fsverity_info *vi,\n \t\treturn 0;\n \t}\n \n-\tif (fsverity_keyring-\u003ekeys.nr_leaves_on_tree == 0) {\n+\tif (keyring_is_empty(fsverity_keyring)) {\n \t\t/*\n \t\t * The \".fs-verity\" keyring is empty, due to builtin signatures\n \t\t * being supported by the kernel but not actually being used.\ndiff --git a/include/keys/keyring-type.h b/include/keys/keyring-type.h\nindex 1dc83862f519ad..314832f5dc4a99 100644\n--- a/include/keys/keyring-type.h\n+++ b/include/keys/keyring-type.h\n@@ -9,6 +9,5 @@\n #define _KEYS_KEYRING_TYPE_H\n \n #include \u003clinux/key.h\u003e\n-#include \u003clinux/assoc_array.h\u003e\n \n #endif /* _KEYS_KEYRING_TYPE_H */\ndiff --git a/include/linux/assoc_array.h b/include/linux/assoc_array.h\ndeleted file mode 100644\nindex 8b3f230ce89440..00000000000000\n--- a/include/linux/assoc_array.h\n+++ /dev/null\n@@ -1,88 +0,0 @@\n-/* SPDX-License-Identifier: GPL-2.0-or-later */\n-/* Generic associative array implementation.\n- *\n- * See Documentation/core-api/assoc_array.rst for information.\n- *\n- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.\n- * Written by David Howells (dhowells@redhat.com)\n- */\n-\n-#ifndef _LINUX_ASSOC_ARRAY_H\n-#define _LINUX_ASSOC_ARRAY_H\n-\n-#ifdef CONFIG_ASSOCIATIVE_ARRAY\n-\n-#include \u003clinux/types.h\u003e\n-\n-#define ASSOC_ARRAY_KEY_CHUNK_SIZE BITS_PER_LONG /* Key data retrieved in chunks of this size */\n-\n-/*\n- * Generic associative array.\n- */\n-struct assoc_array {\n-\tstruct assoc_array_ptr\t*root;\t\t/* The node at the root of the tree */\n-\tunsigned long\t\tnr_leaves_on_tree;\n-};\n-\n-/*\n- * Operations on objects and index keys for use by array manipulation routines.\n- */\n-struct assoc_array_ops {\n-\t/* Method to get a chunk of an index key from caller-supplied data */\n-\tunsigned long (*get_key_chunk)(const void *index_key, int level);\n-\n-\t/* Method to get a piece of an object's index key */\n-\tunsigned long (*get_object_key_chunk)(const void *object, int level);\n-\n-\t/* Is this the object we're looking for? */\n-\tbool (*compare_object)(const void *object, const void *index_key);\n-\n-\t/* How different is an object from an index key, to a bit position in\n-\t * their keys? (or -1 if they're the same)\n-\t */\n-\tint (*diff_objects)(const void *object, const void *index_key);\n-\n-\t/* Method to free an object. */\n-\tvoid (*free_object)(void *object);\n-};\n-\n-/*\n- * Access and manipulation functions.\n- */\n-struct assoc_array_edit;\n-\n-static inline void assoc_array_init(struct assoc_array *array)\n-{\n-\tarray-\u003eroot = NULL;\n-\tarray-\u003enr_leaves_on_tree = 0;\n-}\n-\n-extern int assoc_array_iterate(const struct assoc_array *array,\n-\t\t\t       int (*iterator)(const void *object,\n-\t\t\t\t\t       void *iterator_data),\n-\t\t\t       void *iterator_data);\n-extern void *assoc_array_find(const struct assoc_array *array,\n-\t\t\t      const struct assoc_array_ops *ops,\n-\t\t\t      const void *index_key);\n-extern void assoc_array_destroy(struct assoc_array *array,\n-\t\t\t\tconst struct assoc_array_ops *ops);\n-extern struct assoc_array_edit *assoc_array_insert(struct assoc_array *array,\n-\t\t\t\t\t\t   const struct assoc_array_ops *ops,\n-\t\t\t\t\t\t   const void *index_key,\n-\t\t\t\t\t\t   void *object);\n-extern void assoc_array_insert_set_object(struct assoc_array_edit *edit,\n-\t\t\t\t\t  void *object);\n-extern struct assoc_array_edit *assoc_array_delete(struct assoc_array *array,\n-\t\t\t\t\t\t   const struct assoc_array_ops *ops,\n-\t\t\t\t\t\t   const void *index_key);\n-extern struct assoc_array_edit *assoc_array_clear(struct assoc_array *array,\n-\t\t\t\t\t\t  const struct assoc_array_ops *ops);\n-extern void assoc_array_apply_edit(struct assoc_array_edit *edit);\n-extern void assoc_array_cancel_edit(struct assoc_array_edit *edit);\n-extern int assoc_array_gc(struct assoc_array *array,\n-\t\t\t  const struct assoc_array_ops *ops,\n-\t\t\t  bool (*iterator)(void *object, void *iterator_data),\n-\t\t\t  void *iterator_data);\n-\n-#endif /* CONFIG_ASSOCIATIVE_ARRAY */\n-#endif /* _LINUX_ASSOC_ARRAY_H */\ndiff --git a/include/linux/assoc_array_priv.h b/include/linux/assoc_array_priv.h\ndeleted file mode 100644\nindex dca733ef675038..00000000000000\n--- a/include/linux/assoc_array_priv.h\n+++ /dev/null\n@@ -1,178 +0,0 @@\n-/* SPDX-License-Identifier: GPL-2.0-or-later */\n-/* Private definitions for the generic associative array implementation.\n- *\n- * See Documentation/core-api/assoc_array.rst for information.\n- *\n- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.\n- * Written by David Howells (dhowells@redhat.com)\n- */\n-\n-#ifndef _LINUX_ASSOC_ARRAY_PRIV_H\n-#define _LINUX_ASSOC_ARRAY_PRIV_H\n-\n-#ifdef CONFIG_ASSOCIATIVE_ARRAY\n-\n-#include \u003clinux/assoc_array.h\u003e\n-\n-#define ASSOC_ARRAY_FAN_OUT\t\t16\t/* Number of slots per node */\n-#define ASSOC_ARRAY_FAN_MASK\t\t(ASSOC_ARRAY_FAN_OUT - 1)\n-#define ASSOC_ARRAY_LEVEL_STEP\t\t(ilog2(ASSOC_ARRAY_FAN_OUT))\n-#define ASSOC_ARRAY_LEVEL_STEP_MASK\t(ASSOC_ARRAY_LEVEL_STEP - 1)\n-#define ASSOC_ARRAY_KEY_CHUNK_MASK\t(ASSOC_ARRAY_KEY_CHUNK_SIZE - 1)\n-#define ASSOC_ARRAY_KEY_CHUNK_SHIFT\t(ilog2(BITS_PER_LONG))\n-\n-/*\n- * Undefined type representing a pointer with type information in the bottom\n- * two bits.\n- */\n-struct assoc_array_ptr;\n-\n-/*\n- * An N-way node in the tree.\n- *\n- * Each slot contains one of four things:\n- *\n- *\t(1) Nothing (NULL).\n- *\n- *\t(2) A leaf object (pointer types 0).\n- *\n- *\t(3) A next-level node (pointer type 1, subtype 0).\n- *\n- *\t(4) A shortcut (pointer type 1, subtype 1).\n- *\n- * The tree is optimised for search-by-ID, but permits reasonable iteration\n- * also.\n- *\n- * The tree is navigated by constructing an index key consisting of an array of\n- * segments, where each segment is ilog2(ASSOC_ARRAY_FAN_OUT) bits in size.\n- *\n- * The segments correspond to levels of the tree (the first segment is used at\n- * level 0, the second at level 1, etc.).\n- */\n-struct assoc_array_node {\n-\tstruct assoc_array_ptr\t*back_pointer;\n-\tu8\t\t\tparent_slot;\n-\tstruct assoc_array_ptr\t*slots[ASSOC_ARRAY_FAN_OUT];\n-\tunsigned long\t\tnr_leaves_on_branch;\n-};\n-\n-/*\n- * A shortcut through the index space out to where a collection of nodes/leaves\n- * with the same IDs live.\n- */\n-struct assoc_array_shortcut {\n-\tstruct assoc_array_ptr\t*back_pointer;\n-\tint\t\t\tparent_slot;\n-\tint\t\t\tskip_to_level;\n-\tstruct assoc_array_ptr\t*next_node;\n-\tunsigned long\t\tindex_key[];\n-};\n-\n-/*\n- * Preallocation cache.\n- */\n-struct assoc_array_edit {\n-\tstruct rcu_head\t\t\trcu;\n-\tstruct assoc_array\t\t*array;\n-\tconst struct assoc_array_ops\t*ops;\n-\tconst struct assoc_array_ops\t*ops_for_excised_subtree;\n-\tstruct assoc_array_ptr\t\t*leaf;\n-\tstruct assoc_array_ptr\t\t**leaf_p;\n-\tstruct assoc_array_ptr\t\t*dead_leaf;\n-\tstruct assoc_array_ptr\t\t*new_meta[3];\n-\tstruct assoc_array_ptr\t\t*excised_meta[1];\n-\tstruct assoc_array_ptr\t\t*excised_subtree;\n-\tstruct assoc_array_ptr\t\t**set_backpointers[ASSOC_ARRAY_FAN_OUT];\n-\tstruct assoc_array_ptr\t\t*set_backpointers_to;\n-\tstruct assoc_array_node\t\t*adjust_count_on;\n-\tlong\t\t\t\tadjust_count_by;\n-\tstruct {\n-\t\tstruct assoc_array_ptr\t**ptr;\n-\t\tstruct assoc_array_ptr\t*to;\n-\t} set[2];\n-\tstruct {\n-\t\tu8\t\t\t*p;\n-\t\tu8\t\t\tto;\n-\t} set_parent_slot[1];\n-\tu8\t\t\t\tsegment_cache[ASSOC_ARRAY_FAN_OUT + 1];\n-};\n-\n-/*\n- * Internal tree member pointers are marked in the bottom one or two bits to\n- * indicate what type they are so that we don't have to look behind every\n- * pointer to see what it points to.\n- *\n- * We provide functions to test type annotations and to create and translate\n- * the annotated pointers.\n- */\n-#define ASSOC_ARRAY_PTR_TYPE_MASK 0x1UL\n-#define ASSOC_ARRAY_PTR_LEAF_TYPE 0x0UL\t/* Points to leaf (or nowhere) */\n-#define ASSOC_ARRAY_PTR_META_TYPE 0x1UL\t/* Points to node or shortcut */\n-#define ASSOC_ARRAY_PTR_SUBTYPE_MASK\t0x2UL\n-#define ASSOC_ARRAY_PTR_NODE_SUBTYPE\t0x0UL\n-#define ASSOC_ARRAY_PTR_SHORTCUT_SUBTYPE 0x2UL\n-\n-static inline bool assoc_array_ptr_is_meta(const struct assoc_array_ptr *x)\n-{\n-\treturn (unsigned long)x \u0026 ASSOC_ARRAY_PTR_TYPE_MASK;\n-}\n-static inline bool assoc_array_ptr_is_leaf(const struct assoc_array_ptr *x)\n-{\n-\treturn !assoc_array_ptr_is_meta(x);\n-}\n-static inline bool assoc_array_ptr_is_shortcut(const struct assoc_array_ptr *x)\n-{\n-\treturn (unsigned long)x \u0026 ASSOC_ARRAY_PTR_SUBTYPE_MASK;\n-}\n-static inline bool assoc_array_ptr_is_node(const struct assoc_array_ptr *x)\n-{\n-\treturn !assoc_array_ptr_is_shortcut(x);\n-}\n-\n-static inline void *assoc_array_ptr_to_leaf(const struct assoc_array_ptr *x)\n-{\n-\treturn (void *)((unsigned long)x \u0026 ~ASSOC_ARRAY_PTR_TYPE_MASK);\n-}\n-\n-static inline\n-unsigned long __assoc_array_ptr_to_meta(const struct assoc_array_ptr *x)\n-{\n-\treturn (unsigned long)x \u0026\n-\t\t~(ASSOC_ARRAY_PTR_SUBTYPE_MASK | ASSOC_ARRAY_PTR_TYPE_MASK);\n-}\n-static inline\n-struct assoc_array_node *assoc_array_ptr_to_node(const struct assoc_array_ptr *x)\n-{\n-\treturn (struct assoc_array_node *)__assoc_array_ptr_to_meta(x);\n-}\n-static inline\n-struct assoc_array_shortcut *assoc_array_ptr_to_shortcut(const struct assoc_array_ptr *x)\n-{\n-\treturn (struct assoc_array_shortcut *)__assoc_array_ptr_to_meta(x);\n-}\n-\n-static inline\n-struct assoc_array_ptr *__assoc_array_x_to_ptr(const void *p, unsigned long t)\n-{\n-\treturn (struct assoc_array_ptr *)((unsigned long)p | t);\n-}\n-static inline\n-struct assoc_array_ptr *assoc_array_leaf_to_ptr(const void *p)\n-{\n-\treturn __assoc_array_x_to_ptr(p, ASSOC_ARRAY_PTR_LEAF_TYPE);\n-}\n-static inline\n-struct assoc_array_ptr *assoc_array_node_to_ptr(const struct assoc_array_node *p)\n-{\n-\treturn __assoc_array_x_to_ptr(\n-\t\tp, ASSOC_ARRAY_PTR_META_TYPE | ASSOC_ARRAY_PTR_NODE_SUBTYPE);\n-}\n-static inline\n-struct assoc_array_ptr *assoc_array_shortcut_to_ptr(const struct assoc_array_shortcut *p)\n-{\n-\treturn __assoc_array_x_to_ptr(\n-\t\tp, ASSOC_ARRAY_PTR_META_TYPE | ASSOC_ARRAY_PTR_SHORTCUT_SUBTYPE);\n-}\n-\n-#endif /* CONFIG_ASSOCIATIVE_ARRAY */\n-#endif /* _LINUX_ASSOC_ARRAY_PRIV_H */\ndiff --git a/include/linux/key-type.h b/include/linux/key-type.h\nindex c4f329b6ae3fed..bb97bd3e5af4fa 100644\n--- a/include/linux/key-type.h\n+++ b/include/linux/key-type.h\n@@ -161,7 +161,6 @@ struct key_type {\n \t\t\t\t     const void *in, const void *in2);\n \n \t/* internal fields */\n-\tatomic64_t\t\tindex_id;\t/* Opaque keyring index ID */\n \tstruct list_head\tlink;\t\t/* link in types list */\n \tstruct lock_class_key\tlock_class;\t/* key-\u003esem lock class */\n } __randomize_layout;\ndiff --git a/include/linux/key.h b/include/linux/key.h\nindex 420412aab9263a..0d2d64e10f7baf 100644\n--- a/include/linux/key.h\n+++ b/include/linux/key.h\n@@ -17,7 +17,6 @@\n #include \u003clinux/sysctl.h\u003e\n #include \u003clinux/rwsem.h\u003e\n #include \u003clinux/atomic.h\u003e\n-#include \u003clinux/assoc_array.h\u003e\n #include \u003clinux/refcount.h\u003e\n #include \u003clinux/time64.h\u003e\n \n@@ -107,34 +106,21 @@ struct key_owner;\n struct key_tag;\n struct keyring_list;\n struct keyring_name;\n+struct keyring_index;\n \n struct key_tag {\n \tstruct rcu_head\t\trcu;\n-\tatomic64_t\t\tindex_id;\t/* Opaque keyring index ID */\n \trefcount_t\t\tusage;\n \tbool\t\t\tremoved;\t/* T when subject removed */\n };\n \n struct keyring_index_key {\n \t/* [!] If this structure is altered, the union in struct key must change too! */\n-\tunsigned long\t\thash;\t\t\t/* Hash value */\n-\tunion {\n-\t\tstruct {\n-#ifdef __LITTLE_ENDIAN /* Put desc_len at the LSB of x */\n-\t\t\tu16\tdesc_len;\n-\t\t\tchar\tdesc[sizeof(long) - 2];\t/* First few chars of description */\n-#else\n-\t\t\tchar\tdesc[sizeof(long) - 2];\t/* First few chars of description */\n-\t\t\tu16\tdesc_len;\n-#endif\n-\t\t};\n-\t\tunsigned long x;\n-\t};\n+\tu32\t\t\thash;\t\t\t/* Hash value */\n+\tunsigned int\t\tdesc_len;\n \tstruct key_type\t\t*type;\n \tstruct key_tag\t\t*domain_tag;\t/* Domain of operation */\n \tconst char\t\t*description;\n-\tu64\t\t\ttype_id;\t/* Cached index IDs */\n-\tu64\t\t\tdomain_id;\n };\n \n union key_payload {\n@@ -252,13 +238,11 @@ struct key {\n \tunion {\n \t\tstruct keyring_index_key index_key;\n \t\tstruct {\n-\t\t\tunsigned long\thash;\n-\t\t\tunsigned long\tlen_desc;\n+\t\t\tu32\t\thash;\n+\t\t\tunsigned int\tdesc_len;\n \t\t\tstruct key_type\t*type;\t\t/* type of key */\n \t\t\tstruct key_tag\t*domain_tag;\t/* Domain of operation */\n \t\t\tchar\t\t*description;\n-\t\t\tu64\t\ttype_id;\n-\t\t\tu64\t\tdomain_id;\n \t\t};\n \t};\n \n@@ -271,7 +255,7 @@ struct key {\n \t\tstruct {\n \t\t\t/* Keyring bits */\n \t\t\tstruct list_head name_link;\n-\t\t\tstruct assoc_array keys;\n+\t\t\tstruct keyring_index __rcu *index;\n \t\t};\n \t};\n \n@@ -439,6 +423,7 @@ extern int restrict_link_reject(struct key *keyring,\n \t\t\t\tstruct key *restriction_key);\n \n extern int keyring_clear(struct key *keyring);\n+bool keyring_is_empty(const struct key *keyring);\n \n extern key_ref_t keyring_search(key_ref_t keyring,\n \t\t\t\tstruct key_type *type,\ndiff --git a/kernel/bpf/keys.c b/kernel/bpf/keys.c\nindex bffc356839ac56..24e0416abc99dd 100644\n--- a/kernel/bpf/keys.c\n+++ b/kernel/bpf/keys.c\n@@ -29,7 +29,7 @@ struct bpf_key *bpf_lookup_keyring(void)\n \n \tif (!bpf_keyring)\n \t\treturn NULL;\n-\tif (!READ_ONCE(bpf_keyring-\u003ekeys.nr_leaves_on_tree) ||\n+\tif (keyring_is_empty(bpf_keyring) ||\n \t    !READ_ONCE(bpf_keyring-\u003erestrict_link))\n \t\treturn NULL;\n \ndiff --git a/lib/Kconfig b/lib/Kconfig\nindex 1e42f5167c68bc..f70382dbb15954 100644\n--- a/lib/Kconfig\n+++ b/lib/Kconfig\n@@ -349,20 +349,6 @@ config XARRAY_MULTI\n \t  Support entries which occupy multiple consecutive indices in the\n \t  XArray.\n \n-config ASSOCIATIVE_ARRAY\n-\tbool\n-\thelp\n-\t  Generic associative array.  Can be searched and iterated over whilst\n-\t  it is being modified.  It is also reasonably quick to search and\n-\t  modify.  The algorithms are non-recursive, and the trees are highly\n-\t  capacious.\n-\n-\t  See:\n-\n-\t\tDocumentation/core-api/assoc_array.rst\n-\n-\t  for more information.\n-\n config CLOSURES\n \tbool\n \ndiff --git a/lib/Makefile b/lib/Makefile\nindex a2afe954805cb8..4777dfcc824405 100644\n--- a/lib/Makefile\n+++ b/lib/Makefile\n@@ -141,7 +141,6 @@ obj-$(CONFIG_GENERIC_HWEIGHT) += hweight.o\n \n obj-$(CONFIG_BTREE) += btree.o\n obj-$(CONFIG_INTERVAL_TREE) += interval_tree.o\n-obj-$(CONFIG_ASSOCIATIVE_ARRAY) += assoc_array.o\n obj-$(CONFIG_DEBUG_PREEMPT) += smp_processor_id.o\n obj-$(CONFIG_LIST_HARDENED) += list_debug.o\n obj-$(CONFIG_DEBUG_OBJECTS) += debugobjects.o\ndiff --git a/lib/assoc_array.c b/lib/assoc_array.c\ndeleted file mode 100644\nindex b6c9723e12ced5..00000000000000\n--- a/lib/assoc_array.c\n+++ /dev/null\n@@ -1,1724 +0,0 @@\n-// SPDX-License-Identifier: GPL-2.0-or-later\n-/* Generic associative array implementation.\n- *\n- * See Documentation/core-api/assoc_array.rst for information.\n- *\n- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.\n- * Written by David Howells (dhowells@redhat.com)\n- */\n-//#define DEBUG\n-#include \u003clinux/rcupdate.h\u003e\n-#include \u003clinux/slab.h\u003e\n-#include \u003clinux/err.h\u003e\n-#include \u003clinux/assoc_array_priv.h\u003e\n-\n-/*\n- * Iterate over an associative array.  The caller must hold the RCU read lock\n- * or better.\n- */\n-static int assoc_array_subtree_iterate(const struct assoc_array_ptr *root,\n-\t\t\t\t       const struct assoc_array_ptr *stop,\n-\t\t\t\t       int (*iterator)(const void *leaf,\n-\t\t\t\t\t\t       void *iterator_data),\n-\t\t\t\t       void *iterator_data)\n-{\n-\tconst struct assoc_array_shortcut *shortcut;\n-\tconst struct assoc_array_node *node;\n-\tconst struct assoc_array_ptr *cursor, *ptr, *parent;\n-\tunsigned long has_meta;\n-\tint slot, ret;\n-\n-\tcursor = root;\n-\n-begin_node:\n-\tif (assoc_array_ptr_is_shortcut(cursor)) {\n-\t\t/* Descend through a shortcut */\n-\t\tshortcut = assoc_array_ptr_to_shortcut(cursor);\n-\t\tcursor = READ_ONCE(shortcut-\u003enext_node); /* Address dependency. */\n-\t}\n-\n-\tnode = assoc_array_ptr_to_node(cursor);\n-\tslot = 0;\n-\n-\t/* We perform two passes of each node.\n-\t *\n-\t * The first pass does all the leaves in this node.  This means we\n-\t * don't miss any leaves if the node is split up by insertion whilst\n-\t * we're iterating over the branches rooted here (we may, however, see\n-\t * some leaves twice).\n-\t */\n-\thas_meta = 0;\n-\tfor (; slot \u003c ASSOC_ARRAY_FAN_OUT; slot++) {\n-\t\tptr = READ_ONCE(node-\u003eslots[slot]); /* Address dependency. */\n-\t\thas_meta |= (unsigned long)ptr;\n-\t\tif (ptr \u0026\u0026 assoc_array_ptr_is_leaf(ptr)) {\n-\t\t\t/* We need a barrier between the read of the pointer,\n-\t\t\t * which is supplied by the above READ_ONCE().\n-\t\t\t */\n-\t\t\t/* Invoke the callback */\n-\t\t\tret = iterator(assoc_array_ptr_to_leaf(ptr),\n-\t\t\t\t       iterator_data);\n-\t\t\tif (ret)\n-\t\t\t\treturn ret;\n-\t\t}\n-\t}\n-\n-\t/* The second pass attends to all the metadata pointers.  If we follow\n-\t * one of these we may find that we don't come back here, but rather go\n-\t * back to a replacement node with the leaves in a different layout.\n-\t *\n-\t * We are guaranteed to make progress, however, as the slot number for\n-\t * a particular portion of the key space cannot change - and we\n-\t * continue at the back pointer + 1.\n-\t */\n-\tif (!(has_meta \u0026 ASSOC_ARRAY_PTR_META_TYPE))\n-\t\tgoto finished_node;\n-\tslot = 0;\n-\n-continue_node:\n-\tnode = assoc_array_ptr_to_node(cursor);\n-\tfor (; slot \u003c ASSOC_ARRAY_FAN_OUT; slot++) {\n-\t\tptr = READ_ONCE(node-\u003eslots[slot]); /* Address dependency. */\n-\t\tif (assoc_array_ptr_is_meta(ptr)) {\n-\t\t\tcursor = ptr;\n-\t\t\tgoto begin_node;\n-\t\t}\n-\t}\n-\n-finished_node:\n-\t/* Move up to the parent (may need to skip back over a shortcut) */\n-\tparent = READ_ONCE(node-\u003eback_pointer); /* Address dependency. */\n-\tslot = node-\u003eparent_slot;\n-\tif (parent == stop)\n-\t\treturn 0;\n-\n-\tif (assoc_array_ptr_is_shortcut(parent)) {\n-\t\tshortcut = assoc_array_ptr_to_shortcut(parent);\n-\t\tcursor = parent;\n-\t\tparent = READ_ONCE(shortcut-\u003eback_pointer); /* Address dependency. */\n-\t\tslot = shortcut-\u003eparent_slot;\n-\t\tif (parent == stop)\n-\t\t\treturn 0;\n-\t}\n-\n-\t/* Ascend to next slot in parent node */\n-\tcursor = parent;\n-\tslot++;\n-\tgoto continue_node;\n-}\n-\n-/**\n- * assoc_array_iterate - Pass all objects in the array to a callback\n- * @array: The array to iterate over.\n- * @iterator: The callback function.\n- * @iterator_data: Private data for the callback function.\n- *\n- * Iterate over all the objects in an associative array.  Each one will be\n- * presented to the iterator function.\n- *\n- * If the array is being modified concurrently with the iteration then it is\n- * possible that some objects in the array will be passed to the iterator\n- * callback more than once - though every object should be passed at least\n- * once.  If this is undesirable then the caller must lock against modification\n- * for the duration of this function.\n- *\n- * The function will return 0 if no objects were in the array or else it will\n- * return the result of the last iterator function called.  Iteration stops\n- * immediately if any call to the iteration function results in a non-zero\n- * return.\n- *\n- * The caller should hold the RCU read lock or better if concurrent\n- * modification is possible.\n- */\n-int assoc_array_iterate(const struct assoc_array *array,\n-\t\t\tint (*iterator)(const void *object,\n-\t\t\t\t\tvoid *iterator_data),\n-\t\t\tvoid *iterator_data)\n-{\n-\tstruct assoc_array_ptr *root = READ_ONCE(array-\u003eroot); /* Address dependency. */\n-\n-\tif (!root)\n-\t\treturn 0;\n-\treturn assoc_array_subtree_iterate(root, NULL, iterator, iterator_data);\n-}\n-\n-enum assoc_array_walk_status {\n-\tassoc_array_walk_tree_empty,\n-\tassoc_array_walk_found_terminal_node,\n-\tassoc_array_walk_found_wrong_shortcut,\n-};\n-\n-struct assoc_array_walk_result {\n-\tstruct {\n-\t\tstruct assoc_array_node\t*node;\t/* Node in which leaf might be found */\n-\t\tint\t\tlevel;\n-\t\tint\t\tslot;\n-\t} terminal_node;\n-\tstruct {\n-\t\tstruct assoc_array_shortcut *shortcut;\n-\t\tint\t\tlevel;\n-\t\tint\t\tsc_level;\n-\t\tunsigned long\tsc_segments;\n-\t\tunsigned long\tdissimilarity;\n-\t} wrong_shortcut;\n-};\n-\n-/*\n- * Navigate through the internal tree looking for the closest node to the key.\n- */\n-static enum assoc_array_walk_status\n-assoc_array_walk(const struct assoc_array *array,\n-\t\t const struct assoc_array_ops *ops,\n-\t\t const void *index_key,\n-\t\t struct assoc_array_walk_result *result)\n-{\n-\tstruct assoc_array_shortcut *shortcut;\n-\tstruct assoc_array_node *node;\n-\tstruct assoc_array_ptr *cursor, *ptr;\n-\tunsigned long sc_segments, dissimilarity;\n-\tunsigned long segments;\n-\tint level, sc_level, next_sc_level;\n-\tint slot;\n-\n-\tpr_devel(\"--\u003e%s()\\n\", __func__);\n-\n-\tcursor = READ_ONCE(array-\u003eroot);  /* Address dependency. */\n-\tif (!cursor)\n-\t\treturn assoc_array_walk_tree_empty;\n-\n-\tlevel = 0;\n-\n-\t/* Use segments from the key for the new leaf to navigate through the\n-\t * internal tree, skipping through nodes and shortcuts that are on\n-\t * route to the destination.  Eventually we'll come to a slot that is\n-\t * either empty or contains a leaf at which point we've found a node in\n-\t * which the leaf we're looking for might be found or into which it\n-\t * should be inserted.\n-\t */\n-jumped:\n-\tsegments = ops-\u003eget_key_chunk(index_key, level);\n-\tpr_devel(\"segments[%d]: %lx\\n\", level, segments);\n-\n-\tif (assoc_array_ptr_is_shortcut(cursor))\n-\t\tgoto follow_shortcut;\n-\n-consider_node:\n-\tnode = assoc_array_ptr_to_node(cursor);\n-\tslot = segments \u003e\u003e (level \u0026 ASSOC_ARRAY_KEY_CHUNK_MASK);\n-\tslot \u0026= ASSOC_ARRAY_FAN_MASK;\n-\tptr = READ_ONCE(node-\u003eslots[slot]); /* Address dependency. */\n-\n-\tpr_devel(\"consider slot %x [ix=%d type=%lu]\\n\",\n-\t\t slot, level, (unsigned long)ptr \u0026 3);\n-\n-\tif (!assoc_array_ptr_is_meta(ptr)) {\n-\t\t/* The node doesn't have a node/shortcut pointer in the slot\n-\t\t * corresponding to the index key that we have to follow.\n-\t\t */\n-\t\tresult-\u003eterminal_node.node = node;\n-\t\tresult-\u003eterminal_node.level = level;\n-\t\tresult-\u003eterminal_node.slot = slot;\n-\t\tpr_devel(\"\u003c--%s() = terminal_node\\n\", __func__);\n-\t\treturn assoc_array_walk_found_terminal_node;\n-\t}\n-\n-\tif (assoc_array_ptr_is_node(ptr)) {\n-\t\t/* There is a pointer to a node in the slot corresponding to\n-\t\t * this index key segment, so we need to follow it.\n-\t\t */\n-\t\tcursor = ptr;\n-\t\tlevel += ASSOC_ARRAY_LEVEL_STEP;\n-\t\tif ((level \u0026 ASSOC_ARRAY_KEY_CHUNK_MASK) != 0)\n-\t\t\tgoto consider_node;\n-\t\tgoto jumped;\n-\t}\n-\n-\t/* There is a shortcut in the slot corresponding to the index key\n-\t * segment.  We follow the shortcut if its partial index key matches\n-\t * this leaf's.  Otherwise we need to split the shortcut.\n-\t */\n-\tcursor = ptr;\n-follow_shortcut:\n-\tshortcut = assoc_array_ptr_to_shortcut(cursor);\n-\tpr_devel(\"shortcut to %d\\n\", shortcut-\u003eskip_to_level);\n-\tsc_level = level + ASSOC_ARRAY_LEVEL_STEP;\n-\tBUG_ON(sc_level \u003e shortcut-\u003eskip_to_level);\n-\n-\tdo {\n-\t\t/* Check the leaf against the shortcut's index key a word at a\n-\t\t * time, trimming the final word (the shortcut stores the index\n-\t\t * key completely from the root to the shortcut's target).\n-\t\t */\n-\t\tif ((sc_level \u0026 ASSOC_ARRAY_KEY_CHUNK_MASK) == 0)\n-\t\t\tsegments = ops-\u003eget_key_chunk(index_key, sc_level);\n-\n-\t\tsc_segments = shortcut-\u003eindex_key[sc_level \u003e\u003e ASSOC_ARRAY_KEY_CHUNK_SHIFT];\n-\t\tdissimilarity = segments ^ sc_segments;\n-\n-\t\tif (shortcut-\u003eskip_to_level \u003c round_down(sc_level,\n-\t\t\t\tASSOC_ARRAY_KEY_CHUNK_SIZE) + ASSOC_ARRAY_KEY_CHUNK_SIZE) {\n-\t\t\t/* Trim segments that are beyond the shortcut */\n-\t\t\tint shift = shortcut-\u003eskip_to_level \u0026 ASSOC_ARRAY_KEY_CHUNK_MASK;\n-\t\t\tdissimilarity \u0026= ~(ULONG_MAX \u003c\u003c shift);\n-\t\t\tnext_sc_level = shortcut-\u003eskip_to_level;\n-\t\t} else {\n-\t\t\tnext_sc_level = sc_level + ASSOC_ARRAY_KEY_CHUNK_SIZE;\n-\t\t\tnext_sc_level = round_down(next_sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);\n-\t\t}\n-\n-\t\tif (dissimilarity != 0) {\n-\t\t\t/* This shortcut points elsewhere */\n-\t\t\tresult-\u003ewrong_shortcut.shortcut = shortcut;\n-\t\t\tresult-\u003ewrong_shortcut.level = level;\n-\t\t\tresult-\u003ewrong_shortcut.sc_level = sc_level;\n-\t\t\tresult-\u003ewrong_shortcut.sc_segments = sc_segments;\n-\t\t\tresult-\u003ewrong_shortcut.dissimilarity = dissimilarity;\n-\t\t\treturn assoc_array_walk_found_wrong_shortcut;\n-\t\t}\n-\n-\t\tsc_level = next_sc_level;\n-\t} while (sc_level \u003c shortcut-\u003eskip_to_level);\n-\n-\t/* The shortcut matches the leaf's index to this point. */\n-\tcursor = READ_ONCE(shortcut-\u003enext_node); /* Address dependency. */\n-\tif (((level ^ sc_level) \u0026 ~ASSOC_ARRAY_KEY_CHUNK_MASK) != 0) {\n-\t\tlevel = sc_level;\n-\t\tgoto jumped;\n-\t} else {\n-\t\tlevel = sc_level;\n-\t\tgoto consider_node;\n-\t}\n-}\n-\n-/**\n- * assoc_array_find - Find an object by index key\n- * @array: The associative array to search.\n- * @ops: The operations to use.\n- * @index_key: The key to the object.\n- *\n- * Find an object in an associative array by walking through the internal tree\n- * to the node that should contain the object and then searching the leaves\n- * there.  NULL is returned if the requested object was not found in the array.\n- *\n- * The caller must hold the RCU read lock or better.\n- */\n-void *assoc_array_find(const struct assoc_array *array,\n-\t\t       const struct assoc_array_ops *ops,\n-\t\t       const void *index_key)\n-{\n-\tstruct assoc_array_walk_result result;\n-\tconst struct assoc_array_node *node;\n-\tconst struct assoc_array_ptr *ptr;\n-\tconst void *leaf;\n-\tint slot;\n-\n-\tif (assoc_array_walk(array, ops, index_key, \u0026result) !=\n-\t    assoc_array_walk_found_terminal_node)\n-\t\treturn NULL;\n-\n-\tnode = result.terminal_node.node;\n-\n-\t/* If the target key is available to us, it's has to be pointed to by\n-\t * the terminal node.\n-\t */\n-\tfor (slot = 0; slot \u003c ASSOC_ARRAY_FAN_OUT; slot++) {\n-\t\tptr = READ_ONCE(node-\u003eslots[slot]); /* Address dependency. */\n-\t\tif (ptr \u0026\u0026 assoc_array_ptr_is_leaf(ptr)) {\n-\t\t\t/* We need a barrier between the read of the pointer\n-\t\t\t * and dereferencing the pointer - but only if we are\n-\t\t\t * actually going to dereference it.\n-\t\t\t */\n-\t\t\tleaf = assoc_array_ptr_to_leaf(ptr);\n-\t\t\tif (ops-\u003ecompare_object(leaf, index_key))\n-\t\t\t\treturn (void *)leaf;\n-\t\t}\n-\t}\n-\n-\treturn NULL;\n-}\n-\n-/*\n- * Destructively iterate over an associative array.  The caller must prevent\n- * other simultaneous accesses.\n- */\n-static void assoc_array_destroy_subtree(struct assoc_array_ptr *root,\n-\t\t\t\t\tconst struct assoc_array_ops *ops)\n-{\n-\tstruct assoc_array_shortcut *shortcut;\n-\tstruct assoc_array_node *node;\n-\tstruct assoc_array_ptr *cursor, *parent = NULL;\n-\tint slot = -1;\n-\n-\tpr_devel(\"--\u003e%s()\\n\", __func__);\n-\n-\tcursor = root;\n-\tif (!cursor) {\n-\t\tpr_devel(\"empty\\n\");\n-\t\treturn;\n-\t}\n-\n-move_to_meta:\n-\tif (assoc_array_ptr_is_shortcut(cursor)) {\n-\t\t/* Descend through a shortcut */\n-\t\tpr_devel(\"[%d] shortcut\\n\", slot);\n-\t\tBUG_ON(!assoc_array_ptr_is_shortcut(cursor));\n-\t\tshortcut = assoc_array_ptr_to_shortcut(cursor);\n-\t\tBUG_ON(shortcut-\u003eback_pointer != parent);\n-\t\tBUG_ON(slot != -1 \u0026\u0026 shortcut-\u003eparent_slot != slot);\n-\t\tparent = cursor;\n-\t\tcursor = shortcut-\u003enext_node;\n-\t\tslot = -1;\n-\t\tBUG_ON(!assoc_array_ptr_is_node(cursor));\n-\t}\n-\n-\tpr_devel(\"[%d] node\\n\", slot);\n-\tnode = assoc_array_ptr_to_node(cursor);\n-\tBUG_ON(node-\u003eback_pointer != parent);\n-\tBUG_ON(slot != -1 \u0026\u0026 node-\u003eparent_slot != slot);\n-\tslot = 0;\n-\n-continue_node:\n-\tpr_devel(\"Node %p [back=%p]\\n\", node, node-\u003eback_pointer);\n-\tfor (; slot \u003c ASSOC_ARRAY_FAN_OUT; slot++) {\n-\t\tstruct assoc_array_ptr *ptr = node-\u003eslots[slot];\n-\t\tif (!ptr)\n-\t\t\tcontinue;\n-\t\tif (assoc_array_ptr_is_meta(ptr)) {\n-\t\t\tparent = cursor;\n-\t\t\tcursor = ptr;\n-\t\t\tgoto move_to_meta;\n-\t\t}\n-\n-\t\tif (ops) {\n-\t\t\tpr_devel(\"[%d] free leaf\\n\", slot);\n-\t\t\tops-\u003efree_object(assoc_array_ptr_to_leaf(ptr));\n-\t\t}\n-\t}\n-\n-\tparent = node-\u003eback_pointer;\n-\tslot = node-\u003eparent_slot;\n-\tpr_devel(\"free node\\n\");\n-\tkfree(node);\n-\tif (!parent)\n-\t\treturn; /* Done */\n-\n-\t/* Move back up to the parent (may need to free a shortcut on\n-\t * the way up) */\n-\tif (assoc_array_ptr_is_shortcut(parent)) {\n-\t\tshortcut = assoc_array_ptr_to_shortcut(parent);\n-\t\tBUG_ON(shortcut-\u003enext_node != cursor);\n-\t\tcursor = parent;\n-\t\tparent = shortcut-\u003eback_pointer;\n-\t\tslot = shortcut-\u003eparent_slot;\n-\t\tpr_devel(\"free shortcut\\n\");\n-\t\tkfree(shortcut);\n-\t\tif (!parent)\n-\t\t\treturn;\n-\n-\t\tBUG_ON(!assoc_array_ptr_is_node(parent));\n-\t}\n-\n-\t/* Ascend to next slot in parent node */\n-\tpr_devel(\"ascend to %p[%d]\\n\", parent, slot);\n-\tcursor = parent;\n-\tnode = assoc_array_ptr_to_node(cursor);\n-\tslot++;\n-\tgoto continue_node;\n-}\n-\n-/**\n- * assoc_array_destroy - Destroy an associative array\n- * @array: The array to destroy.\n- * @ops: The operations to use.\n- *\n- * Discard all metadata and free all objects in an associative array.  The\n- * array will be empty and ready to use again upon completion.  This function\n- * cannot fail.\n- *\n- * The caller must prevent all other accesses whilst this takes place as no\n- * attempt is made to adjust pointers gracefully to permit RCU readlock-holding\n- * accesses to continue.  On the other hand, no memory allocation is required.\n- */\n-void assoc_array_destroy(struct assoc_array *array,\n-\t\t\t const struct assoc_array_ops *ops)\n-{\n-\tassoc_array_destroy_subtree(array-\u003eroot, ops);\n-\tarray-\u003eroot = NULL;\n-}\n-\n-/*\n- * Handle insertion into an empty tree.\n- */\n-static bool assoc_array_insert_in_empty_tree(struct assoc_array_edit *edit)\n-{\n-\tstruct assoc_array_node *new_n0;\n-\n-\tpr_devel(\"--\u003e%s()\\n\", __func__);\n-\n-\tnew_n0 = kzalloc_obj(struct assoc_array_node);\n-\tif (!new_n0)\n-\t\treturn false;\n-\n-\tedit-\u003enew_meta[0] = assoc_array_node_to_ptr(new_n0);\n-\tedit-\u003eleaf_p = \u0026new_n0-\u003eslots[0];\n-\tedit-\u003eadjust_count_on = new_n0;\n-\tedit-\u003eset[0].ptr = \u0026edit-\u003earray-\u003eroot;\n-\tedit-\u003eset[0].to = assoc_array_node_to_ptr(new_n0);\n-\n-\tpr_devel(\"\u003c--%s() = ok [no root]\\n\", __func__);\n-\treturn true;\n-}\n-\n-/*\n- * Handle insertion into a terminal node.\n- */\n-static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit,\n-\t\t\t\t\t\t  const struct assoc_array_ops *ops,\n-\t\t\t\t\t\t  const void *index_key,\n-\t\t\t\t\t\t  struct assoc_array_walk_result *result)\n-{\n-\tstruct assoc_array_shortcut *shortcut, *new_s0;\n-\tstruct assoc_array_node *node, *new_n0, *new_n1, *side;\n-\tstruct assoc_array_ptr *ptr;\n-\tunsigned long dissimilarity, base_seg, blank;\n-\tsize_t keylen;\n-\tbool have_meta;\n-\tint level, diff;\n-\tint slot, next_slot, free_slot, i, j;\n-\n-\tnode\t= result-\u003eterminal_node.node;\n-\tlevel\t= result-\u003eterminal_node.level;\n-\tedit-\u003esegment_cache[ASSOC_ARRAY_FAN_OUT] = result-\u003eterminal_node.slot;\n-\n-\tpr_devel(\"--\u003e%s()\\n\", __func__);\n-\n-\t/* We arrived at a node which doesn't have an onward node or shortcut\n-\t * pointer that we have to follow.  This means that (a) the leaf we\n-\t * want must go here (either by insertion or replacement) or (b) we\n-\t * need to split this node and insert in one of the fragments.\n-\t */\n-\tfree_slot = -1;\n-\n-\t/* Firstly, we have to check the leaves in this node to see if there's\n-\t * a matching one we should replace in place.\n-\t */\n-\tfor (i = 0; i \u003c ASSOC_ARRAY_FAN_OUT; i++) {\n-\t\tptr = node-\u003eslots[i];\n-\t\tif (!ptr) {\n-\t\t\tfree_slot = i;\n-\t\t\tcontinue;\n-\t\t}\n-\t\tif (assoc_array_ptr_is_leaf(ptr) \u0026\u0026\n-\t\t    ops-\u003ecompare_object(assoc_array_ptr_to_leaf(ptr),\n-\t\t\t\t\tindex_key)) {\n-\t\t\tpr_devel(\"replace in slot %d\\n\", i);\n-\t\t\tedit-\u003eleaf_p = \u0026node-\u003eslots[i];\n-\t\t\tedit-\u003edead_leaf = node-\u003eslots[i];\n-\t\t\tpr_devel(\"\u003c--%s() = ok [replace]\\n\", __func__);\n-\t\t\treturn true;\n-\t\t}\n-\t}\n-\n-\t/* If there is a free slot in this node then we can just insert the\n-\t * leaf here.\n-\t */\n-\tif (free_slot \u003e= 0) {\n-\t\tpr_devel(\"insert in free slot %d\\n\", free_slot);\n-\t\tedit-\u003eleaf_p = \u0026node-\u003eslots[free_slot];\n-\t\tedit-\u003eadjust_count_on = node;\n-\t\tpr_devel(\"\u003c--%s() = ok [insert]\\n\", __func__);\n-\t\treturn true;\n-\t}\n-\n-\t/* The node has no spare slots - so we're either going to have to split\n-\t * it or insert another node before it.\n-\t *\n-\t * Whatever, we're going to need at least two new nodes - so allocate\n-\t * those now.  We may also need a new shortcut, but we deal with that\n-\t * when we need it.\n-\t */\n-\tnew_n0 = kzalloc_obj(struct assoc_array_node);\n-\tif (!new_n0)\n-\t\treturn false;\n-\tedit-\u003enew_meta[0] = assoc_array_node_to_ptr(new_n0);\n-\tnew_n1 = kzalloc_obj(struct assoc_array_node);\n-\tif (!new_n1)\n-\t\treturn false;\n-\tedit-\u003enew_meta[1] = assoc_array_node_to_ptr(new_n1);\n-\n-\t/* We need to find out how similar the leaves are. */\n-\tpr_devel(\"no spare slots\\n\");\n-\thave_meta = false;\n-\tfor (i = 0; i \u003c ASSOC_ARRAY_FAN_OUT; i++) {\n-\t\tptr = node-\u003eslots[i];\n-\t\tif (assoc_array_ptr_is_meta(ptr)) {\n-\t\t\tedit-\u003esegment_cache[i] = 0xff;\n-\t\t\thave_meta = true;\n-\t\t\tcontinue;\n-\t\t}\n-\t\tbase_seg = ops-\u003eget_object_key_chunk(\n-\t\t\tassoc_array_ptr_to_leaf(ptr), level);\n-\t\tbase_seg \u003e\u003e= level \u0026 ASSOC_ARRAY_KEY_CHUNK_MASK;\n-\t\tedit-\u003esegment_cache[i] = base_seg \u0026 ASSOC_ARRAY_FAN_MASK;\n-\t}\n-\n-\tif (have_meta) {\n-\t\tpr_devel(\"have meta\\n\");\n-\t\tgoto split_node;\n-\t}\n-\n-\t/* The node contains only leaves */\n-\tdissimilarity = 0;\n-\tbase_seg = edit-\u003esegment_cache[0];\n-\tfor (i = 1; i \u003c ASSOC_ARRAY_FAN_OUT; i++)\n-\t\tdissimilarity |= edit-\u003esegment_cache[i] ^ base_seg;\n-\n-\tpr_devel(\"only leaves; dissimilarity=%lx\\n\", dissimilarity);\n-\n-\tif ((dissimilarity \u0026 ASSOC_ARRAY_FAN_MASK) == 0) {\n-\t\t/* The old leaves all cluster in the same slot.  We will need\n-\t\t * to insert a shortcut if the new node wants to cluster with them.\n-\t\t */\n-\t\tif ((edit-\u003esegment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0)\n-\t\t\tgoto all_leaves_cluster_together;\n-\n-\t\t/* Otherwise all the old leaves cluster in the same slot, but\n-\t\t * the new leaf wants to go into a different slot - so we\n-\t\t * create a new node (n0) to hold the new leaf and a pointer to\n-\t\t * a new node (n1) holding all the old leaves.\n-\t\t *\n-\t\t * This can be done by falling through to the node splitting\n-\t\t * path.\n-\t\t */\n-\t\tpr_devel(\"present leaves cluster but not new leaf\\n\");\n-\t}\n-\n-split_node:\n-\tpr_devel(\"split node\\n\");\n-\n-\t/* We need to split the current node.  The node must contain anything\n-\t * from a single leaf (in the one leaf case, this leaf will cluster\n-\t * with the new leaf) and the rest meta-pointers, to all leaves, some\n-\t * of which may cluster.\n-\t *\n-\t * It won't contain the case in which all the current leaves plus the\n-\t * new leaves want to cluster in the same slot.\n-\t *\n-\t * We need to expel at least two leaves out of a set consisting of the\n-\t * leaves in the node and the new leaf.  The current meta pointers can\n-\t * just be copied as they shouldn't cluster with any of the leaves.\n-\t *\n-\t * We need a new node (n0) to replace the current one and a new node to\n-\t * take the expelled nodes (n1).\n-\t */\n-\tedit-\u003eset[0].to = assoc_array_node_to_ptr(new_n0);\n-\tnew_n0-\u003eback_pointer = node-\u003eback_pointer;\n-\tnew_n0-\u003eparent_slot = node-\u003eparent_slot;\n-\tnew_n1-\u003eback_pointer = assoc_array_node_to_ptr(new_n0);\n-\tnew_n1-\u003eparent_slot = -1; /* Need to calculate this */\n-\n-do_split_node:\n-\tpr_devel(\"do_split_node\\n\");\n-\n-\tnew_n0-\u003enr_leaves_on_branch = node-\u003enr_leaves_on_branch;\n-\tnew_n1-\u003enr_leaves_on_branch = 0;\n-\n-\t/* Begin by finding two matching leaves.  There have to be at least two\n-\t * that match - even if there are meta pointers - because any leaf that\n-\t * would match a slot with a meta pointer in it must be somewhere\n-\t * behind that meta pointer and cannot be here.  Further, given N\n-\t * remaining leaf slots, we now have N+1 leaves to go in them.\n-\t */\n-\tfor (i = 0; i \u003c ASSOC_ARRAY_FAN_OUT; i++) {\n-\t\tslot = edit-\u003esegment_cache[i];\n-\t\tif (slot != 0xff)\n-\t\t\tfor (j = i + 1; j \u003c ASSOC_ARRAY_FAN_OUT + 1; j++)\n-\t\t\t\tif (edit-\u003esegment_cache[j] == slot)\n-\t\t\t\t\tgoto found_slot_for_multiple_occupancy;\n-\t}\n-found_slot_for_multiple_occupancy:\n-\tpr_devel(\"same slot: %x %x [%02x]\\n\", i, j, slot);\n-\tBUG_ON(i \u003e= ASSOC_ARRAY_FAN_OUT);\n-\tBUG_ON(j \u003e= ASSOC_ARRAY_FAN_OUT + 1);\n-\tBUG_ON(slot \u003e= ASSOC_ARRAY_FAN_OUT);\n-\n-\tnew_n1-\u003eparent_slot = slot;\n-\n-\t/* Metadata pointers cannot change slot */\n-\tfor (i = 0; i \u003c ASSOC_ARRAY_FAN_OUT; i++)\n-\t\tif (assoc_array_ptr_is_meta(node-\u003eslots[i]))\n-\t\t\tnew_n0-\u003eslots[i] = node-\u003eslots[i];\n-\t\telse\n-\t\t\tnew_n0-\u003eslots[i] = NULL;\n-\tBUG_ON(new_n0-\u003eslots[slot] != NULL);\n-\tnew_n0-\u003eslots[slot] = assoc_array_node_to_ptr(new_n1);\n-\n-\t/* Filter the leaf pointers between the new nodes */\n-\tfree_slot = -1;\n-\tnext_slot = 0;\n-\tfor (i = 0; i \u003c ASSOC_ARRAY_FAN_OUT; i++) {\n-\t\tif (assoc_array_ptr_is_meta(node-\u003eslots[i]))\n-\t\t\tcontinue;\n-\t\tif (edit-\u003esegment_cache[i] == slot) {\n-\t\t\tnew_n1-\u003eslots[next_slot++] = node-\u003eslots[i];\n-\t\t\tnew_n1-\u003enr_leaves_on_branch++;\n-\t\t} else {\n-\t\t\tdo {\n-\t\t\t\tfree_slot++;\n-\t\t\t} while (new_n0-\u003eslots[free_slot] != NULL);\n-\t\t\tnew_n0-\u003eslots[free_slot] = node-\u003eslots[i];\n-\t\t}\n-\t}\n-\n-\tpr_devel(\"filtered: f=%x n=%x\\n\", free_slot, next_slot);\n-\n-\tif (edit-\u003esegment_cache[ASSOC_ARRAY_FAN_OUT] != slot) {\n-\t\tdo {\n-\t\t\tfree_slot++;\n-\t\t} while (new_n0-\u003eslots[free_slot] != NULL);\n-\t\tedit-\u003eleaf_p = \u0026new_n0-\u003eslots[free_slot];\n-\t\tedit-\u003eadjust_count_on = new_n0;\n-\t} else {\n-\t\tedit-\u003eleaf_p = \u0026new_n1-\u003eslots[next_slot++];\n-\t\tedit-\u003eadjust_count_on = new_n1;\n-\t}\n-\n-\tBUG_ON(next_slot \u003c= 1);\n-\n-\tedit-\u003eset_backpointers_to = assoc_array_node_to_ptr(new_n0);\n-\tfor (i = 0; i \u003c ASSOC_ARRAY_FAN_OUT; i++) {\n-\t\tif (edit-\u003esegment_cache[i] == 0xff) {\n-\t\t\tptr = node-\u003eslots[i];\n-\t\t\tBUG_ON(assoc_array_ptr_is_leaf(ptr));\n-\t\t\tif (assoc_array_ptr_is_node(ptr)) {\n-\t\t\t\tside = assoc_array_ptr_to_node(ptr);\n-\t\t\t\tedit-\u003eset_backpointers[i] = \u0026side-\u003eback_pointer;\n-\t\t\t} else {\n-\t\t\t\tshortcut = assoc_array_ptr_to_shortcut(ptr);\n-\t\t\t\tedit-\u003eset_backpointers[i] = \u0026shortcut-\u003eback_pointer;\n-\t\t\t}\n-\t\t}\n-\t}\n-\n-\tptr = node-\u003eback_pointer;\n-\tif (!ptr)\n-\t\tedit-\u003eset[0].ptr = \u0026edit-\u003earray-\u003eroot;\n-\telse if (assoc_array_ptr_is_node(ptr))\n-\t\tedit-\u003eset[0].ptr = \u0026assoc_array_ptr_to_node(ptr)-\u003eslots[node-\u003eparent_slot];\n-\telse\n-\t\tedit-\u003eset[0].ptr = \u0026assoc_array_ptr_to_shortcut(ptr)-\u003enext_node;\n-\tedit-\u003eexcised_meta[0] = assoc_array_node_to_ptr(node);\n-\tpr_devel(\"\u003c--%s() = ok [split node]\\n\", __func__);\n-\treturn true;\n-\n-all_leaves_cluster_together:\n-\t/* All the leaves, new and old, want to cluster together in this node\n-\t * in the same slot, so we have to replace this node with a shortcut to\n-\t * skip over the identical parts of the key and then place a pair of\n-\t * nodes, one inside the other, at the end of the shortcut and\n-\t * distribute the keys between them.\n-\t *\n-\t * Firstly we need to work out where the leaves start diverging as a\n-\t * bit position into their keys so that we know how big the shortcut\n-\t * needs to be.\n-\t *\n-\t * We only need to make a single pass of N of the N+1 leaves because if\n-\t * any keys differ between themselves at bit X then at least one of\n-\t * them must also differ with the base key at bit X or before.\n-\t */\n-\tpr_devel(\"all leaves cluster together\\n\");\n-\tdiff = INT_MAX;\n-\tfor (i = 0; i \u003c ASSOC_ARRAY_FAN_OUT; i++) {\n-\t\tint x = ops-\u003ediff_objects(assoc_array_ptr_to_leaf(node-\u003eslots[i]),\n-\t\t\t\t\t  index_key);\n-\t\tif (x \u003c diff) {\n-\t\t\tBUG_ON(x \u003c 0);\n-\t\t\tdiff = x;\n-\t\t}\n-\t}\n-\tBUG_ON(diff == INT_MAX);\n-\tBUG_ON(diff \u003c level + ASSOC_ARRAY_LEVEL_STEP);\n-\n-\tkeylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);\n-\tkeylen \u003e\u003e= ASSOC_ARRAY_KEY_CHUNK_SHIFT;\n-\n-\tnew_s0 = kzalloc_flex(*new_s0, index_key, keylen);\n-\tif (!new_s0)\n-\t\treturn false;\n-\tedit-\u003enew_meta[2] = assoc_array_shortcut_to_ptr(new_s0);\n-\n-\tedit-\u003eset[0].to = assoc_array_shortcut_to_ptr(new_s0);\n-\tnew_s0-\u003eback_pointer = node-\u003eback_pointer;\n-\tnew_s0-\u003eparent_slot = node-\u003eparent_slot;\n-\tnew_s0-\u003enext_node = assoc_array_node_to_ptr(new_n0);\n-\tnew_n0-\u003eback_pointer = assoc_array_shortcut_to_ptr(new_s0);\n-\tnew_n0-\u003eparent_slot = 0;\n-\tnew_n1-\u003eback_pointer = assoc_array_node_to_ptr(new_n0);\n-\tnew_n1-\u003eparent_slot = -1; /* Need to calculate this */\n-\n-\tnew_s0-\u003eskip_to_level = level = diff \u0026 ~ASSOC_ARRAY_LEVEL_STEP_MASK;\n-\tpr_devel(\"skip_to_level = %d [diff %d]\\n\", level, diff);\n-\tBUG_ON(level \u003c= 0);\n-\n-\tfor (i = 0; i \u003c keylen; i++)\n-\t\tnew_s0-\u003eindex_key[i] =\n-\t\t\tops-\u003eget_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE);\n-\n-\tif (level \u0026 ASSOC_ARRAY_KEY_CHUNK_MASK) {\n-\t\tblank = ULONG_MAX \u003c\u003c (level \u0026 ASSOC_ARRAY_KEY_CHUNK_MASK);\n-\t\tpr_devel(\"blank off [%zu] %d: %lx\\n\", keylen - 1, level, blank);\n-\t\tnew_s0-\u003eindex_key[keylen - 1] \u0026= ~blank;\n-\t}\n-\n-\t/* This now reduces to a node splitting exercise for which we'll need\n-\t * to regenerate the disparity table.\n-\t */\n-\tfor (i = 0; i \u003c ASSOC_ARRAY_FAN_OUT; i++) {\n-\t\tptr = node-\u003eslots[i];\n-\t\tbase_seg = ops-\u003eget_object_key_chunk(assoc_array_ptr_to_leaf(ptr),\n-\t\t\t\t\t\t     level);\n-\t\tbase_seg \u003e\u003e= level \u0026 ASSOC_ARRAY_KEY_CHUNK_MASK;\n-\t\tedit-\u003esegment_cache[i] = base_seg \u0026 ASSOC_ARRAY_FAN_MASK;\n-\t}\n-\n-\tbase_seg = ops-\u003eget_key_chunk(index_key, level);\n-\tbase_seg \u003e\u003e= level \u0026 ASSOC_ARRAY_KEY_CHUNK_MASK;\n-\tedit-\u003esegment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg \u0026 ASSOC_ARRAY_FAN_MASK;\n-\tgoto do_split_node;\n-}\n-\n-/*\n- * Handle insertion into the middle of a shortcut.\n- */\n-static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit,\n-\t\t\t\t\t    const struct assoc_array_ops *ops,\n-\t\t\t\t\t    struct assoc_array_walk_result *result)\n-{\n-\tstruct assoc_array_shortcut *shortcut, *new_s0, *new_s1;\n-\tstruct assoc_array_node *node, *new_n0, *side;\n-\tunsigned long sc_segments, dissimilarity, blank;\n-\tsize_t keylen;\n-\tint level, sc_level, diff;\n-\tint sc_slot;\n-\n-\tshortcut\t= result-\u003ewrong_shortcut.shortcut;\n-\tlevel\t\t= result-\u003ewrong_shortcut.level;\n-\tsc_level\t= result-\u003ewrong_shortcut.sc_level;\n-\tsc_segments\t= result-\u003ewrong_shortcut.sc_segments;\n-\tdissimilarity\t= result-\u003ewrong_shortcut.dissimilarity;\n-\n-\tpr_devel(\"--\u003e%s(ix=%d dis=%lx scix=%d)\\n\",\n-\t\t __func__, level, dissimilarity, sc_level);\n-\n-\t/* We need to split a shortcut and insert a node between the two\n-\t * pieces.  Zero-length pieces will be dispensed with entirely.\n-\t *\n-\t * First of all, we need to find out in which level the first\n-\t * difference was.\n-\t */\n-\tdiff = __ffs(dissimilarity);\n-\tdiff \u0026= ~ASSOC_ARRAY_LEVEL_STEP_MASK;\n-\tdiff += sc_level \u0026 ~ASSOC_ARRAY_KEY_CHUNK_MASK;\n-\tpr_devel(\"diff=%d\\n\", diff);\n-\n-\tif (!shortcut-\u003eback_pointer) {\n-\t\tedit-\u003eset[0].ptr = \u0026edit-\u003earray-\u003eroot;\n-\t} else if (assoc_array_ptr_is_node(shortcut-\u003eback_pointer)) {\n-\t\tnode = assoc_array_ptr_to_node(shortcut-\u003eback_pointer);\n-\t\tedit-\u003eset[0].ptr = \u0026node-\u003eslots[shortcut-\u003eparent_slot];\n-\t} else {\n-\t\tBUG();\n-\t}\n-\n-\tedit-\u003eexcised_meta[0] = assoc_array_shortcut_to_ptr(shortcut);\n-\n-\t/* Create a new node now since we're going to need it anyway */\n-\tnew_n0 = kzalloc_obj(struct assoc_array_node);\n-\tif (!new_n0)\n-\t\treturn false;\n-\tedit-\u003enew_meta[0] = assoc_array_node_to_ptr(new_n0);\n-\tedit-\u003eadjust_count_on = new_n0;\n-\n-\t/* Insert a new shortcut before the new node if this segment isn't of\n-\t * zero length - otherwise we just connect the new node directly to the\n-\t * parent.\n-\t */\n-\tlevel += ASSOC_ARRAY_LEVEL_STEP;\n-\tif (diff \u003e level) {\n-\t\tpr_devel(\"pre-shortcut %d...%d\\n\", level, diff);\n-\t\tkeylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);\n-\t\tkeylen \u003e\u003e= ASSOC_ARRAY_KEY_CHUNK_SHIFT;\n-\n-\t\tnew_s0 = kzalloc_flex(*new_s0, index_key, keylen);\n-\t\tif (!new_s0)\n-\t\t\treturn false;\n-\t\tedit-\u003enew_meta[1] = assoc_array_shortcut_to_ptr(new_s0);\n-\t\tedit-\u003eset[0].to = assoc_array_shortcut_to_ptr(new_s0);\n-\t\tnew_s0-\u003eback_pointer = shortcut-\u003eback_pointer;\n-\t\tnew_s0-\u003eparent_slot = shortcut-\u003eparent_slot;\n-\t\tnew_s0-\u003enext_node = assoc_array_node_to_ptr(new_n0);\n-\t\tnew_s0-\u003eskip_to_level = diff;\n-\n-\t\tnew_n0-\u003eback_pointer = assoc_array_shortcut_to_ptr(new_s0);\n-\t\tnew_n0-\u003eparent_slot = 0;\n-\n-\t\tmemcpy(new_s0-\u003eindex_key, shortcut-\u003eindex_key,\n-\t\t       flex_array_size(new_s0, index_key, keylen));\n-\n-\t\tblank = ULONG_MAX \u003c\u003c (diff \u0026 ASSOC_ARRAY_KEY_CHUNK_MASK);\n-\t\tpr_devel(\"blank off [%zu] %d: %lx\\n\", keylen - 1, diff, blank);\n-\t\tnew_s0-\u003eindex_key[keylen - 1] \u0026= ~blank;\n-\t} else {\n-\t\tpr_devel(\"no pre-shortcut\\n\");\n-\t\tedit-\u003eset[0].to = assoc_array_node_to_ptr(new_n0);\n-\t\tnew_n0-\u003eback_pointer = shortcut-\u003eback_pointer;\n-\t\tnew_n0-\u003eparent_slot = shortcut-\u003eparent_slot;\n-\t}\n-\n-\tside = assoc_array_ptr_to_node(shortcut-\u003enext_node);\n-\tnew_n0-\u003enr_leaves_on_branch = side-\u003enr_leaves_on_branch;\n-\n-\t/* We need to know which slot in the new node is going to take a\n-\t * metadata pointer.\n-\t */\n-\tsc_slot = sc_segments \u003e\u003e (diff \u0026 ASSOC_ARRAY_KEY_CHUNK_MASK);\n-\tsc_slot \u0026= ASSOC_ARRAY_FAN_MASK;\n-\n-\tpr_devel(\"new slot %lx \u003e\u003e %d -\u003e %d\\n\",\n-\t\t sc_segments, diff \u0026 ASSOC_ARRAY_KEY_CHUNK_MASK, sc_slot);\n-\n-\t/* Determine whether we need to follow the new node with a replacement\n-\t * for the current shortcut.  We could in theory reuse the current\n-\t * shortcut if its parent slot number doesn't change - but that's a\n-\t * 1-in-16 chance so not worth expending the code upon.\n-\t */\n-\tlevel = diff + ASSOC_ARRAY_LEVEL_STEP;\n-\tif (level \u003c shortcut-\u003eskip_to_level) {\n-\t\tpr_devel(\"post-shortcut %d...%d\\n\", level, shortcut-\u003eskip_to_level);\n-\t\tkeylen = round_up(shortcut-\u003eskip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);\n-\t\tkeylen \u003e\u003e= ASSOC_ARRAY_KEY_CHUNK_SHIFT;\n-\n-\t\tnew_s1 = kzalloc_flex(*new_s1, index_key, keylen);\n-\t\tif (!new_s1)\n-\t\t\treturn false;\n-\t\tedit-\u003enew_meta[2] = assoc_array_shortcut_to_ptr(new_s1);\n-\n-\t\tnew_s1-\u003eback_pointer = assoc_array_node_to_ptr(new_n0);\n-\t\tnew_s1-\u003eparent_slot = sc_slot;\n-\t\tnew_s1-\u003enext_node = shortcut-\u003enext_node;\n-\t\tnew_s1-\u003eskip_to_level = shortcut-\u003eskip_to_level;\n-\n-\t\tnew_n0-\u003eslots[sc_slot] = assoc_array_shortcut_to_ptr(new_s1);\n-\n-\t\tmemcpy(new_s1-\u003eindex_key, shortcut-\u003eindex_key,\n-\t\t       flex_array_size(new_s1, index_key, keylen));\n-\n-\t\tedit-\u003eset[1].ptr = \u0026side-\u003eback_pointer;\n-\t\tedit-\u003eset[1].to = assoc_array_shortcut_to_ptr(new_s1);\n-\t} else {\n-\t\tpr_devel(\"no post-shortcut\\n\");\n-\n-\t\t/* We don't have to replace the pointed-to node as long as we\n-\t\t * use memory barriers to make sure the parent slot number is\n-\t\t * changed before the back pointer (the parent slot number is\n-\t\t * irrelevant to the old parent shortcut).\n-\t\t */\n-\t\tnew_n0-\u003eslots[sc_slot] = shortcut-\u003enext_node;\n-\t\tedit-\u003eset_parent_slot[0].p = \u0026side-\u003eparent_slot;\n-\t\tedit-\u003eset_parent_slot[0].to = sc_slot;\n-\t\tedit-\u003eset[1].ptr = \u0026side-\u003eback_pointer;\n-\t\tedit-\u003eset[1].to = assoc_array_node_to_ptr(new_n0);\n-\t}\n-\n-\t/* Install the new leaf in a spare slot in the new node. */\n-\tif (sc_slot == 0)\n-\t\tedit-\u003eleaf_p = \u0026new_n0-\u003eslots[1];\n-\telse\n-\t\tedit-\u003eleaf_p = \u0026new_n0-\u003eslots[0];\n-\n-\tpr_devel(\"\u003c--%s() = ok [split shortcut]\\n\", __func__);\n-\treturn true;\n-}\n-\n-/**\n- * assoc_array_insert - Script insertion of an object into an associative array\n- * @array: The array to insert into.\n- * @ops: The operations to use.\n- * @index_key: The key to insert at.\n- * @object: The object to insert.\n- *\n- * Precalculate and preallocate a script for the insertion or replacement of an\n- * object in an associative array.  This results in an edit script that can\n- * either be applied or cancelled.\n- *\n- * The function returns a pointer to an edit script or -ENOMEM.\n- *\n- * The caller should lock against other modifications and must continue to hold\n- * the lock until assoc_array_apply_edit() has been called.\n- *\n- * Accesses to the tree may take place concurrently with this function,\n- * provided they hold the RCU read lock.\n- */\n-struct assoc_array_edit *assoc_array_insert(struct assoc_array *array,\n-\t\t\t\t\t    const struct assoc_array_ops *ops,\n-\t\t\t\t\t    const void *index_key,\n-\t\t\t\t\t    void *object)\n-{\n-\tstruct assoc_array_walk_result result;\n-\tstruct assoc_array_edit *edit;\n-\n-\tpr_devel(\"--\u003e%s()\\n\", __func__);\n-\n-\t/* The leaf pointer we're given must not have the bottom bit set as we\n-\t * use those for type-marking the pointer.  NULL pointers are also not\n-\t * allowed as they indicate an empty slot but we have to allow them\n-\t * here as they can be updated later.\n-\t */\n-\tBUG_ON(assoc_array_ptr_is_meta(object));\n-\n-\tedit = kzalloc_obj(struct assoc_array_edit);\n-\tif (!edit)\n-\t\treturn ERR_PTR(-ENOMEM);\n-\tedit-\u003earray = array;\n-\tedit-\u003eops = ops;\n-\tedit-\u003eleaf = assoc_array_leaf_to_ptr(object);\n-\tedit-\u003eadjust_count_by = 1;\n-\n-\tswitch (assoc_array_walk(array, ops, index_key, \u0026result)) {\n-\tcase assoc_array_walk_tree_empty:\n-\t\t/* Allocate a root node if there isn't one yet */\n-\t\tif (!assoc_array_insert_in_empty_tree(edit))\n-\t\t\tgoto enomem;\n-\t\treturn edit;\n-\n-\tcase assoc_array_walk_found_terminal_node:\n-\t\t/* We found a node that doesn't have a node/shortcut pointer in\n-\t\t * the slot corresponding to the index key that we have to\n-\t\t * follow.\n-\t\t */\n-\t\tif (!assoc_array_insert_into_terminal_node(edit, ops, index_key,\n-\t\t\t\t\t\t\t   \u0026result))\n-\t\t\tgoto enomem;\n-\t\treturn edit;\n-\n-\tcase assoc_array_walk_found_wrong_shortcut:\n-\t\t/* We found a shortcut that didn't match our key in a slot we\n-\t\t * needed to follow.\n-\t\t */\n-\t\tif (!assoc_array_insert_mid_shortcut(edit, ops, \u0026result))\n-\t\t\tgoto enomem;\n-\t\treturn edit;\n-\t}\n-\n-enomem:\n-\t/* Clean up after an out of memory error */\n-\tpr_devel(\"enomem\\n\");\n-\tassoc_array_cancel_edit(edit);\n-\treturn ERR_PTR(-ENOMEM);\n-}\n-\n-/**\n- * assoc_array_insert_set_object - Set the new object pointer in an edit script\n- * @edit: The edit script to modify.\n- * @object: The object pointer to set.\n- *\n- * Change the object to be inserted in an edit script.  The object pointed to\n- * by the old object is not freed.  This must be done prior to applying the\n- * script.\n- */\n-void assoc_array_insert_set_object(struct assoc_array_edit *edit, void *object)\n-{\n-\tBUG_ON(!object);\n-\tedit-\u003eleaf = assoc_array_leaf_to_ptr(object);\n-}\n-\n-struct assoc_array_delete_collapse_context {\n-\tstruct assoc_array_node\t*node;\n-\tconst void\t\t*skip_leaf;\n-\tint\t\t\tslot;\n-};\n-\n-/*\n- * Subtree collapse to node iterator.\n- */\n-static int assoc_array_delete_collapse_iterator(const void *leaf,\n-\t\t\t\t\t\tvoid *iterator_data)\n-{\n-\tstruct assoc_array_delete_collapse_context *collapse = iterator_data;\n-\n-\tif (leaf == collapse-\u003eskip_leaf)\n-\t\treturn 0;\n-\n-\tBUG_ON(collapse-\u003eslot \u003e= ASSOC_ARRAY_FAN_OUT);\n-\n-\tcollapse-\u003enode-\u003eslots[collapse-\u003eslot++] = assoc_array_leaf_to_ptr(leaf);\n-\treturn 0;\n-}\n-\n-/**\n- * assoc_array_delete - Script deletion of an object from an associative array\n- * @array: The array to search.\n- * @ops: The operations to use.\n- * @index_key: The key to the object.\n- *\n- * Precalculate and preallocate a script for the deletion of an object from an\n- * associative array.  This results in an edit script that can either be\n- * applied or cancelled.\n- *\n- * The function returns a pointer to an edit script if the object was found,\n- * NULL if the object was not found or -ENOMEM.\n- *\n- * The caller should lock against other modifications and must continue to hold\n- * the lock until assoc_array_apply_edit() has been called.\n- *\n- * Accesses to the tree may take place concurrently with this function,\n- * provided they hold the RCU read lock.\n- */\n-struct assoc_array_edit *assoc_array_delete(struct assoc_array *array,\n-\t\t\t\t\t    const struct assoc_array_ops *ops,\n-\t\t\t\t\t    const void *index_key)\n-{\n-\tstruct assoc_array_delete_collapse_context collapse;\n-\tstruct assoc_array_walk_result result;\n-\tstruct assoc_array_node *node, *new_n0;\n-\tstruct assoc_array_edit *edit;\n-\tstruct assoc_array_ptr *ptr;\n-\tbool has_meta;\n-\tint slot, i;\n-\n-\tpr_devel(\"--\u003e%s()\\n\", __func__);\n-\n-\tedit = kzalloc_obj(struct assoc_array_edit);\n-\tif (!edit)\n-\t\treturn ERR_PTR(-ENOMEM);\n-\tedit-\u003earray = array;\n-\tedit-\u003eops = ops;\n-\tedit-\u003eadjust_count_by = -1;\n-\n-\tswitch (assoc_array_walk(array, ops, index_key, \u0026result)) {\n-\tcase assoc_array_walk_found_terminal_node:\n-\t\t/* We found a node that should contain the leaf we've been\n-\t\t * asked to remove - *if* it's in the tree.\n-\t\t */\n-\t\tpr_devel(\"terminal_node\\n\");\n-\t\tnode = result.terminal_node.node;\n-\n-\t\tfor (slot = 0; slot \u003c ASSOC_ARRAY_FAN_OUT; slot++) {\n-\t\t\tptr = node-\u003eslots[slot];\n-\t\t\tif (ptr \u0026\u0026\n-\t\t\t    assoc_array_ptr_is_leaf(ptr) \u0026\u0026\n-\t\t\t    ops-\u003ecompare_object(assoc_array_ptr_to_leaf(ptr),\n-\t\t\t\t\t\tindex_key))\n-\t\t\t\tgoto found_leaf;\n-\t\t}\n-\t\tfallthrough;\n-\tcase assoc_array_walk_tree_empty:\n-\tcase assoc_array_walk_found_wrong_shortcut:\n-\tdefault:\n-\t\tassoc_array_cancel_edit(edit);\n-\t\tpr_devel(\"not found\\n\");\n-\t\treturn NULL;\n-\t}\n-\n-found_leaf:\n-\tBUG_ON(array-\u003enr_leaves_on_tree \u003c= 0);\n-\n-\t/* In the simplest form of deletion we just clear the slot and release\n-\t * the leaf after a suitable interval.\n-\t */\n-\tedit-\u003edead_leaf = node-\u003eslots[slot];\n-\tedit-\u003eset[0].ptr = \u0026node-\u003eslots[slot];\n-\tedit-\u003eset[0].to = NULL;\n-\tedit-\u003eadjust_count_on = node;\n-\n-\t/* If that concludes erasure of the last leaf, then delete the entire\n-\t * internal array.\n-\t */\n-\tif (array-\u003enr_leaves_on_tree == 1) {\n-\t\tedit-\u003eset[1].ptr = \u0026array-\u003eroot;\n-\t\tedit-\u003eset[1].to = NULL;\n-\t\tedit-\u003eadjust_count_on = NULL;\n-\t\tedit-\u003eexcised_subtree = array-\u003eroot;\n-\t\tpr_devel(\"all gone\\n\");\n-\t\treturn edit;\n-\t}\n-\n-\t/* However, we'd also like to clear up some metadata blocks if we\n-\t * possibly can.\n-\t *\n-\t * We go for a simple algorithm of: if this node has FAN_OUT or fewer\n-\t * leaves in it, then attempt to collapse it - and attempt to\n-\t * recursively collapse up the tree.\n-\t *\n-\t * We could also try and collapse in partially filled subtrees to take\n-\t * up space in this node.\n-\t */\n-\tif (node-\u003enr_leaves_on_branch \u003c= ASSOC_ARRAY_FAN_OUT + 1) {\n-\t\tstruct assoc_array_node *parent, *grandparent;\n-\t\tstruct assoc_array_ptr *ptr;\n-\n-\t\t/* First of all, we need to know if this node has metadata so\n-\t\t * that we don't try collapsing if all the leaves are already\n-\t\t * here.\n-\t\t */\n-\t\thas_meta = false;\n-\t\tfor (i = 0; i \u003c ASSOC_ARRAY_FAN_OUT; i++) {\n-\t\t\tptr = node-\u003eslots[i];\n-\t\t\tif (assoc_array_ptr_is_meta(ptr)) {\n-\t\t\t\thas_meta = true;\n-\t\t\t\tbreak;\n-\t\t\t}\n-\t\t}\n-\n-\t\tpr_devel(\"leaves: %ld [m=%d]\\n\",\n-\t\t\t node-\u003enr_leaves_on_branch - 1, has_meta);\n-\n-\t\t/* Look further up the tree to see if we can collapse this node\n-\t\t * into a more proximal node too.\n-\t\t */\n-\t\tparent = node;\n-\tcollapse_up:\n-\t\tpr_devel(\"collapse subtree: %ld\\n\", parent-\u003enr_leaves_on_branch);\n-\n-\t\tptr = parent-\u003eback_pointer;\n-\t\tif (!ptr)\n-\t\t\tgoto do_collapse;\n-\t\tif (assoc_array_ptr_is_shortcut(ptr)) {\n-\t\t\tstruct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(ptr);\n-\t\t\tptr = s-\u003eback_pointer;\n-\t\t\tif (!ptr)\n-\t\t\t\tgoto do_collapse;\n-\t\t}\n-\n-\t\tgrandparent = assoc_array_ptr_to_node(ptr);\n-\t\tif (grandparent-\u003enr_leaves_on_branch \u003c= ASSOC_ARRAY_FAN_OUT + 1) {\n-\t\t\tparent = grandparent;\n-\t\t\tgoto collapse_up;\n-\t\t}\n-\n-\tdo_collapse:\n-\t\t/* There's no point collapsing if the original node has no meta\n-\t\t * pointers to discard and if we didn't merge into one of that\n-\t\t * node's ancestry.\n-\t\t */\n-\t\tif (has_meta || parent != node) {\n-\t\t\tnode = parent;\n-\n-\t\t\t/* Create a new node to collapse into */\n-\t\t\tnew_n0 = kzalloc_obj(struct assoc_array_node);\n-\t\t\tif (!new_n0)\n-\t\t\t\tgoto enomem;\n-\t\t\tedit-\u003enew_meta[0] = assoc_array_node_to_ptr(new_n0);\n-\n-\t\t\tnew_n0-\u003eback_pointer = node-\u003eback_pointer;\n-\t\t\tnew_n0-\u003eparent_slot = node-\u003eparent_slot;\n-\t\t\tnew_n0-\u003enr_leaves_on_branch = node-\u003enr_leaves_on_branch;\n-\t\t\tedit-\u003eadjust_count_on = new_n0;\n-\n-\t\t\tcollapse.node = new_n0;\n-\t\t\tcollapse.skip_leaf = assoc_array_ptr_to_leaf(edit-\u003edead_leaf);\n-\t\t\tcollapse.slot = 0;\n-\t\t\tassoc_array_subtree_iterate(assoc_array_node_to_ptr(node),\n-\t\t\t\t\t\t    node-\u003eback_pointer,\n-\t\t\t\t\t\t    assoc_array_delete_collapse_iterator,\n-\t\t\t\t\t\t    \u0026collapse);\n-\t\t\tpr_devel(\"collapsed %d,%lu\\n\", collapse.slot, new_n0-\u003enr_leaves_on_branch);\n-\t\t\tBUG_ON(collapse.slot != new_n0-\u003enr_leaves_on_branch - 1);\n-\n-\t\t\tif (!node-\u003eback_pointer) {\n-\t\t\t\tedit-\u003eset[1].ptr = \u0026array-\u003eroot;\n-\t\t\t} else if (assoc_array_ptr_is_leaf(node-\u003eback_pointer)) {\n-\t\t\t\tBUG();\n-\t\t\t} else if (assoc_array_ptr_is_node(node-\u003eback_pointer)) {\n-\t\t\t\tstruct assoc_array_node *p =\n-\t\t\t\t\tassoc_array_ptr_to_node(node-\u003eback_pointer);\n-\t\t\t\tedit-\u003eset[1].ptr = \u0026p-\u003eslots[node-\u003eparent_slot];\n-\t\t\t} else if (assoc_array_ptr_is_shortcut(node-\u003eback_pointer)) {\n-\t\t\t\tstruct assoc_array_shortcut *s =\n-\t\t\t\t\tassoc_array_ptr_to_shortcut(node-\u003eback_pointer);\n-\t\t\t\tedit-\u003eset[1].ptr = \u0026s-\u003enext_node;\n-\t\t\t}\n-\t\t\tedit-\u003eset[1].to = assoc_array_node_to_ptr(new_n0);\n-\t\t\tedit-\u003eexcised_subtree = assoc_array_node_to_ptr(node);\n-\t\t}\n-\t}\n-\n-\treturn edit;\n-\n-enomem:\n-\t/* Clean up after an out of memory error */\n-\tpr_devel(\"enomem\\n\");\n-\tassoc_array_cancel_edit(edit);\n-\treturn ERR_PTR(-ENOMEM);\n-}\n-\n-/**\n- * assoc_array_clear - Script deletion of all objects from an associative array\n- * @array: The array to clear.\n- * @ops: The operations to use.\n- *\n- * Precalculate and preallocate a script for the deletion of all the objects\n- * from an associative array.  This results in an edit script that can either\n- * be applied or cancelled.\n- *\n- * The function returns a pointer to an edit script if there are objects to be\n- * deleted, NULL if there are no objects in the array or -ENOMEM.\n- *\n- * The caller should lock against other modifications and must continue to hold\n- * the lock until assoc_array_apply_edit() has been called.\n- *\n- * Accesses to the tree may take place concurrently with this function,\n- * provided they hold the RCU read lock.\n- */\n-struct assoc_array_edit *assoc_array_clear(struct assoc_array *array,\n-\t\t\t\t\t   const struct assoc_array_ops *ops)\n-{\n-\tstruct assoc_array_edit *edit;\n-\n-\tpr_devel(\"--\u003e%s()\\n\", __func__);\n-\n-\tif (!array-\u003eroot)\n-\t\treturn NULL;\n-\n-\tedit = kzalloc_obj(struct assoc_array_edit);\n-\tif (!edit)\n-\t\treturn ERR_PTR(-ENOMEM);\n-\tedit-\u003earray = array;\n-\tedit-\u003eops = ops;\n-\tedit-\u003eset[1].ptr = \u0026array-\u003eroot;\n-\tedit-\u003eset[1].to = NULL;\n-\tedit-\u003eexcised_subtree = array-\u003eroot;\n-\tedit-\u003eops_for_excised_subtree = ops;\n-\tpr_devel(\"all gone\\n\");\n-\treturn edit;\n-}\n-\n-/*\n- * Handle the deferred destruction after an applied edit.\n- */\n-static void assoc_array_rcu_cleanup(struct rcu_head *head)\n-{\n-\tstruct assoc_array_edit *edit =\n-\t\tcontainer_of(head, struct assoc_array_edit, rcu);\n-\tint i;\n-\n-\tpr_devel(\"--\u003e%s()\\n\", __func__);\n-\n-\tif (edit-\u003edead_leaf)\n-\t\tedit-\u003eops-\u003efree_object(assoc_array_ptr_to_leaf(edit-\u003edead_leaf));\n-\tfor (i = 0; i \u003c ARRAY_SIZE(edit-\u003eexcised_meta); i++)\n-\t\tif (edit-\u003eexcised_meta[i])\n-\t\t\tkfree(assoc_array_ptr_to_node(edit-\u003eexcised_meta[i]));\n-\n-\tif (edit-\u003eexcised_subtree) {\n-\t\tBUG_ON(assoc_array_ptr_is_leaf(edit-\u003eexcised_subtree));\n-\t\tif (assoc_array_ptr_is_node(edit-\u003eexcised_subtree)) {\n-\t\t\tstruct assoc_array_node *n =\n-\t\t\t\tassoc_array_ptr_to_node(edit-\u003eexcised_subtree);\n-\t\t\tn-\u003eback_pointer = NULL;\n-\t\t} else {\n-\t\t\tstruct assoc_array_shortcut *s =\n-\t\t\t\tassoc_array_ptr_to_shortcut(edit-\u003eexcised_subtree);\n-\t\t\ts-\u003eback_pointer = NULL;\n-\t\t}\n-\t\tassoc_array_destroy_subtree(edit-\u003eexcised_subtree,\n-\t\t\t\t\t    edit-\u003eops_for_excised_subtree);\n-\t}\n-\n-\tkfree(edit);\n-}\n-\n-/**\n- * assoc_array_apply_edit - Apply an edit script to an associative array\n- * @edit: The script to apply.\n- *\n- * Apply an edit script to an associative array to effect an insertion,\n- * deletion or clearance.  As the edit script includes preallocated memory,\n- * this is guaranteed not to fail.\n- *\n- * The edit script, dead objects and dead metadata will be scheduled for\n- * destruction after an RCU grace period to permit those doing read-only\n- * accesses on the array to continue to do so under the RCU read lock whilst\n- * the edit is taking place.\n- */\n-void assoc_array_apply_edit(struct assoc_array_edit *edit)\n-{\n-\tstruct assoc_array_shortcut *shortcut;\n-\tstruct assoc_array_node *node;\n-\tstruct assoc_array_ptr *ptr;\n-\tint i;\n-\n-\tpr_devel(\"--\u003e%s()\\n\", __func__);\n-\n-\tsmp_wmb();\n-\tif (edit-\u003eleaf_p)\n-\t\t*edit-\u003eleaf_p = edit-\u003eleaf;\n-\n-\tsmp_wmb();\n-\tfor (i = 0; i \u003c ARRAY_SIZE(edit-\u003eset_parent_slot); i++)\n-\t\tif (edit-\u003eset_parent_slot[i].p)\n-\t\t\t*edit-\u003eset_parent_slot[i].p = edit-\u003eset_parent_slot[i].to;\n-\n-\tsmp_wmb();\n-\tfor (i = 0; i \u003c ARRAY_SIZE(edit-\u003eset_backpointers); i++)\n-\t\tif (edit-\u003eset_backpointers[i])\n-\t\t\t*edit-\u003eset_backpointers[i] = edit-\u003eset_backpointers_to;\n-\n-\tsmp_wmb();\n-\tfor (i = 0; i \u003c ARRAY_SIZE(edit-\u003eset); i++)\n-\t\tif (edit-\u003eset[i].ptr)\n-\t\t\t*edit-\u003eset[i].ptr = edit-\u003eset[i].to;\n-\n-\tif (edit-\u003earray-\u003eroot == NULL) {\n-\t\tedit-\u003earray-\u003enr_leaves_on_tree = 0;\n-\t} else if (edit-\u003eadjust_count_on) {\n-\t\tnode = edit-\u003eadjust_count_on;\n-\t\tfor (;;) {\n-\t\t\tnode-\u003enr_leaves_on_branch += edit-\u003eadjust_count_by;\n-\n-\t\t\tptr = node-\u003eback_pointer;\n-\t\t\tif (!ptr)\n-\t\t\t\tbreak;\n-\t\t\tif (assoc_array_ptr_is_shortcut(ptr)) {\n-\t\t\t\tshortcut = assoc_array_ptr_to_shortcut(ptr);\n-\t\t\t\tptr = shortcut-\u003eback_pointer;\n-\t\t\t\tif (!ptr)\n-\t\t\t\t\tbreak;\n-\t\t\t}\n-\t\t\tBUG_ON(!assoc_array_ptr_is_node(ptr));\n-\t\t\tnode = assoc_array_ptr_to_node(ptr);\n-\t\t}\n-\n-\t\tedit-\u003earray-\u003enr_leaves_on_tree += edit-\u003eadjust_count_by;\n-\t}\n-\n-\tcall_rcu(\u0026edit-\u003ercu, assoc_array_rcu_cleanup);\n-}\n-\n-/**\n- * assoc_array_cancel_edit - Discard an edit script.\n- * @edit: The script to discard.\n- *\n- * Free an edit script and all the preallocated data it holds without making\n- * any changes to the associative array it was intended for.\n- *\n- * NOTE!  In the case of an insertion script, this does _not_ release the leaf\n- * that was to be inserted.  That is left to the caller.\n- */\n-void assoc_array_cancel_edit(struct assoc_array_edit *edit)\n-{\n-\tstruct assoc_array_ptr *ptr;\n-\tint i;\n-\n-\tpr_devel(\"--\u003e%s()\\n\", __func__);\n-\n-\t/* Clean up after an out of memory error */\n-\tfor (i = 0; i \u003c ARRAY_SIZE(edit-\u003enew_meta); i++) {\n-\t\tptr = edit-\u003enew_meta[i];\n-\t\tif (ptr) {\n-\t\t\tif (assoc_array_ptr_is_node(ptr))\n-\t\t\t\tkfree(assoc_array_ptr_to_node(ptr));\n-\t\t\telse\n-\t\t\t\tkfree(assoc_array_ptr_to_shortcut(ptr));\n-\t\t}\n-\t}\n-\tkfree(edit);\n-}\n-\n-/**\n- * assoc_array_gc - Garbage collect an associative array.\n- * @array: The array to clean.\n- * @ops: The operations to use.\n- * @iterator: A callback function to pass judgement on each object.\n- * @iterator_data: Private data for the callback function.\n- *\n- * Collect garbage from an associative array and pack down the internal tree to\n- * save memory.\n- *\n- * The iterator function is asked to pass judgement upon each object in the\n- * array.  If it returns false, the object is discard and if it returns true,\n- * the object is kept.  If it returns true, it must increment the object's\n- * usage count (or whatever it needs to do to retain it) before returning.\n- *\n- * This function returns 0 if successful or -ENOMEM if out of memory.  In the\n- * latter case, the array is not changed.\n- *\n- * The caller should lock against other modifications and must continue to hold\n- * the lock until assoc_array_apply_edit() has been called.\n- *\n- * Accesses to the tree may take place concurrently with this function,\n- * provided they hold the RCU read lock.\n- */\n-int assoc_array_gc(struct assoc_array *array,\n-\t\t   const struct assoc_array_ops *ops,\n-\t\t   bool (*iterator)(void *object, void *iterator_data),\n-\t\t   void *iterator_data)\n-{\n-\tstruct assoc_array_shortcut *shortcut, *new_s;\n-\tstruct assoc_array_node *node, *new_n;\n-\tstruct assoc_array_edit *edit;\n-\tstruct assoc_array_ptr *cursor, *ptr;\n-\tstruct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp;\n-\tunsigned long nr_leaves_on_tree;\n-\tbool retained;\n-\tint keylen, slot, nr_free, next_slot, i;\n-\n-\tpr_devel(\"--\u003e%s()\\n\", __func__);\n-\n-\tif (!array-\u003eroot)\n-\t\treturn 0;\n-\n-\tedit = kzalloc_obj(struct assoc_array_edit);\n-\tif (!edit)\n-\t\treturn -ENOMEM;\n-\tedit-\u003earray = array;\n-\tedit-\u003eops = ops;\n-\tedit-\u003eops_for_excised_subtree = ops;\n-\tedit-\u003eset[0].ptr = \u0026array-\u003eroot;\n-\tedit-\u003eexcised_subtree = array-\u003eroot;\n-\n-\tnew_root = new_parent = NULL;\n-\tnew_ptr_pp = \u0026new_root;\n-\tcursor = array-\u003eroot;\n-\n-descend:\n-\t/* If this point is a shortcut, then we need to duplicate it and\n-\t * advance the target cursor.\n-\t */\n-\tif (assoc_array_ptr_is_shortcut(cursor)) {\n-\t\tshortcut = assoc_array_ptr_to_shortcut(cursor);\n-\t\tkeylen = round_up(shortcut-\u003eskip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);\n-\t\tkeylen \u003e\u003e= ASSOC_ARRAY_KEY_CHUNK_SHIFT;\n-\t\tnew_s = kmalloc_flex(*new_s, index_key, keylen);\n-\t\tif (!new_s)\n-\t\t\tgoto enomem;\n-\t\tpr_devel(\"dup shortcut %p -\u003e %p\\n\", shortcut, new_s);\n-\t\tmemcpy(new_s, shortcut, struct_size(new_s, index_key, keylen));\n-\t\tnew_s-\u003eback_pointer = new_parent;\n-\t\tnew_s-\u003eparent_slot = shortcut-\u003eparent_slot;\n-\t\t*new_ptr_pp = new_parent = assoc_array_shortcut_to_ptr(new_s);\n-\t\tnew_ptr_pp = \u0026new_s-\u003enext_node;\n-\t\tcursor = shortcut-\u003enext_node;\n-\t}\n-\n-\t/* Duplicate the node at this position */\n-\tnode = assoc_array_ptr_to_node(cursor);\n-\tnew_n = kzalloc_obj(struct assoc_array_node);\n-\tif (!new_n)\n-\t\tgoto enomem;\n-\tpr_devel(\"dup node %p -\u003e %p\\n\", node, new_n);\n-\tnew_n-\u003eback_pointer = new_parent;\n-\tnew_n-\u003eparent_slot = node-\u003eparent_slot;\n-\t*new_ptr_pp = new_parent = assoc_array_node_to_ptr(new_n);\n-\tnew_ptr_pp = NULL;\n-\tslot = 0;\n-\n-continue_node:\n-\t/* Filter across any leaves and gc any subtrees */\n-\tfor (; slot \u003c ASSOC_ARRAY_FAN_OUT; slot++) {\n-\t\tptr = node-\u003eslots[slot];\n-\t\tif (!ptr)\n-\t\t\tcontinue;\n-\n-\t\tif (assoc_array_ptr_is_leaf(ptr)) {\n-\t\t\tif (iterator(assoc_array_ptr_to_leaf(ptr),\n-\t\t\t\t     iterator_data))\n-\t\t\t\t/* The iterator will have done any reference\n-\t\t\t\t * counting on the object for us.\n-\t\t\t\t */\n-\t\t\t\tnew_n-\u003eslots[slot] = ptr;\n-\t\t\tcontinue;\n-\t\t}\n-\n-\t\tnew_ptr_pp = \u0026new_n-\u003eslots[slot];\n-\t\tcursor = ptr;\n-\t\tgoto descend;\n-\t}\n-\n-retry_compress:\n-\tpr_devel(\"-- compress node %p --\\n\", new_n);\n-\n-\t/* Count up the number of empty slots in this node and work out the\n-\t * subtree leaf count.\n-\t */\n-\tnew_n-\u003enr_leaves_on_branch = 0;\n-\tnr_free = 0;\n-\tfor (slot = 0; slot \u003c ASSOC_ARRAY_FAN_OUT; slot++) {\n-\t\tptr = new_n-\u003eslots[slot];\n-\t\tif (!ptr)\n-\t\t\tnr_free++;\n-\t\telse if (assoc_array_ptr_is_leaf(ptr))\n-\t\t\tnew_n-\u003enr_leaves_on_branch++;\n-\t}\n-\tpr_devel(\"free=%d, leaves=%lu\\n\", nr_free, new_n-\u003enr_leaves_on_branch);\n-\n-\t/* See what we can fold in */\n-\tretained = false;\n-\tnext_slot = 0;\n-\tfor (slot = 0; slot \u003c ASSOC_ARRAY_FAN_OUT; slot++) {\n-\t\tstruct assoc_array_shortcut *s;\n-\t\tstruct assoc_array_node *child;\n-\n-\t\tptr = new_n-\u003eslots[slot];\n-\t\tif (!ptr || assoc_array_ptr_is_leaf(ptr))\n-\t\t\tcontinue;\n-\n-\t\ts = NULL;\n-\t\tif (assoc_array_ptr_is_shortcut(ptr)) {\n-\t\t\ts = assoc_array_ptr_to_shortcut(ptr);\n-\t\t\tptr = s-\u003enext_node;\n-\t\t}\n-\n-\t\tchild = assoc_array_ptr_to_node(ptr);\n-\t\tnew_n-\u003enr_leaves_on_branch += child-\u003enr_leaves_on_branch;\n-\n-\t\tif (child-\u003enr_leaves_on_branch \u003c= nr_free + 1) {\n-\t\t\t/* Fold the child node into this one */\n-\t\t\tpr_devel(\"[%d] fold node %lu/%d [nx %d]\\n\",\n-\t\t\t\t slot, child-\u003enr_leaves_on_branch, nr_free + 1,\n-\t\t\t\t next_slot);\n-\n-\t\t\t/* We would already have reaped an intervening shortcut\n-\t\t\t * on the way back up the tree.\n-\t\t\t */\n-\t\t\tBUG_ON(s);\n-\n-\t\t\tnew_n-\u003eslots[slot] = NULL;\n-\t\t\tnr_free++;\n-\t\t\tif (slot \u003c next_slot)\n-\t\t\t\tnext_slot = slot;\n-\t\t\tfor (i = 0; i \u003c ASSOC_ARRAY_FAN_OUT; i++) {\n-\t\t\t\tstruct assoc_array_ptr *p = child-\u003eslots[i];\n-\t\t\t\tif (!p)\n-\t\t\t\t\tcontinue;\n-\t\t\t\tBUG_ON(assoc_array_ptr_is_meta(p));\n-\t\t\t\twhile (new_n-\u003eslots[next_slot])\n-\t\t\t\t\tnext_slot++;\n-\t\t\t\tBUG_ON(next_slot \u003e= ASSOC_ARRAY_FAN_OUT);\n-\t\t\t\tnew_n-\u003eslots[next_slot++] = p;\n-\t\t\t\tnr_free--;\n-\t\t\t}\n-\t\t\tkfree(child);\n-\t\t} else {\n-\t\t\tpr_devel(\"[%d] retain node %lu/%d [nx %d]\\n\",\n-\t\t\t\t slot, child-\u003enr_leaves_on_branch, nr_free + 1,\n-\t\t\t\t next_slot);\n-\t\t\tretained = true;\n-\t\t}\n-\t}\n-\n-\tif (retained \u0026\u0026 new_n-\u003enr_leaves_on_branch \u003c= ASSOC_ARRAY_FAN_OUT) {\n-\t\tpr_devel(\"internal nodes remain despite enough space, retrying\\n\");\n-\t\tgoto retry_compress;\n-\t}\n-\tpr_devel(\"after: %lu\\n\", new_n-\u003enr_leaves_on_branch);\n-\n-\tnr_leaves_on_tree = new_n-\u003enr_leaves_on_branch;\n-\n-\t/* Excise this node if it is singly occupied by a shortcut */\n-\tif (nr_free == ASSOC_ARRAY_FAN_OUT - 1) {\n-\t\tfor (slot = 0; slot \u003c ASSOC_ARRAY_FAN_OUT; slot++)\n-\t\t\tif ((ptr = new_n-\u003eslots[slot]))\n-\t\t\t\tbreak;\n-\n-\t\tif (assoc_array_ptr_is_meta(ptr) \u0026\u0026\n-\t\t    assoc_array_ptr_is_shortcut(ptr)) {\n-\t\t\tpr_devel(\"excise node %p with 1 shortcut\\n\", new_n);\n-\t\t\tnew_s = assoc_array_ptr_to_shortcut(ptr);\n-\t\t\tnew_parent = new_n-\u003eback_pointer;\n-\t\t\tslot = new_n-\u003eparent_slot;\n-\t\t\tkfree(new_n);\n-\t\t\tif (!new_parent) {\n-\t\t\t\tnew_s-\u003eback_pointer = NULL;\n-\t\t\t\tnew_s-\u003eparent_slot = 0;\n-\t\t\t\tnew_root = ptr;\n-\t\t\t\tgoto gc_complete;\n-\t\t\t}\n-\n-\t\t\tif (assoc_array_ptr_is_shortcut(new_parent)) {\n-\t\t\t\t/* We can discard any preceding shortcut also */\n-\t\t\t\tstruct assoc_array_shortcut *s =\n-\t\t\t\t\tassoc_array_ptr_to_shortcut(new_parent);\n-\n-\t\t\t\tpr_devel(\"excise preceding shortcut\\n\");\n-\n-\t\t\t\tnew_parent = new_s-\u003eback_pointer = s-\u003eback_pointer;\n-\t\t\t\tslot = new_s-\u003eparent_slot = s-\u003eparent_slot;\n-\t\t\t\tkfree(s);\n-\t\t\t\tif (!new_parent) {\n-\t\t\t\t\tnew_s-\u003eback_pointer = NULL;\n-\t\t\t\t\tnew_s-\u003eparent_slot = 0;\n-\t\t\t\t\tnew_root = ptr;\n-\t\t\t\t\tgoto gc_complete;\n-\t\t\t\t}\n-\t\t\t}\n-\n-\t\t\tnew_s-\u003eback_pointer = new_parent;\n-\t\t\tnew_s-\u003eparent_slot = slot;\n-\t\t\tnew_n = assoc_array_ptr_to_node(new_parent);\n-\t\t\tnew_n-\u003eslots[slot] = ptr;\n-\t\t\tgoto ascend_old_tree;\n-\t\t}\n-\t}\n-\n-\t/* Excise any shortcuts we might encounter that point to nodes that\n-\t * only contain leaves.\n-\t */\n-\tptr = new_n-\u003eback_pointer;\n-\tif (!ptr)\n-\t\tgoto gc_complete;\n-\n-\tif (assoc_array_ptr_is_shortcut(ptr)) {\n-\t\tnew_s = assoc_array_ptr_to_shortcut(ptr);\n-\t\tnew_parent = new_s-\u003eback_pointer;\n-\t\tslot = new_s-\u003eparent_slot;\n-\n-\t\tif (new_n-\u003enr_leaves_on_branch \u003c= ASSOC_ARRAY_FAN_OUT) {\n-\t\t\tstruct assoc_array_node *n;\n-\n-\t\t\tpr_devel(\"excise shortcut\\n\");\n-\t\t\tnew_n-\u003eback_pointer = new_parent;\n-\t\t\tnew_n-\u003eparent_slot = slot;\n-\t\t\tkfree(new_s);\n-\t\t\tif (!new_parent) {\n-\t\t\t\tnew_root = assoc_array_node_to_ptr(new_n);\n-\t\t\t\tgoto gc_complete;\n-\t\t\t}\n-\n-\t\t\tn = assoc_array_ptr_to_node(new_parent);\n-\t\t\tn-\u003eslots[slot] = assoc_array_node_to_ptr(new_n);\n-\t\t}\n-\t} else {\n-\t\tnew_parent = ptr;\n-\t}\n-\tnew_n = assoc_array_ptr_to_node(new_parent);\n-\n-ascend_old_tree:\n-\tptr = node-\u003eback_pointer;\n-\tif (assoc_array_ptr_is_shortcut(ptr)) {\n-\t\tshortcut = assoc_array_ptr_to_shortcut(ptr);\n-\t\tslot = shortcut-\u003eparent_slot;\n-\t\tcursor = shortcut-\u003eback_pointer;\n-\t\tif (!cursor)\n-\t\t\tgoto gc_complete;\n-\t} else {\n-\t\tslot = node-\u003eparent_slot;\n-\t\tcursor = ptr;\n-\t}\n-\tBUG_ON(!cursor);\n-\tnode = assoc_array_ptr_to_node(cursor);\n-\tslot++;\n-\tgoto continue_node;\n-\n-gc_complete:\n-\tedit-\u003eset[0].to = new_root;\n-\tassoc_array_apply_edit(edit);\n-\tarray-\u003enr_leaves_on_tree = nr_leaves_on_tree;\n-\treturn 0;\n-\n-enomem:\n-\tpr_devel(\"enomem\\n\");\n-\tassoc_array_destroy_subtree(new_root, edit-\u003eops);\n-\tkfree(edit);\n-\treturn -ENOMEM;\n-}\ndiff --git a/security/keys/Kconfig b/security/keys/Kconfig\nindex f4510d8cb485f4..3f64d60d0f8a69 100644\n--- a/security/keys/Kconfig\n+++ b/security/keys/Kconfig\n@@ -5,7 +5,6 @@\n \n menuconfig KEYS\n \tbool \"Enable access key retention support\"\n-\tselect ASSOCIATIVE_ARRAY\n \thelp\n \t  This option provides support for retaining authentication tokens and\n \t  access keys in the kernel.\ndiff --git a/security/keys/internal.h b/security/keys/internal.h\nindex b7b622bc36a137..c452d71cce038d 100644\n--- a/security/keys/internal.h\n+++ b/security/keys/internal.h\n@@ -21,6 +21,12 @@\n #include \u003clinux/vmalloc.h\u003e\n \n struct iovec;\n+struct keyring_link;\n+\n+struct keyring_edit {\n+\tstruct keyring_link *new;\n+\tstruct keyring_link *old;\n+};\n \n #ifdef __KDEBUG\n #define kenter(FMT, ...) \\\n@@ -98,13 +104,13 @@ extern int __key_move_lock(struct key *l_keyring, struct key *u_keyring,\n \t\t\t   const struct keyring_index_key *index_key);\n extern int __key_link_begin(struct key *keyring,\n \t\t\t    const struct keyring_index_key *index_key,\n-\t\t\t    struct assoc_array_edit **_edit);\n+\t\t\t    struct keyring_edit *edit);\n extern int __key_link_check_live_key(struct key *keyring, struct key *key);\n extern void __key_link(struct key *keyring, struct key *key,\n-\t\t       struct assoc_array_edit **_edit);\n+\t\t       struct keyring_edit *edit);\n extern void __key_link_end(struct key *keyring,\n \t\t\t   const struct keyring_index_key *index_key,\n-\t\t\t   struct assoc_array_edit *edit);\n+\t\t\t   struct keyring_edit *edit);\n \n extern key_ref_t find_key_to_update(key_ref_t keyring_ref,\n \t\t\t\t    const struct keyring_index_key *index_key);\n@@ -122,7 +128,7 @@ struct keyring_search_context {\n #define KEYRING_SEARCH_SKIP_EXPIRED\t0x0020\t/* Ignore expired keys (intention to replace) */\n #define KEYRING_SEARCH_RECURSE\t\t0x0040\t/* Search child keyrings also */\n \n-\tint (*iterator)(const void *object, void *iterator_data);\n+\tint (*iterator)(const struct key *key, void *iterator_data);\n \n \t/* Internal stuff */\n \tint\t\t\tskipped_ret;\ndiff --git a/security/keys/key.c b/security/keys/key.c\nindex 3f1f0fc137109a..20cf273cf4a3de 100644\n--- a/security/keys/key.c\n+++ b/security/keys/key.c\n@@ -430,7 +430,7 @@ static int __key_instantiate_and_link(struct key *key,\n \t\t\t\t      struct key_preparsed_payload *prep,\n \t\t\t\t      struct key *keyring,\n \t\t\t\t      struct key *authkey,\n-\t\t\t\t      struct assoc_array_edit **_edit)\n+\t\t\t\t      struct keyring_edit *edit)\n {\n \tint ret, awaken;\n \n@@ -461,7 +461,7 @@ static int __key_instantiate_and_link(struct key *key,\n \t\t\t\tif (test_bit(KEY_FLAG_KEEP, \u0026keyring-\u003eflags))\n \t\t\t\t\tset_bit(KEY_FLAG_KEEP, \u0026key-\u003eflags);\n \n-\t\t\t\t__key_link(keyring, key, _edit);\n+\t\t\t\t__key_link(keyring, key, edit);\n \t\t\t}\n \n \t\t\t/* disable the authorisation key */\n@@ -505,7 +505,7 @@ int key_instantiate_and_link(struct key *key,\n \t\t\t     struct key *authkey)\n {\n \tstruct key_preparsed_payload prep;\n-\tstruct assoc_array_edit *edit = NULL;\n+\tstruct keyring_edit edit = {};\n \tint ret;\n \n \tmemset(\u0026prep, 0, sizeof(prep));\n@@ -543,7 +543,7 @@ int key_instantiate_and_link(struct key *key,\n \n error_link_end:\n \tif (keyring)\n-\t\t__key_link_end(keyring, \u0026key-\u003eindex_key, edit);\n+\t\t__key_link_end(keyring, \u0026key-\u003eindex_key, \u0026edit);\n \n error:\n \tif (key-\u003etype-\u003epreparse)\n@@ -580,7 +580,7 @@ int key_reject_and_link(struct key *key,\n \t\t\tstruct key *keyring,\n \t\t\tstruct key *authkey)\n {\n-\tstruct assoc_array_edit *edit = NULL;\n+\tstruct keyring_edit edit = {};\n \tint ret, awaken, link_ret = 0;\n \n \tkey_check(key);\n@@ -599,12 +599,12 @@ int key_reject_and_link(struct key *key,\n \t\t\t * concurrent restriction install.\n \t\t\t */\n \t\t\tif (keyring-\u003erestrict_link) {\n-\t\t\t\t__key_link_end(keyring, \u0026key-\u003eindex_key, edit);\n+\t\t\t\t__key_link_end(keyring, \u0026key-\u003eindex_key, \u0026edit);\n \t\t\t\treturn -EPERM;\n \t\t\t}\n \t\t\tlink_ret = __key_link_begin(keyring, \u0026key-\u003eindex_key, \u0026edit);\n \t\t\tif (link_ret \u003c 0)\n-\t\t\t\t__key_link_end(keyring, \u0026key-\u003eindex_key, edit);\n+\t\t\t\t__key_link_end(keyring, \u0026key-\u003eindex_key, \u0026edit);\n \t\t}\n \t}\n \n@@ -635,7 +635,7 @@ int key_reject_and_link(struct key *key,\n \tmutex_unlock(\u0026key_construction_mutex);\n \n \tif (keyring \u0026\u0026 link_ret == 0)\n-\t\t__key_link_end(keyring, \u0026key-\u003eindex_key, edit);\n+\t\t__key_link_end(keyring, \u0026key-\u003eindex_key, \u0026edit);\n \n \t/* wake up anyone waiting for a key to be constructed */\n \tif (awaken)\n@@ -825,7 +825,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,\n \t\t.description\t= description,\n \t};\n \tstruct key_preparsed_payload prep;\n-\tstruct assoc_array_edit *edit = NULL;\n+\tstruct keyring_edit edit = {};\n \tconst struct cred *cred = current_cred();\n \tstruct key *keyring, *key = NULL;\n \tkey_ref_t key_ref;\n@@ -966,7 +966,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,\n \tkey_ref = make_key_ref(key, is_key_possessed(keyring_ref));\n \n error_link_end:\n-\t__key_link_end(keyring, \u0026index_key, edit);\n+\t__key_link_end(keyring, \u0026index_key, \u0026edit);\n error_free_prep:\n \tif (index_key.type-\u003epreparse)\n \t\tindex_key.type-\u003efree_preparse(\u0026prep);\n@@ -979,7 +979,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,\n \t/* we found a matching key, so we're going to try to update it\n \t * - we can drop the locks first as we have the key pinned\n \t */\n-\t__key_link_end(keyring, \u0026index_key, edit);\n+\t__key_link_end(keyring, \u0026index_key, \u0026edit);\n \n \tkey = key_ref_to_ptr(key_ref);\n \tif (test_bit(KEY_FLAG_USER_CONSTRUCT, \u0026key-\u003eflags)) {\ndiff --git a/security/keys/keyring.c b/security/keys/keyring.c\nindex 5281da9d5bf750..6761c6801edcd8 100644\n--- a/security/keys/keyring.c\n+++ b/security/keys/keyring.c\n@@ -12,14 +12,15 @@\n #include \u003clinux/security.h\u003e\n #include \u003clinux/seq_file.h\u003e\n #include \u003clinux/err.h\u003e\n+#include \u003clinux/jhash.h\u003e\n #include \u003clinux/user_namespace.h\u003e\n #include \u003clinux/nsproxy.h\u003e\n #include \u003clinux/once.h\u003e\n #include \u003clinux/random.h\u003e\n+#include \u003clinux/rhashtable.h\u003e\n #include \u003clinux/siphash.h\u003e\n+#include \u003clinux/workqueue.h\u003e\n #include \u003ckeys/keyring-type.h\u003e\n-#include \u003ckeys/user-type.h\u003e\n-#include \u003clinux/assoc_array_priv.h\u003e\n #include \u003clinux/uaccess.h\u003e\n #include \u003cnet/net_namespace.h\u003e\n #include \"internal.h\"\n@@ -31,25 +32,153 @@\n #define KEYRING_SEARCH_MAX_DEPTH 6\n \n /*\n- * We mark pointers we pass to the associative array with bit 1 set if\n- * they're keyrings and clear otherwise.\n+ * Keyrings are inserted at the head of @list, other keys at the tail, so\n+ * recursive search can stop at the first non-keyring.\n  */\n-#define KEYRING_PTR_SUBTYPE\t0x2UL\n+struct keyring_index {\n+\tstruct rhashtable\tht;\n+\tstruct list_head\tlist;\t\t/* Active keys */\n+\tunsigned long\t\tnr;\t\t/* Number of active keys */\n+\tstruct rcu_work\t\trcu_work;\n+};\n+\n+/*\n+ * __key_link_begin() inserts new links with @key NULL so allocation happens\n+ * before __key_link().  @hash is cached so resizing can hash links while @key\n+ * is NULL.\n+ */\n+struct keyring_link {\n+\tstruct rcu_head\t\trcu;\n+\tstruct rhash_head\tnode;\n+\tstruct key __rcu\t*key;\t\t/* NULL while inactive */\n+\tstruct list_head\tlist;\n+\tu32\t\t\thash;\n+};\n+\n+static u32 keyring_hashfn(const void *data, u32 len, u32 seed)\n+{\n+\tconst struct keyring_index_key *index_key = data;\n+\n+\treturn jhash_1word(index_key-\u003ehash, seed);\n+}\n \n-static inline bool keyring_ptr_is_keyring(const struct assoc_array_ptr *x)\n+static u32 keyring_obj_hashfn(const void *data, u32 len, u32 seed)\n {\n-\treturn (unsigned long)x \u0026 KEYRING_PTR_SUBTYPE;\n+\tconst struct keyring_link *link = data;\n+\n+\treturn jhash_1word(link-\u003ehash, seed);\n }\n-static inline struct key *keyring_ptr_to_key(const struct assoc_array_ptr *x)\n+\n+static bool keyring_index_key_equal(const struct keyring_index_key *a,\n+\t\t\t\t    const struct keyring_index_key *b)\n {\n-\tvoid *object = assoc_array_ptr_to_leaf(x);\n-\treturn (struct key *)((unsigned long)object \u0026 ~KEYRING_PTR_SUBTYPE);\n+\treturn a-\u003etype == b-\u003etype \u0026\u0026\n+\t\ta-\u003edomain_tag == b-\u003edomain_tag \u0026\u0026\n+\t\ta-\u003edesc_len == b-\u003edesc_len \u0026\u0026\n+\t\tmemcmp(a-\u003edescription, b-\u003edescription, a-\u003edesc_len) == 0;\n }\n-static inline void *keyring_key_to_ptr(struct key *key)\n+\n+static struct key *keyring_link_key(const struct keyring_link *link)\n {\n-\tif (key-\u003etype == \u0026key_type_keyring)\n-\t\treturn (void *)((unsigned long)key | KEYRING_PTR_SUBTYPE);\n-\treturn key;\n+\treturn rcu_dereference_check(link-\u003ekey, true);\n+}\n+\n+static int keyring_obj_cmpfn(struct rhashtable_compare_arg *arg,\n+\t\t\t     const void *obj)\n+{\n+\tconst struct keyring_link *link = obj;\n+\tconst struct key *key = keyring_link_key(link);\n+\n+\treturn !key || !keyring_index_key_equal(\u0026key-\u003eindex_key, arg-\u003ekey);\n+}\n+\n+static const struct rhashtable_params keyring_link_params = {\n+\t.head_offset\t\t= offsetof(struct keyring_link, node),\n+\t.hashfn\t\t\t= keyring_hashfn,\n+\t.obj_hashfn\t\t= keyring_obj_hashfn,\n+\t.obj_cmpfn\t\t= keyring_obj_cmpfn,\n+\t.min_size\t\t= 4,\n+\t.nelem_hint\t\t= 3,\n+\t.automatic_shrinking\t= true,\n+\t.insecure_elasticity\t= true,\n+};\n+\n+static struct keyring_index *keyring_index_locked(const struct key *keyring)\n+{\n+\treturn rcu_dereference_protected(keyring-\u003eindex,\n+\t\t\t\t\t lockdep_is_held(\u0026keyring-\u003esem));\n+}\n+\n+static struct keyring_link *keyring_find_link(struct keyring_index *index,\n+\t\t\t\t\t      const struct keyring_index_key *index_key)\n+{\n+\tif (!index)\n+\t\treturn NULL;\n+\n+\treturn rhashtable_lookup_fast(\u0026index-\u003eht, index_key, keyring_link_params);\n+}\n+\n+static int keyring_iterate(const struct key *keyring,\n+\t\t\t   int (*iterator)(const struct key *key, void *data),\n+\t\t\t   void *data)\n+{\n+\tstruct keyring_index *index;\n+\tstruct keyring_link *link;\n+\tint ret;\n+\n+\tguard(rcu)();\n+\tindex = rcu_dereference(keyring-\u003eindex);\n+\tif (index) {\n+\t\tlist_for_each_entry_rcu(link, \u0026index-\u003elist, list) {\n+\t\t\tret = iterator(keyring_link_key(link), data);\n+\t\t\tif (ret)\n+\t\t\t\treturn ret;\n+\t\t}\n+\t}\n+\n+\treturn 0;\n+}\n+\n+static void keyring_link_free_rcu(struct rcu_head *rcu)\n+{\n+\tstruct keyring_link *link = container_of(rcu, struct keyring_link, rcu);\n+\n+\tkey_put(rcu_dereference_raw(link-\u003ekey));\n+\tkfree(link);\n+}\n+\n+static void __keyring_index_free(struct keyring_index *index)\n+{\n+\tstruct keyring_link *link, *tmp;\n+\n+\trhashtable_destroy(\u0026index-\u003eht);\n+\n+\tlist_for_each_entry_safe(link, tmp, \u0026index-\u003elist, list) {\n+\t\tkey_put(rcu_dereference_protected(link-\u003ekey, true));\n+\t\tkfree(link);\n+\t}\n+\n+\tkfree(index);\n+}\n+\n+static void keyring_index_free_work(struct work_struct *work)\n+{\n+\tstruct keyring_index *index = container_of(to_rcu_work(work),\n+\t\t\t\t\t\t struct keyring_index, rcu_work);\n+\n+\t__keyring_index_free(index);\n+}\n+\n+static void keyring_index_free(struct key *keyring)\n+{\n+\tstruct keyring_index *index = keyring_index_locked(keyring);\n+\n+\tif (!index)\n+\t\treturn;\n+\n+\trcu_assign_pointer(keyring-\u003eindex, NULL);\n+\t/* rhashtable_destroy() may sleep, so defer via rcu_work. */\n+\tqueue_rcu_work(system_dfl_wq, \u0026index-\u003ercu_work);\n }\n \n static DEFINE_RWLOCK(keyring_name_lock);\n@@ -143,80 +272,44 @@ static void keyring_free_preparse(struct key_preparsed_payload *prep)\n static int keyring_instantiate(struct key *keyring,\n \t\t\t       struct key_preparsed_payload *prep)\n {\n-\tassoc_array_init(\u0026keyring-\u003ekeys);\n+\tRCU_INIT_POINTER(keyring-\u003eindex, NULL);\n \t/* make the keyring available by name if it has one */\n \tkeyring_publish_name(keyring);\n \treturn 0;\n }\n \n /*\n- * Give key types and domains address-independent identities.  Zero means that\n- * an ID has not yet been allocated.  As with inode sequence numbers used by\n- * futexes, this relies on the 64-bit counter not wrapping in a machine's\n- * lifetime.\n- */\n-static u64 key_index_id(atomic64_t *id)\n-{\n-\tstatic atomic64_t next_id;\n-\tu64 old, new;\n-\n-\told = atomic64_read(id);\n-\tif (likely(old))\n-\t\treturn old;\n-\n-\tdo {\n-\t\tnew = atomic64_inc_return(\u0026next_id);\n-\t} while (WARN_ON_ONCE(!new));\n-\n-\told = 0;\n-\tif (!atomic64_try_cmpxchg_relaxed(id, \u0026old, new))\n-\t\treturn old;\n-\treturn new;\n-}\n-\n-/*\n- * Hash a key type, domain and description.  KEYCTL_READ exposes the tree's\n- * traversal order, so no part of the index may contain kernel addresses.\n+ * Hash a key type, domain and description.\n  */\n static void hash_key_type_and_desc(struct keyring_index_key *index_key)\n {\n-\tconst unsigned level_shift = ASSOC_ARRAY_LEVEL_STEP;\n-\tconst unsigned long fan_mask = ASSOC_ARRAY_FAN_MASK;\n \tstatic siphash_key_t hash_key __read_mostly;\n-\tunsigned long hash;\n \tu64 acc;\n \n+\t/*\n+\t * Compute a SipHash value of the description, type pointer, and domain\n+\t * tag pointer using a per-boot random key.\n+\t *\n+\t * Note that using the pointers as input to the hash is safe, since\n+\t * SipHash is a cryptographically secure pseudorandom function.  Thus\n+\t * the hash values don't leak any information about the pointers.\n+\t *\n+\t * Similarly, truncating the SipHash values to the required 32 bits is\n+\t * also safe.  No \"folding\" step is needed.\n+\t */\n \tget_random_once(\u0026hash_key, sizeof(hash_key));\n \tacc = siphash(index_key-\u003edescription, index_key-\u003edesc_len, \u0026hash_key);\n-\tacc = siphash_3u64(index_key-\u003etype_id, index_key-\u003edomain_id, acc,\n-\t\t\t   \u0026hash_key);\n-\n-\t/* Fold the hash down to 32 bits if need be. */\n-\thash = acc;\n-\tif (ASSOC_ARRAY_KEY_CHUNK_SIZE == 32)\n-\t\thash ^= acc \u003e\u003e 32;\n-\n-\t/* Squidge all the keyrings into a separate part of the tree to\n-\t * ordinary keys by making sure the lowest level segment in the hash is\n-\t * zero for keyrings and non-zero otherwise.\n-\t */\n-\tif (index_key-\u003etype != \u0026key_type_keyring \u0026\u0026 (hash \u0026 fan_mask) == 0)\n-\t\thash |= (hash \u003e\u003e (ASSOC_ARRAY_KEY_CHUNK_SIZE - level_shift)) | 1;\n-\telse if (index_key-\u003etype == \u0026key_type_keyring \u0026\u0026 (hash \u0026 fan_mask) != 0)\n-\t\thash = (hash + (hash \u003c\u003c level_shift)) \u0026 ~fan_mask;\n-\tindex_key-\u003ehash = hash;\n+\tindex_key-\u003ehash = siphash_3u64((uintptr_t)index_key-\u003etype,\n+\t\t\t\t       (uintptr_t)index_key-\u003edomain_tag,\n+\t\t\t\t       acc, \u0026hash_key);\n }\n \n /*\n- * Finalise an index key to include a part of the description actually in the\n- * index key, to set the domain tag and index IDs, and to calculate the hash.\n+ * Finalise an index key to set the domain tag and calculate the hash.\n  */\n void key_set_index_key(struct keyring_index_key *index_key)\n {\n \tstatic struct key_tag default_domain_tag = { .usage = REFCOUNT_INIT(1), };\n-\tsize_t n = min_t(size_t, index_key-\u003edesc_len, sizeof(index_key-\u003edesc));\n-\n-\tmemcpy(index_key-\u003edesc, index_key-\u003edescription, n);\n \n \tif (!index_key-\u003edomain_tag) {\n \t\tif (index_key-\u003etype-\u003eflags \u0026 KEY_TYPE_NET_DOMAIN)\n@@ -225,14 +318,6 @@ void key_set_index_key(struct keyring_index_key *index_key)\n \t\t\tindex_key-\u003edomain_tag = \u0026default_domain_tag;\n \t}\n \n-\t/* Preserve the IDs when copying an existing key's index.  In\n-\t * particular, its type may already have been unregistered.\n-\t */\n-\tif (!index_key-\u003etype_id)\n-\t\tindex_key-\u003etype_id = key_index_id(\u0026index_key-\u003etype-\u003eindex_id);\n-\tif (!index_key-\u003edomain_id)\n-\t\tindex_key-\u003edomain_id = key_index_id(\u0026index_key-\u003edomain_tag-\u003eindex_id);\n-\n \thash_key_type_and_desc(index_key);\n }\n \n@@ -268,150 +353,6 @@ void key_remove_domain(struct key_tag *domain_tag)\n \t\tkey_schedule_gc_links();\n }\n \n-/*\n- * Build the next index key chunk.\n- *\n- * The hash and inline description are followed by the 64-bit type and domain\n- * IDs, low word first, and then by the rest of the description.\n- * We return it one word-sized chunk at a time.\n- */\n-static unsigned long keyring_get_key_chunk(const void *data, int level)\n-{\n-\tconst unsigned int id_chunks = sizeof(u64) / sizeof(unsigned long);\n-\tconst struct keyring_index_key *index_key = data;\n-\tint desc_len = index_key-\u003edesc_len;\n-\tunsigned long chunk = 0;\n-\tint n = sizeof(chunk);\n-\tunsigned int offset;\n-\tconst u8 *d;\n-\n-\tlevel /= ASSOC_ARRAY_KEY_CHUNK_SIZE;\n-\tswitch (level) {\n-\tcase 0:\n-\t\treturn index_key-\u003ehash;\n-\tcase 1:\n-\t\treturn index_key-\u003ex;\n-\t}\n-\n-\tlevel -= 2;\n-\tif (level \u003c id_chunks)\n-\t\treturn index_key-\u003etype_id \u003e\u003e (level * ASSOC_ARRAY_KEY_CHUNK_SIZE);\n-\tlevel -= id_chunks;\n-\tif (level \u003c id_chunks)\n-\t\treturn index_key-\u003edomain_id \u003e\u003e (level * ASSOC_ARRAY_KEY_CHUNK_SIZE);\n-\tlevel -= id_chunks;\n-\n-\toffset = sizeof(index_key-\u003edesc) + level * sizeof(long);\n-\tif (desc_len \u003c= offset)\n-\t\treturn 0;\n-\n-\td = index_key-\u003edescription + offset;\n-\tdesc_len -= offset;\n-\tif (desc_len \u003e n)\n-\t\tdesc_len = n;\n-\td += desc_len;\n-\tdo {\n-\t\tchunk \u003c\u003c= 8;\n-\t\tchunk |= *--d;\n-\t} while (--desc_len \u003e 0);\n-\treturn chunk;\n-}\n-\n-static unsigned long keyring_get_object_key_chunk(const void *object, int level)\n-{\n-\tconst struct key *key = keyring_ptr_to_key(object);\n-\treturn keyring_get_key_chunk(\u0026key-\u003eindex_key, level);\n-}\n-\n-static bool keyring_compare_object(const void *object, const void *data)\n-{\n-\tconst struct keyring_index_key *index_key = data;\n-\tconst struct key *key = keyring_ptr_to_key(object);\n-\n-\treturn key-\u003eindex_key.type == index_key-\u003etype \u0026\u0026\n-\t\tkey-\u003eindex_key.domain_tag == index_key-\u003edomain_tag \u0026\u0026\n-\t\tkey-\u003eindex_key.desc_len == index_key-\u003edesc_len \u0026\u0026\n-\t\tmemcmp(key-\u003eindex_key.description, index_key-\u003edescription,\n-\t\t       index_key-\u003edesc_len) == 0;\n-}\n-\n-/*\n- * Compare the index keys of a pair of objects and determine the bit position\n- * at which they differ - if they differ.\n- */\n-static int keyring_diff_objects(const void *object, const void *data)\n-{\n-\tconst struct key *key_a = keyring_ptr_to_key(object);\n-\tconst struct keyring_index_key *a = \u0026key_a-\u003eindex_key;\n-\tconst struct keyring_index_key *b = data;\n-\tunsigned long seg_a, seg_b;\n-\tint level, i;\n-\tu64 diff;\n-\n-\tlevel = 0;\n-\tseg_a = a-\u003ehash;\n-\tseg_b = b-\u003ehash;\n-\tif ((seg_a ^ seg_b) != 0)\n-\t\tgoto differ;\n-\tlevel += ASSOC_ARRAY_KEY_CHUNK_SIZE / 8;\n-\n-\t/* The inline description contributes one machine-word-sized chunk. */\n-\tseg_a = a-\u003ex;\n-\tseg_b = b-\u003ex;\n-\tif ((seg_a ^ seg_b) != 0)\n-\t\tgoto differ;\n-\tlevel += sizeof(unsigned long);\n-\n-\tdiff = a-\u003etype_id ^ b-\u003etype_id;\n-\tif (diff)\n-\t\treturn level * 8 + __ffs64(diff);\n-\tlevel += sizeof(u64);\n-\n-\tdiff = a-\u003edomain_id ^ b-\u003edomain_id;\n-\tif (diff)\n-\t\treturn level * 8 + __ffs64(diff);\n-\tlevel += sizeof(u64);\n-\n-\ti = sizeof(a-\u003edesc);\n-\tif (a-\u003edesc_len \u003c= i)\n-\t\tgoto same;\n-\n-\tfor (; i \u003c a-\u003edesc_len; i++) {\n-\t\tseg_a = *(unsigned char *)(a-\u003edescription + i);\n-\t\tseg_b = *(unsigned char *)(b-\u003edescription + i);\n-\t\tif ((seg_a ^ seg_b) != 0)\n-\t\t\tgoto differ_plus_i;\n-\t}\n-\n-same:\n-\treturn -1;\n-\n-differ_plus_i:\n-\tlevel += i - (int)sizeof(a-\u003edesc);\n-differ:\n-\ti = level * 8 + __ffs(seg_a ^ seg_b);\n-\treturn i;\n-}\n-\n-/*\n- * Free an object after stripping the keyring flag off of the pointer.\n- */\n-static void keyring_free_object(void *object)\n-{\n-\tkey_put(keyring_ptr_to_key(object));\n-}\n-\n-/*\n- * Operations for keyring management by the index-tree routines.\n- */\n-static const struct assoc_array_ops keyring_assoc_array_ops = {\n-\t.get_key_chunk\t\t= keyring_get_key_chunk,\n-\t.get_object_key_chunk\t= keyring_get_object_key_chunk,\n-\t.compare_object\t\t= keyring_compare_object,\n-\t.diff_objects\t\t= keyring_diff_objects,\n-\t.free_object\t\t= keyring_free_object,\n-};\n-\n /*\n  * Clean up a keyring when it is destroyed.  Unpublish its name if it had one\n  * and dispose of its data.\n@@ -423,6 +364,8 @@ static const struct assoc_array_ops keyring_assoc_array_ops = {\n  */\n static void keyring_destroy(struct key *keyring)\n {\n+\tstruct keyring_index *index;\n+\n \tif (keyring-\u003edescription) {\n \t\twrite_lock(\u0026keyring_name_lock);\n \n@@ -440,49 +383,51 @@ static void keyring_destroy(struct key *keyring)\n \t\tkfree(keyres);\n \t}\n \n-\tassoc_array_destroy(\u0026keyring-\u003ekeys, \u0026keyring_assoc_array_ops);\n+\tindex = rcu_dereference_protected(keyring-\u003eindex, true);\n+\tif (index)\n+\t\t__keyring_index_free(index);\n+}\n+\n+static unsigned long keyring_nr_links(const struct key *keyring)\n+{\n+\tconst struct keyring_index *index;\n+\n+\tguard(rcu)();\n+\tindex = rcu_dereference(keyring-\u003eindex);\n+\treturn index ? READ_ONCE(index-\u003enr) : 0;\n+}\n+\n+/**\n+ * keyring_is_empty - Check whether a keyring is empty\n+ * @keyring: The keyring to check.\n+ */\n+bool keyring_is_empty(const struct key *keyring)\n+{\n+\treturn keyring_nr_links(keyring) == 0;\n }\n+EXPORT_SYMBOL(keyring_is_empty);\n \n /*\n  * Describe a keyring for /proc.\n  */\n static void keyring_describe(const struct key *keyring, struct seq_file *m)\n {\n+\tunsigned long nr;\n+\n \tif (keyring-\u003edescription)\n \t\tseq_puts(m, keyring-\u003edescription);\n \telse\n \t\tseq_puts(m, \"[anon]\");\n \n \tif (key_is_positive(keyring)) {\n-\t\tif (keyring-\u003ekeys.nr_leaves_on_tree != 0)\n-\t\t\tseq_printf(m, \": %lu\", keyring-\u003ekeys.nr_leaves_on_tree);\n+\t\tnr = keyring_nr_links(keyring);\n+\t\tif (nr != 0)\n+\t\t\tseq_printf(m, \": %lu\", nr);\n \t\telse\n \t\t\tseq_puts(m, \": empty\");\n \t}\n }\n \n-struct keyring_read_iterator_context {\n-\tsize_t\t\t\tbuflen;\n-\tsize_t\t\t\tcount;\n-\tkey_serial_t\t\t*buffer;\n-};\n-\n-static int keyring_read_iterator(const void *object, void *data)\n-{\n-\tstruct keyring_read_iterator_context *ctx = data;\n-\tconst struct key *key = keyring_ptr_to_key(object);\n-\n-\tkenter(\"{%s,%d},,{%zu/%zu}\",\n-\t       key-\u003etype-\u003ename, key-\u003eserial, ctx-\u003ecount, ctx-\u003ebuflen);\n-\n-\tif (ctx-\u003ecount \u003e= ctx-\u003ebuflen)\n-\t\treturn 1;\n-\n-\t*ctx-\u003ebuffer++ = key-\u003eserial;\n-\tctx-\u003ecount += sizeof(key-\u003eserial);\n-\treturn 0;\n-}\n-\n /*\n  * Read a list of key IDs from the keyring's contents in binary form\n  *\n@@ -493,7 +438,10 @@ static int keyring_read_iterator(const void *object, void *data)\n static long keyring_read(const struct key *keyring,\n \t\t\t char *buffer, size_t buflen)\n {\n-\tstruct keyring_read_iterator_context ctx;\n+\tstruct keyring_index *links = keyring_index_locked(keyring);\n+\tkey_serial_t *serials = (key_serial_t *)buffer;\n+\tstruct keyring_link *link;\n+\tsize_t count = 0;\n \tlong ret;\n \n \tkenter(\"{%d},,%zu\", key_serial(keyring), buflen);\n@@ -501,25 +449,22 @@ static long keyring_read(const struct key *keyring,\n \tif (buflen \u0026 (sizeof(key_serial_t) - 1))\n \t\treturn -EINVAL;\n \n-\t/* Copy as many key IDs as fit into the buffer */\n-\tif (buffer \u0026\u0026 buflen) {\n-\t\tctx.buffer = (key_serial_t *)buffer;\n-\t\tctx.buflen = buflen;\n-\t\tctx.count = 0;\n-\t\tret = assoc_array_iterate(\u0026keyring-\u003ekeys,\n-\t\t\t\t\t  keyring_read_iterator, \u0026ctx);\n-\t\tif (ret \u003c 0) {\n-\t\t\tkleave(\" = %ld [iterate]\", ret);\n-\t\t\treturn ret;\n+\tif (buffer \u0026\u0026 buflen \u0026\u0026 links) {\n+\t\tlist_for_each_entry(link, \u0026links-\u003elist, list) {\n+\t\t\tif (count == buflen / sizeof(*serials))\n+\t\t\t\tbreak;\n+\n+\t\t\tserials[count++] = keyring_link_key(link)-\u003eserial;\n+\t\t\tcond_resched();\n \t\t}\n \t}\n \n-\t/* Return the size of the buffer needed */\n-\tret = keyring-\u003ekeys.nr_leaves_on_tree * sizeof(key_serial_t);\n+\tret = links ? links-\u003enr * sizeof(key_serial_t) : 0;\n \tif (ret \u003c= buflen)\n \t\tkleave(\"= %ld [ok]\", ret);\n \telse\n \t\tkleave(\"= %ld [buffer too small]\", ret);\n+\n \treturn ret;\n }\n \n@@ -583,10 +528,9 @@ bool key_default_cmp(const struct key *key,\n /*\n  * Iteration function to consider each key found.\n  */\n-static int keyring_search_iterator(const void *object, void *iterator_data)\n+static int keyring_search_iterator(const struct key *key, void *iterator_data)\n {\n \tstruct keyring_search_context *ctx = iterator_data;\n-\tconst struct key *key = keyring_ptr_to_key(object);\n \tunsigned long kflags = READ_ONCE(key-\u003eflags);\n \tshort state = key_read_state(key);\n \n@@ -653,19 +597,78 @@ static int keyring_search_iterator(const void *object, void *iterator_data)\n /*\n  * Search inside a keyring for a key.  We can search by walking to it\n  * directly based on its index-key or we can iterate over the entire\n- * tree looking for it, based on the match function.\n+ * list looking for it, based on the match function.\n  */\n static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)\n {\n \tif (ctx-\u003ematch_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) {\n-\t\tconst void *object;\n+\t\tstruct keyring_link *link;\n+\t\tstruct key *key;\n+\n+\t\tlink = keyring_find_link(rcu_dereference(keyring-\u003eindex),\n+\t\t\t\t\t \u0026ctx-\u003eindex_key);\n+\t\tif (!link)\n+\t\t\treturn 0;\n+\t\tkey = keyring_link_key(link);\n+\t\treturn ctx-\u003eiterator(key, ctx);\n+\t}\n+\n+\treturn keyring_iterate(keyring, ctx-\u003eiterator, ctx);\n+}\n \n-\t\tobject = assoc_array_find(\u0026keyring-\u003ekeys,\n-\t\t\t\t\t  \u0026keyring_assoc_array_ops,\n-\t\t\t\t\t  \u0026ctx-\u003eindex_key);\n-\t\treturn object ? ctx-\u003eiterator(object, ctx) : 0;\n+/*\n+ * Depth-first search of @keyring and its nested keyrings.\n+ */\n+static int search_keyring_tree(struct key *keyring,\n+\t\t\t       struct keyring_search_context *ctx, int depth)\n+{\n+\tstruct keyring_index *links;\n+\tstruct keyring_link *link;\n+\tint ret;\n+\n+\tif (keyring-\u003eflags \u0026 ((1 \u003c\u003c KEY_FLAG_INVALIDATED) |\n+\t\t\t      (1 \u003c\u003c KEY_FLAG_REVOKED)))\n+\t\treturn 0;\n+\n+\tif (search_keyring(keyring, ctx))\n+\t\tgoto found;\n+\n+\tif (!(ctx-\u003eflags \u0026 KEYRING_SEARCH_RECURSE))\n+\t\treturn 0;\n+\tlinks = rcu_dereference(keyring-\u003eindex);\n+\tif (!links)\n+\t\treturn 0;\n+\n+\tlist_for_each_entry_rcu(link, \u0026links-\u003elist, list) {\n+\t\tstruct key *key = keyring_link_key(link);\n+\n+\t\tif (key-\u003etype != \u0026key_type_keyring)\n+\t\t\tbreak;\n+\t\tif (depth \u003e= KEYRING_SEARCH_MAX_DEPTH) {\n+\t\t\tif (!(ctx-\u003eflags \u0026 KEYRING_SEARCH_DETECT_TOO_DEEP))\n+\t\t\t\treturn 0;\n+\t\t\tctx-\u003eresult = ERR_PTR(-ELOOP);\n+\t\t\treturn -ELOOP;\n+\t\t}\n+\n+\t\tif (!(ctx-\u003eflags \u0026 KEYRING_SEARCH_NO_CHECK_PERM) \u0026\u0026\n+\t\t    key_task_permission(make_key_ref(key, ctx-\u003epossessed),\n+\t\t\t\t\tctx-\u003ecred, KEY_NEED_SEARCH) \u003c 0)\n+\t\t\tcontinue;\n+\n+\t\tret = search_keyring_tree(key, ctx, depth + 1);\n+\t\tif (ret \u003c 0)\n+\t\t\treturn ret;\n+\t\tif (ret)\n+\t\t\tgoto found;\n \t}\n-\treturn assoc_array_iterate(\u0026keyring-\u003ekeys, ctx-\u003eiterator, ctx);\n+\n+\treturn 0;\n+\n+found:\n+\tif (!(ctx-\u003eflags \u0026 KEYRING_SEARCH_NO_UPDATE_TIME))\n+\t\tkeyring-\u003elast_used_at = ctx-\u003enow;\n+\treturn 1;\n }\n \n /*\n@@ -675,17 +678,7 @@ static int search_keyring(struct key *keyring, struct keyring_search_context *ct\n static bool search_nested_keyrings(struct key *keyring,\n \t\t\t\t   struct keyring_search_context *ctx)\n {\n-\tstruct {\n-\t\tstruct key *keyring;\n-\t\tstruct assoc_array_node *node;\n-\t\tint slot;\n-\t} stack[KEYRING_SEARCH_MAX_DEPTH];\n-\n-\tstruct assoc_array_shortcut *shortcut;\n-\tstruct assoc_array_node *node;\n-\tstruct assoc_array_ptr *ptr;\n \tstruct key *key;\n-\tint sp = 0, slot;\n \n \tkenter(\"{%d},{%s,%s}\",\n \t       keyring-\u003eserial,\n@@ -703,9 +696,9 @@ static bool search_nested_keyrings(struct key *keyring,\n \t * and whether it is valid or not.\n \t */\n \tif (ctx-\u003ematch_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||\n-\t    keyring_compare_object(keyring, \u0026ctx-\u003eindex_key)) {\n+\t    keyring_index_key_equal(\u0026keyring-\u003eindex_key, \u0026ctx-\u003eindex_key)) {\n \t\tctx-\u003eskipped_ret = 2;\n-\t\tswitch (ctx-\u003eiterator(keyring_key_to_ptr(keyring), ctx)) {\n+\t\tswitch (ctx-\u003eiterator(keyring, ctx)) {\n \t\tcase 1:\n \t\t\tgoto found;\n \t\tcase 2:\n@@ -717,152 +710,11 @@ static bool search_nested_keyrings(struct key *keyring,\n \n \tctx-\u003eskipped_ret = 0;\n \n-\t/* Start processing a new keyring */\n-descend_to_keyring:\n-\tkdebug(\"descend to %d\", keyring-\u003eserial);\n-\tif (keyring-\u003eflags \u0026 ((1 \u003c\u003c KEY_FLAG_INVALIDATED) |\n-\t\t\t      (1 \u003c\u003c KEY_FLAG_REVOKED)))\n-\t\tgoto not_this_keyring;\n-\n-\t/* Search through the keys in this keyring before its searching its\n-\t * subtrees.\n-\t */\n-\tif (search_keyring(keyring, ctx))\n-\t\tgoto found;\n-\n-\t/* Then manually iterate through the keyrings nested in this one.\n-\t *\n-\t * Start from the root node of the index tree.  Because of the way the\n-\t * hash function has been set up, keyrings cluster on the leftmost\n-\t * branch of the root node (root slot 0) or in the root node itself.\n-\t * Non-keyrings avoid the leftmost branch of the root entirely (root\n-\t * slots 1-15).\n-\t */\n-\tif (!(ctx-\u003eflags \u0026 KEYRING_SEARCH_RECURSE))\n-\t\tgoto not_this_keyring;\n-\n-\tptr = READ_ONCE(keyring-\u003ekeys.root);\n-\tif (!ptr)\n-\t\tgoto not_this_keyring;\n-\n-\tif (assoc_array_ptr_is_shortcut(ptr)) {\n-\t\t/* If the root is a shortcut, either the keyring only contains\n-\t\t * keyring pointers (everything clusters behind root slot 0) or\n-\t\t * doesn't contain any keyring pointers.\n-\t\t */\n-\t\tshortcut = assoc_array_ptr_to_shortcut(ptr);\n-\t\tif ((shortcut-\u003eindex_key[0] \u0026 ASSOC_ARRAY_FAN_MASK) != 0)\n-\t\t\tgoto not_this_keyring;\n-\n-\t\tptr = READ_ONCE(shortcut-\u003enext_node);\n-\t\tnode = assoc_array_ptr_to_node(ptr);\n-\t\tgoto begin_node;\n-\t}\n-\n-\tnode = assoc_array_ptr_to_node(ptr);\n-\tptr = node-\u003eslots[0];\n-\tif (!assoc_array_ptr_is_meta(ptr))\n-\t\tgoto begin_node;\n-\n-descend_to_node:\n-\t/* Descend to a more distal node in this keyring's content tree and go\n-\t * through that.\n-\t */\n-\tkdebug(\"descend\");\n-\tif (assoc_array_ptr_is_shortcut(ptr)) {\n-\t\tshortcut = assoc_array_ptr_to_shortcut(ptr);\n-\t\tptr = READ_ONCE(shortcut-\u003enext_node);\n-\t\tBUG_ON(!assoc_array_ptr_is_node(ptr));\n-\t}\n-\tnode = assoc_array_ptr_to_node(ptr);\n-\n-begin_node:\n-\tkdebug(\"begin_node\");\n-\tslot = 0;\n-ascend_to_node:\n-\t/* Go through the slots in a node */\n-\tfor (; slot \u003c ASSOC_ARRAY_FAN_OUT; slot++) {\n-\t\tptr = READ_ONCE(node-\u003eslots[slot]);\n-\n-\t\tif (assoc_array_ptr_is_meta(ptr)) {\n-\t\t\tif (node-\u003eback_pointer ||\n-\t\t\t    assoc_array_ptr_is_shortcut(ptr))\n-\t\t\t\tgoto descend_to_node;\n-\t\t}\n-\n-\t\tif (!keyring_ptr_is_keyring(ptr))\n-\t\t\tcontinue;\n-\n-\t\tkey = keyring_ptr_to_key(ptr);\n-\n-\t\tif (sp \u003e= KEYRING_SEARCH_MAX_DEPTH) {\n-\t\t\tif (ctx-\u003eflags \u0026 KEYRING_SEARCH_DETECT_TOO_DEEP) {\n-\t\t\t\tctx-\u003eresult = ERR_PTR(-ELOOP);\n-\t\t\t\treturn false;\n-\t\t\t}\n-\t\t\tgoto not_this_keyring;\n-\t\t}\n-\n-\t\t/* Search a nested keyring */\n-\t\tif (!(ctx-\u003eflags \u0026 KEYRING_SEARCH_NO_CHECK_PERM) \u0026\u0026\n-\t\t    key_task_permission(make_key_ref(key, ctx-\u003epossessed),\n-\t\t\t\t\tctx-\u003ecred, KEY_NEED_SEARCH) \u003c 0)\n-\t\t\tcontinue;\n-\n-\t\t/* stack the current position */\n-\t\tstack[sp].keyring = keyring;\n-\t\tstack[sp].node = node;\n-\t\tstack[sp].slot = slot;\n-\t\tsp++;\n-\n-\t\t/* begin again with the new keyring */\n-\t\tkeyring = key;\n-\t\tgoto descend_to_keyring;\n-\t}\n-\n-\t/* We've dealt with all the slots in the current node, so now we need\n-\t * to ascend to the parent and continue processing there.\n-\t */\n-\tptr = READ_ONCE(node-\u003eback_pointer);\n-\tslot = node-\u003eparent_slot;\n-\n-\tif (ptr \u0026\u0026 assoc_array_ptr_is_shortcut(ptr)) {\n-\t\tshortcut = assoc_array_ptr_to_shortcut(ptr);\n-\t\tptr = READ_ONCE(shortcut-\u003eback_pointer);\n-\t\tslot = shortcut-\u003eparent_slot;\n-\t}\n-\tif (!ptr)\n-\t\tgoto not_this_keyring;\n-\tnode = assoc_array_ptr_to_node(ptr);\n-\tslot++;\n-\n-\t/* If we've ascended to the root (zero backpointer), we must have just\n-\t * finished processing the leftmost branch rather than the root slots -\n-\t * so there can't be any more keyrings for us to find.\n-\t */\n-\tif (node-\u003eback_pointer) {\n-\t\tkdebug(\"ascend %d\", slot);\n-\t\tgoto ascend_to_node;\n-\t}\n-\n-\t/* The keyring we're looking at was disqualified or didn't contain a\n-\t * matching key.\n-\t */\n-not_this_keyring:\n-\tkdebug(\"not_this_keyring %d\", sp);\n-\tif (sp \u003c= 0) {\n+\tif (search_keyring_tree(keyring, ctx, 0) \u003c= 0) {\n \t\tkleave(\" = false\");\n \t\treturn false;\n \t}\n \n-\t/* Resume the processing of a keyring higher up in the tree */\n-\tsp--;\n-\tkeyring = stack[sp].keyring;\n-\tnode = stack[sp].node;\n-\tslot = stack[sp].slot + 1;\n-\tkdebug(\"ascend to %d [%d]\", keyring-\u003eserial, slot);\n-\tgoto ascend_to_node;\n-\n \t/* We found a viable match */\n found:\n \tkey = key_ref_to_ptr(ctx-\u003eresult);\n@@ -870,8 +722,6 @@ static bool search_nested_keyrings(struct key *keyring,\n \tif (!(ctx-\u003eflags \u0026 KEYRING_SEARCH_NO_UPDATE_TIME)) {\n \t\tkey-\u003elast_used_at = ctx-\u003enow;\n \t\tkeyring-\u003elast_used_at = ctx-\u003enow;\n-\t\twhile (sp \u003e 0)\n-\t\t\tstack[--sp].keyring-\u003elast_used_at = ctx-\u003enow;\n \t}\n \tkleave(\" = true\");\n \treturn true;\n@@ -1118,8 +968,8 @@ EXPORT_SYMBOL(keyring_restrict);\n key_ref_t find_key_to_update(key_ref_t keyring_ref,\n \t\t\t     const struct keyring_index_key *index_key)\n {\n+\tstruct keyring_link *link;\n \tstruct key *keyring, *key;\n-\tconst void *object;\n \n \tkeyring = key_ref_to_ptr(keyring_ref);\n \n@@ -1127,17 +977,16 @@ key_ref_t find_key_to_update(key_ref_t keyring_ref,\n \t       keyring-\u003eserial, index_key-\u003etype-\u003ename, index_key-\u003edescription);\n \n \tguard(rcu)();\n-\tobject = assoc_array_find(\u0026keyring-\u003ekeys, \u0026keyring_assoc_array_ops,\n-\t\t\t\t  index_key);\n+\tlink = keyring_find_link(rcu_dereference(keyring-\u003eindex), index_key);\n \n-\tif (object)\n+\tif (link)\n \t\tgoto found;\n \n \tkleave(\" = NULL\");\n \treturn NULL;\n \n found:\n-\tkey = keyring_ptr_to_key(object);\n+\tkey = keyring_link_key(link);\n \tif (key-\u003eflags \u0026 ((1 \u003c\u003c KEY_FLAG_INVALIDATED) |\n \t\t\t  (1 \u003c\u003c KEY_FLAG_REVOKED))) {\n \t\tkleave(\" = NULL [x]\");\n@@ -1207,11 +1056,10 @@ struct key *find_keyring_by_name(const char *name, bool uid_keyring)\n \treturn keyring;\n }\n \n-static int keyring_detect_cycle_iterator(const void *object,\n+static int keyring_detect_cycle_iterator(const struct key *key,\n \t\t\t\t\t void *iterator_data)\n {\n \tstruct keyring_search_context *ctx = iterator_data;\n-\tconst struct key *key = keyring_ptr_to_key(object);\n \n \tkenter(\"{%d}\", key-\u003eserial);\n \n@@ -1307,56 +1155,90 @@ int __key_move_lock(struct key *l_keyring, struct key *u_keyring,\n \treturn 0;\n }\n \n+static struct keyring_index *keyring_get_index(struct key *keyring)\n+{\n+\tstruct keyring_index *links = keyring_index_locked(keyring);\n+\tint ret;\n+\n+\tif (links)\n+\t\treturn links;\n+\n+\tlinks = kzalloc_obj(struct keyring_index);\n+\tif (!links)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\tret = rhashtable_init(\u0026links-\u003eht, \u0026keyring_link_params);\n+\tif (ret \u003c 0) {\n+\t\tkfree(links);\n+\t\treturn ERR_PTR(ret);\n+\t}\n+\n+\tINIT_LIST_HEAD(\u0026links-\u003elist);\n+\tINIT_RCU_WORK(\u0026links-\u003ercu_work, keyring_index_free_work);\n+\trcu_assign_pointer(keyring-\u003eindex, links);\n+\treturn links;\n+}\n+\n /*\n  * Preallocate memory so that a key can be linked into to a keyring.\n  */\n int __key_link_begin(struct key *keyring,\n \t\t     const struct keyring_index_key *index_key,\n-\t\t     struct assoc_array_edit **_edit)\n+\t\t     struct keyring_edit *edit)\n {\n-\tstruct assoc_array_edit *edit;\n+\tstruct keyring_link *link __free(kfree) = NULL;\n+\tstruct keyring_link *replace;\n+\tstruct keyring_index *links;\n \tint ret;\n \n \tkenter(\"%d,%s,%s,\",\n \t       keyring-\u003eserial, index_key-\u003etype-\u003ename, index_key-\u003edescription);\n \n-\tBUG_ON(index_key-\u003edesc_len == 0);\n-\tBUG_ON(*_edit != NULL);\n+\tif (WARN_ON(index_key-\u003edesc_len == 0) || WARN_ON(edit-\u003enew))\n+\t\treturn -EINVAL;\n \n-\t*_edit = NULL;\n+\tedit-\u003enew = NULL;\n+\tedit-\u003eold = NULL;\n \n \tret = -EKEYREVOKED;\n \tif (test_bit(KEY_FLAG_REVOKED, \u0026keyring-\u003eflags))\n \t\tgoto error;\n \n-\t/* Create an edit script that will insert/replace the key in the\n-\t * keyring tree.\n-\t */\n-\tedit = assoc_array_insert(\u0026keyring-\u003ekeys,\n-\t\t\t\t  \u0026keyring_assoc_array_ops,\n-\t\t\t\t  index_key,\n-\t\t\t\t  NULL);\n-\tif (IS_ERR(edit)) {\n-\t\tret = PTR_ERR(edit);\n+\tlinks = keyring_get_index(keyring);\n+\tif (IS_ERR(links)) {\n+\t\tret = PTR_ERR(links);\n \t\tgoto error;\n \t}\n \n+\tret = -ENOMEM;\n+\tlink = kzalloc_obj(struct keyring_link);\n+\tif (!link)\n+\t\tgoto error;\n+\tlink-\u003ehash = index_key-\u003ehash;\n+\n+\treplace = keyring_find_link(links, index_key);\n \t/* If we're not replacing a link in-place then we're going to need some\n \t * extra quota.\n \t */\n-\tif (!edit-\u003edead_leaf) {\n+\tif (!replace) {\n \t\tret = key_payload_reserve(keyring,\n \t\t\t\t\t  keyring-\u003edatalen + KEYQUOTA_LINK_BYTES);\n \t\tif (ret \u003c 0)\n-\t\t\tgoto error_cancel;\n+\t\t\tgoto error;\n+\n+\t\tret = rhashtable_insert_fast(\u0026links-\u003eht, \u0026link-\u003enode,\n+\t\t\t\t\t     keyring_link_params);\n+\t\tif (ret \u003c 0) {\n+\t\t\tkey_payload_reserve(keyring,\n+\t\t\t\t\t    keyring-\u003edatalen - KEYQUOTA_LINK_BYTES);\n+\t\t\tgoto error;\n+\t\t}\n \t}\n \n-\t*_edit = edit;\n+\tedit-\u003enew = no_free_ptr(link);\n+\tedit-\u003eold = replace;\n \tkleave(\" = 0\");\n \treturn 0;\n \n-error_cancel:\n-\tassoc_array_cancel_edit(edit);\n error:\n \tkleave(\" = %d\", ret);\n \treturn ret;\n@@ -1385,13 +1267,35 @@ int __key_link_check_live_key(struct key *keyring, struct key *key)\n  * holds at most one link to any given key of a particular type+description\n  * combination.\n  */\n-void __key_link(struct key *keyring, struct key *key,\n-\t\tstruct assoc_array_edit **_edit)\n+void __key_link(struct key *keyring, struct key *key, struct keyring_edit *edit)\n {\n+\tstruct keyring_index *index = keyring_index_locked(keyring);\n+\tint ret;\n+\n \t__key_get(key);\n-\tassoc_array_insert_set_object(*_edit, keyring_key_to_ptr(key));\n-\tassoc_array_apply_edit(*_edit);\n-\t*_edit = NULL;\n+\trcu_assign_pointer(edit-\u003enew-\u003ekey, key);\n+\n+\tif (edit-\u003eold) {\n+\t\tret = rhashtable_replace_fast(\u0026index-\u003eht, \u0026edit-\u003eold-\u003enode,\n+\t\t\t\t\t      \u0026edit-\u003enew-\u003enode, keyring_link_params);\n+\t\tif (WARN_ON(ret)) {\n+\t\t\tkey_put(key);\n+\t\t\treturn;\n+\t\t}\n+\n+\t\tlist_replace_rcu(\u0026edit-\u003eold-\u003elist, \u0026edit-\u003enew-\u003elist);\n+\t\tcall_rcu(\u0026edit-\u003eold-\u003ercu, keyring_link_free_rcu);\n+\t} else {\n+\t\tif (key-\u003etype == \u0026key_type_keyring)\n+\t\t\tlist_add_rcu(\u0026edit-\u003enew-\u003elist, \u0026index-\u003elist);\n+\t\telse\n+\t\t\tlist_add_tail_rcu(\u0026edit-\u003enew-\u003elist, \u0026index-\u003elist);\n+\n+\t\tWRITE_ONCE(index-\u003enr, index-\u003enr + 1);\n+\t}\n+\n+\tedit-\u003enew = NULL;\n+\tedit-\u003eold = NULL;\n \tnotify_key(keyring, NOTIFY_KEY_LINKED, key_serial(key));\n }\n \n@@ -1402,20 +1306,31 @@ void __key_link(struct key *keyring, struct key *key,\n  */\n void __key_link_end(struct key *keyring,\n \t\t    const struct keyring_index_key *index_key,\n-\t\t    struct assoc_array_edit *edit)\n+\t\t    struct keyring_edit *edit)\n \t__releases(\u0026keyring-\u003esem)\n \t__releases(\u0026keyring_serialise_link_lock)\n {\n+\tstruct keyring_link *link = edit-\u003enew;\n+\n \tBUG_ON(index_key-\u003etype == NULL);\n \tkenter(\"%d,%s,\", keyring-\u003eserial, index_key-\u003etype-\u003ename);\n \n-\tif (edit) {\n-\t\tif (!edit-\u003edead_leaf) {\n+\tif (link) {\n+\t\tif (!edit-\u003eold) {\n \t\t\tkey_payload_reserve(keyring,\n \t\t\t\tkeyring-\u003edatalen - KEYQUOTA_LINK_BYTES);\n+\t\t\tWARN_ON(rhashtable_remove_fast(\u0026keyring_index_locked(keyring)-\u003eht,\n+\t\t\t\t\t\t       \u0026link-\u003enode,\n+\t\t\t\t\t\t       keyring_link_params));\n+\t\t\tcall_rcu(\u0026link-\u003ercu, keyring_link_free_rcu);\n+\t\t} else {\n+\t\t\tkfree(link);\n \t\t}\n-\t\tassoc_array_cancel_edit(edit);\n+\n+\t\tedit-\u003enew = NULL;\n+\t\tedit-\u003eold = NULL;\n \t}\n+\n \tup_write(\u0026keyring-\u003esem);\n \n \tif (index_key-\u003etype == \u0026key_type_keyring)\n@@ -1445,9 +1360,9 @@ static int __key_link_check_restriction(struct key *keyring, struct key *key)\n  * of the user's key data quota to hold the link.\n  *\n  * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,\n- * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is\n- * full, -EDQUOT if there is insufficient key data quota remaining to add\n- * another link or -ENOMEM if there's insufficient memory.\n+ * -EKEYREVOKED if the keyring has been revoked, -EDQUOT if there is insufficient\n+ * key data quota remaining to add another link or -ENOMEM if there's\n+ * insufficient memory.\n  *\n  * It is assumed that the caller has checked that it is permitted for a link to\n  * be made (the keyring should have Write permission and the key Link\n@@ -1455,7 +1370,7 @@ static int __key_link_check_restriction(struct key *keyring, struct key *key)\n  */\n int key_link(struct key *keyring, struct key *key)\n {\n-\tstruct assoc_array_edit *edit = NULL;\n+\tstruct keyring_edit edit = {};\n \tint ret;\n \n \tkenter(\"{%d,%d}\", keyring-\u003eserial, refcount_read(\u0026keyring-\u003eusage));\n@@ -1479,7 +1394,7 @@ int key_link(struct key *keyring, struct key *key)\n \t\t__key_link(keyring, key, \u0026edit);\n \n error_end:\n-\t__key_link_end(keyring, \u0026key-\u003eindex_key, edit);\n+\t__key_link_end(keyring, \u0026key-\u003eindex_key, \u0026edit);\n error:\n \tkleave(\" = %d {%d,%d}\", ret, keyring-\u003eserial, refcount_read(\u0026keyring-\u003eusage));\n \treturn ret;\n@@ -1503,27 +1418,21 @@ static int __key_unlink_lock(struct key *keyring)\n  * Begin the process of unlinking a key from a keyring.\n  */\n static int __key_unlink_begin(struct key *keyring, struct key *key,\n-\t\t\t      struct assoc_array_edit **_edit)\n+\t\t\t      struct keyring_link **edit)\n {\n-\tstruct assoc_array_edit *edit;\n-\tconst void *object;\n+\tstruct keyring_link *link;\n \n-\tBUG_ON(*_edit != NULL);\n+\tif (WARN_ON(*edit))\n+\t\treturn -EINVAL;\n \n-\tobject = assoc_array_find(\u0026keyring-\u003ekeys, \u0026keyring_assoc_array_ops,\n-\t\t\t\t  \u0026key-\u003eindex_key);\n-\tif (!object || keyring_ptr_to_key(object) != key)\n+\tlink = keyring_find_link(keyring_index_locked(keyring), \u0026key-\u003eindex_key);\n+\tif (!link)\n \t\treturn -ENOENT;\n \n-\tedit = assoc_array_delete(\u0026keyring-\u003ekeys, \u0026keyring_assoc_array_ops,\n-\t\t\t\t  \u0026key-\u003eindex_key);\n-\tif (IS_ERR(edit))\n-\t\treturn PTR_ERR(edit);\n-\n-\tif (!edit)\n+\tif (keyring_link_key(link) != key)\n \t\treturn -ENOENT;\n \n-\t*_edit = edit;\n+\t*edit = link;\n \treturn 0;\n }\n \n@@ -1531,27 +1440,22 @@ static int __key_unlink_begin(struct key *keyring, struct key *key,\n  * Apply an unlink change.\n  */\n static void __key_unlink(struct key *keyring, struct key *key,\n-\t\t\t struct assoc_array_edit **_edit)\n+\t\t\t struct keyring_link *link)\n {\n-\tassoc_array_apply_edit(*_edit);\n+\tstruct keyring_index *index = keyring_index_locked(keyring);\n+\tint ret;\n+\n+\tret = rhashtable_remove_fast(\u0026index-\u003eht, \u0026link-\u003enode, keyring_link_params);\n+\tif (WARN_ON(ret))\n+\t\treturn;\n+\n+\tlist_del_rcu(\u0026link-\u003elist);\n+\tWRITE_ONCE(index-\u003enr, index-\u003enr - 1);\n+\tcall_rcu(\u0026link-\u003ercu, keyring_link_free_rcu);\n \tnotify_key(keyring, NOTIFY_KEY_UNLINKED, key_serial(key));\n-\t*_edit = NULL;\n \tkey_payload_reserve(keyring, keyring-\u003edatalen - KEYQUOTA_LINK_BYTES);\n }\n \n-/*\n- * Finish unlinking a key from to a keyring.\n- */\n-static void __key_unlink_end(struct key *keyring,\n-\t\t\t     struct key *key,\n-\t\t\t     struct assoc_array_edit *edit)\n-\t__releases(\u0026keyring-\u003esem)\n-{\n-\tif (edit)\n-\t\tassoc_array_cancel_edit(edit);\n-\tup_write(\u0026keyring-\u003esem);\n-}\n-\n /**\n  * key_unlink - Unlink the first link to a key from a keyring.\n  * @keyring: The keyring to remove the link from.\n@@ -1561,9 +1465,8 @@ static void __key_unlink_end(struct key *keyring,\n  *\n  * This function will write-lock the keyring's semaphore.\n  *\n- * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring, -ENOENT if\n- * the key isn't linked to by the keyring or -ENOMEM if there's insufficient\n- * memory.\n+ * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring or -ENOENT if\n+ * the key isn't linked to by the keyring.\n  *\n  * It is assumed that the caller has checked that it is permitted for a link to\n  * be removed (the keyring should have Write permission; no permissions are\n@@ -1571,7 +1474,7 @@ static void __key_unlink_end(struct key *keyring,\n  */\n int key_unlink(struct key *keyring, struct key *key)\n {\n-\tstruct assoc_array_edit *edit = NULL;\n+\tstruct keyring_link *edit = NULL;\n \tint ret;\n \n \tkey_check(keyring);\n@@ -1583,8 +1486,8 @@ int key_unlink(struct key *keyring, struct key *key)\n \n \tret = __key_unlink_begin(keyring, key, \u0026edit);\n \tif (ret == 0)\n-\t\t__key_unlink(keyring, key, \u0026edit);\n-\t__key_unlink_end(keyring, key, edit);\n+\t\t__key_unlink(keyring, key, edit);\n+\tup_write(\u0026keyring-\u003esem);\n \treturn ret;\n }\n EXPORT_SYMBOL(key_unlink);\n@@ -1604,11 +1507,10 @@ EXPORT_SYMBOL(key_unlink);\n  * some of the user's key data quota to hold the link on @to_keyring.\n  *\n  * Returns 0 if successful, -ENOTDIR if either keyring isn't a keyring,\n- * -EKEYREVOKED if either keyring has been revoked, -ENFILE if the second\n- * keyring is full, -EDQUOT if there is insufficient key data quota remaining\n- * to add another link or -ENOMEM if there's insufficient memory.  If\n- * KEYCTL_MOVE_EXCL is set, then -EEXIST will be returned if there's already a\n- * matching key in @to_keyring.\n+ * -EKEYREVOKED if either keyring has been revoked, -EDQUOT if there is\n+ * insufficient key data quota remaining to add another link or -ENOMEM if\n+ * there's insufficient memory.  If KEYCTL_MOVE_EXCL is set, then -EEXIST will\n+ * be returned if there's already a matching key in @to_keyring.\n  *\n  * It is assumed that the caller has checked that it is permitted for a link to\n  * be made (the keyring should have Write permission and the key Link\n@@ -1619,7 +1521,8 @@ int key_move(struct key *key,\n \t     struct key *to_keyring,\n \t     unsigned int flags)\n {\n-\tstruct assoc_array_edit *from_edit = NULL, *to_edit = NULL;\n+\tstruct keyring_link *from_edit = NULL;\n+\tstruct keyring_edit to_edit = {};\n \tint ret;\n \n \tkenter(\"%d,%d,%d\", key-\u003eserial, from_keyring-\u003eserial, to_keyring-\u003eserial);\n@@ -1642,7 +1545,7 @@ int key_move(struct key *key,\n \t\tgoto error;\n \n \tret = -EEXIST;\n-\tif (to_edit-\u003edead_leaf \u0026\u0026 (flags \u0026 KEYCTL_MOVE_EXCL))\n+\tif (to_edit.old \u0026\u0026 (flags \u0026 KEYCTL_MOVE_EXCL))\n \t\tgoto error;\n \n \tret = __key_link_check_restriction(to_keyring, key);\n@@ -1652,11 +1555,11 @@ int key_move(struct key *key,\n \tif (ret \u003c 0)\n \t\tgoto error;\n \n-\t__key_unlink(from_keyring, key, \u0026from_edit);\n+\t__key_unlink(from_keyring, key, from_edit);\n \t__key_link(to_keyring, key, \u0026to_edit);\n error:\n-\t__key_link_end(to_keyring, \u0026key-\u003eindex_key, to_edit);\n-\t__key_unlink_end(from_keyring, key, from_edit);\n+\t__key_link_end(to_keyring, \u0026key-\u003eindex_key, \u0026to_edit);\n+\tup_write(\u0026from_keyring-\u003esem);\n out:\n \tkleave(\" = %d\", ret);\n \treturn ret;\n@@ -1673,27 +1576,17 @@ EXPORT_SYMBOL(key_move);\n  */\n int keyring_clear(struct key *keyring)\n {\n-\tstruct assoc_array_edit *edit;\n-\tint ret;\n-\n \tif (keyring-\u003etype != \u0026key_type_keyring)\n \t\treturn -ENOTDIR;\n \n \tdown_write(\u0026keyring-\u003esem);\n \n-\tedit = assoc_array_clear(\u0026keyring-\u003ekeys, \u0026keyring_assoc_array_ops);\n-\tif (IS_ERR(edit)) {\n-\t\tret = PTR_ERR(edit);\n-\t} else {\n-\t\tif (edit)\n-\t\t\tassoc_array_apply_edit(edit);\n-\t\tnotify_key(keyring, NOTIFY_KEY_CLEARED, 0);\n-\t\tkey_payload_reserve(keyring, 0);\n-\t\tret = 0;\n-\t}\n+\tkeyring_index_free(keyring);\n+\tnotify_key(keyring, NOTIFY_KEY_CLEARED, 0);\n+\tkey_payload_reserve(keyring, 0);\n \n \tup_write(\u0026keyring-\u003esem);\n-\treturn ret;\n+\treturn 0;\n }\n EXPORT_SYMBOL(keyring_clear);\n \n@@ -1704,30 +1597,12 @@ EXPORT_SYMBOL(keyring_clear);\n  */\n static void keyring_revoke(struct key *keyring)\n {\n-\tstruct assoc_array_edit *edit;\n-\n-\tedit = assoc_array_clear(\u0026keyring-\u003ekeys, \u0026keyring_assoc_array_ops);\n-\tif (!IS_ERR(edit)) {\n-\t\tif (edit)\n-\t\t\tassoc_array_apply_edit(edit);\n-\t\tkey_payload_reserve(keyring, 0);\n-\t}\n+\tkeyring_index_free(keyring);\n+\tkey_payload_reserve(keyring, 0);\n }\n \n-static bool keyring_gc_select_iterator(void *object, void *iterator_data)\n+static int keyring_gc_check_iterator(const struct key *key, void *iterator_data)\n {\n-\tstruct key *key = keyring_ptr_to_key(object);\n-\ttime64_t *limit = iterator_data;\n-\n-\tif (key_is_dead(key, *limit))\n-\t\treturn false;\n-\tkey_get(key);\n-\treturn true;\n-}\n-\n-static int keyring_gc_check_iterator(const void *object, void *iterator_data)\n-{\n-\tconst struct key *key = keyring_ptr_to_key(object);\n \ttime64_t *limit = iterator_data;\n \n \tkey_check(key);\n@@ -1742,7 +1617,9 @@ static int keyring_gc_check_iterator(const void *object, void *iterator_data)\n  */\n void keyring_gc(struct key *keyring, time64_t limit)\n {\n-\tint result;\n+\tstruct keyring_link *link, *tmp;\n+\tstruct keyring_index *index;\n+\tint ret;\n \n \tkenter(\"%x{%s}\", keyring-\u003eserial, keyring-\u003edescription ?: \"\");\n \n@@ -1751,11 +1628,7 @@ void keyring_gc(struct key *keyring, time64_t limit)\n \t\tgoto dont_gc;\n \n \t/* scan the keyring looking for dead keys */\n-\trcu_read_lock();\n-\tresult = assoc_array_iterate(\u0026keyring-\u003ekeys,\n-\t\t\t\t     keyring_gc_check_iterator, \u0026limit);\n-\trcu_read_unlock();\n-\tif (result == true)\n+\tif (keyring_iterate(keyring, keyring_gc_check_iterator, \u0026limit))\n \t\tgoto do_gc;\n \n dont_gc:\n@@ -1764,8 +1637,23 @@ void keyring_gc(struct key *keyring, time64_t limit)\n \n do_gc:\n \tdown_write(\u0026keyring-\u003esem);\n-\tassoc_array_gc(\u0026keyring-\u003ekeys, \u0026keyring_assoc_array_ops,\n-\t\t       keyring_gc_select_iterator, \u0026limit);\n+\tindex = keyring_index_locked(keyring);\n+\tif (index) {\n+\t\tlist_for_each_entry_safe(link, tmp, \u0026index-\u003elist, list) {\n+\t\t\tif (!key_is_dead(keyring_link_key(link), limit))\n+\t\t\t\tcontinue;\n+\n+\t\t\tret = rhashtable_remove_fast(\u0026index-\u003eht, \u0026link-\u003enode,\n+\t\t\t\t\t\t     keyring_link_params);\n+\t\t\tif (WARN_ON(ret))\n+\t\t\t\tbreak;\n+\n+\t\t\tlist_del_rcu(\u0026link-\u003elist);\n+\t\t\tWRITE_ONCE(index-\u003enr, index-\u003enr - 1);\n+\t\t\tcall_rcu(\u0026link-\u003ercu, keyring_link_free_rcu);\n+\t\t}\n+\t}\n+\n \tup_write(\u0026keyring-\u003esem);\n \tkleave(\" [gc]\");\n }\ndiff --git a/security/keys/request_key.c b/security/keys/request_key.c\nindex 22cd66a44da562..40fbcd15be4308 100644\n--- a/security/keys/request_key.c\n+++ b/security/keys/request_key.c\n@@ -372,7 +372,7 @@ static int construct_alloc_key(struct keyring_search_context *ctx,\n \t\t\t       struct key_user *user,\n \t\t\t       struct key **_key)\n {\n-\tstruct assoc_array_edit *edit = NULL;\n+\tstruct keyring_edit edit = {};\n \tstruct key *key;\n \tkey_perm_t perm;\n \tkey_ref_t key_ref;\n@@ -433,7 +433,7 @@ static int construct_alloc_key(struct keyring_search_context *ctx,\n \n \tmutex_unlock(\u0026key_construction_mutex);\n \tif (dest_keyring)\n-\t\t__key_link_end(dest_keyring, \u0026key-\u003eindex_key, edit);\n+\t\t__key_link_end(dest_keyring, \u0026key-\u003eindex_key, \u0026edit);\n \tmutex_unlock(\u0026user-\u003econs_lock);\n \t*_key = key;\n \tkleave(\" = 0 [%d]\", key_serial(key));\n@@ -452,7 +452,7 @@ static int construct_alloc_key(struct keyring_search_context *ctx,\n \t\tret = __key_link_check_live_key(dest_keyring, key);\n \t\tif (ret == 0)\n \t\t\t__key_link(dest_keyring, key, \u0026edit);\n-\t\t__key_link_end(dest_keyring, \u0026key-\u003eindex_key, edit);\n+\t\t__key_link_end(dest_keyring, \u0026key-\u003eindex_key, \u0026edit);\n \t\tif (ret \u003c 0)\n \t\t\tgoto link_check_failed;\n \t}\n@@ -470,7 +470,7 @@ static int construct_alloc_key(struct keyring_search_context *ctx,\n link_alloc_failed:\n \tmutex_unlock(\u0026key_construction_mutex);\n link_alloc_failed_unlocked:\n-\t__key_link_end(dest_keyring, \u0026key-\u003eindex_key, edit);\n+\t__key_link_end(dest_keyring, \u0026key-\u003eindex_key, \u0026edit);\n link_lock_failed:\n \tmutex_unlock(\u0026user-\u003econs_lock);\n \tkey_put(key);\ndiff --git a/tools/testing/selftests/dm-verity/test-dm-verity-keyring.sh b/tools/testing/selftests/dm-verity/test-dm-verity-keyring.sh\nindex 1f9601ef22f859..792449d356cf56 100755\n--- a/tools/testing/selftests/dm-verity/test-dm-verity-keyring.sh\n+++ b/tools/testing/selftests/dm-verity/test-dm-verity-keyring.sh\n@@ -746,7 +746,7 @@ test_keyring_inactive_when_empty() {\n     log_info \"TEST: Verify dm-verity keyring is inactive when sealed empty\"\n \n     # When keyring_unsealed=0, the keyring is sealed immediately while empty\n-    # This means it should NOT be used for verification (nr_leaves_on_tree=0)\n+    # An empty keyring should NOT be used for verification.\n \n     log_info \"Keyring state (should be empty and sealed):\"\n     list_keyring_keys\n"
}

2/1 2026/11/10 21:40 agent patch-evaluator
0m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "KEYS"
  ],
  "FocusSymbols": [
    "key_link",
    "key_unlink",
    "key_move",
    "keyring_clear",
    "keyring_gc",
    "keyring_read",
    "search_nested_keyrings",
    "find_key_to_update",
    "keyring_is_empty",
    "__key_link_begin",
    "__key_link",
    "__key_link_end"
  ],
  "Reasoning": "The patch series removes the generic associative array (assoc_array) implementation and replaces the internal keyring indexing mechanism in the keys subsystem with an rhashtable and RCU-protected linked list. This refactors core data structures and concurrency/locking logic in reachable security/keys code, directly accessible via keyctl, add_key, and request_key syscalls. Hence, it is worth fuzzing.",
  "WorthFuzzing": true
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 9b677570f5d4a445ef4a8b94fb6e5bf96ecddb01
Author: syz-cluster <triage@syzkaller.com>
Date:   Tue Nov 10 21:40:32 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/core-api/assoc_array.rst b/Documentation/core-api/assoc_array.rst
deleted file mode 100644
index 19d89f92bf8da8..00000000000000
--- a/Documentation/core-api/assoc_array.rst
+++ /dev/null
@@ -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.
diff --git a/Documentation/core-api/index.rst b/Documentation/core-api/index.rst
index 92f91c6a0d79d6..d56c60663b0c40 100644
--- a/Documentation/core-api/index.rst
+++ b/Documentation/core-api/index.rst
@@ -38,7 +38,6 @@ Library functionality that is used throughout the kernel.
    kobject
    kref
    cleanup
-   assoc_array
    folio_queue
    xarray
    maple_tree
diff --git a/Documentation/translations/zh_CN/core-api/assoc_array.rst b/Documentation/translations/zh_CN/core-api/assoc_array.rst
deleted file mode 100644
index 3649bf0d148807..00000000000000
--- a/Documentation/translations/zh_CN/core-api/assoc_array.rst
+++ /dev/null
@@ -1,473 +0,0 @@
-.. include:: ../disclaimer-zh_CN.rst
-
-:Original: Documentation/core-api/assoc_array.rst
-
-:翻译:
-
- 司延腾 Yanteng Si <siyanteng@loongson.cn>
-
-:校译:
-
-
-
-.. _cn_core-api_assoc_array:
-
-==================
-通用关联数组的实现
-==================
-
-简介
-====
-
-这个关联数组的实现是一个具有以下属性的对象容器:
-
-1. 对象是不透明的指针。该实现不关心它们指向哪里(如果有的话)或它们指向什么(如果有的
-   话)。
-
-   .. note::
-
-      指向对象的指针 *必须* 在最小有效位为零。
-
-2. 对象不需要包含供数组使用的链接块。这允许一个对象同时位于多个数组中。相反,数组是
-   由指向对象的元数据块组成的。
-
-3. 对象需要索引键来定位它们在阵列中的位置。
-
-4. 索引键必须是唯一的。插入一个与已经在数组中的且具有相同键值的对象将取代旧的对象。
-
-5. 索引键可以是任何长度,也可以是不同的长度。
-
-6. 索引键应该在早期就对长度进行编码,即在任何由于长度引起的变化出现之前。
-
-7. 索引键可以包括一个哈希值,以便将对象分散到整个数组中。
-
-8. 该数组可以迭代。对象不一定会按索引键的顺序出现。
-
-9.  数组可以在被修改的时候进行迭代,只要RCU的读锁被迭代器持有。然而,请注意,在这种情
-    况下,一些对象可能会被看到不止一次。如果这是个问题,迭代器应该锁定以防止修改。然
-    而,除非删除,否则对象不会被错过。
-
-10. 数组中的对象可以通过其索引键进行查询。
-
-11. 当数组被修改时,对象可以被查询,前提是进行查询的线程持有RCU的读锁。
-
-该实现在内部使用了一棵由16个指针节点组成的树,这些节点在每一层都由索引键的小数点进行索
-引,其方式与基数树相同。为了提高内存效率,可以放置快捷键,以跳过本来是一系列单占节点的地
-方。此外,节点将叶子对象指针打包到节点的空闲空间中,而不是做一个额外的分支,直到有对象
-需要被添加到一个完整的节点中。
-
-公用API
-=======
-
-公用API可以在 ``<linux/assoc_array.h>`` 中找到。关联数组的根是以下结构::
-
-    struct assoc_array {
-            ...
-    };
-
-该代码是通过启用 ``CONFIG_ASSOCIATIVE_ARRAY`` 来选择的,以::
-
-    ./script/config -e ASSOCIATIVE_ARRAY
-
-
-编辑脚本
---------
-
-插入和删除功能会产生一个“编辑脚本”,以后可以应用这个脚本来实现更改,而不会造成 ``ENOMEM``
-风险。这保留了将被安装在内部树中的预分配的元数据块,并跟踪应用脚本时将从树中删除的元数
-据块。
-
-在脚本应用后,这也被用来跟踪死块和死对象,以便以后可以释放它们。释放是在RCU宽限期过后
-进行的--因此允许访问功能在RCU读锁下进行。
-
-脚本在API之外显示为一个类型为::
-
-    struct assoc_array_edit;
-
-有两个处理脚本的功能:
-
-1. 应用一个编辑脚本::
-
-    void assoc_array_apply_edit(struct assoc_array_edit *edit);
-
-这将执行编辑功能,插值各种写屏障,以允许在RCU读锁下的访问继续进行。然后,编辑脚本将被
-传递给 ``call_rcu()`` ,以释放它和它所指向的任何死的东西。
-
-2. Cancel an edit script::
-
-    void assoc_array_cancel_edit(struct assoc_array_edit *edit);
-
-这将立即释放编辑脚本和所有预分配的内存。如果这是为了插入,新的对象不会被这个函数释放,
-而是必须由调用者释放。
-
-这些函数保证不会失败。
-
-
-操作表
-------
-
-各种功能采用了一个操作表::
-
-    struct assoc_array_ops {
-            ...
-    };
-
-这指出了一些方法,所有这些方法都需要提供:
-
-1. 从调用者数据中获取索引键的一个块::
-
-    unsigned long (*get_key_chunk)(const void *index_key, int level);
-
-这应该返回一个由调用者提供的索引键的块,从level参数给出的 *比特* 位置开始。level参数将
-是 ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` 的倍数,该函数应返回 ``ASSOC_ARRAY_KEY_CHUNK_SIZE``
-位。不可能出现错误。
-
-
-2. 获取一个对象的索引键的一个块::
-
-    unsigned long (*get_object_key_chunk)(const void *object, int level);
-
-和前面的函数一样,但是从数组中的一个对象而不是从调用者提供的索引键中获取数据。
-
-
-3. 看看这是否是我们要找的对象::
-
-    bool (*compare_object)(const void *object, const void *index_key);
-
-将对象与一个索引键进行比较,如果匹配则返回 ``true`` ,不匹配则返回 ``false`` 。
-
-
-4. 对两个对象的索引键进行比较::
-
-    int (*diff_objects)(const void *object, const void *index_key);
-
-返回指定对象的索引键与给定索引键不同的比特位置,如果它们相同,则返回-1。
-
-
-5. 释放一个对象::
-
-    void (*free_object)(void *object);
-
-释放指定的对象。注意,这可能是在调用 ``assoc_array_apply_edit()`` 后的一个RCU宽限期内
-调用的,所以在模块卸载时可能需要 ``synchronize_rcu()`` 。
-
-
-操控函数
---------
-
-有一些函数用于操控关联数组:
-
-1. 初始化一个关联数组::
-
-    void assoc_array_init(struct assoc_array *array);
-
-这将初始化一个关联数组的基础结构。它不会失败。
-
-
-2. 在一个关联数组中插入/替换一个对象::
-
-    struct assoc_array_edit *
-    assoc_array_insert(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       const void *index_key,
-                       void *object);
-
-这将把给定的对象插入数组中。注意,指针的最小有效位必须是0,因为它被用来在内部标记指针的类
-型。
-
-如果该键已经存在一个对象,那么它将被新的对象所取代,旧的对象将被自动释放。
-
-``index_key`` 参数应持有索引键信息,并在调用OPP表中的方法时传递给它们。
-
-这个函数不对数组本身做任何改动,而是返回一个必须应用的编辑脚本。如果出现内存不足的错误,会
-返回 ``-ENOMEM`` 。
-
-调用者应专门锁定数组的其他修改器。
-
-
-3. 从一个关联数组中删除一个对象::
-
-    struct assoc_array_edit *
-    assoc_array_delete(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       const void *index_key);
-
-这将从数组中删除一个符合指定数据的对象。
-
-``index_key`` 参数应持有索引键信息,并在调用OPP表中的方法时传递给它们。
-
-这个函数不对数组本身做任何改动,而是返回一个必须应用的编辑脚本。 ``-ENOMEM`` 在出现内存不足
-的错误时返回。如果在数组中没有找到指定的对象,将返回 ``NULL`` 。
-
-调用者应该对数组的其他修改者进行专门锁定。
-
-
-4. 从一个关联数组中删除所有对象::
-
-    struct assoc_array_edit *
-    assoc_array_clear(struct assoc_array *array,
-                      const struct assoc_array_ops *ops);
-
-这个函数删除了一个关联数组中的所有对象,使其完全为空。
-
-这个函数没有对数组本身做任何改动,而是返回一个必须应用的编辑脚本。如果出现内存不足
-的错误,则返回 ``-ENOMEM`` 。
-
-调用者应专门锁定数组的其他修改者。
-
-
-5. 销毁一个关联数组,删除所有对象::
-
-    void assoc_array_destroy(struct assoc_array *array,
-                             const struct assoc_array_ops *ops);
-
-这将破坏关联数组的内容,使其完全为空。在这个函数销毁数组的同时,不允许另一个线程在RCU读锁
-下遍历数组,因为在内存释放时不执行RCU延迟,这需要分配内存。
-
-调用者应该专门针对数组的其他修改者和访问者进行锁定。
-
-
-6. 垃圾回收一个关联数组::
-
-    int assoc_array_gc(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       bool (*iterator)(void *object, void *iterator_data),
-                       void *iterator_data);
-
-这是对一个关联数组中的对象进行迭代,并将每个对象传递给 ``iterator()`` 。如果 ``iterator()`` 返回
-true,该对象被保留。如果它返回 ``false`` ,该对象将被释放。如果 ``iterator()`` 函数返回 ``true`` ,它必须
-在返回之前对该对象进行适当的 ``refcount`` 递增。
-
-如果可能的话,内部树将被打包下来,作为迭代的一部分,以减少其中的节点数量。
-
-``iterator_data`` 被直接传递给 ``iterator()`` ,否则会被函数忽略。
-
-如果成功,该函数将返回 ``0`` ,如果没有足够的内存,则返回 ``-ENOMEM`` 。
-
-在这个函数执行过程中,其他线程有可能在RCU读锁下迭代或搜索阵列。调用者应该专门针对数组的其他
-修改者进行锁定。
-
-
-访问函数
---------
-
-有两个函数用于访问一个关联数组:
-
-1. 遍历一个关联数组中的所有对象::
-
-    int assoc_array_iterate(const struct assoc_array *array,
-                            int (*iterator)(const void *object,
-                                            void *iterator_data),
-                            void *iterator_data);
-
-这将数组中的每个对象传递给迭代器回调函数。 ``iterator_data`` 是该函数的私有数据。
-
-在数组被修改的同时,可以在数组上使用这个方法,前提是RCU读锁被持有。在这种情况下,迭代函数有
-可能两次看到某些对象。如果这是个问题,那么修改应该被锁定。然而,迭代算法不应该错过任何对象。
-
-如果数组中没有对象,该函数将返回 ``0`` ,否则将返回最后一次调用的迭代器函数的结果。如果对迭代函数
-的任何调用导致非零返回,迭代立即停止。
-
-
-2. 在一个关联数组中寻找一个对象::
-
-    void *assoc_array_find(const struct assoc_array *array,
-                           const struct assoc_array_ops *ops,
-                           const void *index_key);
-
-这将直接穿过数组的内部树,到达索引键所指定的对象。
-
-这个函数可以在修改数组的同时用在数组上,前提是RCU读锁被持有。
-
-如果找到对象,该函数将返回对象(并将 ``*_type`` 设置为对象的类型),如果没有找到对象,将返回 ``NULL`` 。
-
-
-索引键形式
-----------
-
-索引键可以是任何形式的,但是由于算法没有被告知键有多长,所以强烈建议在任何由于长度而产生的变化
-对比较产生影响之前,索引键应该很早就包括其长度。
-
-这将导致具有不同长度键的叶子相互分散,而具有相同长度键的叶子则聚集在一起。
-
-我们还建议索引键以键的其余部分的哈希值开始,以最大限度地提高整个键空间的散布情况。
-
-分散性越好,内部树就越宽,越低。
-
-分散性差并不是一个太大的问题,因为有快捷键,节点可以包含叶子和元数据指针的混合物。
-
-索引键是以机器字的块状来读取的。每个块被细分为每层一个nibble(4比特),所以在32位CPU上这适合8层,
-在64位CPU上适合16层。除非散布情况真的很差,否则不太可能有超过一个字的任何特定索引键需要被使用。
-
-
-内部工作机制
-============
-
-关联数组数据结构有一个内部树。这个树由两种类型的元数据块构成:节点和快捷键。
-
-一个节点是一个槽的数组。每个槽可以包含以下四种东西之一:
-
-* 一个NULL的指针,表示槽是空的。
-* 一个指向对象(叶子)的指针。
-* 一个指向下一级节点的指针。
-* 一个指向快捷键的指针。
-
-
-基本的内部树形布局
-------------------
-
-暂时不考虑快捷键,节点形成一个多级树。索引键空间被树上的节点严格细分,节点出现在固定的层次上。例如::
-
- 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 |
-                        +---+
-
-在上述例子中,有7个节点(A-G),每个节点有16个槽(0-f)。假设树上没有其他元数据节点,那么密钥空间
-是这样划分的::
-
-    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
-
-因此,例如,具有以下示例索引键的键将在适当的节点中被找到::
-
-    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
-
-为了节省内存,如果一个节点可以容纳它的那部分键空间中的所有叶子,那么这个节点将有所有这些叶子,而不
-会有任何元数据指针——即使其中一些叶子想在同一个槽中。
-
-一个节点可以包含叶子和元数据指针的异质性混合。元数据指针必须在与它们的关键空间的细分相匹配的槽中。
-叶子可以在任何没有被元数据指针占据的槽中。保证一个节点中没有一个叶子会与元数据指针占据的槽相匹配。
-如果元数据指针在那里,任何键与元数据键前缀相匹配的叶必须在元数据指针指向的子树中。
-
-在上面的索引键的例子列表中,节点A将包含::
-
-    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
-
-和节点B::
-
-    3	PTR TO NODE C	13*
-    any	LEAF		1458952489
-
-
-快捷键
----------
-
-快捷键是跳过一块键空间的元数据记录。快捷键是一系列通过层次上升的单占节点的替代物。快捷键的存在是
-为了节省内存和加快遍历速度。
-
-树的根部有可能是一个快捷键——比如说,树至少包含17个节点,都有键前缀 ``1111`` 。插入算法将插入一个快捷键,
-以单次跳过 ``1111`` 的键位,并到达第四层,在这里,这些键位实际上变得不同。
-
-
-拆分和合并节点
-------------------------------
-
-每个节点的最大容量为16个叶子和元数据指针。如果插入算法发现它正试图将一个第17个对象插入到一个节点中,
-该节点将被拆分,使得至少两个在该层有一个共同的关键段的叶子最终在一个单独的节点中,该共同的关键段的根
-在该槽上。
-
-如果一个完整的节点中的叶子和被插入的叶子足够相似,那么就会在树中插入一个快捷键。
-
-当根植于某个节点的子树中的对象数量下降到16个或更少时,那么该子树将被合并成一个单独的节点——如果可能的
-话,这将向根部扩散。
-
-
-非递归式迭代
-------------
-
-每个节点和快捷键都包含一个指向其父节点的后置指针,以及该父节点中指向它的槽数。非递归迭代使用这些来
-通过树的根部进行,前往父节点,槽N+1,以确保在没有堆栈的情况下取得进展。
-
-然而,反向指针使得同时改变和迭代变得很棘手。
-
-
-同时改变和迭代
---------------
-
-有一些情况需要考虑:
-
-1. 简单的插入/替换。这涉及到简单地将一个NULL或旧的匹配叶子的指针替换为屏障后的新叶子的指针。否则元数
-   据块不会改变。一个旧的叶子直到RCU宽限期过后才会被释放。
-
-2. 简单删除。这只是涉及到清除一个旧的匹配叶子。元数据块不会有其他变化。旧的叶子直到RCU宽限期之后才会
-   被释放。
-
-3. 插入,替换我们还没有进入的子树的一部分。这可能涉及到替换该子树的一部分——但这不会影响迭代,因为我们
-   还没有到达它的指针,而且祖先块也不会被替换(这些块的布局不会改变)。
-
-4. 插入替换了我们正在处理的节点。这不是一个问题,因为我们已经通过了锚定指针,直到我们跟随后面的指针才
-   会切换到新的布局上——这时我们已经检查了被替换节点的叶子(在跟随任何元数据指针之前,我们会迭代一个节
-   点的所有叶子)。
-
-   然而,我们可能会重新看到一些叶子,这些叶子已经被分割成一个新的分支,而这个分支的位置比我们之前的位
-   置更远。
-
-5. 插入替换了我们正在处理的依赖分支的节点。这不会影响到我们,直到我们跟随后面的指针。与(4)类似。
-
-6. 删掉我们下面的一个分支。这不会影响我们,因为在我们看到新节点之前,回溯指针会让我们回到新节点的父节
-   点。整个崩溃的子树被扔掉了,没有任何变化——而且仍然会在同一个槽上生根,所以我们不应该第二次处理它,
-   因为我们会回到槽+1。
-
-.. note::
-
-    在某些情况下,我们需要同时改变一个节点的父指针和父槽指针(比如说,我们在它之前插入了另一个节点,
-    并把它往上移了一层)。我们不能在不锁定读取的情况下这样做——所以我们必须同时替换该节点。
-
-    然而,当我们把一个快捷键改成一个节点时,这不是一个问题,因为快捷键只有一个槽,所以当向后遍
-    历一个槽时,不会使用父槽号。这意味着先改变槽位号是可以的——只要使用适当的屏障来确保父槽位号在后
-    退指针之后被读取。
-
-过时的块和叶子在RCU宽限期过后会被释放,所以只要任何进行遍历或迭代的人持有RCU读锁,旧的上层建筑就不
-应该在他们身上消失。
diff --git a/Documentation/translations/zh_CN/core-api/index.rst b/Documentation/translations/zh_CN/core-api/index.rst
index 453a02cd1f4486..ec4b03b2a0a60e 100644
--- a/Documentation/translations/zh_CN/core-api/index.rst
+++ b/Documentation/translations/zh_CN/core-api/index.rst
@@ -41,7 +41,6 @@
 
    kobject
    kref
-   assoc_array
    xarray
    rbtree
    idr
diff --git a/drivers/md/dm-verity-verify-sig.c b/drivers/md/dm-verity-verify-sig.c
index 0c65c7a31da8bd..bd5143aae4fa96 100644
--- a/drivers/md/dm-verity-verify-sig.c
+++ b/drivers/md/dm-verity-verify-sig.c
@@ -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,
diff --git a/fs/verity/signature.c b/fs/verity/signature.c
index 2f49c5d9d98705..b45b39b829b298 100644
--- a/fs/verity/signature.c
+++ b/fs/verity/signature.c
@@ -70,7 +70,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.
diff --git a/include/keys/keyring-type.h b/include/keys/keyring-type.h
index 1dc83862f519ad..314832f5dc4a99 100644
--- a/include/keys/keyring-type.h
+++ b/include/keys/keyring-type.h
@@ -9,6 +9,5 @@
 #define _KEYS_KEYRING_TYPE_H
 
 #include <linux/key.h>
-#include <linux/assoc_array.h>
 
 #endif /* _KEYS_KEYRING_TYPE_H */
diff --git a/include/linux/assoc_array.h b/include/linux/assoc_array.h
deleted file mode 100644
index 8b3f230ce89440..00000000000000
--- a/include/linux/assoc_array.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0-or-later */
-/* Generic associative array implementation.
- *
- * See Documentation/core-api/assoc_array.rst for information.
- *
- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.
- * Written by David Howells (dhowells@redhat.com)
- */
-
-#ifndef _LINUX_ASSOC_ARRAY_H
-#define _LINUX_ASSOC_ARRAY_H
-
-#ifdef CONFIG_ASSOCIATIVE_ARRAY
-
-#include <linux/types.h>
-
-#define ASSOC_ARRAY_KEY_CHUNK_SIZE BITS_PER_LONG /* Key data retrieved in chunks of this size */
-
-/*
- * Generic associative array.
- */
-struct assoc_array {
-	struct assoc_array_ptr	*root;		/* The node at the root of the tree */
-	unsigned long		nr_leaves_on_tree;
-};
-
-/*
- * Operations on objects and index keys for use by array manipulation routines.
- */
-struct assoc_array_ops {
-	/* Method to get a chunk of an index key from caller-supplied data */
-	unsigned long (*get_key_chunk)(const void *index_key, int level);
-
-	/* Method to get a piece of an object's index key */
-	unsigned long (*get_object_key_chunk)(const void *object, int level);
-
-	/* Is this the object we're looking for? */
-	bool (*compare_object)(const void *object, const void *index_key);
-
-	/* How different is an object from an index key, to a bit position in
-	 * their keys? (or -1 if they're the same)
-	 */
-	int (*diff_objects)(const void *object, const void *index_key);
-
-	/* Method to free an object. */
-	void (*free_object)(void *object);
-};
-
-/*
- * Access and manipulation functions.
- */
-struct assoc_array_edit;
-
-static inline void assoc_array_init(struct assoc_array *array)
-{
-	array->root = NULL;
-	array->nr_leaves_on_tree = 0;
-}
-
-extern int assoc_array_iterate(const struct assoc_array *array,
-			       int (*iterator)(const void *object,
-					       void *iterator_data),
-			       void *iterator_data);
-extern void *assoc_array_find(const struct assoc_array *array,
-			      const struct assoc_array_ops *ops,
-			      const void *index_key);
-extern void assoc_array_destroy(struct assoc_array *array,
-				const struct assoc_array_ops *ops);
-extern struct assoc_array_edit *assoc_array_insert(struct assoc_array *array,
-						   const struct assoc_array_ops *ops,
-						   const void *index_key,
-						   void *object);
-extern void assoc_array_insert_set_object(struct assoc_array_edit *edit,
-					  void *object);
-extern struct assoc_array_edit *assoc_array_delete(struct assoc_array *array,
-						   const struct assoc_array_ops *ops,
-						   const void *index_key);
-extern struct assoc_array_edit *assoc_array_clear(struct assoc_array *array,
-						  const struct assoc_array_ops *ops);
-extern void assoc_array_apply_edit(struct assoc_array_edit *edit);
-extern void assoc_array_cancel_edit(struct assoc_array_edit *edit);
-extern int assoc_array_gc(struct assoc_array *array,
-			  const struct assoc_array_ops *ops,
-			  bool (*iterator)(void *object, void *iterator_data),
-			  void *iterator_data);
-
-#endif /* CONFIG_ASSOCIATIVE_ARRAY */
-#endif /* _LINUX_ASSOC_ARRAY_H */
diff --git a/include/linux/assoc_array_priv.h b/include/linux/assoc_array_priv.h
deleted file mode 100644
index dca733ef675038..00000000000000
--- a/include/linux/assoc_array_priv.h
+++ /dev/null
@@ -1,178 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0-or-later */
-/* Private definitions for the generic associative array implementation.
- *
- * See Documentation/core-api/assoc_array.rst for information.
- *
- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.
- * Written by David Howells (dhowells@redhat.com)
- */
-
-#ifndef _LINUX_ASSOC_ARRAY_PRIV_H
-#define _LINUX_ASSOC_ARRAY_PRIV_H
-
-#ifdef CONFIG_ASSOCIATIVE_ARRAY
-
-#include <linux/assoc_array.h>
-
-#define ASSOC_ARRAY_FAN_OUT		16	/* Number of slots per node */
-#define ASSOC_ARRAY_FAN_MASK		(ASSOC_ARRAY_FAN_OUT - 1)
-#define ASSOC_ARRAY_LEVEL_STEP		(ilog2(ASSOC_ARRAY_FAN_OUT))
-#define ASSOC_ARRAY_LEVEL_STEP_MASK	(ASSOC_ARRAY_LEVEL_STEP - 1)
-#define ASSOC_ARRAY_KEY_CHUNK_MASK	(ASSOC_ARRAY_KEY_CHUNK_SIZE - 1)
-#define ASSOC_ARRAY_KEY_CHUNK_SHIFT	(ilog2(BITS_PER_LONG))
-
-/*
- * Undefined type representing a pointer with type information in the bottom
- * two bits.
- */
-struct assoc_array_ptr;
-
-/*
- * An N-way node in the tree.
- *
- * Each slot contains one of four things:
- *
- *	(1) Nothing (NULL).
- *
- *	(2) A leaf object (pointer types 0).
- *
- *	(3) A next-level node (pointer type 1, subtype 0).
- *
- *	(4) A shortcut (pointer type 1, subtype 1).
- *
- * The tree is optimised for search-by-ID, but permits reasonable iteration
- * also.
- *
- * The tree is navigated by constructing an index key consisting of an array of
- * segments, where each segment is ilog2(ASSOC_ARRAY_FAN_OUT) bits in size.
- *
- * The segments correspond to levels of the tree (the first segment is used at
- * level 0, the second at level 1, etc.).
- */
-struct assoc_array_node {
-	struct assoc_array_ptr	*back_pointer;
-	u8			parent_slot;
-	struct assoc_array_ptr	*slots[ASSOC_ARRAY_FAN_OUT];
-	unsigned long		nr_leaves_on_branch;
-};
-
-/*
- * A shortcut through the index space out to where a collection of nodes/leaves
- * with the same IDs live.
- */
-struct assoc_array_shortcut {
-	struct assoc_array_ptr	*back_pointer;
-	int			parent_slot;
-	int			skip_to_level;
-	struct assoc_array_ptr	*next_node;
-	unsigned long		index_key[];
-};
-
-/*
- * Preallocation cache.
- */
-struct assoc_array_edit {
-	struct rcu_head			rcu;
-	struct assoc_array		*array;
-	const struct assoc_array_ops	*ops;
-	const struct assoc_array_ops	*ops_for_excised_subtree;
-	struct assoc_array_ptr		*leaf;
-	struct assoc_array_ptr		**leaf_p;
-	struct assoc_array_ptr		*dead_leaf;
-	struct assoc_array_ptr		*new_meta[3];
-	struct assoc_array_ptr		*excised_meta[1];
-	struct assoc_array_ptr		*excised_subtree;
-	struct assoc_array_ptr		**set_backpointers[ASSOC_ARRAY_FAN_OUT];
-	struct assoc_array_ptr		*set_backpointers_to;
-	struct assoc_array_node		*adjust_count_on;
-	long				adjust_count_by;
-	struct {
-		struct assoc_array_ptr	**ptr;
-		struct assoc_array_ptr	*to;
-	} set[2];
-	struct {
-		u8			*p;
-		u8			to;
-	} set_parent_slot[1];
-	u8				segment_cache[ASSOC_ARRAY_FAN_OUT + 1];
-};
-
-/*
- * Internal tree member pointers are marked in the bottom one or two bits to
- * indicate what type they are so that we don't have to look behind every
- * pointer to see what it points to.
- *
- * We provide functions to test type annotations and to create and translate
- * the annotated pointers.
- */
-#define ASSOC_ARRAY_PTR_TYPE_MASK 0x1UL
-#define ASSOC_ARRAY_PTR_LEAF_TYPE 0x0UL	/* Points to leaf (or nowhere) */
-#define ASSOC_ARRAY_PTR_META_TYPE 0x1UL	/* Points to node or shortcut */
-#define ASSOC_ARRAY_PTR_SUBTYPE_MASK	0x2UL
-#define ASSOC_ARRAY_PTR_NODE_SUBTYPE	0x0UL
-#define ASSOC_ARRAY_PTR_SHORTCUT_SUBTYPE 0x2UL
-
-static inline bool assoc_array_ptr_is_meta(const struct assoc_array_ptr *x)
-{
-	return (unsigned long)x & ASSOC_ARRAY_PTR_TYPE_MASK;
-}
-static inline bool assoc_array_ptr_is_leaf(const struct assoc_array_ptr *x)
-{
-	return !assoc_array_ptr_is_meta(x);
-}
-static inline bool assoc_array_ptr_is_shortcut(const struct assoc_array_ptr *x)
-{
-	return (unsigned long)x & ASSOC_ARRAY_PTR_SUBTYPE_MASK;
-}
-static inline bool assoc_array_ptr_is_node(const struct assoc_array_ptr *x)
-{
-	return !assoc_array_ptr_is_shortcut(x);
-}
-
-static inline void *assoc_array_ptr_to_leaf(const struct assoc_array_ptr *x)
-{
-	return (void *)((unsigned long)x & ~ASSOC_ARRAY_PTR_TYPE_MASK);
-}
-
-static inline
-unsigned long __assoc_array_ptr_to_meta(const struct assoc_array_ptr *x)
-{
-	return (unsigned long)x &
-		~(ASSOC_ARRAY_PTR_SUBTYPE_MASK | ASSOC_ARRAY_PTR_TYPE_MASK);
-}
-static inline
-struct assoc_array_node *assoc_array_ptr_to_node(const struct assoc_array_ptr *x)
-{
-	return (struct assoc_array_node *)__assoc_array_ptr_to_meta(x);
-}
-static inline
-struct assoc_array_shortcut *assoc_array_ptr_to_shortcut(const struct assoc_array_ptr *x)
-{
-	return (struct assoc_array_shortcut *)__assoc_array_ptr_to_meta(x);
-}
-
-static inline
-struct assoc_array_ptr *__assoc_array_x_to_ptr(const void *p, unsigned long t)
-{
-	return (struct assoc_array_ptr *)((unsigned long)p | t);
-}
-static inline
-struct assoc_array_ptr *assoc_array_leaf_to_ptr(const void *p)
-{
-	return __assoc_array_x_to_ptr(p, ASSOC_ARRAY_PTR_LEAF_TYPE);
-}
-static inline
-struct assoc_array_ptr *assoc_array_node_to_ptr(const struct assoc_array_node *p)
-{
-	return __assoc_array_x_to_ptr(
-		p, ASSOC_ARRAY_PTR_META_TYPE | ASSOC_ARRAY_PTR_NODE_SUBTYPE);
-}
-static inline
-struct assoc_array_ptr *assoc_array_shortcut_to_ptr(const struct assoc_array_shortcut *p)
-{
-	return __assoc_array_x_to_ptr(
-		p, ASSOC_ARRAY_PTR_META_TYPE | ASSOC_ARRAY_PTR_SHORTCUT_SUBTYPE);
-}
-
-#endif /* CONFIG_ASSOCIATIVE_ARRAY */
-#endif /* _LINUX_ASSOC_ARRAY_PRIV_H */
diff --git a/include/linux/key-type.h b/include/linux/key-type.h
index c4f329b6ae3fed..bb97bd3e5af4fa 100644
--- a/include/linux/key-type.h
+++ b/include/linux/key-type.h
@@ -161,7 +161,6 @@ struct key_type {
 				     const void *in, const void *in2);
 
 	/* internal fields */
-	atomic64_t		index_id;	/* Opaque keyring index ID */
 	struct list_head	link;		/* link in types list */
 	struct lock_class_key	lock_class;	/* key->sem lock class */
 } __randomize_layout;
diff --git a/include/linux/key.h b/include/linux/key.h
index 420412aab9263a..0d2d64e10f7baf 100644
--- a/include/linux/key.h
+++ b/include/linux/key.h
@@ -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>
 
@@ -107,34 +106,21 @@ struct key_owner;
 struct key_tag;
 struct keyring_list;
 struct keyring_name;
+struct keyring_index;
 
 struct key_tag {
 	struct rcu_head		rcu;
-	atomic64_t		index_id;	/* Opaque keyring index ID */
 	refcount_t		usage;
 	bool			removed;	/* T when subject removed */
 };
 
 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;
-	};
+	u32			hash;			/* Hash value */
+	unsigned int		desc_len;
 	struct key_type		*type;
 	struct key_tag		*domain_tag;	/* Domain of operation */
 	const char		*description;
-	u64			type_id;	/* Cached index IDs */
-	u64			domain_id;
 };
 
 union key_payload {
@@ -252,13 +238,11 @@ struct key {
 	union {
 		struct keyring_index_key index_key;
 		struct {
-			unsigned long	hash;
-			unsigned long	len_desc;
+			u32		hash;
+			unsigned int	desc_len;
 			struct key_type	*type;		/* type of key */
 			struct key_tag	*domain_tag;	/* Domain of operation */
 			char		*description;
-			u64		type_id;
-			u64		domain_id;
 		};
 	};
 
@@ -271,7 +255,7 @@ struct key {
 		struct {
 			/* Keyring bits */
 			struct list_head name_link;
-			struct assoc_array keys;
+			struct keyring_index __rcu *index;
 		};
 	};
 
@@ -439,6 +423,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,
diff --git a/kernel/bpf/keys.c b/kernel/bpf/keys.c
index bffc356839ac56..24e0416abc99dd 100644
--- a/kernel/bpf/keys.c
+++ b/kernel/bpf/keys.c
@@ -29,7 +29,7 @@ struct bpf_key *bpf_lookup_keyring(void)
 
 	if (!bpf_keyring)
 		return NULL;
-	if (!READ_ONCE(bpf_keyring->keys.nr_leaves_on_tree) ||
+	if (keyring_is_empty(bpf_keyring) ||
 	    !READ_ONCE(bpf_keyring->restrict_link))
 		return NULL;
 
diff --git a/lib/Kconfig b/lib/Kconfig
index 1e42f5167c68bc..f70382dbb15954 100644
--- a/lib/Kconfig
+++ b/lib/Kconfig
@@ -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
 
diff --git a/lib/Makefile b/lib/Makefile
index a2afe954805cb8..4777dfcc824405 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -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
diff --git a/lib/assoc_array.c b/lib/assoc_array.c
deleted file mode 100644
index b6c9723e12ced5..00000000000000
--- a/lib/assoc_array.c
+++ /dev/null
@@ -1,1724 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0-or-later
-/* Generic associative array implementation.
- *
- * See Documentation/core-api/assoc_array.rst for information.
- *
- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.
- * Written by David Howells (dhowells@redhat.com)
- */
-//#define DEBUG
-#include <linux/rcupdate.h>
-#include <linux/slab.h>
-#include <linux/err.h>
-#include <linux/assoc_array_priv.h>
-
-/*
- * Iterate over an associative array.  The caller must hold the RCU read lock
- * or better.
- */
-static int assoc_array_subtree_iterate(const struct assoc_array_ptr *root,
-				       const struct assoc_array_ptr *stop,
-				       int (*iterator)(const void *leaf,
-						       void *iterator_data),
-				       void *iterator_data)
-{
-	const struct assoc_array_shortcut *shortcut;
-	const struct assoc_array_node *node;
-	const struct assoc_array_ptr *cursor, *ptr, *parent;
-	unsigned long has_meta;
-	int slot, ret;
-
-	cursor = root;
-
-begin_node:
-	if (assoc_array_ptr_is_shortcut(cursor)) {
-		/* Descend through a shortcut */
-		shortcut = assoc_array_ptr_to_shortcut(cursor);
-		cursor = READ_ONCE(shortcut->next_node); /* Address dependency. */
-	}
-
-	node = assoc_array_ptr_to_node(cursor);
-	slot = 0;
-
-	/* We perform two passes of each node.
-	 *
-	 * The first pass does all the leaves in this node.  This means we
-	 * don't miss any leaves if the node is split up by insertion whilst
-	 * we're iterating over the branches rooted here (we may, however, see
-	 * some leaves twice).
-	 */
-	has_meta = 0;
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-		has_meta |= (unsigned long)ptr;
-		if (ptr && assoc_array_ptr_is_leaf(ptr)) {
-			/* We need a barrier between the read of the pointer,
-			 * which is supplied by the above READ_ONCE().
-			 */
-			/* Invoke the callback */
-			ret = iterator(assoc_array_ptr_to_leaf(ptr),
-				       iterator_data);
-			if (ret)
-				return ret;
-		}
-	}
-
-	/* The second pass attends to all the metadata pointers.  If we follow
-	 * one of these we may find that we don't come back here, but rather go
-	 * back to a replacement node with the leaves in a different layout.
-	 *
-	 * We are guaranteed to make progress, however, as the slot number for
-	 * a particular portion of the key space cannot change - and we
-	 * continue at the back pointer + 1.
-	 */
-	if (!(has_meta & ASSOC_ARRAY_PTR_META_TYPE))
-		goto finished_node;
-	slot = 0;
-
-continue_node:
-	node = assoc_array_ptr_to_node(cursor);
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-		if (assoc_array_ptr_is_meta(ptr)) {
-			cursor = ptr;
-			goto begin_node;
-		}
-	}
-
-finished_node:
-	/* Move up to the parent (may need to skip back over a shortcut) */
-	parent = READ_ONCE(node->back_pointer); /* Address dependency. */
-	slot = node->parent_slot;
-	if (parent == stop)
-		return 0;
-
-	if (assoc_array_ptr_is_shortcut(parent)) {
-		shortcut = assoc_array_ptr_to_shortcut(parent);
-		cursor = parent;
-		parent = READ_ONCE(shortcut->back_pointer); /* Address dependency. */
-		slot = shortcut->parent_slot;
-		if (parent == stop)
-			return 0;
-	}
-
-	/* Ascend to next slot in parent node */
-	cursor = parent;
-	slot++;
-	goto continue_node;
-}
-
-/**
- * assoc_array_iterate - Pass all objects in the array to a callback
- * @array: The array to iterate over.
- * @iterator: The callback function.
- * @iterator_data: Private data for the callback function.
- *
- * Iterate over all the objects in an associative array.  Each one will be
- * presented to the iterator function.
- *
- * If the array is being modified concurrently with the iteration then it is
- * possible that some objects in the array will be passed to the iterator
- * callback more than once - though every object should be passed at least
- * once.  If this is undesirable then the caller must lock against modification
- * for the duration of this function.
- *
- * 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.
- *
- * The caller should hold the RCU read lock or better if concurrent
- * modification is possible.
- */
-int assoc_array_iterate(const struct assoc_array *array,
-			int (*iterator)(const void *object,
-					void *iterator_data),
-			void *iterator_data)
-{
-	struct assoc_array_ptr *root = READ_ONCE(array->root); /* Address dependency. */
-
-	if (!root)
-		return 0;
-	return assoc_array_subtree_iterate(root, NULL, iterator, iterator_data);
-}
-
-enum assoc_array_walk_status {
-	assoc_array_walk_tree_empty,
-	assoc_array_walk_found_terminal_node,
-	assoc_array_walk_found_wrong_shortcut,
-};
-
-struct assoc_array_walk_result {
-	struct {
-		struct assoc_array_node	*node;	/* Node in which leaf might be found */
-		int		level;
-		int		slot;
-	} terminal_node;
-	struct {
-		struct assoc_array_shortcut *shortcut;
-		int		level;
-		int		sc_level;
-		unsigned long	sc_segments;
-		unsigned long	dissimilarity;
-	} wrong_shortcut;
-};
-
-/*
- * Navigate through the internal tree looking for the closest node to the key.
- */
-static enum assoc_array_walk_status
-assoc_array_walk(const struct assoc_array *array,
-		 const struct assoc_array_ops *ops,
-		 const void *index_key,
-		 struct assoc_array_walk_result *result)
-{
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *cursor, *ptr;
-	unsigned long sc_segments, dissimilarity;
-	unsigned long segments;
-	int level, sc_level, next_sc_level;
-	int slot;
-
-	pr_devel("-->%s()\n", __func__);
-
-	cursor = READ_ONCE(array->root);  /* Address dependency. */
-	if (!cursor)
-		return assoc_array_walk_tree_empty;
-
-	level = 0;
-
-	/* Use segments from the key for the new leaf to navigate through the
-	 * internal tree, skipping through nodes and shortcuts that are on
-	 * route to the destination.  Eventually we'll come to a slot that is
-	 * either empty or contains a leaf at which point we've found a node in
-	 * which the leaf we're looking for might be found or into which it
-	 * should be inserted.
-	 */
-jumped:
-	segments = ops->get_key_chunk(index_key, level);
-	pr_devel("segments[%d]: %lx\n", level, segments);
-
-	if (assoc_array_ptr_is_shortcut(cursor))
-		goto follow_shortcut;
-
-consider_node:
-	node = assoc_array_ptr_to_node(cursor);
-	slot = segments >> (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
-	slot &= ASSOC_ARRAY_FAN_MASK;
-	ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-
-	pr_devel("consider slot %x [ix=%d type=%lu]\n",
-		 slot, level, (unsigned long)ptr & 3);
-
-	if (!assoc_array_ptr_is_meta(ptr)) {
-		/* The node doesn't have a node/shortcut pointer in the slot
-		 * corresponding to the index key that we have to follow.
-		 */
-		result->terminal_node.node = node;
-		result->terminal_node.level = level;
-		result->terminal_node.slot = slot;
-		pr_devel("<--%s() = terminal_node\n", __func__);
-		return assoc_array_walk_found_terminal_node;
-	}
-
-	if (assoc_array_ptr_is_node(ptr)) {
-		/* There is a pointer to a node in the slot corresponding to
-		 * this index key segment, so we need to follow it.
-		 */
-		cursor = ptr;
-		level += ASSOC_ARRAY_LEVEL_STEP;
-		if ((level & ASSOC_ARRAY_KEY_CHUNK_MASK) != 0)
-			goto consider_node;
-		goto jumped;
-	}
-
-	/* There is a shortcut in the slot corresponding to the index key
-	 * segment.  We follow the shortcut if its partial index key matches
-	 * this leaf's.  Otherwise we need to split the shortcut.
-	 */
-	cursor = ptr;
-follow_shortcut:
-	shortcut = assoc_array_ptr_to_shortcut(cursor);
-	pr_devel("shortcut to %d\n", shortcut->skip_to_level);
-	sc_level = level + ASSOC_ARRAY_LEVEL_STEP;
-	BUG_ON(sc_level > shortcut->skip_to_level);
-
-	do {
-		/* Check the leaf against the shortcut's index key a word at a
-		 * time, trimming the final word (the shortcut stores the index
-		 * key completely from the root to the shortcut's target).
-		 */
-		if ((sc_level & ASSOC_ARRAY_KEY_CHUNK_MASK) == 0)
-			segments = ops->get_key_chunk(index_key, sc_level);
-
-		sc_segments = shortcut->index_key[sc_level >> ASSOC_ARRAY_KEY_CHUNK_SHIFT];
-		dissimilarity = segments ^ sc_segments;
-
-		if (shortcut->skip_to_level < round_down(sc_level,
-				ASSOC_ARRAY_KEY_CHUNK_SIZE) + ASSOC_ARRAY_KEY_CHUNK_SIZE) {
-			/* Trim segments that are beyond the shortcut */
-			int shift = shortcut->skip_to_level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-			dissimilarity &= ~(ULONG_MAX << shift);
-			next_sc_level = shortcut->skip_to_level;
-		} else {
-			next_sc_level = sc_level + ASSOC_ARRAY_KEY_CHUNK_SIZE;
-			next_sc_level = round_down(next_sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		}
-
-		if (dissimilarity != 0) {
-			/* This shortcut points elsewhere */
-			result->wrong_shortcut.shortcut = shortcut;
-			result->wrong_shortcut.level = level;
-			result->wrong_shortcut.sc_level = sc_level;
-			result->wrong_shortcut.sc_segments = sc_segments;
-			result->wrong_shortcut.dissimilarity = dissimilarity;
-			return assoc_array_walk_found_wrong_shortcut;
-		}
-
-		sc_level = next_sc_level;
-	} while (sc_level < shortcut->skip_to_level);
-
-	/* The shortcut matches the leaf's index to this point. */
-	cursor = READ_ONCE(shortcut->next_node); /* Address dependency. */
-	if (((level ^ sc_level) & ~ASSOC_ARRAY_KEY_CHUNK_MASK) != 0) {
-		level = sc_level;
-		goto jumped;
-	} else {
-		level = sc_level;
-		goto consider_node;
-	}
-}
-
-/**
- * assoc_array_find - Find an object by index key
- * @array: The associative array to search.
- * @ops: The operations to use.
- * @index_key: The key to the object.
- *
- * Find an object in an associative array by walking through the internal tree
- * to the node that should contain the object and then searching the leaves
- * there.  NULL is returned if the requested object was not found in the array.
- *
- * The caller must hold the RCU read lock or better.
- */
-void *assoc_array_find(const struct assoc_array *array,
-		       const struct assoc_array_ops *ops,
-		       const void *index_key)
-{
-	struct assoc_array_walk_result result;
-	const struct assoc_array_node *node;
-	const struct assoc_array_ptr *ptr;
-	const void *leaf;
-	int slot;
-
-	if (assoc_array_walk(array, ops, index_key, &result) !=
-	    assoc_array_walk_found_terminal_node)
-		return NULL;
-
-	node = result.terminal_node.node;
-
-	/* If the target key is available to us, it's has to be pointed to by
-	 * the terminal node.
-	 */
-	for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-		if (ptr && assoc_array_ptr_is_leaf(ptr)) {
-			/* We need a barrier between the read of the pointer
-			 * and dereferencing the pointer - but only if we are
-			 * actually going to dereference it.
-			 */
-			leaf = assoc_array_ptr_to_leaf(ptr);
-			if (ops->compare_object(leaf, index_key))
-				return (void *)leaf;
-		}
-	}
-
-	return NULL;
-}
-
-/*
- * Destructively iterate over an associative array.  The caller must prevent
- * other simultaneous accesses.
- */
-static void assoc_array_destroy_subtree(struct assoc_array_ptr *root,
-					const struct assoc_array_ops *ops)
-{
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *cursor, *parent = NULL;
-	int slot = -1;
-
-	pr_devel("-->%s()\n", __func__);
-
-	cursor = root;
-	if (!cursor) {
-		pr_devel("empty\n");
-		return;
-	}
-
-move_to_meta:
-	if (assoc_array_ptr_is_shortcut(cursor)) {
-		/* Descend through a shortcut */
-		pr_devel("[%d] shortcut\n", slot);
-		BUG_ON(!assoc_array_ptr_is_shortcut(cursor));
-		shortcut = assoc_array_ptr_to_shortcut(cursor);
-		BUG_ON(shortcut->back_pointer != parent);
-		BUG_ON(slot != -1 && shortcut->parent_slot != slot);
-		parent = cursor;
-		cursor = shortcut->next_node;
-		slot = -1;
-		BUG_ON(!assoc_array_ptr_is_node(cursor));
-	}
-
-	pr_devel("[%d] node\n", slot);
-	node = assoc_array_ptr_to_node(cursor);
-	BUG_ON(node->back_pointer != parent);
-	BUG_ON(slot != -1 && node->parent_slot != slot);
-	slot = 0;
-
-continue_node:
-	pr_devel("Node %p [back=%p]\n", node, node->back_pointer);
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		struct assoc_array_ptr *ptr = node->slots[slot];
-		if (!ptr)
-			continue;
-		if (assoc_array_ptr_is_meta(ptr)) {
-			parent = cursor;
-			cursor = ptr;
-			goto move_to_meta;
-		}
-
-		if (ops) {
-			pr_devel("[%d] free leaf\n", slot);
-			ops->free_object(assoc_array_ptr_to_leaf(ptr));
-		}
-	}
-
-	parent = node->back_pointer;
-	slot = node->parent_slot;
-	pr_devel("free node\n");
-	kfree(node);
-	if (!parent)
-		return; /* Done */
-
-	/* Move back up to the parent (may need to free a shortcut on
-	 * the way up) */
-	if (assoc_array_ptr_is_shortcut(parent)) {
-		shortcut = assoc_array_ptr_to_shortcut(parent);
-		BUG_ON(shortcut->next_node != cursor);
-		cursor = parent;
-		parent = shortcut->back_pointer;
-		slot = shortcut->parent_slot;
-		pr_devel("free shortcut\n");
-		kfree(shortcut);
-		if (!parent)
-			return;
-
-		BUG_ON(!assoc_array_ptr_is_node(parent));
-	}
-
-	/* Ascend to next slot in parent node */
-	pr_devel("ascend to %p[%d]\n", parent, slot);
-	cursor = parent;
-	node = assoc_array_ptr_to_node(cursor);
-	slot++;
-	goto continue_node;
-}
-
-/**
- * assoc_array_destroy - Destroy an associative array
- * @array: The array to destroy.
- * @ops: The operations to use.
- *
- * Discard all metadata and free all objects in an associative array.  The
- * array will be empty and ready to use again upon completion.  This function
- * cannot fail.
- *
- * The caller must prevent all other accesses whilst this takes place as no
- * attempt is made to adjust pointers gracefully to permit RCU readlock-holding
- * accesses to continue.  On the other hand, no memory allocation is required.
- */
-void assoc_array_destroy(struct assoc_array *array,
-			 const struct assoc_array_ops *ops)
-{
-	assoc_array_destroy_subtree(array->root, ops);
-	array->root = NULL;
-}
-
-/*
- * Handle insertion into an empty tree.
- */
-static bool assoc_array_insert_in_empty_tree(struct assoc_array_edit *edit)
-{
-	struct assoc_array_node *new_n0;
-
-	pr_devel("-->%s()\n", __func__);
-
-	new_n0 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n0)
-		return false;
-
-	edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-	edit->leaf_p = &new_n0->slots[0];
-	edit->adjust_count_on = new_n0;
-	edit->set[0].ptr = &edit->array->root;
-	edit->set[0].to = assoc_array_node_to_ptr(new_n0);
-
-	pr_devel("<--%s() = ok [no root]\n", __func__);
-	return true;
-}
-
-/*
- * Handle insertion into a terminal node.
- */
-static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit,
-						  const struct assoc_array_ops *ops,
-						  const void *index_key,
-						  struct assoc_array_walk_result *result)
-{
-	struct assoc_array_shortcut *shortcut, *new_s0;
-	struct assoc_array_node *node, *new_n0, *new_n1, *side;
-	struct assoc_array_ptr *ptr;
-	unsigned long dissimilarity, base_seg, blank;
-	size_t keylen;
-	bool have_meta;
-	int level, diff;
-	int slot, next_slot, free_slot, i, j;
-
-	node	= result->terminal_node.node;
-	level	= result->terminal_node.level;
-	edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot;
-
-	pr_devel("-->%s()\n", __func__);
-
-	/* We arrived at a node which doesn't have an onward node or shortcut
-	 * pointer that we have to follow.  This means that (a) the leaf we
-	 * want must go here (either by insertion or replacement) or (b) we
-	 * need to split this node and insert in one of the fragments.
-	 */
-	free_slot = -1;
-
-	/* Firstly, we have to check the leaves in this node to see if there's
-	 * a matching one we should replace in place.
-	 */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		ptr = node->slots[i];
-		if (!ptr) {
-			free_slot = i;
-			continue;
-		}
-		if (assoc_array_ptr_is_leaf(ptr) &&
-		    ops->compare_object(assoc_array_ptr_to_leaf(ptr),
-					index_key)) {
-			pr_devel("replace in slot %d\n", i);
-			edit->leaf_p = &node->slots[i];
-			edit->dead_leaf = node->slots[i];
-			pr_devel("<--%s() = ok [replace]\n", __func__);
-			return true;
-		}
-	}
-
-	/* If there is a free slot in this node then we can just insert the
-	 * leaf here.
-	 */
-	if (free_slot >= 0) {
-		pr_devel("insert in free slot %d\n", free_slot);
-		edit->leaf_p = &node->slots[free_slot];
-		edit->adjust_count_on = node;
-		pr_devel("<--%s() = ok [insert]\n", __func__);
-		return true;
-	}
-
-	/* The node has no spare slots - so we're either going to have to split
-	 * it or insert another node before it.
-	 *
-	 * Whatever, we're going to need at least two new nodes - so allocate
-	 * those now.  We may also need a new shortcut, but we deal with that
-	 * when we need it.
-	 */
-	new_n0 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n0)
-		return false;
-	edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-	new_n1 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n1)
-		return false;
-	edit->new_meta[1] = assoc_array_node_to_ptr(new_n1);
-
-	/* We need to find out how similar the leaves are. */
-	pr_devel("no spare slots\n");
-	have_meta = false;
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		ptr = node->slots[i];
-		if (assoc_array_ptr_is_meta(ptr)) {
-			edit->segment_cache[i] = 0xff;
-			have_meta = true;
-			continue;
-		}
-		base_seg = ops->get_object_key_chunk(
-			assoc_array_ptr_to_leaf(ptr), level);
-		base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-		edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
-	}
-
-	if (have_meta) {
-		pr_devel("have meta\n");
-		goto split_node;
-	}
-
-	/* The node contains only leaves */
-	dissimilarity = 0;
-	base_seg = edit->segment_cache[0];
-	for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++)
-		dissimilarity |= edit->segment_cache[i] ^ base_seg;
-
-	pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity);
-
-	if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) {
-		/* The old leaves all cluster in the same slot.  We will need
-		 * to insert a shortcut if the new node wants to cluster with them.
-		 */
-		if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0)
-			goto all_leaves_cluster_together;
-
-		/* Otherwise all the old leaves cluster in the same slot, but
-		 * the new leaf wants to go into a different slot - so we
-		 * create a new node (n0) to hold the new leaf and a pointer to
-		 * a new node (n1) holding all the old leaves.
-		 *
-		 * This can be done by falling through to the node splitting
-		 * path.
-		 */
-		pr_devel("present leaves cluster but not new leaf\n");
-	}
-
-split_node:
-	pr_devel("split node\n");
-
-	/* We need to split the current node.  The node must contain anything
-	 * from a single leaf (in the one leaf case, this leaf will cluster
-	 * with the new leaf) and the rest meta-pointers, to all leaves, some
-	 * of which may cluster.
-	 *
-	 * It won't contain the case in which all the current leaves plus the
-	 * new leaves want to cluster in the same slot.
-	 *
-	 * We need to expel at least two leaves out of a set consisting of the
-	 * leaves in the node and the new leaf.  The current meta pointers can
-	 * just be copied as they shouldn't cluster with any of the leaves.
-	 *
-	 * We need a new node (n0) to replace the current one and a new node to
-	 * take the expelled nodes (n1).
-	 */
-	edit->set[0].to = assoc_array_node_to_ptr(new_n0);
-	new_n0->back_pointer = node->back_pointer;
-	new_n0->parent_slot = node->parent_slot;
-	new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
-	new_n1->parent_slot = -1; /* Need to calculate this */
-
-do_split_node:
-	pr_devel("do_split_node\n");
-
-	new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
-	new_n1->nr_leaves_on_branch = 0;
-
-	/* Begin by finding two matching leaves.  There have to be at least two
-	 * that match - even if there are meta pointers - because any leaf that
-	 * would match a slot with a meta pointer in it must be somewhere
-	 * behind that meta pointer and cannot be here.  Further, given N
-	 * remaining leaf slots, we now have N+1 leaves to go in them.
-	 */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		slot = edit->segment_cache[i];
-		if (slot != 0xff)
-			for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++)
-				if (edit->segment_cache[j] == slot)
-					goto found_slot_for_multiple_occupancy;
-	}
-found_slot_for_multiple_occupancy:
-	pr_devel("same slot: %x %x [%02x]\n", i, j, slot);
-	BUG_ON(i >= ASSOC_ARRAY_FAN_OUT);
-	BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1);
-	BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT);
-
-	new_n1->parent_slot = slot;
-
-	/* Metadata pointers cannot change slot */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
-		if (assoc_array_ptr_is_meta(node->slots[i]))
-			new_n0->slots[i] = node->slots[i];
-		else
-			new_n0->slots[i] = NULL;
-	BUG_ON(new_n0->slots[slot] != NULL);
-	new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1);
-
-	/* Filter the leaf pointers between the new nodes */
-	free_slot = -1;
-	next_slot = 0;
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		if (assoc_array_ptr_is_meta(node->slots[i]))
-			continue;
-		if (edit->segment_cache[i] == slot) {
-			new_n1->slots[next_slot++] = node->slots[i];
-			new_n1->nr_leaves_on_branch++;
-		} else {
-			do {
-				free_slot++;
-			} while (new_n0->slots[free_slot] != NULL);
-			new_n0->slots[free_slot] = node->slots[i];
-		}
-	}
-
-	pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot);
-
-	if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) {
-		do {
-			free_slot++;
-		} while (new_n0->slots[free_slot] != NULL);
-		edit->leaf_p = &new_n0->slots[free_slot];
-		edit->adjust_count_on = new_n0;
-	} else {
-		edit->leaf_p = &new_n1->slots[next_slot++];
-		edit->adjust_count_on = new_n1;
-	}
-
-	BUG_ON(next_slot <= 1);
-
-	edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0);
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		if (edit->segment_cache[i] == 0xff) {
-			ptr = node->slots[i];
-			BUG_ON(assoc_array_ptr_is_leaf(ptr));
-			if (assoc_array_ptr_is_node(ptr)) {
-				side = assoc_array_ptr_to_node(ptr);
-				edit->set_backpointers[i] = &side->back_pointer;
-			} else {
-				shortcut = assoc_array_ptr_to_shortcut(ptr);
-				edit->set_backpointers[i] = &shortcut->back_pointer;
-			}
-		}
-	}
-
-	ptr = node->back_pointer;
-	if (!ptr)
-		edit->set[0].ptr = &edit->array->root;
-	else if (assoc_array_ptr_is_node(ptr))
-		edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot];
-	else
-		edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node;
-	edit->excised_meta[0] = assoc_array_node_to_ptr(node);
-	pr_devel("<--%s() = ok [split node]\n", __func__);
-	return true;
-
-all_leaves_cluster_together:
-	/* All the leaves, new and old, want to cluster together in this node
-	 * in the same slot, so we have to replace this node with a shortcut to
-	 * skip over the identical parts of the key and then place a pair of
-	 * nodes, one inside the other, at the end of the shortcut and
-	 * distribute the keys between them.
-	 *
-	 * Firstly we need to work out where the leaves start diverging as a
-	 * bit position into their keys so that we know how big the shortcut
-	 * needs to be.
-	 *
-	 * We only need to make a single pass of N of the N+1 leaves because if
-	 * any keys differ between themselves at bit X then at least one of
-	 * them must also differ with the base key at bit X or before.
-	 */
-	pr_devel("all leaves cluster together\n");
-	diff = INT_MAX;
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]),
-					  index_key);
-		if (x < diff) {
-			BUG_ON(x < 0);
-			diff = x;
-		}
-	}
-	BUG_ON(diff == INT_MAX);
-	BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP);
-
-	keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-	keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-
-	new_s0 = kzalloc_flex(*new_s0, index_key, keylen);
-	if (!new_s0)
-		return false;
-	edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0);
-
-	edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
-	new_s0->back_pointer = node->back_pointer;
-	new_s0->parent_slot = node->parent_slot;
-	new_s0->next_node = assoc_array_node_to_ptr(new_n0);
-	new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
-	new_n0->parent_slot = 0;
-	new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
-	new_n1->parent_slot = -1; /* Need to calculate this */
-
-	new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK;
-	pr_devel("skip_to_level = %d [diff %d]\n", level, diff);
-	BUG_ON(level <= 0);
-
-	for (i = 0; i < keylen; i++)
-		new_s0->index_key[i] =
-			ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE);
-
-	if (level & ASSOC_ARRAY_KEY_CHUNK_MASK) {
-		blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
-		pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank);
-		new_s0->index_key[keylen - 1] &= ~blank;
-	}
-
-	/* This now reduces to a node splitting exercise for which we'll need
-	 * to regenerate the disparity table.
-	 */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		ptr = node->slots[i];
-		base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr),
-						     level);
-		base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-		edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
-	}
-
-	base_seg = ops->get_key_chunk(index_key, level);
-	base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-	edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK;
-	goto do_split_node;
-}
-
-/*
- * Handle insertion into the middle of a shortcut.
- */
-static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit,
-					    const struct assoc_array_ops *ops,
-					    struct assoc_array_walk_result *result)
-{
-	struct assoc_array_shortcut *shortcut, *new_s0, *new_s1;
-	struct assoc_array_node *node, *new_n0, *side;
-	unsigned long sc_segments, dissimilarity, blank;
-	size_t keylen;
-	int level, sc_level, diff;
-	int sc_slot;
-
-	shortcut	= result->wrong_shortcut.shortcut;
-	level		= result->wrong_shortcut.level;
-	sc_level	= result->wrong_shortcut.sc_level;
-	sc_segments	= result->wrong_shortcut.sc_segments;
-	dissimilarity	= result->wrong_shortcut.dissimilarity;
-
-	pr_devel("-->%s(ix=%d dis=%lx scix=%d)\n",
-		 __func__, level, dissimilarity, sc_level);
-
-	/* We need to split a shortcut and insert a node between the two
-	 * pieces.  Zero-length pieces will be dispensed with entirely.
-	 *
-	 * First of all, we need to find out in which level the first
-	 * difference was.
-	 */
-	diff = __ffs(dissimilarity);
-	diff &= ~ASSOC_ARRAY_LEVEL_STEP_MASK;
-	diff += sc_level & ~ASSOC_ARRAY_KEY_CHUNK_MASK;
-	pr_devel("diff=%d\n", diff);
-
-	if (!shortcut->back_pointer) {
-		edit->set[0].ptr = &edit->array->root;
-	} else if (assoc_array_ptr_is_node(shortcut->back_pointer)) {
-		node = assoc_array_ptr_to_node(shortcut->back_pointer);
-		edit->set[0].ptr = &node->slots[shortcut->parent_slot];
-	} else {
-		BUG();
-	}
-
-	edit->excised_meta[0] = assoc_array_shortcut_to_ptr(shortcut);
-
-	/* Create a new node now since we're going to need it anyway */
-	new_n0 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n0)
-		return false;
-	edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-	edit->adjust_count_on = new_n0;
-
-	/* Insert a new shortcut before the new node if this segment isn't of
-	 * zero length - otherwise we just connect the new node directly to the
-	 * parent.
-	 */
-	level += ASSOC_ARRAY_LEVEL_STEP;
-	if (diff > level) {
-		pr_devel("pre-shortcut %d...%d\n", level, diff);
-		keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-
-		new_s0 = kzalloc_flex(*new_s0, index_key, keylen);
-		if (!new_s0)
-			return false;
-		edit->new_meta[1] = assoc_array_shortcut_to_ptr(new_s0);
-		edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
-		new_s0->back_pointer = shortcut->back_pointer;
-		new_s0->parent_slot = shortcut->parent_slot;
-		new_s0->next_node = assoc_array_node_to_ptr(new_n0);
-		new_s0->skip_to_level = diff;
-
-		new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
-		new_n0->parent_slot = 0;
-
-		memcpy(new_s0->index_key, shortcut->index_key,
-		       flex_array_size(new_s0, index_key, keylen));
-
-		blank = ULONG_MAX << (diff & ASSOC_ARRAY_KEY_CHUNK_MASK);
-		pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, diff, blank);
-		new_s0->index_key[keylen - 1] &= ~blank;
-	} else {
-		pr_devel("no pre-shortcut\n");
-		edit->set[0].to = assoc_array_node_to_ptr(new_n0);
-		new_n0->back_pointer = shortcut->back_pointer;
-		new_n0->parent_slot = shortcut->parent_slot;
-	}
-
-	side = assoc_array_ptr_to_node(shortcut->next_node);
-	new_n0->nr_leaves_on_branch = side->nr_leaves_on_branch;
-
-	/* We need to know which slot in the new node is going to take a
-	 * metadata pointer.
-	 */
-	sc_slot = sc_segments >> (diff & ASSOC_ARRAY_KEY_CHUNK_MASK);
-	sc_slot &= ASSOC_ARRAY_FAN_MASK;
-
-	pr_devel("new slot %lx >> %d -> %d\n",
-		 sc_segments, diff & ASSOC_ARRAY_KEY_CHUNK_MASK, sc_slot);
-
-	/* Determine whether we need to follow the new node with a replacement
-	 * for the current shortcut.  We could in theory reuse the current
-	 * shortcut if its parent slot number doesn't change - but that's a
-	 * 1-in-16 chance so not worth expending the code upon.
-	 */
-	level = diff + ASSOC_ARRAY_LEVEL_STEP;
-	if (level < shortcut->skip_to_level) {
-		pr_devel("post-shortcut %d...%d\n", level, shortcut->skip_to_level);
-		keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-
-		new_s1 = kzalloc_flex(*new_s1, index_key, keylen);
-		if (!new_s1)
-			return false;
-		edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s1);
-
-		new_s1->back_pointer = assoc_array_node_to_ptr(new_n0);
-		new_s1->parent_slot = sc_slot;
-		new_s1->next_node = shortcut->next_node;
-		new_s1->skip_to_level = shortcut->skip_to_level;
-
-		new_n0->slots[sc_slot] = assoc_array_shortcut_to_ptr(new_s1);
-
-		memcpy(new_s1->index_key, shortcut->index_key,
-		       flex_array_size(new_s1, index_key, keylen));
-
-		edit->set[1].ptr = &side->back_pointer;
-		edit->set[1].to = assoc_array_shortcut_to_ptr(new_s1);
-	} else {
-		pr_devel("no post-shortcut\n");
-
-		/* We don't have to replace the pointed-to node as long as we
-		 * use memory barriers to make sure the parent slot number is
-		 * changed before the back pointer (the parent slot number is
-		 * irrelevant to the old parent shortcut).
-		 */
-		new_n0->slots[sc_slot] = shortcut->next_node;
-		edit->set_parent_slot[0].p = &side->parent_slot;
-		edit->set_parent_slot[0].to = sc_slot;
-		edit->set[1].ptr = &side->back_pointer;
-		edit->set[1].to = assoc_array_node_to_ptr(new_n0);
-	}
-
-	/* Install the new leaf in a spare slot in the new node. */
-	if (sc_slot == 0)
-		edit->leaf_p = &new_n0->slots[1];
-	else
-		edit->leaf_p = &new_n0->slots[0];
-
-	pr_devel("<--%s() = ok [split shortcut]\n", __func__);
-	return true;
-}
-
-/**
- * assoc_array_insert - Script insertion of an object into an associative array
- * @array: The array to insert into.
- * @ops: The operations to use.
- * @index_key: The key to insert at.
- * @object: The object to insert.
- *
- * Precalculate and preallocate a script for the insertion or replacement of an
- * object in an associative array.  This results in an edit script that can
- * either be applied or cancelled.
- *
- * The function returns a pointer to an edit script or -ENOMEM.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-struct assoc_array_edit *assoc_array_insert(struct assoc_array *array,
-					    const struct assoc_array_ops *ops,
-					    const void *index_key,
-					    void *object)
-{
-	struct assoc_array_walk_result result;
-	struct assoc_array_edit *edit;
-
-	pr_devel("-->%s()\n", __func__);
-
-	/* The leaf pointer we're given must not have the bottom bit set as we
-	 * use those for type-marking the pointer.  NULL pointers are also not
-	 * allowed as they indicate an empty slot but we have to allow them
-	 * here as they can be updated later.
-	 */
-	BUG_ON(assoc_array_ptr_is_meta(object));
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return ERR_PTR(-ENOMEM);
-	edit->array = array;
-	edit->ops = ops;
-	edit->leaf = assoc_array_leaf_to_ptr(object);
-	edit->adjust_count_by = 1;
-
-	switch (assoc_array_walk(array, ops, index_key, &result)) {
-	case assoc_array_walk_tree_empty:
-		/* Allocate a root node if there isn't one yet */
-		if (!assoc_array_insert_in_empty_tree(edit))
-			goto enomem;
-		return edit;
-
-	case assoc_array_walk_found_terminal_node:
-		/* We found a node that doesn't have a node/shortcut pointer in
-		 * the slot corresponding to the index key that we have to
-		 * follow.
-		 */
-		if (!assoc_array_insert_into_terminal_node(edit, ops, index_key,
-							   &result))
-			goto enomem;
-		return edit;
-
-	case assoc_array_walk_found_wrong_shortcut:
-		/* We found a shortcut that didn't match our key in a slot we
-		 * needed to follow.
-		 */
-		if (!assoc_array_insert_mid_shortcut(edit, ops, &result))
-			goto enomem;
-		return edit;
-	}
-
-enomem:
-	/* Clean up after an out of memory error */
-	pr_devel("enomem\n");
-	assoc_array_cancel_edit(edit);
-	return ERR_PTR(-ENOMEM);
-}
-
-/**
- * assoc_array_insert_set_object - Set the new object pointer in an edit script
- * @edit: The edit script to modify.
- * @object: The object pointer to set.
- *
- * Change the object to be inserted in an edit script.  The object pointed to
- * by the old object is not freed.  This must be done prior to applying the
- * script.
- */
-void assoc_array_insert_set_object(struct assoc_array_edit *edit, void *object)
-{
-	BUG_ON(!object);
-	edit->leaf = assoc_array_leaf_to_ptr(object);
-}
-
-struct assoc_array_delete_collapse_context {
-	struct assoc_array_node	*node;
-	const void		*skip_leaf;
-	int			slot;
-};
-
-/*
- * Subtree collapse to node iterator.
- */
-static int assoc_array_delete_collapse_iterator(const void *leaf,
-						void *iterator_data)
-{
-	struct assoc_array_delete_collapse_context *collapse = iterator_data;
-
-	if (leaf == collapse->skip_leaf)
-		return 0;
-
-	BUG_ON(collapse->slot >= ASSOC_ARRAY_FAN_OUT);
-
-	collapse->node->slots[collapse->slot++] = assoc_array_leaf_to_ptr(leaf);
-	return 0;
-}
-
-/**
- * assoc_array_delete - Script deletion of an object from an associative array
- * @array: The array to search.
- * @ops: The operations to use.
- * @index_key: The key to the object.
- *
- * Precalculate and preallocate a script for the deletion of an object from an
- * associative array.  This results in an edit script that can either be
- * applied or cancelled.
- *
- * The function returns a pointer to an edit script if the object was found,
- * NULL if the object was not found or -ENOMEM.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-struct assoc_array_edit *assoc_array_delete(struct assoc_array *array,
-					    const struct assoc_array_ops *ops,
-					    const void *index_key)
-{
-	struct assoc_array_delete_collapse_context collapse;
-	struct assoc_array_walk_result result;
-	struct assoc_array_node *node, *new_n0;
-	struct assoc_array_edit *edit;
-	struct assoc_array_ptr *ptr;
-	bool has_meta;
-	int slot, i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return ERR_PTR(-ENOMEM);
-	edit->array = array;
-	edit->ops = ops;
-	edit->adjust_count_by = -1;
-
-	switch (assoc_array_walk(array, ops, index_key, &result)) {
-	case assoc_array_walk_found_terminal_node:
-		/* We found a node that should contain the leaf we've been
-		 * asked to remove - *if* it's in the tree.
-		 */
-		pr_devel("terminal_node\n");
-		node = result.terminal_node.node;
-
-		for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-			ptr = node->slots[slot];
-			if (ptr &&
-			    assoc_array_ptr_is_leaf(ptr) &&
-			    ops->compare_object(assoc_array_ptr_to_leaf(ptr),
-						index_key))
-				goto found_leaf;
-		}
-		fallthrough;
-	case assoc_array_walk_tree_empty:
-	case assoc_array_walk_found_wrong_shortcut:
-	default:
-		assoc_array_cancel_edit(edit);
-		pr_devel("not found\n");
-		return NULL;
-	}
-
-found_leaf:
-	BUG_ON(array->nr_leaves_on_tree <= 0);
-
-	/* In the simplest form of deletion we just clear the slot and release
-	 * the leaf after a suitable interval.
-	 */
-	edit->dead_leaf = node->slots[slot];
-	edit->set[0].ptr = &node->slots[slot];
-	edit->set[0].to = NULL;
-	edit->adjust_count_on = node;
-
-	/* If that concludes erasure of the last leaf, then delete the entire
-	 * internal array.
-	 */
-	if (array->nr_leaves_on_tree == 1) {
-		edit->set[1].ptr = &array->root;
-		edit->set[1].to = NULL;
-		edit->adjust_count_on = NULL;
-		edit->excised_subtree = array->root;
-		pr_devel("all gone\n");
-		return edit;
-	}
-
-	/* However, we'd also like to clear up some metadata blocks if we
-	 * possibly can.
-	 *
-	 * We go for a simple algorithm of: if this node has FAN_OUT or fewer
-	 * leaves in it, then attempt to collapse it - and attempt to
-	 * recursively collapse up the tree.
-	 *
-	 * We could also try and collapse in partially filled subtrees to take
-	 * up space in this node.
-	 */
-	if (node->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) {
-		struct assoc_array_node *parent, *grandparent;
-		struct assoc_array_ptr *ptr;
-
-		/* First of all, we need to know if this node has metadata so
-		 * that we don't try collapsing if all the leaves are already
-		 * here.
-		 */
-		has_meta = false;
-		for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-			ptr = node->slots[i];
-			if (assoc_array_ptr_is_meta(ptr)) {
-				has_meta = true;
-				break;
-			}
-		}
-
-		pr_devel("leaves: %ld [m=%d]\n",
-			 node->nr_leaves_on_branch - 1, has_meta);
-
-		/* Look further up the tree to see if we can collapse this node
-		 * into a more proximal node too.
-		 */
-		parent = node;
-	collapse_up:
-		pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch);
-
-		ptr = parent->back_pointer;
-		if (!ptr)
-			goto do_collapse;
-		if (assoc_array_ptr_is_shortcut(ptr)) {
-			struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(ptr);
-			ptr = s->back_pointer;
-			if (!ptr)
-				goto do_collapse;
-		}
-
-		grandparent = assoc_array_ptr_to_node(ptr);
-		if (grandparent->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) {
-			parent = grandparent;
-			goto collapse_up;
-		}
-
-	do_collapse:
-		/* There's no point collapsing if the original node has no meta
-		 * pointers to discard and if we didn't merge into one of that
-		 * node's ancestry.
-		 */
-		if (has_meta || parent != node) {
-			node = parent;
-
-			/* Create a new node to collapse into */
-			new_n0 = kzalloc_obj(struct assoc_array_node);
-			if (!new_n0)
-				goto enomem;
-			edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-
-			new_n0->back_pointer = node->back_pointer;
-			new_n0->parent_slot = node->parent_slot;
-			new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
-			edit->adjust_count_on = new_n0;
-
-			collapse.node = new_n0;
-			collapse.skip_leaf = assoc_array_ptr_to_leaf(edit->dead_leaf);
-			collapse.slot = 0;
-			assoc_array_subtree_iterate(assoc_array_node_to_ptr(node),
-						    node->back_pointer,
-						    assoc_array_delete_collapse_iterator,
-						    &collapse);
-			pr_devel("collapsed %d,%lu\n", collapse.slot, new_n0->nr_leaves_on_branch);
-			BUG_ON(collapse.slot != new_n0->nr_leaves_on_branch - 1);
-
-			if (!node->back_pointer) {
-				edit->set[1].ptr = &array->root;
-			} else if (assoc_array_ptr_is_leaf(node->back_pointer)) {
-				BUG();
-			} else if (assoc_array_ptr_is_node(node->back_pointer)) {
-				struct assoc_array_node *p =
-					assoc_array_ptr_to_node(node->back_pointer);
-				edit->set[1].ptr = &p->slots[node->parent_slot];
-			} else if (assoc_array_ptr_is_shortcut(node->back_pointer)) {
-				struct assoc_array_shortcut *s =
-					assoc_array_ptr_to_shortcut(node->back_pointer);
-				edit->set[1].ptr = &s->next_node;
-			}
-			edit->set[1].to = assoc_array_node_to_ptr(new_n0);
-			edit->excised_subtree = assoc_array_node_to_ptr(node);
-		}
-	}
-
-	return edit;
-
-enomem:
-	/* Clean up after an out of memory error */
-	pr_devel("enomem\n");
-	assoc_array_cancel_edit(edit);
-	return ERR_PTR(-ENOMEM);
-}
-
-/**
- * assoc_array_clear - Script deletion of all objects from an associative array
- * @array: The array to clear.
- * @ops: The operations to use.
- *
- * Precalculate and preallocate a script for the deletion of all the objects
- * from an associative array.  This results in an edit script that can either
- * be applied or cancelled.
- *
- * The function returns a pointer to an edit script if there are objects to be
- * deleted, NULL if there are no objects in the array or -ENOMEM.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-struct assoc_array_edit *assoc_array_clear(struct assoc_array *array,
-					   const struct assoc_array_ops *ops)
-{
-	struct assoc_array_edit *edit;
-
-	pr_devel("-->%s()\n", __func__);
-
-	if (!array->root)
-		return NULL;
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return ERR_PTR(-ENOMEM);
-	edit->array = array;
-	edit->ops = ops;
-	edit->set[1].ptr = &array->root;
-	edit->set[1].to = NULL;
-	edit->excised_subtree = array->root;
-	edit->ops_for_excised_subtree = ops;
-	pr_devel("all gone\n");
-	return edit;
-}
-
-/*
- * Handle the deferred destruction after an applied edit.
- */
-static void assoc_array_rcu_cleanup(struct rcu_head *head)
-{
-	struct assoc_array_edit *edit =
-		container_of(head, struct assoc_array_edit, rcu);
-	int i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	if (edit->dead_leaf)
-		edit->ops->free_object(assoc_array_ptr_to_leaf(edit->dead_leaf));
-	for (i = 0; i < ARRAY_SIZE(edit->excised_meta); i++)
-		if (edit->excised_meta[i])
-			kfree(assoc_array_ptr_to_node(edit->excised_meta[i]));
-
-	if (edit->excised_subtree) {
-		BUG_ON(assoc_array_ptr_is_leaf(edit->excised_subtree));
-		if (assoc_array_ptr_is_node(edit->excised_subtree)) {
-			struct assoc_array_node *n =
-				assoc_array_ptr_to_node(edit->excised_subtree);
-			n->back_pointer = NULL;
-		} else {
-			struct assoc_array_shortcut *s =
-				assoc_array_ptr_to_shortcut(edit->excised_subtree);
-			s->back_pointer = NULL;
-		}
-		assoc_array_destroy_subtree(edit->excised_subtree,
-					    edit->ops_for_excised_subtree);
-	}
-
-	kfree(edit);
-}
-
-/**
- * assoc_array_apply_edit - Apply an edit script to an associative array
- * @edit: The script to apply.
- *
- * Apply an edit script to an associative array to effect an insertion,
- * deletion or clearance.  As the edit script includes preallocated memory,
- * this is guaranteed not to fail.
- *
- * The edit script, dead objects and dead metadata will be scheduled for
- * destruction after an RCU grace period to permit those doing read-only
- * accesses on the array to continue to do so under the RCU read lock whilst
- * the edit is taking place.
- */
-void assoc_array_apply_edit(struct assoc_array_edit *edit)
-{
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *ptr;
-	int i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	smp_wmb();
-	if (edit->leaf_p)
-		*edit->leaf_p = edit->leaf;
-
-	smp_wmb();
-	for (i = 0; i < ARRAY_SIZE(edit->set_parent_slot); i++)
-		if (edit->set_parent_slot[i].p)
-			*edit->set_parent_slot[i].p = edit->set_parent_slot[i].to;
-
-	smp_wmb();
-	for (i = 0; i < ARRAY_SIZE(edit->set_backpointers); i++)
-		if (edit->set_backpointers[i])
-			*edit->set_backpointers[i] = edit->set_backpointers_to;
-
-	smp_wmb();
-	for (i = 0; i < ARRAY_SIZE(edit->set); i++)
-		if (edit->set[i].ptr)
-			*edit->set[i].ptr = edit->set[i].to;
-
-	if (edit->array->root == NULL) {
-		edit->array->nr_leaves_on_tree = 0;
-	} else if (edit->adjust_count_on) {
-		node = edit->adjust_count_on;
-		for (;;) {
-			node->nr_leaves_on_branch += edit->adjust_count_by;
-
-			ptr = node->back_pointer;
-			if (!ptr)
-				break;
-			if (assoc_array_ptr_is_shortcut(ptr)) {
-				shortcut = assoc_array_ptr_to_shortcut(ptr);
-				ptr = shortcut->back_pointer;
-				if (!ptr)
-					break;
-			}
-			BUG_ON(!assoc_array_ptr_is_node(ptr));
-			node = assoc_array_ptr_to_node(ptr);
-		}
-
-		edit->array->nr_leaves_on_tree += edit->adjust_count_by;
-	}
-
-	call_rcu(&edit->rcu, assoc_array_rcu_cleanup);
-}
-
-/**
- * assoc_array_cancel_edit - Discard an edit script.
- * @edit: The script to discard.
- *
- * Free an edit script and all the preallocated data it holds without making
- * any changes to the associative array it was intended for.
- *
- * NOTE!  In the case of an insertion script, this does _not_ release the leaf
- * that was to be inserted.  That is left to the caller.
- */
-void assoc_array_cancel_edit(struct assoc_array_edit *edit)
-{
-	struct assoc_array_ptr *ptr;
-	int i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	/* Clean up after an out of memory error */
-	for (i = 0; i < ARRAY_SIZE(edit->new_meta); i++) {
-		ptr = edit->new_meta[i];
-		if (ptr) {
-			if (assoc_array_ptr_is_node(ptr))
-				kfree(assoc_array_ptr_to_node(ptr));
-			else
-				kfree(assoc_array_ptr_to_shortcut(ptr));
-		}
-	}
-	kfree(edit);
-}
-
-/**
- * assoc_array_gc - Garbage collect an associative array.
- * @array: The array to clean.
- * @ops: The operations to use.
- * @iterator: A callback function to pass judgement on each object.
- * @iterator_data: Private data for the callback function.
- *
- * Collect garbage from an associative array and pack down the internal tree to
- * save memory.
- *
- * The iterator function is asked to pass judgement upon each object in the
- * array.  If it returns false, the object is discard and if it returns true,
- * the object is kept.  If it returns true, it must increment the object's
- * usage count (or whatever it needs to do to retain it) before returning.
- *
- * This function returns 0 if successful or -ENOMEM if out of memory.  In the
- * latter case, the array is not changed.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-int assoc_array_gc(struct assoc_array *array,
-		   const struct assoc_array_ops *ops,
-		   bool (*iterator)(void *object, void *iterator_data),
-		   void *iterator_data)
-{
-	struct assoc_array_shortcut *shortcut, *new_s;
-	struct assoc_array_node *node, *new_n;
-	struct assoc_array_edit *edit;
-	struct assoc_array_ptr *cursor, *ptr;
-	struct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp;
-	unsigned long nr_leaves_on_tree;
-	bool retained;
-	int keylen, slot, nr_free, next_slot, i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	if (!array->root)
-		return 0;
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return -ENOMEM;
-	edit->array = array;
-	edit->ops = ops;
-	edit->ops_for_excised_subtree = ops;
-	edit->set[0].ptr = &array->root;
-	edit->excised_subtree = array->root;
-
-	new_root = new_parent = NULL;
-	new_ptr_pp = &new_root;
-	cursor = array->root;
-
-descend:
-	/* If this point is a shortcut, then we need to duplicate it and
-	 * advance the target cursor.
-	 */
-	if (assoc_array_ptr_is_shortcut(cursor)) {
-		shortcut = assoc_array_ptr_to_shortcut(cursor);
-		keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-		new_s = kmalloc_flex(*new_s, index_key, keylen);
-		if (!new_s)
-			goto enomem;
-		pr_devel("dup shortcut %p -> %p\n", shortcut, new_s);
-		memcpy(new_s, shortcut, struct_size(new_s, index_key, keylen));
-		new_s->back_pointer = new_parent;
-		new_s->parent_slot = shortcut->parent_slot;
-		*new_ptr_pp = new_parent = assoc_array_shortcut_to_ptr(new_s);
-		new_ptr_pp = &new_s->next_node;
-		cursor = shortcut->next_node;
-	}
-
-	/* Duplicate the node at this position */
-	node = assoc_array_ptr_to_node(cursor);
-	new_n = kzalloc_obj(struct assoc_array_node);
-	if (!new_n)
-		goto enomem;
-	pr_devel("dup node %p -> %p\n", node, new_n);
-	new_n->back_pointer = new_parent;
-	new_n->parent_slot = node->parent_slot;
-	*new_ptr_pp = new_parent = assoc_array_node_to_ptr(new_n);
-	new_ptr_pp = NULL;
-	slot = 0;
-
-continue_node:
-	/* Filter across any leaves and gc any subtrees */
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = node->slots[slot];
-		if (!ptr)
-			continue;
-
-		if (assoc_array_ptr_is_leaf(ptr)) {
-			if (iterator(assoc_array_ptr_to_leaf(ptr),
-				     iterator_data))
-				/* The iterator will have done any reference
-				 * counting on the object for us.
-				 */
-				new_n->slots[slot] = ptr;
-			continue;
-		}
-
-		new_ptr_pp = &new_n->slots[slot];
-		cursor = ptr;
-		goto descend;
-	}
-
-retry_compress:
-	pr_devel("-- compress node %p --\n", new_n);
-
-	/* Count up the number of empty slots in this node and work out the
-	 * subtree leaf count.
-	 */
-	new_n->nr_leaves_on_branch = 0;
-	nr_free = 0;
-	for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = new_n->slots[slot];
-		if (!ptr)
-			nr_free++;
-		else if (assoc_array_ptr_is_leaf(ptr))
-			new_n->nr_leaves_on_branch++;
-	}
-	pr_devel("free=%d, leaves=%lu\n", nr_free, new_n->nr_leaves_on_branch);
-
-	/* See what we can fold in */
-	retained = false;
-	next_slot = 0;
-	for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		struct assoc_array_shortcut *s;
-		struct assoc_array_node *child;
-
-		ptr = new_n->slots[slot];
-		if (!ptr || assoc_array_ptr_is_leaf(ptr))
-			continue;
-
-		s = NULL;
-		if (assoc_array_ptr_is_shortcut(ptr)) {
-			s = assoc_array_ptr_to_shortcut(ptr);
-			ptr = s->next_node;
-		}
-
-		child = assoc_array_ptr_to_node(ptr);
-		new_n->nr_leaves_on_branch += child->nr_leaves_on_branch;
-
-		if (child->nr_leaves_on_branch <= nr_free + 1) {
-			/* Fold the child node into this one */
-			pr_devel("[%d] fold node %lu/%d [nx %d]\n",
-				 slot, child->nr_leaves_on_branch, nr_free + 1,
-				 next_slot);
-
-			/* We would already have reaped an intervening shortcut
-			 * on the way back up the tree.
-			 */
-			BUG_ON(s);
-
-			new_n->slots[slot] = NULL;
-			nr_free++;
-			if (slot < next_slot)
-				next_slot = slot;
-			for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-				struct assoc_array_ptr *p = child->slots[i];
-				if (!p)
-					continue;
-				BUG_ON(assoc_array_ptr_is_meta(p));
-				while (new_n->slots[next_slot])
-					next_slot++;
-				BUG_ON(next_slot >= ASSOC_ARRAY_FAN_OUT);
-				new_n->slots[next_slot++] = p;
-				nr_free--;
-			}
-			kfree(child);
-		} else {
-			pr_devel("[%d] retain node %lu/%d [nx %d]\n",
-				 slot, child->nr_leaves_on_branch, nr_free + 1,
-				 next_slot);
-			retained = true;
-		}
-	}
-
-	if (retained && new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) {
-		pr_devel("internal nodes remain despite enough space, retrying\n");
-		goto retry_compress;
-	}
-	pr_devel("after: %lu\n", new_n->nr_leaves_on_branch);
-
-	nr_leaves_on_tree = new_n->nr_leaves_on_branch;
-
-	/* Excise this node if it is singly occupied by a shortcut */
-	if (nr_free == ASSOC_ARRAY_FAN_OUT - 1) {
-		for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++)
-			if ((ptr = new_n->slots[slot]))
-				break;
-
-		if (assoc_array_ptr_is_meta(ptr) &&
-		    assoc_array_ptr_is_shortcut(ptr)) {
-			pr_devel("excise node %p with 1 shortcut\n", new_n);
-			new_s = assoc_array_ptr_to_shortcut(ptr);
-			new_parent = new_n->back_pointer;
-			slot = new_n->parent_slot;
-			kfree(new_n);
-			if (!new_parent) {
-				new_s->back_pointer = NULL;
-				new_s->parent_slot = 0;
-				new_root = ptr;
-				goto gc_complete;
-			}
-
-			if (assoc_array_ptr_is_shortcut(new_parent)) {
-				/* We can discard any preceding shortcut also */
-				struct assoc_array_shortcut *s =
-					assoc_array_ptr_to_shortcut(new_parent);
-
-				pr_devel("excise preceding shortcut\n");
-
-				new_parent = new_s->back_pointer = s->back_pointer;
-				slot = new_s->parent_slot = s->parent_slot;
-				kfree(s);
-				if (!new_parent) {
-					new_s->back_pointer = NULL;
-					new_s->parent_slot = 0;
-					new_root = ptr;
-					goto gc_complete;
-				}
-			}
-
-			new_s->back_pointer = new_parent;
-			new_s->parent_slot = slot;
-			new_n = assoc_array_ptr_to_node(new_parent);
-			new_n->slots[slot] = ptr;
-			goto ascend_old_tree;
-		}
-	}
-
-	/* Excise any shortcuts we might encounter that point to nodes that
-	 * only contain leaves.
-	 */
-	ptr = new_n->back_pointer;
-	if (!ptr)
-		goto gc_complete;
-
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		new_s = assoc_array_ptr_to_shortcut(ptr);
-		new_parent = new_s->back_pointer;
-		slot = new_s->parent_slot;
-
-		if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) {
-			struct assoc_array_node *n;
-
-			pr_devel("excise shortcut\n");
-			new_n->back_pointer = new_parent;
-			new_n->parent_slot = slot;
-			kfree(new_s);
-			if (!new_parent) {
-				new_root = assoc_array_node_to_ptr(new_n);
-				goto gc_complete;
-			}
-
-			n = assoc_array_ptr_to_node(new_parent);
-			n->slots[slot] = assoc_array_node_to_ptr(new_n);
-		}
-	} else {
-		new_parent = ptr;
-	}
-	new_n = assoc_array_ptr_to_node(new_parent);
-
-ascend_old_tree:
-	ptr = node->back_pointer;
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		slot = shortcut->parent_slot;
-		cursor = shortcut->back_pointer;
-		if (!cursor)
-			goto gc_complete;
-	} else {
-		slot = node->parent_slot;
-		cursor = ptr;
-	}
-	BUG_ON(!cursor);
-	node = assoc_array_ptr_to_node(cursor);
-	slot++;
-	goto continue_node;
-
-gc_complete:
-	edit->set[0].to = new_root;
-	assoc_array_apply_edit(edit);
-	array->nr_leaves_on_tree = nr_leaves_on_tree;
-	return 0;
-
-enomem:
-	pr_devel("enomem\n");
-	assoc_array_destroy_subtree(new_root, edit->ops);
-	kfree(edit);
-	return -ENOMEM;
-}
diff --git a/security/keys/Kconfig b/security/keys/Kconfig
index f4510d8cb485f4..3f64d60d0f8a69 100644
--- a/security/keys/Kconfig
+++ b/security/keys/Kconfig
@@ -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.
diff --git a/security/keys/internal.h b/security/keys/internal.h
index b7b622bc36a137..c452d71cce038d 100644
--- a/security/keys/internal.h
+++ b/security/keys/internal.h
@@ -21,6 +21,12 @@
 #include <linux/vmalloc.h>
 
 struct iovec;
+struct keyring_link;
+
+struct keyring_edit {
+	struct keyring_link *new;
+	struct keyring_link *old;
+};
 
 #ifdef __KDEBUG
 #define kenter(FMT, ...) \
@@ -98,13 +104,13 @@ extern int __key_move_lock(struct key *l_keyring, struct key *u_keyring,
 			   const struct keyring_index_key *index_key);
 extern int __key_link_begin(struct key *keyring,
 			    const struct keyring_index_key *index_key,
-			    struct assoc_array_edit **_edit);
+			    struct keyring_edit *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_edit *edit);
 extern void __key_link_end(struct key *keyring,
 			   const struct keyring_index_key *index_key,
-			   struct assoc_array_edit *edit);
+			   struct keyring_edit *edit);
 
 extern key_ref_t find_key_to_update(key_ref_t keyring_ref,
 				    const struct keyring_index_key *index_key);
@@ -122,7 +128,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;
diff --git a/security/keys/key.c b/security/keys/key.c
index 3f1f0fc137109a..20cf273cf4a3de 100644
--- a/security/keys/key.c
+++ b/security/keys/key.c
@@ -430,7 +430,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_edit *edit)
 {
 	int ret, awaken;
 
@@ -461,7 +461,7 @@ static int __key_instantiate_and_link(struct key *key,
 				if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
 					set_bit(KEY_FLAG_KEEP, &key->flags);
 
-				__key_link(keyring, key, _edit);
+				__key_link(keyring, key, edit);
 			}
 
 			/* disable the authorisation key */
@@ -505,7 +505,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_edit edit = {};
 	int ret;
 
 	memset(&prep, 0, sizeof(prep));
@@ -543,7 +543,7 @@ int key_instantiate_and_link(struct key *key,
 
 error_link_end:
 	if (keyring)
-		__key_link_end(keyring, &key->index_key, edit);
+		__key_link_end(keyring, &key->index_key, &edit);
 
 error:
 	if (key->type->preparse)
@@ -580,7 +580,7 @@ int key_reject_and_link(struct key *key,
 			struct key *keyring,
 			struct key *authkey)
 {
-	struct assoc_array_edit *edit = NULL;
+	struct keyring_edit edit = {};
 	int ret, awaken, link_ret = 0;
 
 	key_check(key);
@@ -599,12 +599,12 @@ int key_reject_and_link(struct key *key,
 			 * concurrent restriction install.
 			 */
 			if (keyring->restrict_link) {
-				__key_link_end(keyring, &key->index_key, edit);
+				__key_link_end(keyring, &key->index_key, &edit);
 				return -EPERM;
 			}
 			link_ret = __key_link_begin(keyring, &key->index_key, &edit);
 			if (link_ret < 0)
-				__key_link_end(keyring, &key->index_key, edit);
+				__key_link_end(keyring, &key->index_key, &edit);
 		}
 	}
 
@@ -635,7 +635,7 @@ int key_reject_and_link(struct key *key,
 	mutex_unlock(&key_construction_mutex);
 
 	if (keyring && link_ret == 0)
-		__key_link_end(keyring, &key->index_key, edit);
+		__key_link_end(keyring, &key->index_key, &edit);
 
 	/* wake up anyone waiting for a key to be constructed */
 	if (awaken)
@@ -825,7 +825,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_edit edit = {};
 	const struct cred *cred = current_cred();
 	struct key *keyring, *key = NULL;
 	key_ref_t key_ref;
@@ -966,7 +966,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
 	key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
 
 error_link_end:
-	__key_link_end(keyring, &index_key, edit);
+	__key_link_end(keyring, &index_key, &edit);
 error_free_prep:
 	if (index_key.type->preparse)
 		index_key.type->free_preparse(&prep);
@@ -979,7 +979,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
 	/* we found a matching key, so we're going to try to update it
 	 * - we can drop the locks first as we have the key pinned
 	 */
-	__key_link_end(keyring, &index_key, edit);
+	__key_link_end(keyring, &index_key, &edit);
 
 	key = key_ref_to_ptr(key_ref);
 	if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) {
diff --git a/security/keys/keyring.c b/security/keys/keyring.c
index 5281da9d5bf750..6761c6801edcd8 100644
--- a/security/keys/keyring.c
+++ b/security/keys/keyring.c
@@ -12,14 +12,15 @@
 #include <linux/security.h>
 #include <linux/seq_file.h>
 #include <linux/err.h>
+#include <linux/jhash.h>
 #include <linux/user_namespace.h>
 #include <linux/nsproxy.h>
 #include <linux/once.h>
 #include <linux/random.h>
+#include <linux/rhashtable.h>
 #include <linux/siphash.h>
+#include <linux/workqueue.h>
 #include <keys/keyring-type.h>
-#include <keys/user-type.h>
-#include <linux/assoc_array_priv.h>
 #include <linux/uaccess.h>
 #include <net/net_namespace.h>
 #include "internal.h"
@@ -31,25 +32,153 @@
 #define KEYRING_SEARCH_MAX_DEPTH 6
 
 /*
- * We mark pointers we pass to the associative array with bit 1 set if
- * they're keyrings and clear otherwise.
+ * Keyrings are inserted at the head of @list, other keys at the tail, so
+ * recursive search can stop at the first non-keyring.
  */
-#define KEYRING_PTR_SUBTYPE	0x2UL
+struct keyring_index {
+	struct rhashtable	ht;
+	struct list_head	list;		/* Active keys */
+	unsigned long		nr;		/* Number of active keys */
+	struct rcu_work		rcu_work;
+};
+
+/*
+ * __key_link_begin() inserts new links with @key NULL so allocation happens
+ * before __key_link().  @hash is cached so resizing can hash links while @key
+ * is NULL.
+ */
+struct keyring_link {
+	struct rcu_head		rcu;
+	struct rhash_head	node;
+	struct key __rcu	*key;		/* NULL while inactive */
+	struct list_head	list;
+	u32			hash;
+};
+
+static u32 keyring_hashfn(const void *data, u32 len, u32 seed)
+{
+	const struct keyring_index_key *index_key = data;
+
+	return jhash_1word(index_key->hash, seed);
+}
 
-static inline bool keyring_ptr_is_keyring(const struct assoc_array_ptr *x)
+static u32 keyring_obj_hashfn(const void *data, u32 len, u32 seed)
 {
-	return (unsigned long)x & KEYRING_PTR_SUBTYPE;
+	const struct keyring_link *link = data;
+
+	return jhash_1word(link->hash, seed);
 }
-static inline struct key *keyring_ptr_to_key(const struct assoc_array_ptr *x)
+
+static bool keyring_index_key_equal(const struct keyring_index_key *a,
+				    const struct keyring_index_key *b)
 {
-	void *object = assoc_array_ptr_to_leaf(x);
-	return (struct key *)((unsigned long)object & ~KEYRING_PTR_SUBTYPE);
+	return a->type == b->type &&
+		a->domain_tag == b->domain_tag &&
+		a->desc_len == b->desc_len &&
+		memcmp(a->description, b->description, a->desc_len) == 0;
 }
-static inline void *keyring_key_to_ptr(struct key *key)
+
+static struct key *keyring_link_key(const struct keyring_link *link)
 {
-	if (key->type == &key_type_keyring)
-		return (void *)((unsigned long)key | KEYRING_PTR_SUBTYPE);
-	return key;
+	return rcu_dereference_check(link->key, true);
+}
+
+static int keyring_obj_cmpfn(struct rhashtable_compare_arg *arg,
+			     const void *obj)
+{
+	const struct keyring_link *link = obj;
+	const struct key *key = keyring_link_key(link);
+
+	return !key || !keyring_index_key_equal(&key->index_key, arg->key);
+}
+
+static const struct rhashtable_params keyring_link_params = {
+	.head_offset		= offsetof(struct keyring_link, node),
+	.hashfn			= keyring_hashfn,
+	.obj_hashfn		= keyring_obj_hashfn,
+	.obj_cmpfn		= keyring_obj_cmpfn,
+	.min_size		= 4,
+	.nelem_hint		= 3,
+	.automatic_shrinking	= true,
+	.insecure_elasticity	= true,
+};
+
+static struct keyring_index *keyring_index_locked(const struct key *keyring)
+{
+	return rcu_dereference_protected(keyring->index,
+					 lockdep_is_held(&keyring->sem));
+}
+
+static struct keyring_link *keyring_find_link(struct keyring_index *index,
+					      const struct keyring_index_key *index_key)
+{
+	if (!index)
+		return NULL;
+
+	return rhashtable_lookup_fast(&index->ht, index_key, keyring_link_params);
+}
+
+static int keyring_iterate(const struct key *keyring,
+			   int (*iterator)(const struct key *key, void *data),
+			   void *data)
+{
+	struct keyring_index *index;
+	struct keyring_link *link;
+	int ret;
+
+	guard(rcu)();
+	index = rcu_dereference(keyring->index);
+	if (index) {
+		list_for_each_entry_rcu(link, &index->list, list) {
+			ret = iterator(keyring_link_key(link), data);
+			if (ret)
+				return ret;
+		}
+	}
+
+	return 0;
+}
+
+static void keyring_link_free_rcu(struct rcu_head *rcu)
+{
+	struct keyring_link *link = container_of(rcu, struct keyring_link, rcu);
+
+	key_put(rcu_dereference_raw(link->key));
+	kfree(link);
+}
+
+static void __keyring_index_free(struct keyring_index *index)
+{
+	struct keyring_link *link, *tmp;
+
+	rhashtable_destroy(&index->ht);
+
+	list_for_each_entry_safe(link, tmp, &index->list, list) {
+		key_put(rcu_dereference_protected(link->key, true));
+		kfree(link);
+	}
+
+	kfree(index);
+}
+
+static void keyring_index_free_work(struct work_struct *work)
+{
+	struct keyring_index *index = container_of(to_rcu_work(work),
+						 struct keyring_index, rcu_work);
+
+	__keyring_index_free(index);
+}
+
+static void keyring_index_free(struct key *keyring)
+{
+	struct keyring_index *index = keyring_index_locked(keyring);
+
+	if (!index)
+		return;
+
+	rcu_assign_pointer(keyring->index, NULL);
+	/* rhashtable_destroy() may sleep, so defer via rcu_work. */
+	queue_rcu_work(system_dfl_wq, &index->rcu_work);
 }
 
 static DEFINE_RWLOCK(keyring_name_lock);
@@ -143,80 +272,44 @@ static void keyring_free_preparse(struct key_preparsed_payload *prep)
 static int keyring_instantiate(struct key *keyring,
 			       struct key_preparsed_payload *prep)
 {
-	assoc_array_init(&keyring->keys);
+	RCU_INIT_POINTER(keyring->index, NULL);
 	/* make the keyring available by name if it has one */
 	keyring_publish_name(keyring);
 	return 0;
 }
 
 /*
- * Give key types and domains address-independent identities.  Zero means that
- * an ID has not yet been allocated.  As with inode sequence numbers used by
- * futexes, this relies on the 64-bit counter not wrapping in a machine's
- * lifetime.
- */
-static u64 key_index_id(atomic64_t *id)
-{
-	static atomic64_t next_id;
-	u64 old, new;
-
-	old = atomic64_read(id);
-	if (likely(old))
-		return old;
-
-	do {
-		new = atomic64_inc_return(&next_id);
-	} while (WARN_ON_ONCE(!new));
-
-	old = 0;
-	if (!atomic64_try_cmpxchg_relaxed(id, &old, new))
-		return old;
-	return new;
-}
-
-/*
- * Hash a key type, domain and description.  KEYCTL_READ exposes the tree's
- * traversal order, so no part of the index may contain kernel addresses.
+ * Hash a key type, domain and description.
  */
 static void hash_key_type_and_desc(struct keyring_index_key *index_key)
 {
-	const unsigned level_shift = ASSOC_ARRAY_LEVEL_STEP;
-	const unsigned long fan_mask = ASSOC_ARRAY_FAN_MASK;
 	static siphash_key_t hash_key __read_mostly;
-	unsigned long hash;
 	u64 acc;
 
+	/*
+	 * 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.
+	 */
 	get_random_once(&hash_key, sizeof(hash_key));
 	acc = siphash(index_key->description, index_key->desc_len, &hash_key);
-	acc = siphash_3u64(index_key->type_id, index_key->domain_id, acc,
-			   &hash_key);
-
-	/* Fold the hash down to 32 bits if need be. */
-	hash = acc;
-	if (ASSOC_ARRAY_KEY_CHUNK_SIZE == 32)
-		hash ^= acc >> 32;
-
-	/* Squidge all the keyrings into a separate part of the tree to
-	 * ordinary keys by making sure the lowest level segment in the hash is
-	 * zero for keyrings and non-zero otherwise.
-	 */
-	if (index_key->type != &key_type_keyring && (hash & fan_mask) == 0)
-		hash |= (hash >> (ASSOC_ARRAY_KEY_CHUNK_SIZE - level_shift)) | 1;
-	else if (index_key->type == &key_type_keyring && (hash & fan_mask) != 0)
-		hash = (hash + (hash << level_shift)) & ~fan_mask;
-	index_key->hash = hash;
+	index_key->hash = siphash_3u64((uintptr_t)index_key->type,
+				       (uintptr_t)index_key->domain_tag,
+				       acc, &hash_key);
 }
 
 /*
- * Finalise an index key to include a part of the description actually in the
- * index key, to set the domain tag and index IDs, and to calculate the hash.
+ * Finalise an index key to 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), };
-	size_t n = min_t(size_t, index_key->desc_len, sizeof(index_key->desc));
-
-	memcpy(index_key->desc, index_key->description, n);
 
 	if (!index_key->domain_tag) {
 		if (index_key->type->flags & KEY_TYPE_NET_DOMAIN)
@@ -225,14 +318,6 @@ void key_set_index_key(struct keyring_index_key *index_key)
 			index_key->domain_tag = &default_domain_tag;
 	}
 
-	/* Preserve the IDs when copying an existing key's index.  In
-	 * particular, its type may already have been unregistered.
-	 */
-	if (!index_key->type_id)
-		index_key->type_id = key_index_id(&index_key->type->index_id);
-	if (!index_key->domain_id)
-		index_key->domain_id = key_index_id(&index_key->domain_tag->index_id);
-
 	hash_key_type_and_desc(index_key);
 }
 
@@ -268,150 +353,6 @@ void key_remove_domain(struct key_tag *domain_tag)
 		key_schedule_gc_links();
 }
 
-/*
- * 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;
-	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;
-
-	d = index_key->description + offset;
-	desc_len -= offset;
-	if (desc_len > n)
-		desc_len = n;
-	d += desc_len;
-	do {
-		chunk <<= 8;
-		chunk |= *--d;
-	} while (--desc_len > 0);
-	return chunk;
-}
-
-static unsigned long keyring_get_object_key_chunk(const void *object, int level)
-{
-	const struct key *key = keyring_ptr_to_key(object);
-	return keyring_get_key_chunk(&key->index_key, level);
-}
-
-static bool keyring_compare_object(const void *object, const void *data)
-{
-	const struct keyring_index_key *index_key = data;
-	const struct key *key = keyring_ptr_to_key(object);
-
-	return key->index_key.type == index_key->type &&
-		key->index_key.domain_tag == index_key->domain_tag &&
-		key->index_key.desc_len == index_key->desc_len &&
-		memcmp(key->index_key.description, index_key->description,
-		       index_key->desc_len) == 0;
-}
-
-/*
- * Compare the index keys of a pair of objects and determine the bit position
- * at which they differ - if they differ.
- */
-static int keyring_diff_objects(const void *object, const void *data)
-{
-	const struct key *key_a = keyring_ptr_to_key(object);
-	const struct keyring_index_key *a = &key_a->index_key;
-	const struct keyring_index_key *b = data;
-	unsigned long seg_a, seg_b;
-	int level, i;
-	u64 diff;
-
-	level = 0;
-	seg_a = a->hash;
-	seg_b = b->hash;
-	if ((seg_a ^ seg_b) != 0)
-		goto differ;
-	level += ASSOC_ARRAY_KEY_CHUNK_SIZE / 8;
-
-	/* The inline description contributes one machine-word-sized chunk. */
-	seg_a = a->x;
-	seg_b = b->x;
-	if ((seg_a ^ seg_b) != 0)
-		goto differ;
-	level += sizeof(unsigned long);
-
-	diff = a->type_id ^ b->type_id;
-	if (diff)
-		return level * 8 + __ffs64(diff);
-	level += sizeof(u64);
-
-	diff = a->domain_id ^ b->domain_id;
-	if (diff)
-		return level * 8 + __ffs64(diff);
-	level += sizeof(u64);
-
-	i = sizeof(a->desc);
-	if (a->desc_len <= i)
-		goto same;
-
-	for (; i < a->desc_len; i++) {
-		seg_a = *(unsigned char *)(a->description + i);
-		seg_b = *(unsigned char *)(b->description + i);
-		if ((seg_a ^ seg_b) != 0)
-			goto differ_plus_i;
-	}
-
-same:
-	return -1;
-
-differ_plus_i:
-	level += i - (int)sizeof(a->desc);
-differ:
-	i = level * 8 + __ffs(seg_a ^ seg_b);
-	return i;
-}
-
-/*
- * Free an object after stripping the keyring flag off of the pointer.
- */
-static void keyring_free_object(void *object)
-{
-	key_put(keyring_ptr_to_key(object));
-}
-
-/*
- * Operations for keyring management by the index-tree routines.
- */
-static const struct assoc_array_ops keyring_assoc_array_ops = {
-	.get_key_chunk		= keyring_get_key_chunk,
-	.get_object_key_chunk	= keyring_get_object_key_chunk,
-	.compare_object		= keyring_compare_object,
-	.diff_objects		= keyring_diff_objects,
-	.free_object		= keyring_free_object,
-};
-
 /*
  * Clean up a keyring when it is destroyed.  Unpublish its name if it had one
  * and dispose of its data.
@@ -423,6 +364,8 @@ static const struct assoc_array_ops keyring_assoc_array_ops = {
  */
 static void keyring_destroy(struct key *keyring)
 {
+	struct keyring_index *index;
+
 	if (keyring->description) {
 		write_lock(&keyring_name_lock);
 
@@ -440,49 +383,51 @@ static void keyring_destroy(struct key *keyring)
 		kfree(keyres);
 	}
 
-	assoc_array_destroy(&keyring->keys, &keyring_assoc_array_ops);
+	index = rcu_dereference_protected(keyring->index, true);
+	if (index)
+		__keyring_index_free(index);
+}
+
+static unsigned long keyring_nr_links(const struct key *keyring)
+{
+	const struct keyring_index *index;
+
+	guard(rcu)();
+	index = rcu_dereference(keyring->index);
+	return index ? READ_ONCE(index->nr) : 0;
+}
+
+/**
+ * keyring_is_empty - Check whether a keyring is empty
+ * @keyring: The keyring to check.
+ */
+bool keyring_is_empty(const struct key *keyring)
+{
+	return keyring_nr_links(keyring) == 0;
 }
+EXPORT_SYMBOL(keyring_is_empty);
 
 /*
  * Describe a keyring for /proc.
  */
 static void keyring_describe(const struct key *keyring, struct seq_file *m)
 {
+	unsigned long nr;
+
 	if (keyring->description)
 		seq_puts(m, keyring->description);
 	else
 		seq_puts(m, "[anon]");
 
 	if (key_is_positive(keyring)) {
-		if (keyring->keys.nr_leaves_on_tree != 0)
-			seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree);
+		nr = keyring_nr_links(keyring);
+		if (nr != 0)
+			seq_printf(m, ": %lu", nr);
 		else
 			seq_puts(m, ": empty");
 	}
 }
 
-struct keyring_read_iterator_context {
-	size_t			buflen;
-	size_t			count;
-	key_serial_t		*buffer;
-};
-
-static int keyring_read_iterator(const void *object, void *data)
-{
-	struct keyring_read_iterator_context *ctx = data;
-	const struct key *key = keyring_ptr_to_key(object);
-
-	kenter("{%s,%d},,{%zu/%zu}",
-	       key->type->name, key->serial, ctx->count, ctx->buflen);
-
-	if (ctx->count >= ctx->buflen)
-		return 1;
-
-	*ctx->buffer++ = key->serial;
-	ctx->count += sizeof(key->serial);
-	return 0;
-}
-
 /*
  * Read a list of key IDs from the keyring's contents in binary form
  *
@@ -493,7 +438,10 @@ static int keyring_read_iterator(const void *object, void *data)
 static long keyring_read(const struct key *keyring,
 			 char *buffer, size_t buflen)
 {
-	struct keyring_read_iterator_context ctx;
+	struct keyring_index *links = keyring_index_locked(keyring);
+	key_serial_t *serials = (key_serial_t *)buffer;
+	struct keyring_link *link;
+	size_t count = 0;
 	long ret;
 
 	kenter("{%d},,%zu", key_serial(keyring), buflen);
@@ -501,25 +449,22 @@ static long keyring_read(const struct key *keyring,
 	if (buflen & (sizeof(key_serial_t) - 1))
 		return -EINVAL;
 
-	/* Copy as many key IDs as fit into the buffer */
-	if (buffer && buflen) {
-		ctx.buffer = (key_serial_t *)buffer;
-		ctx.buflen = buflen;
-		ctx.count = 0;
-		ret = assoc_array_iterate(&keyring->keys,
-					  keyring_read_iterator, &ctx);
-		if (ret < 0) {
-			kleave(" = %ld [iterate]", ret);
-			return ret;
+	if (buffer && buflen && links) {
+		list_for_each_entry(link, &links->list, list) {
+			if (count == buflen / sizeof(*serials))
+				break;
+
+			serials[count++] = keyring_link_key(link)->serial;
+			cond_resched();
 		}
 	}
 
-	/* Return the size of the buffer needed */
-	ret = keyring->keys.nr_leaves_on_tree * sizeof(key_serial_t);
+	ret = links ? links->nr * sizeof(key_serial_t) : 0;
 	if (ret <= buflen)
 		kleave("= %ld [ok]", ret);
 	else
 		kleave("= %ld [buffer too small]", ret);
+
 	return ret;
 }
 
@@ -583,10 +528,9 @@ bool key_default_cmp(const struct key *key,
 /*
  * Iteration function to consider each key found.
  */
-static int keyring_search_iterator(const void *object, void *iterator_data)
+static int keyring_search_iterator(const struct key *key, void *iterator_data)
 {
 	struct keyring_search_context *ctx = iterator_data;
-	const struct key *key = keyring_ptr_to_key(object);
 	unsigned long kflags = READ_ONCE(key->flags);
 	short state = key_read_state(key);
 
@@ -653,19 +597,78 @@ static int keyring_search_iterator(const void *object, void *iterator_data)
 /*
  * 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.
+ * list looking for it, based on the match function.
  */
 static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)
 {
 	if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) {
-		const void *object;
+		struct keyring_link *link;
+		struct key *key;
+
+		link = keyring_find_link(rcu_dereference(keyring->index),
+					 &ctx->index_key);
+		if (!link)
+			return 0;
+		key = keyring_link_key(link);
+		return ctx->iterator(key, ctx);
+	}
+
+	return keyring_iterate(keyring, ctx->iterator, ctx);
+}
 
-		object = assoc_array_find(&keyring->keys,
-					  &keyring_assoc_array_ops,
-					  &ctx->index_key);
-		return object ? ctx->iterator(object, ctx) : 0;
+/*
+ * Depth-first search of @keyring and its nested keyrings.
+ */
+static int search_keyring_tree(struct key *keyring,
+			       struct keyring_search_context *ctx, int depth)
+{
+	struct keyring_index *links;
+	struct keyring_link *link;
+	int ret;
+
+	if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
+			      (1 << KEY_FLAG_REVOKED)))
+		return 0;
+
+	if (search_keyring(keyring, ctx))
+		goto found;
+
+	if (!(ctx->flags & KEYRING_SEARCH_RECURSE))
+		return 0;
+	links = rcu_dereference(keyring->index);
+	if (!links)
+		return 0;
+
+	list_for_each_entry_rcu(link, &links->list, list) {
+		struct key *key = keyring_link_key(link);
+
+		if (key->type != &key_type_keyring)
+			break;
+		if (depth >= KEYRING_SEARCH_MAX_DEPTH) {
+			if (!(ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP))
+				return 0;
+			ctx->result = ERR_PTR(-ELOOP);
+			return -ELOOP;
+		}
+
+		if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
+		    key_task_permission(make_key_ref(key, ctx->possessed),
+					ctx->cred, KEY_NEED_SEARCH) < 0)
+			continue;
+
+		ret = search_keyring_tree(key, ctx, depth + 1);
+		if (ret < 0)
+			return ret;
+		if (ret)
+			goto found;
 	}
-	return assoc_array_iterate(&keyring->keys, ctx->iterator, ctx);
+
+	return 0;
+
+found:
+	if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME))
+		keyring->last_used_at = ctx->now;
+	return 1;
 }
 
 /*
@@ -675,17 +678,7 @@ static int search_keyring(struct key *keyring, struct keyring_search_context *ct
 static bool search_nested_keyrings(struct key *keyring,
 				   struct keyring_search_context *ctx)
 {
-	struct {
-		struct key *keyring;
-		struct assoc_array_node *node;
-		int slot;
-	} stack[KEYRING_SEARCH_MAX_DEPTH];
-
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *ptr;
 	struct key *key;
-	int sp = 0, slot;
 
 	kenter("{%d},{%s,%s}",
 	       keyring->serial,
@@ -703,9 +696,9 @@ static bool search_nested_keyrings(struct key *keyring,
 	 * and whether it is valid or not.
 	 */
 	if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||
-	    keyring_compare_object(keyring, &ctx->index_key)) {
+	    keyring_index_key_equal(&keyring->index_key, &ctx->index_key)) {
 		ctx->skipped_ret = 2;
-		switch (ctx->iterator(keyring_key_to_ptr(keyring), ctx)) {
+		switch (ctx->iterator(keyring, ctx)) {
 		case 1:
 			goto found;
 		case 2:
@@ -717,152 +710,11 @@ static bool search_nested_keyrings(struct key *keyring,
 
 	ctx->skipped_ret = 0;
 
-	/* Start processing a new keyring */
-descend_to_keyring:
-	kdebug("descend to %d", keyring->serial);
-	if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
-			      (1 << KEY_FLAG_REVOKED)))
-		goto not_this_keyring;
-
-	/* Search through the keys in this keyring before its searching its
-	 * subtrees.
-	 */
-	if (search_keyring(keyring, ctx))
-		goto found;
-
-	/* Then manually iterate through the keyrings nested in this one.
-	 *
-	 * Start from the root node of the index tree.  Because of the way the
-	 * hash function has been set up, keyrings cluster on the leftmost
-	 * branch of the root node (root slot 0) or in the root node itself.
-	 * Non-keyrings avoid the leftmost branch of the root entirely (root
-	 * slots 1-15).
-	 */
-	if (!(ctx->flags & KEYRING_SEARCH_RECURSE))
-		goto not_this_keyring;
-
-	ptr = READ_ONCE(keyring->keys.root);
-	if (!ptr)
-		goto not_this_keyring;
-
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		/* If the root is a shortcut, either the keyring only contains
-		 * keyring pointers (everything clusters behind root slot 0) or
-		 * doesn't contain any keyring pointers.
-		 */
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		if ((shortcut->index_key[0] & ASSOC_ARRAY_FAN_MASK) != 0)
-			goto not_this_keyring;
-
-		ptr = READ_ONCE(shortcut->next_node);
-		node = assoc_array_ptr_to_node(ptr);
-		goto begin_node;
-	}
-
-	node = assoc_array_ptr_to_node(ptr);
-	ptr = node->slots[0];
-	if (!assoc_array_ptr_is_meta(ptr))
-		goto begin_node;
-
-descend_to_node:
-	/* Descend to a more distal node in this keyring's content tree and go
-	 * through that.
-	 */
-	kdebug("descend");
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		ptr = READ_ONCE(shortcut->next_node);
-		BUG_ON(!assoc_array_ptr_is_node(ptr));
-	}
-	node = assoc_array_ptr_to_node(ptr);
-
-begin_node:
-	kdebug("begin_node");
-	slot = 0;
-ascend_to_node:
-	/* Go through the slots in a node */
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]);
-
-		if (assoc_array_ptr_is_meta(ptr)) {
-			if (node->back_pointer ||
-			    assoc_array_ptr_is_shortcut(ptr))
-				goto descend_to_node;
-		}
-
-		if (!keyring_ptr_is_keyring(ptr))
-			continue;
-
-		key = keyring_ptr_to_key(ptr);
-
-		if (sp >= KEYRING_SEARCH_MAX_DEPTH) {
-			if (ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP) {
-				ctx->result = ERR_PTR(-ELOOP);
-				return false;
-			}
-			goto not_this_keyring;
-		}
-
-		/* Search a nested keyring */
-		if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
-		    key_task_permission(make_key_ref(key, ctx->possessed),
-					ctx->cred, KEY_NEED_SEARCH) < 0)
-			continue;
-
-		/* stack the current position */
-		stack[sp].keyring = keyring;
-		stack[sp].node = node;
-		stack[sp].slot = slot;
-		sp++;
-
-		/* begin again with the new keyring */
-		keyring = key;
-		goto descend_to_keyring;
-	}
-
-	/* We've dealt with all the slots in the current node, so now we need
-	 * to ascend to the parent and continue processing there.
-	 */
-	ptr = READ_ONCE(node->back_pointer);
-	slot = node->parent_slot;
-
-	if (ptr && assoc_array_ptr_is_shortcut(ptr)) {
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		ptr = READ_ONCE(shortcut->back_pointer);
-		slot = shortcut->parent_slot;
-	}
-	if (!ptr)
-		goto not_this_keyring;
-	node = assoc_array_ptr_to_node(ptr);
-	slot++;
-
-	/* If we've ascended to the root (zero backpointer), we must have just
-	 * finished processing the leftmost branch rather than the root slots -
-	 * so there can't be any more keyrings for us to find.
-	 */
-	if (node->back_pointer) {
-		kdebug("ascend %d", slot);
-		goto ascend_to_node;
-	}
-
-	/* The keyring we're looking at was disqualified or didn't contain a
-	 * matching key.
-	 */
-not_this_keyring:
-	kdebug("not_this_keyring %d", sp);
-	if (sp <= 0) {
+	if (search_keyring_tree(keyring, ctx, 0) <= 0) {
 		kleave(" = false");
 		return false;
 	}
 
-	/* Resume the processing of a keyring higher up in the tree */
-	sp--;
-	keyring = stack[sp].keyring;
-	node = stack[sp].node;
-	slot = stack[sp].slot + 1;
-	kdebug("ascend to %d [%d]", keyring->serial, slot);
-	goto ascend_to_node;
-
 	/* We found a viable match */
 found:
 	key = key_ref_to_ptr(ctx->result);
@@ -870,8 +722,6 @@ static bool search_nested_keyrings(struct key *keyring,
 	if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) {
 		key->last_used_at = ctx->now;
 		keyring->last_used_at = ctx->now;
-		while (sp > 0)
-			stack[--sp].keyring->last_used_at = ctx->now;
 	}
 	kleave(" = true");
 	return true;
@@ -1118,8 +968,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);
 
@@ -1127,17 +977,16 @@ key_ref_t find_key_to_update(key_ref_t keyring_ref,
 	       keyring->serial, index_key->type->name, index_key->description);
 
 	guard(rcu)();
-	object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
-				  index_key);
+	link = keyring_find_link(rcu_dereference(keyring->index), index_key);
 
-	if (object)
+	if (link)
 		goto found;
 
 	kleave(" = NULL");
 	return NULL;
 
 found:
-	key = keyring_ptr_to_key(object);
+	key = keyring_link_key(link);
 	if (key->flags & ((1 << KEY_FLAG_INVALIDATED) |
 			  (1 << KEY_FLAG_REVOKED))) {
 		kleave(" = NULL [x]");
@@ -1207,11 +1056,10 @@ struct key *find_keyring_by_name(const char *name, bool uid_keyring)
 	return keyring;
 }
 
-static int keyring_detect_cycle_iterator(const void *object,
+static int keyring_detect_cycle_iterator(const struct key *key,
 					 void *iterator_data)
 {
 	struct keyring_search_context *ctx = iterator_data;
-	const struct key *key = keyring_ptr_to_key(object);
 
 	kenter("{%d}", key->serial);
 
@@ -1307,56 +1155,90 @@ int __key_move_lock(struct key *l_keyring, struct key *u_keyring,
 	return 0;
 }
 
+static struct keyring_index *keyring_get_index(struct key *keyring)
+{
+	struct keyring_index *links = keyring_index_locked(keyring);
+	int ret;
+
+	if (links)
+		return links;
+
+	links = kzalloc_obj(struct keyring_index);
+	if (!links)
+		return ERR_PTR(-ENOMEM);
+	ret = rhashtable_init(&links->ht, &keyring_link_params);
+	if (ret < 0) {
+		kfree(links);
+		return ERR_PTR(ret);
+	}
+
+	INIT_LIST_HEAD(&links->list);
+	INIT_RCU_WORK(&links->rcu_work, keyring_index_free_work);
+	rcu_assign_pointer(keyring->index, links);
+	return links;
+}
+
 /*
  * Preallocate memory so that a key can be linked into to a keyring.
  */
 int __key_link_begin(struct key *keyring,
 		     const struct keyring_index_key *index_key,
-		     struct assoc_array_edit **_edit)
+		     struct keyring_edit *edit)
 {
-	struct assoc_array_edit *edit;
+	struct keyring_link *link __free(kfree) = NULL;
+	struct keyring_link *replace;
+	struct keyring_index *links;
 	int ret;
 
 	kenter("%d,%s,%s,",
 	       keyring->serial, index_key->type->name, index_key->description);
 
-	BUG_ON(index_key->desc_len == 0);
-	BUG_ON(*_edit != NULL);
+	if (WARN_ON(index_key->desc_len == 0) || WARN_ON(edit->new))
+		return -EINVAL;
 
-	*_edit = NULL;
+	edit->new = NULL;
+	edit->old = NULL;
 
 	ret = -EKEYREVOKED;
 	if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
 		goto error;
 
-	/* Create an edit script that will insert/replace the key in the
-	 * keyring tree.
-	 */
-	edit = assoc_array_insert(&keyring->keys,
-				  &keyring_assoc_array_ops,
-				  index_key,
-				  NULL);
-	if (IS_ERR(edit)) {
-		ret = PTR_ERR(edit);
+	links = keyring_get_index(keyring);
+	if (IS_ERR(links)) {
+		ret = PTR_ERR(links);
 		goto error;
 	}
 
+	ret = -ENOMEM;
+	link = kzalloc_obj(struct keyring_link);
+	if (!link)
+		goto error;
+	link->hash = index_key->hash;
+
+	replace = keyring_find_link(links, index_key);
 	/* If we're not replacing a link in-place then we're going to need some
 	 * extra quota.
 	 */
-	if (!edit->dead_leaf) {
+	if (!replace) {
 		ret = key_payload_reserve(keyring,
 					  keyring->datalen + KEYQUOTA_LINK_BYTES);
 		if (ret < 0)
-			goto error_cancel;
+			goto error;
+
+		ret = rhashtable_insert_fast(&links->ht, &link->node,
+					     keyring_link_params);
+		if (ret < 0) {
+			key_payload_reserve(keyring,
+					    keyring->datalen - KEYQUOTA_LINK_BYTES);
+			goto error;
+		}
 	}
 
-	*_edit = edit;
+	edit->new = no_free_ptr(link);
+	edit->old = replace;
 	kleave(" = 0");
 	return 0;
 
-error_cancel:
-	assoc_array_cancel_edit(edit);
 error:
 	kleave(" = %d", ret);
 	return ret;
@@ -1385,13 +1267,35 @@ int __key_link_check_live_key(struct key *keyring, struct key *key)
  * holds at most one link to any given key of a particular type+description
  * combination.
  */
-void __key_link(struct key *keyring, struct key *key,
-		struct assoc_array_edit **_edit)
+void __key_link(struct key *keyring, struct key *key, struct keyring_edit *edit)
 {
+	struct keyring_index *index = keyring_index_locked(keyring);
+	int ret;
+
 	__key_get(key);
-	assoc_array_insert_set_object(*_edit, keyring_key_to_ptr(key));
-	assoc_array_apply_edit(*_edit);
-	*_edit = NULL;
+	rcu_assign_pointer(edit->new->key, key);
+
+	if (edit->old) {
+		ret = rhashtable_replace_fast(&index->ht, &edit->old->node,
+					      &edit->new->node, keyring_link_params);
+		if (WARN_ON(ret)) {
+			key_put(key);
+			return;
+		}
+
+		list_replace_rcu(&edit->old->list, &edit->new->list);
+		call_rcu(&edit->old->rcu, keyring_link_free_rcu);
+	} else {
+		if (key->type == &key_type_keyring)
+			list_add_rcu(&edit->new->list, &index->list);
+		else
+			list_add_tail_rcu(&edit->new->list, &index->list);
+
+		WRITE_ONCE(index->nr, index->nr + 1);
+	}
+
+	edit->new = NULL;
+	edit->old = NULL;
 	notify_key(keyring, NOTIFY_KEY_LINKED, key_serial(key));
 }
 
@@ -1402,20 +1306,31 @@ void __key_link(struct key *keyring, struct key *key,
  */
 void __key_link_end(struct key *keyring,
 		    const struct keyring_index_key *index_key,
-		    struct assoc_array_edit *edit)
+		    struct keyring_edit *edit)
 	__releases(&keyring->sem)
 	__releases(&keyring_serialise_link_lock)
 {
+	struct keyring_link *link = edit->new;
+
 	BUG_ON(index_key->type == NULL);
 	kenter("%d,%s,", keyring->serial, index_key->type->name);
 
-	if (edit) {
-		if (!edit->dead_leaf) {
+	if (link) {
+		if (!edit->old) {
 			key_payload_reserve(keyring,
 				keyring->datalen - KEYQUOTA_LINK_BYTES);
+			WARN_ON(rhashtable_remove_fast(&keyring_index_locked(keyring)->ht,
+						       &link->node,
+						       keyring_link_params));
+			call_rcu(&link->rcu, keyring_link_free_rcu);
+		} else {
+			kfree(link);
 		}
-		assoc_array_cancel_edit(edit);
+
+		edit->new = NULL;
+		edit->old = NULL;
 	}
+
 	up_write(&keyring->sem);
 
 	if (index_key->type == &key_type_keyring)
@@ -1445,9 +1360,9 @@ static int __key_link_check_restriction(struct key *keyring, struct key *key)
  * of the user's key data quota to hold the link.
  *
  * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
- * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
- * full, -EDQUOT if there is insufficient key data quota remaining to add
- * another link or -ENOMEM if there's insufficient memory.
+ * -EKEYREVOKED if the keyring has been revoked, -EDQUOT if there is insufficient
+ * key data quota remaining to add another link or -ENOMEM if there's
+ * insufficient memory.
  *
  * It is assumed that the caller has checked that it is permitted for a link to
  * be made (the keyring should have Write permission and the key Link
@@ -1455,7 +1370,7 @@ static int __key_link_check_restriction(struct key *keyring, struct key *key)
  */
 int key_link(struct key *keyring, struct key *key)
 {
-	struct assoc_array_edit *edit = NULL;
+	struct keyring_edit edit = {};
 	int ret;
 
 	kenter("{%d,%d}", keyring->serial, refcount_read(&keyring->usage));
@@ -1479,7 +1394,7 @@ int key_link(struct key *keyring, struct key *key)
 		__key_link(keyring, key, &edit);
 
 error_end:
-	__key_link_end(keyring, &key->index_key, edit);
+	__key_link_end(keyring, &key->index_key, &edit);
 error:
 	kleave(" = %d {%d,%d}", ret, keyring->serial, refcount_read(&keyring->usage));
 	return ret;
@@ -1503,27 +1418,21 @@ static int __key_unlink_lock(struct key *keyring)
  * Begin the process of unlinking a key from a keyring.
  */
 static int __key_unlink_begin(struct key *keyring, struct key *key,
-			      struct assoc_array_edit **_edit)
+			      struct keyring_link **edit)
 {
-	struct assoc_array_edit *edit;
-	const void *object;
+	struct keyring_link *link;
 
-	BUG_ON(*_edit != NULL);
+	if (WARN_ON(*edit))
+		return -EINVAL;
 
-	object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
-				  &key->index_key);
-	if (!object || keyring_ptr_to_key(object) != key)
+	link = keyring_find_link(keyring_index_locked(keyring), &key->index_key);
+	if (!link)
 		return -ENOENT;
 
-	edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops,
-				  &key->index_key);
-	if (IS_ERR(edit))
-		return PTR_ERR(edit);
-
-	if (!edit)
+	if (keyring_link_key(link) != key)
 		return -ENOENT;
 
-	*_edit = edit;
+	*edit = link;
 	return 0;
 }
 
@@ -1531,27 +1440,22 @@ static int __key_unlink_begin(struct key *keyring, struct key *key,
  * Apply an unlink change.
  */
 static void __key_unlink(struct key *keyring, struct key *key,
-			 struct assoc_array_edit **_edit)
+			 struct keyring_link *link)
 {
-	assoc_array_apply_edit(*_edit);
+	struct keyring_index *index = keyring_index_locked(keyring);
+	int ret;
+
+	ret = rhashtable_remove_fast(&index->ht, &link->node, keyring_link_params);
+	if (WARN_ON(ret))
+		return;
+
+	list_del_rcu(&link->list);
+	WRITE_ONCE(index->nr, index->nr - 1);
+	call_rcu(&link->rcu, keyring_link_free_rcu);
 	notify_key(keyring, NOTIFY_KEY_UNLINKED, key_serial(key));
-	*_edit = NULL;
 	key_payload_reserve(keyring, keyring->datalen - KEYQUOTA_LINK_BYTES);
 }
 
-/*
- * 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);
-}
-
 /**
  * key_unlink - Unlink the first link to a key from a keyring.
  * @keyring: The keyring to remove the link from.
@@ -1561,9 +1465,8 @@ static void __key_unlink_end(struct key *keyring,
  *
  * This function will write-lock the keyring's semaphore.
  *
- * 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.
+ * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring or -ENOENT if
+ * the key isn't linked to by the keyring.
  *
  * It is assumed that the caller has checked that it is permitted for a link to
  * be removed (the keyring should have Write permission; no permissions are
@@ -1571,7 +1474,7 @@ static void __key_unlink_end(struct key *keyring,
  */
 int key_unlink(struct key *keyring, struct key *key)
 {
-	struct assoc_array_edit *edit = NULL;
+	struct keyring_link *edit = NULL;
 	int ret;
 
 	key_check(keyring);
@@ -1583,8 +1486,8 @@ int key_unlink(struct key *keyring, struct key *key)
 
 	ret = __key_unlink_begin(keyring, key, &edit);
 	if (ret == 0)
-		__key_unlink(keyring, key, &edit);
-	__key_unlink_end(keyring, key, edit);
+		__key_unlink(keyring, key, edit);
+	up_write(&keyring->sem);
 	return ret;
 }
 EXPORT_SYMBOL(key_unlink);
@@ -1604,11 +1507,10 @@ EXPORT_SYMBOL(key_unlink);
  * some of the user's key data quota to hold the link on @to_keyring.
  *
  * Returns 0 if successful, -ENOTDIR if either keyring isn't a keyring,
- * -EKEYREVOKED if either keyring has been revoked, -ENFILE if the second
- * keyring is full, -EDQUOT if there is insufficient key data quota remaining
- * to add another link or -ENOMEM if there's insufficient memory.  If
- * KEYCTL_MOVE_EXCL is set, then -EEXIST will be returned if there's already a
- * matching key in @to_keyring.
+ * -EKEYREVOKED if either keyring has been revoked, -EDQUOT if there is
+ * insufficient key data quota remaining to add another link or -ENOMEM if
+ * there's insufficient memory.  If KEYCTL_MOVE_EXCL is set, then -EEXIST will
+ * be returned if there's already a matching key in @to_keyring.
  *
  * It is assumed that the caller has checked that it is permitted for a link to
  * be made (the keyring should have Write permission and the key Link
@@ -1619,7 +1521,8 @@ int key_move(struct key *key,
 	     struct key *to_keyring,
 	     unsigned int flags)
 {
-	struct assoc_array_edit *from_edit = NULL, *to_edit = NULL;
+	struct keyring_link *from_edit = NULL;
+	struct keyring_edit to_edit = {};
 	int ret;
 
 	kenter("%d,%d,%d", key->serial, from_keyring->serial, to_keyring->serial);
@@ -1642,7 +1545,7 @@ int key_move(struct key *key,
 		goto error;
 
 	ret = -EEXIST;
-	if (to_edit->dead_leaf && (flags & KEYCTL_MOVE_EXCL))
+	if (to_edit.old && (flags & KEYCTL_MOVE_EXCL))
 		goto error;
 
 	ret = __key_link_check_restriction(to_keyring, key);
@@ -1652,11 +1555,11 @@ int key_move(struct key *key,
 	if (ret < 0)
 		goto error;
 
-	__key_unlink(from_keyring, key, &from_edit);
+	__key_unlink(from_keyring, key, from_edit);
 	__key_link(to_keyring, key, &to_edit);
 error:
-	__key_link_end(to_keyring, &key->index_key, to_edit);
-	__key_unlink_end(from_keyring, key, from_edit);
+	__key_link_end(to_keyring, &key->index_key, &to_edit);
+	up_write(&from_keyring->sem);
 out:
 	kleave(" = %d", ret);
 	return ret;
@@ -1673,27 +1576,17 @@ EXPORT_SYMBOL(key_move);
  */
 int keyring_clear(struct key *keyring)
 {
-	struct assoc_array_edit *edit;
-	int ret;
-
 	if (keyring->type != &key_type_keyring)
 		return -ENOTDIR;
 
 	down_write(&keyring->sem);
 
-	edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
-	if (IS_ERR(edit)) {
-		ret = PTR_ERR(edit);
-	} else {
-		if (edit)
-			assoc_array_apply_edit(edit);
-		notify_key(keyring, NOTIFY_KEY_CLEARED, 0);
-		key_payload_reserve(keyring, 0);
-		ret = 0;
-	}
+	keyring_index_free(keyring);
+	notify_key(keyring, NOTIFY_KEY_CLEARED, 0);
+	key_payload_reserve(keyring, 0);
 
 	up_write(&keyring->sem);
-	return ret;
+	return 0;
 }
 EXPORT_SYMBOL(keyring_clear);
 
@@ -1704,30 +1597,12 @@ EXPORT_SYMBOL(keyring_clear);
  */
 static void keyring_revoke(struct key *keyring)
 {
-	struct assoc_array_edit *edit;
-
-	edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
-	if (!IS_ERR(edit)) {
-		if (edit)
-			assoc_array_apply_edit(edit);
-		key_payload_reserve(keyring, 0);
-	}
+	keyring_index_free(keyring);
+	key_payload_reserve(keyring, 0);
 }
 
-static bool keyring_gc_select_iterator(void *object, void *iterator_data)
+static int keyring_gc_check_iterator(const struct key *key, void *iterator_data)
 {
-	struct key *key = keyring_ptr_to_key(object);
-	time64_t *limit = iterator_data;
-
-	if (key_is_dead(key, *limit))
-		return false;
-	key_get(key);
-	return true;
-}
-
-static int keyring_gc_check_iterator(const void *object, void *iterator_data)
-{
-	const struct key *key = keyring_ptr_to_key(object);
 	time64_t *limit = iterator_data;
 
 	key_check(key);
@@ -1742,7 +1617,9 @@ static int keyring_gc_check_iterator(const void *object, void *iterator_data)
  */
 void keyring_gc(struct key *keyring, time64_t limit)
 {
-	int result;
+	struct keyring_link *link, *tmp;
+	struct keyring_index *index;
+	int ret;
 
 	kenter("%x{%s}", keyring->serial, keyring->description ?: "");
 
@@ -1751,11 +1628,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();
-	if (result == true)
+	if (keyring_iterate(keyring, keyring_gc_check_iterator, &limit))
 		goto do_gc;
 
 dont_gc:
@@ -1764,8 +1637,23 @@ 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);
+	index = keyring_index_locked(keyring);
+	if (index) {
+		list_for_each_entry_safe(link, tmp, &index->list, list) {
+			if (!key_is_dead(keyring_link_key(link), limit))
+				continue;
+
+			ret = rhashtable_remove_fast(&index->ht, &link->node,
+						     keyring_link_params);
+			if (WARN_ON(ret))
+				break;
+
+			list_del_rcu(&link->list);
+			WRITE_ONCE(index->nr, index->nr - 1);
+			call_rcu(&link->rcu, keyring_link_free_rcu);
+		}
+	}
+
 	up_write(&keyring->sem);
 	kleave(" [gc]");
 }
diff --git a/security/keys/request_key.c b/security/keys/request_key.c
index 22cd66a44da562..40fbcd15be4308 100644
--- a/security/keys/request_key.c
+++ b/security/keys/request_key.c
@@ -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_edit edit = {};
 	struct key *key;
 	key_perm_t perm;
 	key_ref_t key_ref;
@@ -433,7 +433,7 @@ static int construct_alloc_key(struct keyring_search_context *ctx,
 
 	mutex_unlock(&key_construction_mutex);
 	if (dest_keyring)
-		__key_link_end(dest_keyring, &key->index_key, edit);
+		__key_link_end(dest_keyring, &key->index_key, &edit);
 	mutex_unlock(&user->cons_lock);
 	*_key = key;
 	kleave(" = 0 [%d]", key_serial(key));
@@ -452,7 +452,7 @@ static int construct_alloc_key(struct keyring_search_context *ctx,
 		ret = __key_link_check_live_key(dest_keyring, key);
 		if (ret == 0)
 			__key_link(dest_keyring, key, &edit);
-		__key_link_end(dest_keyring, &key->index_key, edit);
+		__key_link_end(dest_keyring, &key->index_key, &edit);
 		if (ret < 0)
 			goto link_check_failed;
 	}
@@ -470,7 +470,7 @@ static int construct_alloc_key(struct keyring_search_context *ctx,
 link_alloc_failed:
 	mutex_unlock(&key_construction_mutex);
 link_alloc_failed_unlocked:
-	__key_link_end(dest_keyring, &key->index_key, edit);
+	__key_link_end(dest_keyring, &key->index_key, &edit);
 link_lock_failed:
 	mutex_unlock(&user->cons_lock);
 	key_put(key);
diff --git a/tools/testing/selftests/dm-verity/test-dm-verity-keyring.sh b/tools/testing/selftests/dm-verity/test-dm-verity-keyring.sh
index 1f9601ef22f859..792449d356cf56 100755
--- a/tools/testing/selftests/dm-verity/test-dm-verity-keyring.sh
+++ b/tools/testing/selftests/dm-verity/test-dm-verity-keyring.sh
@@ -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

3/2 2026/11/10 21:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 59783
							output: 29
							thoughts: 911
						

Thoughts:
**Fuzzing Evaluation: Keyrings Subsystem Rewrite**

Okay, let's break this down. My primary concern here is determining if this patch series warrants syzkaller fuzzing.

Looking at the diff, this is a significant undertaking. The `assoc_array` data structure is completely removed, root and branch. Specifically, all associated code and documentation are gone.

Crucially, this entire patch series *replaces* the `assoc_array` implementation *within the keyring subsystem* with an `rhashtable` combined with a `struct list_head`. This is a MAJOR structural change, fundamentally altering how the kernel manages keys.  We're talking about a complete rewrite of keyring data structures in `security/keys/`!  Every major function is impacted: linking, searching, unlinking, iteration, garbage collection, and revocation have all been rewritten to use the new `rhashtable`-based structure. And this touches multiple files, not just the core implementation, but associated files within `security/keys/` and other areas, too.

The `security/keys/` subsystem is also of great interest because it's a *core* kernel subsystem.  It's directly exposed to userspace via syscalls like `add_key`, `keyctl`, and `request_key`.  This makes it highly fuzzable by syzkaller.

And yes, this patch *does* touch critical, reachable code: functions such as `search_keyring_tree`, `search_nested_keyrings`, `keyring_read`, `__key_link_begin`, `__key_link`, `__key_link_end`, `__key_unlink_begin`, `__key_unlink`, `keyring_gc`, `keyring_clear`, `keyring_revoke`, and `key_move` are all modified.

My verdict? This *absolutely* warrants fuzzing. The patch rewrites complex lockless/RCU data structures, including concurrent searching, insertion, deletion, replacement, and garbage collection, all within a core subsystem.

The "WorthFuzzing" criteria are a clear match here: this is a restructuring of a major data structure, impacting reachable code. The keyring data structure has been entirely replaced, and it’s heavily exercised via userspace syscalls.

Next step: determine the required kernel configuration. It seems like the obvious choice is the `KEYS` config, which I’ll now need to verify with a simple check.



4/2 2026/11/10 21:40 tool grepper
0m Args:
{
  "Expression": "config KEYS",
  "PathPrefixes": [
    "security/keys/Kconfig"
  ]
}

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

5/2 2026/11/10 21:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 61366
							output: 32
							thoughts: 21
						

Thoughts:
Here's a summary of my thought process, as requested:

**Kconfig Inspection - Initial Assessment**

Okay, time to dive into `security/keys/Kconfig`. My initial focus is on the first 30 lines – that's usually where the high-level configuration options and dependencies are defined. I'm expecting to find the overall structure of the key management subsystem configuration, any crucial dependencies on other kernel components (like crypto or filesystem support), and perhaps the top-level selection options that enable or disable the entire feature set. I need to quickly grasp the scope of what's configurable here; are we talking about a broad range of key types and uses, or a more focused set? What are the entry points for enabling the key management features? Any unusual or vendor-specific options that stand out? I'll be looking for things that might indicate where to look for interesting extension points. I'm already anticipating conditionals and boolean logic in the Kconfig syntax. Let's get to it.



6/2 2026/11/10 21:40 tool read-file
0m Args:
{
  "File": "security/keys/Kconfig",
  "FirstLine": 1,
  "LineCount": 35
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0-only\n   2:\t#\n   3:\t# Key management configuration\n   4:\t#\n   5:\t\n   6:\tmenuconfig KEYS\n   7:\t\tbool \"Enable access key retention support\"\n   8:\t\thelp\n   9:\t\t  This option provides support for retaining authentication tokens and\n  10:\t\t  access keys in the kernel.\n  11:\t\n  12:\t\t  It also includes provision of methods by which such keys might be\n  13:\t\t  associated with a process so that network filesystems, encryption\n  14:\t\t  support and the like can find them.\n  15:\t\n  16:\t\t  Furthermore, a special type of key is available that acts as keyring:\n  17:\t\t  a searchable sequence of keys. Each process is equipped with access\n  18:\t\t  to five standard keyrings: UID-specific, GID-specific, session,\n  19:\t\t  process and thread.\n  20:\t\n  21:\t\t  If you are unsure as to whether this is required, answer N.\n  22:\t\n  23:\tif KEYS\n  24:\t\n  25:\tconfig KEYS_REQUEST_CACHE\n  26:\t\tbool \"Enable temporary caching of the last request_key() result\"\n  27:\t\thelp\n  28:\t\t  This option causes the result of the last successful request_key()\n  29:\t\t  call that didn't upcall to the kernel to be cached temporarily in the\n  30:\t\t  task_struct.  The cache is cleared by exit and just prior to the\n  31:\t\t  resumption of userspace.\n  32:\t\n  33:\t\t  This allows the key used for multiple step processes where each step\n  34:\t\t  wants to request a key that is likely the same as the one requested\n  35:\t\t  by the last step to save on the searching.\n"
}

7/2 2026/11/10 21:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 62109
							output: 31
							thoughts: 47
						

Thoughts:
**Analyzing the Key Configuration Changes**

Okay, so the prompt mentions "KEYS" as being standard, which is good to note. But I can't assume that's the *only* relevant piece. I need to be thorough. My immediate thought is, are there any other configurations that might be impacted by these changes?

To figure this out, I need to know the bigger picture. I'll need to figure out where the changed files are compiled, which is the key to understanding the scope of the impact. I suspect there's a specific Makefile involved. Let's start by checking where these files are compiled. Based on the file paths, my instinct tells me to look at `security/keys/Makefile`.

Now, I'll read that Makefile carefully. That will give me the key information on the build process and dependencies, and allow me to see if there are any other areas I need to investigate.



8/2 2026/11/10 21:40 tool read-file
0m Args:
{
  "File": "security/keys/Makefile",
  "FirstLine": 1,
  "LineCount": 40
}

Results:
{
  "Contents": "   1:\t# SPDX-License-Identifier: GPL-2.0\n   2:\t#\n   3:\t# Makefile for key management\n   4:\t#\n   5:\t\n   6:\t#\n   7:\t# Core\n   8:\t#\n   9:\tobj-y := \\\n  10:\t\tgc.o \\\n  11:\t\tkey.o \\\n  12:\t\tkeyring.o \\\n  13:\t\tkeyctl.o \\\n  14:\t\tpermission.o \\\n  15:\t\tprocess_keys.o \\\n  16:\t\trequest_key.o \\\n  17:\t\trequest_key_auth.o \\\n  18:\t\tuser_defined.o\n  19:\tcompat-obj-$(CONFIG_KEY_DH_OPERATIONS) += compat_dh.o\n  20:\tobj-$(CONFIG_COMPAT) += compat.o $(compat-obj-y)\n  21:\tobj-$(CONFIG_PROC_FS) += proc.o\n  22:\tobj-$(CONFIG_SYSCTL) += sysctl.o\n  23:\tobj-$(CONFIG_PERSISTENT_KEYRINGS) += persistent.o\n  24:\tobj-$(CONFIG_KEY_DH_OPERATIONS) += dh.o\n  25:\tobj-$(CONFIG_ASYMMETRIC_KEY_TYPE) += keyctl_pkey.o\n  26:\t\n  27:\t#\n  28:\t# Key types\n  29:\t#\n  30:\tobj-$(CONFIG_BIG_KEYS) += big_key.o\n  31:\tobj-$(CONFIG_TRUSTED_KEYS) += trusted-keys/\n  32:\tobj-$(CONFIG_ENCRYPTED_KEYS) += encrypted-keys/\n"
}

9/2 2026/11/10 21:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 62819
							output: 25
							thoughts: 54
						

Thoughts:
Okay, here's my assessment of this, from a kernel expert's perspective:

**Kernel Object Dependencies & Security Module Inclusion**

Right, so I see we're dealing with the key management subsystem. Specifically, my mind is immediately drawn to the objects `keyring.o`, `key.o`, and `request_key.o`. They're being compiled into the kernel (`obj-y`) when `CONFIG_KEYS` is enabled. That's the expected behavior; those are foundational for the key management infrastructure. I'd expect to find those objects included in the core key management logic.

Next, I need to understand how the `security/keys` module itself is incorporated into the overall build. I'm going to turn my attention to the `security/Makefile` in order to determine how that module is built, linked, and potentially conditionally included within the kernel's build process. I'll need to trace the dependency chain to see what other security features they might be related to, and how they contribute to the kernel's overall security posture. This is an important consideration for secure boot.



10/2 2026/11/10 21:41 tool grepper
0m Args:
{
  "Expression": "keys",
  "PathPrefixes": [
    "security/Makefile"
  ]
}

Results:
{
  "Output": "security/Makefile-5-\nsecurity/Makefile:6:obj-$(CONFIG_KEYS)\t\t\t+= keys/\nsecurity/Makefile-7-\n"
}

11/2 2026/11/10 21:41 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 63175
							output: 31
							thoughts: 977
						

Thoughts:
**Focusing on Keyring Feature Logic for Fuzzing**

Alright, let's break this down. With `CONFIG_KEYS` enabled, we're dealing with the core key management subsystem, including `keyring.o` and related files. The immediate question is how to define `FocusSymbols` effectively for fuzzing. Given the recent changes, my thinking is:

First, let's dissect the modifications in `security/keys/keyring.c`. I've already identified a list of functions that have been added or heavily modified: `keyring_is_empty`, `keyring_read`, `search_keyring_tree`, `search_nested_keyrings`, `find_key_to_update`, `__key_link_begin`, `__key_link`, `__key_link_end`, `key_link`, `__key_unlink_begin`, `__key_unlink`, `key_unlink`, `key_move`, `keyring_clear`, `keyring_revoke`, `keyring_gc`, `key_instantiate_and_link`, `key_reject_and_link`, and `__key_create_or_update`.

Now, we need to apply the FocusSymbols guidelines: avoid ubiquitous lifecycle functions and target specific feature logic and entry points. I know from experience that, in typical kernel builds (KASAN, syzkaller, ftrace), static functions not inlined usually have symbols in `vmlinux`. So, non-static or exported functions are definitely candidates, and represent entrypoints. Functions like `key_link`, `key_unlink`, `key_move`, `keyring_clear`, `keyring_gc`, `key_instantiate_and_link`, `key_reject_and_link`, `keyring_is_empty`, and `find_key_to_update` are prime targets. Even though I know `keyring_read` is a static method in `key_type_keyring`, it *is* an entry point through the `key_type_keyring.read` pointer.

To reiterate, the following are the functions I'm considering as FocusSymbols: `keyring_read`, `keyring_clear`, `keyring_gc`, `key_link`, `key_unlink`, `key_move`, `search_keyring_tree`, `search_nested_keyrings`, `__key_link_begin`, `__key_link`, `__key_link_end`, and `keyring_is_empty`. This is based on both their visibility and their direct involvement in the specific keyring logic.



12/2 2026/11/10 21:41 tool grepper
0m Args:
{
  "Expression": "key_type_keyring",
  "PathPrefixes": [
    "security/keys/"
  ]
}

Results:
{
  "Output": "security/keys/gc.c=178=static void key_garbage_collector(struct work_struct *work)\n--\nsecurity/keys/gc.c-231-\t\t\t\tgoto skip_dead_key;\nsecurity/keys/gc.c:232:\t\t\t} else if (key-\u003etype == \u0026key_type_keyring \u0026\u0026\nsecurity/keys/gc.c-233-\t\t\t\t   key-\u003erestrict_link) {\n--\nsecurity/keys/gc.c-254-\t\t    unlikely(gc_state \u0026 KEY_GC_REAPING_DEAD_2)) {\nsecurity/keys/gc.c:255:\t\t\tif (key-\u003etype == \u0026key_type_keyring)\nsecurity/keys/gc.c-256-\t\t\t\tgoto found_keyring;\n--\nsecurity/keys/key.c=815=static key_ref_t __key_create_or_update(key_ref_t keyring_ref,\n--\nsecurity/keys/key.c-853-\tkey_ref = ERR_PTR(-ENOTDIR);\nsecurity/keys/key.c:854:\tif (keyring-\u003etype != \u0026key_type_keyring)\nsecurity/keys/key.c-855-\t\tgoto error_put_type;\n--\nsecurity/keys/key.c-941-\nsecurity/keys/key.c:942:\t\tif (index_key.type == \u0026key_type_keyring ||\nsecurity/keys/key.c-943-\t\t    index_key.type-\u003eupdate)\n--\nsecurity/keys/key.c=1291=void __init key_init(void)\n--\nsecurity/keys/key.c-1297-\t/* add the special key types */\nsecurity/keys/key.c:1298:\tlist_add_tail(\u0026key_type_keyring.link, \u0026key_types_list);\nsecurity/keys/key.c-1299-\tlist_add_tail(\u0026key_type_dead.link, \u0026key_types_list);\n--\nsecurity/keys/keyring.c=213=static long keyring_read(const struct key *keyring,\n--\nsecurity/keys/keyring.c-215-\nsecurity/keys/keyring.c:216:struct key_type key_type_keyring = {\nsecurity/keys/keyring.c-217-\t.name\t\t= \"keyring\",\n--\nsecurity/keys/keyring.c-226-};\nsecurity/keys/keyring.c:227:EXPORT_SYMBOL(key_type_keyring);\nsecurity/keys/keyring.c-228-\n--\nsecurity/keys/keyring.c=474=struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,\n--\nsecurity/keys/keyring.c-482-\nsecurity/keys/keyring.c:483:\tkeyring = key_alloc(\u0026key_type_keyring, description,\nsecurity/keys/keyring.c-484-\t\t\t    uid, gid, cred, perm, flags, restrict_link);\n--\nsecurity/keys/keyring.c=622=static int search_keyring_tree(struct key *keyring,\n--\nsecurity/keys/keyring.c-644-\nsecurity/keys/keyring.c:645:\t\tif (key-\u003etype != \u0026key_type_keyring)\nsecurity/keys/keyring.c-646-\t\t\tbreak;\n--\nsecurity/keys/keyring.c=764=key_ref_t keyring_search_rcu(key_ref_t keyring_ref,\n--\nsecurity/keys/keyring.c-776-\nsecurity/keys/keyring.c:777:\tif (keyring-\u003etype != \u0026key_type_keyring)\nsecurity/keys/keyring.c-778-\t\treturn ERR_PTR(-ENOTDIR);\n--\nsecurity/keys/keyring.c=867=static bool keyring_detect_restriction_cycle(const struct key *dest_keyring,\n--\nsecurity/keys/keyring.c-870-\twhile (keyres \u0026\u0026 keyres-\u003ekey \u0026\u0026\nsecurity/keys/keyring.c:871:\t       keyres-\u003ekey-\u003etype == \u0026key_type_keyring) {\nsecurity/keys/keyring.c-872-\t\tif (keyres-\u003ekey == dest_keyring)\n--\nsecurity/keys/keyring.c=891=int keyring_restrict(key_ref_t keyring_ref, const char *type,\n--\nsecurity/keys/keyring.c-901-\nsecurity/keys/keyring.c:902:\tif (keyring-\u003etype != \u0026key_type_keyring)\nsecurity/keys/keyring.c-903-\t\treturn -ENOTDIR;\n--\nsecurity/keys/keyring.c=1105=int __key_link_lock(struct key *keyring,\n--\nsecurity/keys/keyring.c-1109-{\nsecurity/keys/keyring.c:1110:\tif (keyring-\u003etype != \u0026key_type_keyring)\nsecurity/keys/keyring.c-1111-\t\treturn -ENOTDIR;\n--\nsecurity/keys/keyring.c-1117-\t */\nsecurity/keys/keyring.c:1118:\tif (index_key-\u003etype == \u0026key_type_keyring)\nsecurity/keys/keyring.c-1119-\t\tmutex_lock(\u0026keyring_serialise_link_lock);\n--\nsecurity/keys/keyring.c=1127=int __key_move_lock(struct key *l_keyring, struct key *u_keyring,\n--\nsecurity/keys/keyring.c-1132-{\nsecurity/keys/keyring.c:1133:\tif (l_keyring-\u003etype != \u0026key_type_keyring ||\nsecurity/keys/keyring.c:1134:\t    u_keyring-\u003etype != \u0026key_type_keyring)\nsecurity/keys/keyring.c-1135-\t\treturn -ENOTDIR;\n--\nsecurity/keys/keyring.c-1151-\t */\nsecurity/keys/keyring.c:1152:\tif (index_key-\u003etype == \u0026key_type_keyring)\nsecurity/keys/keyring.c-1153-\t\tmutex_lock(\u0026keyring_serialise_link_lock);\n--\nsecurity/keys/keyring.c=1253=int __key_link_check_live_key(struct key *keyring, struct key *key)\nsecurity/keys/keyring.c-1254-{\nsecurity/keys/keyring.c:1255:\tif (key-\u003etype == \u0026key_type_keyring)\nsecurity/keys/keyring.c-1256-\t\t/* check that we aren't going to create a cycle by linking one\n--\nsecurity/keys/keyring.c=1270=void __key_link(struct key *keyring, struct key *key, struct keyring_edit *edit)\n--\nsecurity/keys/keyring.c-1288-\t} else {\nsecurity/keys/keyring.c:1289:\t\tif (key-\u003etype == \u0026key_type_keyring)\nsecurity/keys/keyring.c-1290-\t\t\tlist_add_rcu(\u0026edit-\u003enew-\u003elist, \u0026index-\u003elist);\n--\nsecurity/keys/keyring.c=1307=void __key_link_end(struct key *keyring,\n--\nsecurity/keys/keyring.c-1335-\nsecurity/keys/keyring.c:1336:\tif (index_key-\u003etype == \u0026key_type_keyring)\nsecurity/keys/keyring.c-1337-\t\tmutex_unlock(\u0026keyring_serialise_link_lock);\n--\nsecurity/keys/keyring.c=1407=static int __key_unlink_lock(struct key *keyring)\n--\nsecurity/keys/keyring.c-1409-{\nsecurity/keys/keyring.c:1410:\tif (keyring-\u003etype != \u0026key_type_keyring)\nsecurity/keys/keyring.c-1411-\t\treturn -ENOTDIR;\n--\nsecurity/keys/keyring.c=1577=int keyring_clear(struct key *keyring)\nsecurity/keys/keyring.c-1578-{\nsecurity/keys/keyring.c:1579:\tif (keyring-\u003etype != \u0026key_type_keyring)\nsecurity/keys/keyring.c-1580-\t\treturn -ENOTDIR;\n--\nsecurity/keys/persistent.c=80=static long key_get_persistent(struct user_namespace *ns, kuid_t uid,\n--\nsecurity/keys/persistent.c-91-\tmemset(\u0026index_key, 0, sizeof(index_key));\nsecurity/keys/persistent.c:92:\tindex_key.type = \u0026key_type_keyring;\nsecurity/keys/persistent.c-93-\tindex_key.description = buf;\n--\nsecurity/keys/persistent.c=138=long keyctl_get_persistent(uid_t _uid, key_serial_t destid)\n--\nsecurity/keys/persistent.c-165-\t\treturn PTR_ERR(dest_ref);\nsecurity/keys/persistent.c:166:\tif (key_ref_to_ptr(dest_ref)-\u003etype != \u0026key_type_keyring) {\nsecurity/keys/persistent.c-167-\t\tret = -ENOTDIR;\n--\nsecurity/keys/process_keys.c=84=int look_up_user_keyrings(struct key **_user_keyring,\n--\nsecurity/keys/process_keys.c-112-\tuid_keyring_r = keyring_search(make_key_ref(reg_keyring, true),\nsecurity/keys/process_keys.c:113:\t\t\t\t       \u0026key_type_keyring, buf, false);\nsecurity/keys/process_keys.c-114-\tkdebug(\"_uid %p\", uid_keyring_r);\n--\nsecurity/keys/process_keys.c-134-\tsession_keyring_r = keyring_search(make_key_ref(reg_keyring, true),\nsecurity/keys/process_keys.c:135:\t\t\t\t\t   \u0026key_type_keyring, buf, false);\nsecurity/keys/process_keys.c-136-\tkdebug(\"_uid_ses %p\", session_keyring_r);\n--\nsecurity/keys/process_keys.c=195=struct key *get_user_session_keyring_rcu(const struct cred *cred)\n--\nsecurity/keys/process_keys.c-201-\tstruct keyring_search_context ctx = {\nsecurity/keys/process_keys.c:202:\t\t.index_key.type\t\t= \u0026key_type_keyring,\nsecurity/keys/process_keys.c-203-\t\t.index_key.description\t= buf,\n--\nsecurity/keys/request_key.c=369=static int construct_alloc_key(struct keyring_search_context *ctx,\n--\nsecurity/keys/request_key.c-390-\t\tperm |= KEY_POS_READ;\nsecurity/keys/request_key.c:391:\tif (ctx-\u003eindex_key.type == \u0026key_type_keyring ||\nsecurity/keys/request_key.c-392-\t    ctx-\u003eindex_key.type-\u003eupdate)\n--\nsecurity/keys/request_key.c=489=static struct key *construct_key_and_link(struct keyring_search_context *ctx,\n--\nsecurity/keys/request_key.c-501-\nsecurity/keys/request_key.c:502:\tif (ctx-\u003eindex_key.type == \u0026key_type_keyring)\nsecurity/keys/request_key.c-503-\t\treturn ERR_PTR(-EPERM);\n"
}

13/2 2026/11/10 21:41 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 67729
							output: 206
							thoughts: 720
						

Thoughts:
**Analysis of the Keys/Keyring Subsystem for Fuzzing**

Okay, let's break this down. First, I'm checking the key exported and key functions within `security/keys/`. From `keyring.c`, I've got `key_link`, `key_unlink`, `key_move`, `keyring_clear`, `keyring_gc`, `keyring_is_empty`, `keyring_read`, `keyring_search_rcu`, `search_nested_keyrings`, `search_keyring_tree`, `__key_link_begin`, `__key_link`, `__key_link_end`, and `find_key_to_update`. Then in `key.c`, there's `key_instantiate_and_link` and `key_reject_and_link`. These are all very specific to the keys and keyring subsystem; they aren't some universally used kernel primitives.

I've confirmed that none of these functions are ubiquitous. They are invoked by user-space calls like `keyctl(KEYCTL_LINK)`, `keyctl(KEYCTL_UNLINK)`, and similar operations, so they are the core of the keys subsystem. They are not concerned with low-level allocation, or scheduling, etc.

Next, I'm verifying the patch details. `WorthFuzzing` is true, and the patch has provided `"KEYS"` as an enabling configuration. The focus symbols are spot on: it includes all the function names I identified earlier, namely `key_link`, `key_unlink`, `key_move`, `keyring_clear`, `keyring_gc`, `keyring_read`, `search_nested_keyrings`, `find_key_to_update`, `keyring_is_empty`, `__key_link_begin`, `__key_link`, and `__key_link_end`.

I'm now checking what's required for `set-results`. The arguments need `EnableConfigs`, which is `"KEYS"`, `FocusSymbols`, which I've got, a reasoning for the verdict (which I'm building), and `WorthFuzzing`, which is true.

I also need to make sure that there aren't any other configs I'm missing. I checked dm-verity, fs-verity, and bpf to see if any of their dependencies required other configurations. I found `keyring_is_empty` calls in `dm-verity-verify-sig.c`, `fs/verity/signature.c`, and `kernel/bpf/keys.c`. However, these are just call sites, and the main configuration is definitely `CONFIG_KEYS`. This patch series focuses on replacing the associative array with an RCU linked list and `rhashtable`. Therefore, `CONFIG_KEYS` is the necessary and sufficient configuration to enable building and fuzzing this code.

I think I've got a solid understanding of this now. It's time to call `set-results`.



14/2 2026/11/10 21:41 tool set-results
0m Args:
{
  "EnableConfigs": [
    "KEYS"
  ],
  "FocusSymbols": [
    "key_link",
    "key_unlink",
    "key_move",
    "keyring_clear",
    "keyring_gc",
    "keyring_read",
    "search_nested_keyrings",
    "find_key_to_update",
    "keyring_is_empty",
    "__key_link_begin",
    "__key_link",
    "__key_link_end"
  ],
  "Reasoning": "The patch series removes the generic associative array (assoc_array) implementation and replaces the internal keyring indexing mechanism in the keys subsystem with an rhashtable and RCU-protected linked list. This refactors core data structures and concurrency/locking logic in reachable security/keys code, directly accessible via keyctl, add_key, and request_key syscalls. Hence, it is worth fuzzing.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "KEYS"
  ],
  "FocusSymbols": [
    "key_link",
    "key_unlink",
    "key_move",
    "keyring_clear",
    "keyring_gc",
    "keyring_read",
    "search_nested_keyrings",
    "find_key_to_update",
    "keyring_is_empty",
    "__key_link_begin",
    "__key_link",
    "__key_link_end"
  ],
  "Reasoning": "The patch series removes the generic associative array (assoc_array) implementation and replaces the internal keyring indexing mechanism in the keys subsystem with an rhashtable and RCU-protected linked list. This refactors core data structures and concurrency/locking logic in reachable security/keys code, directly accessible via keyctl, add_key, and request_key syscalls. Hence, it is worth fuzzing.",
  "WorthFuzzing": true
}

15/1 2026/11/10 21:41 action If
3m Args:
{
  "WorthFuzzing": true
}

Results:
null

16/2 2026/11/10 21:41 agent kmsan-evaluator
3m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series completely removes the generic associative array (`assoc_array`) data structure and replaces its usage in the keys subsystem (`security/keys/keyring.c`) with a combination of `rhashtable` and `list_head`.\n\nEvaluation of uninitialized memory and info-leak risks:\n1. Memory Allocation: All newly introduced heap structures (`struct keyring_index` and `struct keyring_link`) are allocated using `kzalloc_obj()`, ensuring all fields and padding are zero-initialized before insertion into the hash table or list.\n2. Stack Initialization: All stack variables of `struct keyring_edit` and link pointers introduced across `key.c`, `keyring.c`, and `request_key.c` are explicitly zero-initialized (`= {}` or `= NULL`).\n3. User-space Exposure: Keyring listing (`keyring_read`) iterates through active keys and writes `key_serial_t` scalars into the provided buffer up to `links-\u003enr` entries, leaving no uninitialized buffer bytes or padding copied to user space.\n4. Structure Redesign: The simplified `struct keyring_index_key` removes the previous union containing partial description bytes and replaces ad-hoc index IDs with direct SipHash hashing of initialized pointers and description data.\n\nKASAN vs. KMSAN Applicability:\n- The risks introduced by this change involve concurrent RCU iteration and mutation (`rhashtable_replace_fast`, `list_replace_rcu`, `call_rcu`), rwsem lock synchronization (`keyring-\u003esem`), key reference counting (`key_get`, `key_put`), and pointer dereferences.\n- These issues are comprehensively covered by standard KASAN (use-after-free, double-free), LOCKDEP (locking violations), and general kernel assertions.\n- There are no uninitialized memory reads, uninitialized branch conditions, or kernel-to-user info-leaks that would necessitate a dedicated KMSAN fuzzing session.",
  "NeedsKMSAN": false
}

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

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

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

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

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

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

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


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

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 9b677570f5d4a445ef4a8b94fb6e5bf96ecddb01
Author: syz-cluster <triage@syzkaller.com>
Date:   Tue Nov 10 21:40:32 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/core-api/assoc_array.rst b/Documentation/core-api/assoc_array.rst
deleted file mode 100644
index 19d89f92bf8da8..00000000000000
--- a/Documentation/core-api/assoc_array.rst
+++ /dev/null
@@ -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.
diff --git a/Documentation/core-api/index.rst b/Documentation/core-api/index.rst
index 92f91c6a0d79d6..d56c60663b0c40 100644
--- a/Documentation/core-api/index.rst
+++ b/Documentation/core-api/index.rst
@@ -38,7 +38,6 @@ Library functionality that is used throughout the kernel.
    kobject
    kref
    cleanup
-   assoc_array
    folio_queue
    xarray
    maple_tree
diff --git a/Documentation/translations/zh_CN/core-api/assoc_array.rst b/Documentation/translations/zh_CN/core-api/assoc_array.rst
deleted file mode 100644
index 3649bf0d148807..00000000000000
--- a/Documentation/translations/zh_CN/core-api/assoc_array.rst
+++ /dev/null
@@ -1,473 +0,0 @@
-.. include:: ../disclaimer-zh_CN.rst
-
-:Original: Documentation/core-api/assoc_array.rst
-
-:翻译:
-
- 司延腾 Yanteng Si <siyanteng@loongson.cn>
-
-:校译:
-
-
-
-.. _cn_core-api_assoc_array:
-
-==================
-通用关联数组的实现
-==================
-
-简介
-====
-
-这个关联数组的实现是一个具有以下属性的对象容器:
-
-1. 对象是不透明的指针。该实现不关心它们指向哪里(如果有的话)或它们指向什么(如果有的
-   话)。
-
-   .. note::
-
-      指向对象的指针 *必须* 在最小有效位为零。
-
-2. 对象不需要包含供数组使用的链接块。这允许一个对象同时位于多个数组中。相反,数组是
-   由指向对象的元数据块组成的。
-
-3. 对象需要索引键来定位它们在阵列中的位置。
-
-4. 索引键必须是唯一的。插入一个与已经在数组中的且具有相同键值的对象将取代旧的对象。
-
-5. 索引键可以是任何长度,也可以是不同的长度。
-
-6. 索引键应该在早期就对长度进行编码,即在任何由于长度引起的变化出现之前。
-
-7. 索引键可以包括一个哈希值,以便将对象分散到整个数组中。
-
-8. 该数组可以迭代。对象不一定会按索引键的顺序出现。
-
-9.  数组可以在被修改的时候进行迭代,只要RCU的读锁被迭代器持有。然而,请注意,在这种情
-    况下,一些对象可能会被看到不止一次。如果这是个问题,迭代器应该锁定以防止修改。然
-    而,除非删除,否则对象不会被错过。
-
-10. 数组中的对象可以通过其索引键进行查询。
-
-11. 当数组被修改时,对象可以被查询,前提是进行查询的线程持有RCU的读锁。
-
-该实现在内部使用了一棵由16个指针节点组成的树,这些节点在每一层都由索引键的小数点进行索
-引,其方式与基数树相同。为了提高内存效率,可以放置快捷键,以跳过本来是一系列单占节点的地
-方。此外,节点将叶子对象指针打包到节点的空闲空间中,而不是做一个额外的分支,直到有对象
-需要被添加到一个完整的节点中。
-
-公用API
-=======
-
-公用API可以在 ``<linux/assoc_array.h>`` 中找到。关联数组的根是以下结构::
-
-    struct assoc_array {
-            ...
-    };
-
-该代码是通过启用 ``CONFIG_ASSOCIATIVE_ARRAY`` 来选择的,以::
-
-    ./script/config -e ASSOCIATIVE_ARRAY
-
-
-编辑脚本
---------
-
-插入和删除功能会产生一个“编辑脚本”,以后可以应用这个脚本来实现更改,而不会造成 ``ENOMEM``
-风险。这保留了将被安装在内部树中的预分配的元数据块,并跟踪应用脚本时将从树中删除的元数
-据块。
-
-在脚本应用后,这也被用来跟踪死块和死对象,以便以后可以释放它们。释放是在RCU宽限期过后
-进行的--因此允许访问功能在RCU读锁下进行。
-
-脚本在API之外显示为一个类型为::
-
-    struct assoc_array_edit;
-
-有两个处理脚本的功能:
-
-1. 应用一个编辑脚本::
-
-    void assoc_array_apply_edit(struct assoc_array_edit *edit);
-
-这将执行编辑功能,插值各种写屏障,以允许在RCU读锁下的访问继续进行。然后,编辑脚本将被
-传递给 ``call_rcu()`` ,以释放它和它所指向的任何死的东西。
-
-2. Cancel an edit script::
-
-    void assoc_array_cancel_edit(struct assoc_array_edit *edit);
-
-这将立即释放编辑脚本和所有预分配的内存。如果这是为了插入,新的对象不会被这个函数释放,
-而是必须由调用者释放。
-
-这些函数保证不会失败。
-
-
-操作表
-------
-
-各种功能采用了一个操作表::
-
-    struct assoc_array_ops {
-            ...
-    };
-
-这指出了一些方法,所有这些方法都需要提供:
-
-1. 从调用者数据中获取索引键的一个块::
-
-    unsigned long (*get_key_chunk)(const void *index_key, int level);
-
-这应该返回一个由调用者提供的索引键的块,从level参数给出的 *比特* 位置开始。level参数将
-是 ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` 的倍数,该函数应返回 ``ASSOC_ARRAY_KEY_CHUNK_SIZE``
-位。不可能出现错误。
-
-
-2. 获取一个对象的索引键的一个块::
-
-    unsigned long (*get_object_key_chunk)(const void *object, int level);
-
-和前面的函数一样,但是从数组中的一个对象而不是从调用者提供的索引键中获取数据。
-
-
-3. 看看这是否是我们要找的对象::
-
-    bool (*compare_object)(const void *object, const void *index_key);
-
-将对象与一个索引键进行比较,如果匹配则返回 ``true`` ,不匹配则返回 ``false`` 。
-
-
-4. 对两个对象的索引键进行比较::
-
-    int (*diff_objects)(const void *object, const void *index_key);
-
-返回指定对象的索引键与给定索引键不同的比特位置,如果它们相同,则返回-1。
-
-
-5. 释放一个对象::
-
-    void (*free_object)(void *object);
-
-释放指定的对象。注意,这可能是在调用 ``assoc_array_apply_edit()`` 后的一个RCU宽限期内
-调用的,所以在模块卸载时可能需要 ``synchronize_rcu()`` 。
-
-
-操控函数
---------
-
-有一些函数用于操控关联数组:
-
-1. 初始化一个关联数组::
-
-    void assoc_array_init(struct assoc_array *array);
-
-这将初始化一个关联数组的基础结构。它不会失败。
-
-
-2. 在一个关联数组中插入/替换一个对象::
-
-    struct assoc_array_edit *
-    assoc_array_insert(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       const void *index_key,
-                       void *object);
-
-这将把给定的对象插入数组中。注意,指针的最小有效位必须是0,因为它被用来在内部标记指针的类
-型。
-
-如果该键已经存在一个对象,那么它将被新的对象所取代,旧的对象将被自动释放。
-
-``index_key`` 参数应持有索引键信息,并在调用OPP表中的方法时传递给它们。
-
-这个函数不对数组本身做任何改动,而是返回一个必须应用的编辑脚本。如果出现内存不足的错误,会
-返回 ``-ENOMEM`` 。
-
-调用者应专门锁定数组的其他修改器。
-
-
-3. 从一个关联数组中删除一个对象::
-
-    struct assoc_array_edit *
-    assoc_array_delete(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       const void *index_key);
-
-这将从数组中删除一个符合指定数据的对象。
-
-``index_key`` 参数应持有索引键信息,并在调用OPP表中的方法时传递给它们。
-
-这个函数不对数组本身做任何改动,而是返回一个必须应用的编辑脚本。 ``-ENOMEM`` 在出现内存不足
-的错误时返回。如果在数组中没有找到指定的对象,将返回 ``NULL`` 。
-
-调用者应该对数组的其他修改者进行专门锁定。
-
-
-4. 从一个关联数组中删除所有对象::
-
-    struct assoc_array_edit *
-    assoc_array_clear(struct assoc_array *array,
-                      const struct assoc_array_ops *ops);
-
-这个函数删除了一个关联数组中的所有对象,使其完全为空。
-
-这个函数没有对数组本身做任何改动,而是返回一个必须应用的编辑脚本。如果出现内存不足
-的错误,则返回 ``-ENOMEM`` 。
-
-调用者应专门锁定数组的其他修改者。
-
-
-5. 销毁一个关联数组,删除所有对象::
-
-    void assoc_array_destroy(struct assoc_array *array,
-                             const struct assoc_array_ops *ops);
-
-这将破坏关联数组的内容,使其完全为空。在这个函数销毁数组的同时,不允许另一个线程在RCU读锁
-下遍历数组,因为在内存释放时不执行RCU延迟,这需要分配内存。
-
-调用者应该专门针对数组的其他修改者和访问者进行锁定。
-
-
-6. 垃圾回收一个关联数组::
-
-    int assoc_array_gc(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       bool (*iterator)(void *object, void *iterator_data),
-                       void *iterator_data);
-
-这是对一个关联数组中的对象进行迭代,并将每个对象传递给 ``iterator()`` 。如果 ``iterator()`` 返回
-true,该对象被保留。如果它返回 ``false`` ,该对象将被释放。如果 ``iterator()`` 函数返回 ``true`` ,它必须
-在返回之前对该对象进行适当的 ``refcount`` 递增。
-
-如果可能的话,内部树将被打包下来,作为迭代的一部分,以减少其中的节点数量。
-
-``iterator_data`` 被直接传递给 ``iterator()`` ,否则会被函数忽略。
-
-如果成功,该函数将返回 ``0`` ,如果没有足够的内存,则返回 ``-ENOMEM`` 。
-
-在这个函数执行过程中,其他线程有可能在RCU读锁下迭代或搜索阵列。调用者应该专门针对数组的其他
-修改者进行锁定。
-
-
-访问函数
---------
-
-有两个函数用于访问一个关联数组:
-
-1. 遍历一个关联数组中的所有对象::
-
-    int assoc_array_iterate(const struct assoc_array *array,
-                            int (*iterator)(const void *object,
-                                            void *iterator_data),
-                            void *iterator_data);
-
-这将数组中的每个对象传递给迭代器回调函数。 ``iterator_data`` 是该函数的私有数据。
-
-在数组被修改的同时,可以在数组上使用这个方法,前提是RCU读锁被持有。在这种情况下,迭代函数有
-可能两次看到某些对象。如果这是个问题,那么修改应该被锁定。然而,迭代算法不应该错过任何对象。
-
-如果数组中没有对象,该函数将返回 ``0`` ,否则将返回最后一次调用的迭代器函数的结果。如果对迭代函数
-的任何调用导致非零返回,迭代立即停止。
-
-
-2. 在一个关联数组中寻找一个对象::
-
-    void *assoc_array_find(const struct assoc_array *array,
-                           const struct assoc_array_ops *ops,
-                           const void *index_key);
-
-这将直接穿过数组的内部树,到达索引键所指定的对象。
-
-这个函数可以在修改数组的同时用在数组上,前提是RCU读锁被持有。
-
-如果找到对象,该函数将返回对象(并将 ``*_type`` 设置为对象的类型),如果没有找到对象,将返回 ``NULL`` 。
-
-
-索引键形式
-----------
-
-索引键可以是任何形式的,但是由于算法没有被告知键有多长,所以强烈建议在任何由于长度而产生的变化
-对比较产生影响之前,索引键应该很早就包括其长度。
-
-这将导致具有不同长度键的叶子相互分散,而具有相同长度键的叶子则聚集在一起。
-
-我们还建议索引键以键的其余部分的哈希值开始,以最大限度地提高整个键空间的散布情况。
-
-分散性越好,内部树就越宽,越低。
-
-分散性差并不是一个太大的问题,因为有快捷键,节点可以包含叶子和元数据指针的混合物。
-
-索引键是以机器字的块状来读取的。每个块被细分为每层一个nibble(4比特),所以在32位CPU上这适合8层,
-在64位CPU上适合16层。除非散布情况真的很差,否则不太可能有超过一个字的任何特定索引键需要被使用。
-
-
-内部工作机制
-============
-
-关联数组数据结构有一个内部树。这个树由两种类型的元数据块构成:节点和快捷键。
-
-一个节点是一个槽的数组。每个槽可以包含以下四种东西之一:
-
-* 一个NULL的指针,表示槽是空的。
-* 一个指向对象(叶子)的指针。
-* 一个指向下一级节点的指针。
-* 一个指向快捷键的指针。
-
-
-基本的内部树形布局
-------------------
-
-暂时不考虑快捷键,节点形成一个多级树。索引键空间被树上的节点严格细分,节点出现在固定的层次上。例如::
-
- 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 |
-                        +---+
-
-在上述例子中,有7个节点(A-G),每个节点有16个槽(0-f)。假设树上没有其他元数据节点,那么密钥空间
-是这样划分的::
-
-    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
-
-因此,例如,具有以下示例索引键的键将在适当的节点中被找到::
-
-    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
-
-为了节省内存,如果一个节点可以容纳它的那部分键空间中的所有叶子,那么这个节点将有所有这些叶子,而不
-会有任何元数据指针——即使其中一些叶子想在同一个槽中。
-
-一个节点可以包含叶子和元数据指针的异质性混合。元数据指针必须在与它们的关键空间的细分相匹配的槽中。
-叶子可以在任何没有被元数据指针占据的槽中。保证一个节点中没有一个叶子会与元数据指针占据的槽相匹配。
-如果元数据指针在那里,任何键与元数据键前缀相匹配的叶必须在元数据指针指向的子树中。
-
-在上面的索引键的例子列表中,节点A将包含::
-
-    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
-
-和节点B::
-
-    3	PTR TO NODE C	13*
-    any	LEAF		1458952489
-
-
-快捷键
----------
-
-快捷键是跳过一块键空间的元数据记录。快捷键是一系列通过层次上升的单占节点的替代物。快捷键的存在是
-为了节省内存和加快遍历速度。
-
-树的根部有可能是一个快捷键——比如说,树至少包含17个节点,都有键前缀 ``1111`` 。插入算法将插入一个快捷键,
-以单次跳过 ``1111`` 的键位,并到达第四层,在这里,这些键位实际上变得不同。
-
-
-拆分和合并节点
-------------------------------
-
-每个节点的最大容量为16个叶子和元数据指针。如果插入算法发现它正试图将一个第17个对象插入到一个节点中,
-该节点将被拆分,使得至少两个在该层有一个共同的关键段的叶子最终在一个单独的节点中,该共同的关键段的根
-在该槽上。
-
-如果一个完整的节点中的叶子和被插入的叶子足够相似,那么就会在树中插入一个快捷键。
-
-当根植于某个节点的子树中的对象数量下降到16个或更少时,那么该子树将被合并成一个单独的节点——如果可能的
-话,这将向根部扩散。
-
-
-非递归式迭代
-------------
-
-每个节点和快捷键都包含一个指向其父节点的后置指针,以及该父节点中指向它的槽数。非递归迭代使用这些来
-通过树的根部进行,前往父节点,槽N+1,以确保在没有堆栈的情况下取得进展。
-
-然而,反向指针使得同时改变和迭代变得很棘手。
-
-
-同时改变和迭代
---------------
-
-有一些情况需要考虑:
-
-1. 简单的插入/替换。这涉及到简单地将一个NULL或旧的匹配叶子的指针替换为屏障后的新叶子的指针。否则元数
-   据块不会改变。一个旧的叶子直到RCU宽限期过后才会被释放。
-
-2. 简单删除。这只是涉及到清除一个旧的匹配叶子。元数据块不会有其他变化。旧的叶子直到RCU宽限期之后才会
-   被释放。
-
-3. 插入,替换我们还没有进入的子树的一部分。这可能涉及到替换该子树的一部分——但这不会影响迭代,因为我们
-   还没有到达它的指针,而且祖先块也不会被替换(这些块的布局不会改变)。
-
-4. 插入替换了我们正在处理的节点。这不是一个问题,因为我们已经通过了锚定指针,直到我们跟随后面的指针才
-   会切换到新的布局上——这时我们已经检查了被替换节点的叶子(在跟随任何元数据指针之前,我们会迭代一个节
-   点的所有叶子)。
-
-   然而,我们可能会重新看到一些叶子,这些叶子已经被分割成一个新的分支,而这个分支的位置比我们之前的位
-   置更远。
-
-5. 插入替换了我们正在处理的依赖分支的节点。这不会影响到我们,直到我们跟随后面的指针。与(4)类似。
-
-6. 删掉我们下面的一个分支。这不会影响我们,因为在我们看到新节点之前,回溯指针会让我们回到新节点的父节
-   点。整个崩溃的子树被扔掉了,没有任何变化——而且仍然会在同一个槽上生根,所以我们不应该第二次处理它,
-   因为我们会回到槽+1。
-
-.. note::
-
-    在某些情况下,我们需要同时改变一个节点的父指针和父槽指针(比如说,我们在它之前插入了另一个节点,
-    并把它往上移了一层)。我们不能在不锁定读取的情况下这样做——所以我们必须同时替换该节点。
-
-    然而,当我们把一个快捷键改成一个节点时,这不是一个问题,因为快捷键只有一个槽,所以当向后遍
-    历一个槽时,不会使用父槽号。这意味着先改变槽位号是可以的——只要使用适当的屏障来确保父槽位号在后
-    退指针之后被读取。
-
-过时的块和叶子在RCU宽限期过后会被释放,所以只要任何进行遍历或迭代的人持有RCU读锁,旧的上层建筑就不
-应该在他们身上消失。
diff --git a/Documentation/translations/zh_CN/core-api/index.rst b/Documentation/translations/zh_CN/core-api/index.rst
index 453a02cd1f4486..ec4b03b2a0a60e 100644
--- a/Documentation/translations/zh_CN/core-api/index.rst
+++ b/Documentation/translations/zh_CN/core-api/index.rst
@@ -41,7 +41,6 @@
 
    kobject
    kref
-   assoc_array
    xarray
    rbtree
    idr
diff --git a/drivers/md/dm-verity-verify-sig.c b/drivers/md/dm-verity-verify-sig.c
index 0c65c7a31da8bd..bd5143aae4fa96 100644
--- a/drivers/md/dm-verity-verify-sig.c
+++ b/drivers/md/dm-verity-verify-sig.c
@@ -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,
diff --git a/fs/verity/signature.c b/fs/verity/signature.c
index 2f49c5d9d98705..b45b39b829b298 100644
--- a/fs/verity/signature.c
+++ b/fs/verity/signature.c
@@ -70,7 +70,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.
diff --git a/include/keys/keyring-type.h b/include/keys/keyring-type.h
index 1dc83862f519ad..314832f5dc4a99 100644
--- a/include/keys/keyring-type.h
+++ b/include/keys/keyring-type.h
@@ -9,6 +9,5 @@
 #define _KEYS_KEYRING_TYPE_H
 
 #include <linux/key.h>
-#include <linux/assoc_array.h>
 
 #endif /* _KEYS_KEYRING_TYPE_H */
diff --git a/include/linux/assoc_array.h b/include/linux/assoc_array.h
deleted file mode 100644
index 8b3f230ce89440..00000000000000
--- a/include/linux/assoc_array.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0-or-later */
-/* Generic associative array implementation.
- *
- * See Documentation/core-api/assoc_array.rst for information.
- *
- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.
- * Written by David Howells (dhowells@redhat.com)
- */
-
-#ifndef _LINUX_ASSOC_ARRAY_H
-#define _LINUX_ASSOC_ARRAY_H
-
-#ifdef CONFIG_ASSOCIATIVE_ARRAY
-
-#include <linux/types.h>
-
-#define ASSOC_ARRAY_KEY_CHUNK_SIZE BITS_PER_LONG /* Key data retrieved in chunks of this size */
-
-/*
- * Generic associative array.
- */
-struct assoc_array {
-	struct assoc_array_ptr	*root;		/* The node at the root of the tree */
-	unsigned long		nr_leaves_on_tree;
-};
-
-/*
- * Operations on objects and index keys for use by array manipulation routines.
- */
-struct assoc_array_ops {
-	/* Method to get a chunk of an index key from caller-supplied data */
-	unsigned long (*get_key_chunk)(const void *index_key, int level);
-
-	/* Method to get a piece of an object's index key */
-	unsigned long (*get_object_key_chunk)(const void *object, int level);
-
-	/* Is this the object we're looking for? */
-	bool (*compare_object)(const void *object, const void *index_key);
-
-	/* How different is an object from an index key, to a bit position in
-	 * their keys? (or -1 if they're the same)
-	 */
-	int (*diff_objects)(const void *object, const void *index_key);
-
-	/* Method to free an object. */
-	void (*free_object)(void *object);
-};
-
-/*
- * Access and manipulation functions.
- */
-struct assoc_array_edit;
-
-static inline void assoc_array_init(struct assoc_array *array)
-{
-	array->root = NULL;
-	array->nr_leaves_on_tree = 0;
-}
-
-extern int assoc_array_iterate(const struct assoc_array *array,
-			       int (*iterator)(const void *object,
-					       void *iterator_data),
-			       void *iterator_data);
-extern void *assoc_array_find(const struct assoc_array *array,
-			      const struct assoc_array_ops *ops,
-			      const void *index_key);
-extern void assoc_array_destroy(struct assoc_array *array,
-				const struct assoc_array_ops *ops);
-extern struct assoc_array_edit *assoc_array_insert(struct assoc_array *array,
-						   const struct assoc_array_ops *ops,
-						   const void *index_key,
-						   void *object);
-extern void assoc_array_insert_set_object(struct assoc_array_edit *edit,
-					  void *object);
-extern struct assoc_array_edit *assoc_array_delete(struct assoc_array *array,
-						   const struct assoc_array_ops *ops,
-						   const void *index_key);
-extern struct assoc_array_edit *assoc_array_clear(struct assoc_array *array,
-						  const struct assoc_array_ops *ops);
-extern void assoc_array_apply_edit(struct assoc_array_edit *edit);
-extern void assoc_array_cancel_edit(struct assoc_array_edit *edit);
-extern int assoc_array_gc(struct assoc_array *array,
-			  const struct assoc_array_ops *ops,
-			  bool (*iterator)(void *object, void *iterator_data),
-			  void *iterator_data);
-
-#endif /* CONFIG_ASSOCIATIVE_ARRAY */
-#endif /* _LINUX_ASSOC_ARRAY_H */
diff --git a/include/linux/assoc_array_priv.h b/include/linux/assoc_array_priv.h
deleted file mode 100644
index dca733ef675038..00000000000000
--- a/include/linux/assoc_array_priv.h
+++ /dev/null
@@ -1,178 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0-or-later */
-/* Private definitions for the generic associative array implementation.
- *
- * See Documentation/core-api/assoc_array.rst for information.
- *
- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.
- * Written by David Howells (dhowells@redhat.com)
- */
-
-#ifndef _LINUX_ASSOC_ARRAY_PRIV_H
-#define _LINUX_ASSOC_ARRAY_PRIV_H
-
-#ifdef CONFIG_ASSOCIATIVE_ARRAY
-
-#include <linux/assoc_array.h>
-
-#define ASSOC_ARRAY_FAN_OUT		16	/* Number of slots per node */
-#define ASSOC_ARRAY_FAN_MASK		(ASSOC_ARRAY_FAN_OUT - 1)
-#define ASSOC_ARRAY_LEVEL_STEP		(ilog2(ASSOC_ARRAY_FAN_OUT))
-#define ASSOC_ARRAY_LEVEL_STEP_MASK	(ASSOC_ARRAY_LEVEL_STEP - 1)
-#define ASSOC_ARRAY_KEY_CHUNK_MASK	(ASSOC_ARRAY_KEY_CHUNK_SIZE - 1)
-#define ASSOC_ARRAY_KEY_CHUNK_SHIFT	(ilog2(BITS_PER_LONG))
-
-/*
- * Undefined type representing a pointer with type information in the bottom
- * two bits.
- */
-struct assoc_array_ptr;
-
-/*
- * An N-way node in the tree.
- *
- * Each slot contains one of four things:
- *
- *	(1) Nothing (NULL).
- *
- *	(2) A leaf object (pointer types 0).
- *
- *	(3) A next-level node (pointer type 1, subtype 0).
- *
- *	(4) A shortcut (pointer type 1, subtype 1).
- *
- * The tree is optimised for search-by-ID, but permits reasonable iteration
- * also.
- *
- * The tree is navigated by constructing an index key consisting of an array of
- * segments, where each segment is ilog2(ASSOC_ARRAY_FAN_OUT) bits in size.
- *
- * The segments correspond to levels of the tree (the first segment is used at
- * level 0, the second at level 1, etc.).
- */
-struct assoc_array_node {
-	struct assoc_array_ptr	*back_pointer;
-	u8			parent_slot;
-	struct assoc_array_ptr	*slots[ASSOC_ARRAY_FAN_OUT];
-	unsigned long		nr_leaves_on_branch;
-};
-
-/*
- * A shortcut through the index space out to where a collection of nodes/leaves
- * with the same IDs live.
- */
-struct assoc_array_shortcut {
-	struct assoc_array_ptr	*back_pointer;
-	int			parent_slot;
-	int			skip_to_level;
-	struct assoc_array_ptr	*next_node;
-	unsigned long		index_key[];
-};
-
-/*
- * Preallocation cache.
- */
-struct assoc_array_edit {
-	struct rcu_head			rcu;
-	struct assoc_array		*array;
-	const struct assoc_array_ops	*ops;
-	const struct assoc_array_ops	*ops_for_excised_subtree;
-	struct assoc_array_ptr		*leaf;
-	struct assoc_array_ptr		**leaf_p;
-	struct assoc_array_ptr		*dead_leaf;
-	struct assoc_array_ptr		*new_meta[3];
-	struct assoc_array_ptr		*excised_meta[1];
-	struct assoc_array_ptr		*excised_subtree;
-	struct assoc_array_ptr		**set_backpointers[ASSOC_ARRAY_FAN_OUT];
-	struct assoc_array_ptr		*set_backpointers_to;
-	struct assoc_array_node		*adjust_count_on;
-	long				adjust_count_by;
-	struct {
-		struct assoc_array_ptr	**ptr;
-		struct assoc_array_ptr	*to;
-	} set[2];
-	struct {
-		u8			*p;
-		u8			to;
-	} set_parent_slot[1];
-	u8				segment_cache[ASSOC_ARRAY_FAN_OUT + 1];
-};
-
-/*
- * Internal tree member pointers are marked in the bottom one or two bits to
- * indicate what type they are so that we don't have to look behind every
- * pointer to see what it points to.
- *
- * We provide functions to test type annotations and to create and translate
- * the annotated pointers.
- */
-#define ASSOC_ARRAY_PTR_TYPE_MASK 0x1UL
-#define ASSOC_ARRAY_PTR_LEAF_TYPE 0x0UL	/* Points to leaf (or nowhere) */
-#define ASSOC_ARRAY_PTR_META_TYPE 0x1UL	/* Points to node or shortcut */
-#define ASSOC_ARRAY_PTR_SUBTYPE_MASK	0x2UL
-#define ASSOC_ARRAY_PTR_NODE_SUBTYPE	0x0UL
-#define ASSOC_ARRAY_PTR_SHORTCUT_SUBTYPE 0x2UL
-
-static inline bool assoc_array_ptr_is_meta(const struct assoc_array_ptr *x)
-{
-	return (unsigned long)x & ASSOC_ARRAY_PTR_TYPE_MASK;
-}
-static inline bool assoc_array_ptr_is_leaf(const struct assoc_array_ptr *x)
-{
-	return !assoc_array_ptr_is_meta(x);
-}
-static inline bool assoc_array_ptr_is_shortcut(const struct assoc_array_ptr *x)
-{
-	return (unsigned long)x & ASSOC_ARRAY_PTR_SUBTYPE_MASK;
-}
-static inline bool assoc_array_ptr_is_node(const struct assoc_array_ptr *x)
-{
-	return !assoc_array_ptr_is_shortcut(x);
-}
-
-static inline void *assoc_array_ptr_to_leaf(const struct assoc_array_ptr *x)
-{
-	return (void *)((unsigned long)x & ~ASSOC_ARRAY_PTR_TYPE_MASK);
-}
-
-static inline
-unsigned long __assoc_array_ptr_to_meta(const struct assoc_array_ptr *x)
-{
-	return (unsigned long)x &
-		~(ASSOC_ARRAY_PTR_SUBTYPE_MASK | ASSOC_ARRAY_PTR_TYPE_MASK);
-}
-static inline
-struct assoc_array_node *assoc_array_ptr_to_node(const struct assoc_array_ptr *x)
-{
-	return (struct assoc_array_node *)__assoc_array_ptr_to_meta(x);
-}
-static inline
-struct assoc_array_shortcut *assoc_array_ptr_to_shortcut(const struct assoc_array_ptr *x)
-{
-	return (struct assoc_array_shortcut *)__assoc_array_ptr_to_meta(x);
-}
-
-static inline
-struct assoc_array_ptr *__assoc_array_x_to_ptr(const void *p, unsigned long t)
-{
-	return (struct assoc_array_ptr *)((unsigned long)p | t);
-}
-static inline
-struct assoc_array_ptr *assoc_array_leaf_to_ptr(const void *p)
-{
-	return __assoc_array_x_to_ptr(p, ASSOC_ARRAY_PTR_LEAF_TYPE);
-}
-static inline
-struct assoc_array_ptr *assoc_array_node_to_ptr(const struct assoc_array_node *p)
-{
-	return __assoc_array_x_to_ptr(
-		p, ASSOC_ARRAY_PTR_META_TYPE | ASSOC_ARRAY_PTR_NODE_SUBTYPE);
-}
-static inline
-struct assoc_array_ptr *assoc_array_shortcut_to_ptr(const struct assoc_array_shortcut *p)
-{
-	return __assoc_array_x_to_ptr(
-		p, ASSOC_ARRAY_PTR_META_TYPE | ASSOC_ARRAY_PTR_SHORTCUT_SUBTYPE);
-}
-
-#endif /* CONFIG_ASSOCIATIVE_ARRAY */
-#endif /* _LINUX_ASSOC_ARRAY_PRIV_H */
diff --git a/include/linux/key-type.h b/include/linux/key-type.h
index c4f329b6ae3fed..bb97bd3e5af4fa 100644
--- a/include/linux/key-type.h
+++ b/include/linux/key-type.h
@@ -161,7 +161,6 @@ struct key_type {
 				     const void *in, const void *in2);
 
 	/* internal fields */
-	atomic64_t		index_id;	/* Opaque keyring index ID */
 	struct list_head	link;		/* link in types list */
 	struct lock_class_key	lock_class;	/* key->sem lock class */
 } __randomize_layout;
diff --git a/include/linux/key.h b/include/linux/key.h
index 420412aab9263a..0d2d64e10f7baf 100644
--- a/include/linux/key.h
+++ b/include/linux/key.h
@@ -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>
 
@@ -107,34 +106,21 @@ struct key_owner;
 struct key_tag;
 struct keyring_list;
 struct keyring_name;
+struct keyring_index;
 
 struct key_tag {
 	struct rcu_head		rcu;
-	atomic64_t		index_id;	/* Opaque keyring index ID */
 	refcount_t		usage;
 	bool			removed;	/* T when subject removed */
 };
 
 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;
-	};
+	u32			hash;			/* Hash value */
+	unsigned int		desc_len;
 	struct key_type		*type;
 	struct key_tag		*domain_tag;	/* Domain of operation */
 	const char		*description;
-	u64			type_id;	/* Cached index IDs */
-	u64			domain_id;
 };
 
 union key_payload {
@@ -252,13 +238,11 @@ struct key {
 	union {
 		struct keyring_index_key index_key;
 		struct {
-			unsigned long	hash;
-			unsigned long	len_desc;
+			u32		hash;
+			unsigned int	desc_len;
 			struct key_type	*type;		/* type of key */
 			struct key_tag	*domain_tag;	/* Domain of operation */
 			char		*description;
-			u64		type_id;
-			u64		domain_id;
 		};
 	};
 
@@ -271,7 +255,7 @@ struct key {
 		struct {
 			/* Keyring bits */
 			struct list_head name_link;
-			struct assoc_array keys;
+			struct keyring_index __rcu *index;
 		};
 	};
 
@@ -439,6 +423,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,
diff --git a/kernel/bpf/keys.c b/kernel/bpf/keys.c
index bffc356839ac56..24e0416abc99dd 100644
--- a/kernel/bpf/keys.c
+++ b/kernel/bpf/keys.c
@@ -29,7 +29,7 @@ struct bpf_key *bpf_lookup_keyring(void)
 
 	if (!bpf_keyring)
 		return NULL;
-	if (!READ_ONCE(bpf_keyring->keys.nr_leaves_on_tree) ||
+	if (keyring_is_empty(bpf_keyring) ||
 	    !READ_ONCE(bpf_keyring->restrict_link))
 		return NULL;
 
diff --git a/lib/Kconfig b/lib/Kconfig
index 1e42f5167c68bc..f70382dbb15954 100644
--- a/lib/Kconfig
+++ b/lib/Kconfig
@@ -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
 
diff --git a/lib/Makefile b/lib/Makefile
index a2afe954805cb8..4777dfcc824405 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -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
diff --git a/lib/assoc_array.c b/lib/assoc_array.c
deleted file mode 100644
index b6c9723e12ced5..00000000000000
--- a/lib/assoc_array.c
+++ /dev/null
@@ -1,1724 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0-or-later
-/* Generic associative array implementation.
- *
- * See Documentation/core-api/assoc_array.rst for information.
- *
- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.
- * Written by David Howells (dhowells@redhat.com)
- */
-//#define DEBUG
-#include <linux/rcupdate.h>
-#include <linux/slab.h>
-#include <linux/err.h>
-#include <linux/assoc_array_priv.h>
-
-/*
- * Iterate over an associative array.  The caller must hold the RCU read lock
- * or better.
- */
-static int assoc_array_subtree_iterate(const struct assoc_array_ptr *root,
-				       const struct assoc_array_ptr *stop,
-				       int (*iterator)(const void *leaf,
-						       void *iterator_data),
-				       void *iterator_data)
-{
-	const struct assoc_array_shortcut *shortcut;
-	const struct assoc_array_node *node;
-	const struct assoc_array_ptr *cursor, *ptr, *parent;
-	unsigned long has_meta;
-	int slot, ret;
-
-	cursor = root;
-
-begin_node:
-	if (assoc_array_ptr_is_shortcut(cursor)) {
-		/* Descend through a shortcut */
-		shortcut = assoc_array_ptr_to_shortcut(cursor);
-		cursor = READ_ONCE(shortcut->next_node); /* Address dependency. */
-	}
-
-	node = assoc_array_ptr_to_node(cursor);
-	slot = 0;
-
-	/* We perform two passes of each node.
-	 *
-	 * The first pass does all the leaves in this node.  This means we
-	 * don't miss any leaves if the node is split up by insertion whilst
-	 * we're iterating over the branches rooted here (we may, however, see
-	 * some leaves twice).
-	 */
-	has_meta = 0;
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-		has_meta |= (unsigned long)ptr;
-		if (ptr && assoc_array_ptr_is_leaf(ptr)) {
-			/* We need a barrier between the read of the pointer,
-			 * which is supplied by the above READ_ONCE().
-			 */
-			/* Invoke the callback */
-			ret = iterator(assoc_array_ptr_to_leaf(ptr),
-				       iterator_data);
-			if (ret)
-				return ret;
-		}
-	}
-
-	/* The second pass attends to all the metadata pointers.  If we follow
-	 * one of these we may find that we don't come back here, but rather go
-	 * back to a replacement node with the leaves in a different layout.
-	 *
-	 * We are guaranteed to make progress, however, as the slot number for
-	 * a particular portion of the key space cannot change - and we
-	 * continue at the back pointer + 1.
-	 */
-	if (!(has_meta & ASSOC_ARRAY_PTR_META_TYPE))
-		goto finished_node;
-	slot = 0;
-
-continue_node:
-	node = assoc_array_ptr_to_node(cursor);
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-		if (assoc_array_ptr_is_meta(ptr)) {
-			cursor = ptr;
-			goto begin_node;
-		}
-	}
-
-finished_node:
-	/* Move up to the parent (may need to skip back over a shortcut) */
-	parent = READ_ONCE(node->back_pointer); /* Address dependency. */
-	slot = node->parent_slot;
-	if (parent == stop)
-		return 0;
-
-	if (assoc_array_ptr_is_shortcut(parent)) {
-		shortcut = assoc_array_ptr_to_shortcut(parent);
-		cursor = parent;
-		parent = READ_ONCE(shortcut->back_pointer); /* Address dependency. */
-		slot = shortcut->parent_slot;
-		if (parent == stop)
-			return 0;
-	}
-
-	/* Ascend to next slot in parent node */
-	cursor = parent;
-	slot++;
-	goto continue_node;
-}
-
-/**
- * assoc_array_iterate - Pass all objects in the array to a callback
- * @array: The array to iterate over.
- * @iterator: The callback function.
- * @iterator_data: Private data for the callback function.
- *
- * Iterate over all the objects in an associative array.  Each one will be
- * presented to the iterator function.
- *
- * If the array is being modified concurrently with the iteration then it is
- * possible that some objects in the array will be passed to the iterator
- * callback more than once - though every object should be passed at least
- * once.  If this is undesirable then the caller must lock against modification
- * for the duration of this function.
- *
- * 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.
- *
- * The caller should hold the RCU read lock or better if concurrent
- * modification is possible.
- */
-int assoc_array_iterate(const struct assoc_array *array,
-			int (*iterator)(const void *object,
-					void *iterator_data),
-			void *iterator_data)
-{
-	struct assoc_array_ptr *root = READ_ONCE(array->root); /* Address dependency. */
-
-	if (!root)
-		return 0;
-	return assoc_array_subtree_iterate(root, NULL, iterator, iterator_data);
-}
-
-enum assoc_array_walk_status {
-	assoc_array_walk_tree_empty,
-	assoc_array_walk_found_terminal_node,
-	assoc_array_walk_found_wrong_shortcut,
-};
-
-struct assoc_array_walk_result {
-	struct {
-		struct assoc_array_node	*node;	/* Node in which leaf might be found */
-		int		level;
-		int		slot;
-	} terminal_node;
-	struct {
-		struct assoc_array_shortcut *shortcut;
-		int		level;
-		int		sc_level;
-		unsigned long	sc_segments;
-		unsigned long	dissimilarity;
-	} wrong_shortcut;
-};
-
-/*
- * Navigate through the internal tree looking for the closest node to the key.
- */
-static enum assoc_array_walk_status
-assoc_array_walk(const struct assoc_array *array,
-		 const struct assoc_array_ops *ops,
-		 const void *index_key,
-		 struct assoc_array_walk_result *result)
-{
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *cursor, *ptr;
-	unsigned long sc_segments, dissimilarity;
-	unsigned long segments;
-	int level, sc_level, next_sc_level;
-	int slot;
-
-	pr_devel("-->%s()\n", __func__);
-
-	cursor = READ_ONCE(array->root);  /* Address dependency. */
-	if (!cursor)
-		return assoc_array_walk_tree_empty;
-
-	level = 0;
-
-	/* Use segments from the key for the new leaf to navigate through the
-	 * internal tree, skipping through nodes and shortcuts that are on
-	 * route to the destination.  Eventually we'll come to a slot that is
-	 * either empty or contains a leaf at which point we've found a node in
-	 * which the leaf we're looking for might be found or into which it
-	 * should be inserted.
-	 */
-jumped:
-	segments = ops->get_key_chunk(index_key, level);
-	pr_devel("segments[%d]: %lx\n", level, segments);
-
-	if (assoc_array_ptr_is_shortcut(cursor))
-		goto follow_shortcut;
-
-consider_node:
-	node = assoc_array_ptr_to_node(cursor);
-	slot = segments >> (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
-	slot &= ASSOC_ARRAY_FAN_MASK;
-	ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-
-	pr_devel("consider slot %x [ix=%d type=%lu]\n",
-		 slot, level, (unsigned long)ptr & 3);
-
-	if (!assoc_array_ptr_is_meta(ptr)) {
-		/* The node doesn't have a node/shortcut pointer in the slot
-		 * corresponding to the index key that we have to follow.
-		 */
-		result->terminal_node.node = node;
-		result->terminal_node.level = level;
-		result->terminal_node.slot = slot;
-		pr_devel("<--%s() = terminal_node\n", __func__);
-		return assoc_array_walk_found_terminal_node;
-	}
-
-	if (assoc_array_ptr_is_node(ptr)) {
-		/* There is a pointer to a node in the slot corresponding to
-		 * this index key segment, so we need to follow it.
-		 */
-		cursor = ptr;
-		level += ASSOC_ARRAY_LEVEL_STEP;
-		if ((level & ASSOC_ARRAY_KEY_CHUNK_MASK) != 0)
-			goto consider_node;
-		goto jumped;
-	}
-
-	/* There is a shortcut in the slot corresponding to the index key
-	 * segment.  We follow the shortcut if its partial index key matches
-	 * this leaf's.  Otherwise we need to split the shortcut.
-	 */
-	cursor = ptr;
-follow_shortcut:
-	shortcut = assoc_array_ptr_to_shortcut(cursor);
-	pr_devel("shortcut to %d\n", shortcut->skip_to_level);
-	sc_level = level + ASSOC_ARRAY_LEVEL_STEP;
-	BUG_ON(sc_level > shortcut->skip_to_level);
-
-	do {
-		/* Check the leaf against the shortcut's index key a word at a
-		 * time, trimming the final word (the shortcut stores the index
-		 * key completely from the root to the shortcut's target).
-		 */
-		if ((sc_level & ASSOC_ARRAY_KEY_CHUNK_MASK) == 0)
-			segments = ops->get_key_chunk(index_key, sc_level);
-
-		sc_segments = shortcut->index_key[sc_level >> ASSOC_ARRAY_KEY_CHUNK_SHIFT];
-		dissimilarity = segments ^ sc_segments;
-
-		if (shortcut->skip_to_level < round_down(sc_level,
-				ASSOC_ARRAY_KEY_CHUNK_SIZE) + ASSOC_ARRAY_KEY_CHUNK_SIZE) {
-			/* Trim segments that are beyond the shortcut */
-			int shift = shortcut->skip_to_level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-			dissimilarity &= ~(ULONG_MAX << shift);
-			next_sc_level = shortcut->skip_to_level;
-		} else {
-			next_sc_level = sc_level + ASSOC_ARRAY_KEY_CHUNK_SIZE;
-			next_sc_level = round_down(next_sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		}
-
-		if (dissimilarity != 0) {
-			/* This shortcut points elsewhere */
-			result->wrong_shortcut.shortcut = shortcut;
-			result->wrong_shortcut.level = level;
-			result->wrong_shortcut.sc_level = sc_level;
-			result->wrong_shortcut.sc_segments = sc_segments;
-			result->wrong_shortcut.dissimilarity = dissimilarity;
-			return assoc_array_walk_found_wrong_shortcut;
-		}
-
-		sc_level = next_sc_level;
-	} while (sc_level < shortcut->skip_to_level);
-
-	/* The shortcut matches the leaf's index to this point. */
-	cursor = READ_ONCE(shortcut->next_node); /* Address dependency. */
-	if (((level ^ sc_level) & ~ASSOC_ARRAY_KEY_CHUNK_MASK) != 0) {
-		level = sc_level;
-		goto jumped;
-	} else {
-		level = sc_level;
-		goto consider_node;
-	}
-}
-
-/**
- * assoc_array_find - Find an object by index key
- * @array: The associative array to search.
- * @ops: The operations to use.
- * @index_key: The key to the object.
- *
- * Find an object in an associative array by walking through the internal tree
- * to the node that should contain the object and then searching the leaves
- * there.  NULL is returned if the requested object was not found in the array.
- *
- * The caller must hold the RCU read lock or better.
- */
-void *assoc_array_find(const struct assoc_array *array,
-		       const struct assoc_array_ops *ops,
-		       const void *index_key)
-{
-	struct assoc_array_walk_result result;
-	const struct assoc_array_node *node;
-	const struct assoc_array_ptr *ptr;
-	const void *leaf;
-	int slot;
-
-	if (assoc_array_walk(array, ops, index_key, &result) !=
-	    assoc_array_walk_found_terminal_node)
-		return NULL;
-
-	node = result.terminal_node.node;
-
-	/* If the target key is available to us, it's has to be pointed to by
-	 * the terminal node.
-	 */
-	for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-		if (ptr && assoc_array_ptr_is_leaf(ptr)) {
-			/* We need a barrier between the read of the pointer
-			 * and dereferencing the pointer - but only if we are
-			 * actually going to dereference it.
-			 */
-			leaf = assoc_array_ptr_to_leaf(ptr);
-			if (ops->compare_object(leaf, index_key))
-				return (void *)leaf;
-		}
-	}
-
-	return NULL;
-}
-
-/*
- * Destructively iterate over an associative array.  The caller must prevent
- * other simultaneous accesses.
- */
-static void assoc_array_destroy_subtree(struct assoc_array_ptr *root,
-					const struct assoc_array_ops *ops)
-{
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *cursor, *parent = NULL;
-	int slot = -1;
-
-	pr_devel("-->%s()\n", __func__);
-
-	cursor = root;
-	if (!cursor) {
-		pr_devel("empty\n");
-		return;
-	}
-
-move_to_meta:
-	if (assoc_array_ptr_is_shortcut(cursor)) {
-		/* Descend through a shortcut */
-		pr_devel("[%d] shortcut\n", slot);
-		BUG_ON(!assoc_array_ptr_is_shortcut(cursor));
-		shortcut = assoc_array_ptr_to_shortcut(cursor);
-		BUG_ON(shortcut->back_pointer != parent);
-		BUG_ON(slot != -1 && shortcut->parent_slot != slot);
-		parent = cursor;
-		cursor = shortcut->next_node;
-		slot = -1;
-		BUG_ON(!assoc_array_ptr_is_node(cursor));
-	}
-
-	pr_devel("[%d] node\n", slot);
-	node = assoc_array_ptr_to_node(cursor);
-	BUG_ON(node->back_pointer != parent);
-	BUG_ON(slot != -1 && node->parent_slot != slot);
-	slot = 0;
-
-continue_node:
-	pr_devel("Node %p [back=%p]\n", node, node->back_pointer);
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		struct assoc_array_ptr *ptr = node->slots[slot];
-		if (!ptr)
-			continue;
-		if (assoc_array_ptr_is_meta(ptr)) {
-			parent = cursor;
-			cursor = ptr;
-			goto move_to_meta;
-		}
-
-		if (ops) {
-			pr_devel("[%d] free leaf\n", slot);
-			ops->free_object(assoc_array_ptr_to_leaf(ptr));
-		}
-	}
-
-	parent = node->back_pointer;
-	slot = node->parent_slot;
-	pr_devel("free node\n");
-	kfree(node);
-	if (!parent)
-		return; /* Done */
-
-	/* Move back up to the parent (may need to free a shortcut on
-	 * the way up) */
-	if (assoc_array_ptr_is_shortcut(parent)) {
-		shortcut = assoc_array_ptr_to_shortcut(parent);
-		BUG_ON(shortcut->next_node != cursor);
-		cursor = parent;
-		parent = shortcut->back_pointer;
-		slot = shortcut->parent_slot;
-		pr_devel("free shortcut\n");
-		kfree(shortcut);
-		if (!parent)
-			return;
-
-		BUG_ON(!assoc_array_ptr_is_node(parent));
-	}
-
-	/* Ascend to next slot in parent node */
-	pr_devel("ascend to %p[%d]\n", parent, slot);
-	cursor = parent;
-	node = assoc_array_ptr_to_node(cursor);
-	slot++;
-	goto continue_node;
-}
-
-/**
- * assoc_array_destroy - Destroy an associative array
- * @array: The array to destroy.
- * @ops: The operations to use.
- *
- * Discard all metadata and free all objects in an associative array.  The
- * array will be empty and ready to use again upon completion.  This function
- * cannot fail.
- *
- * The caller must prevent all other accesses whilst this takes place as no
- * attempt is made to adjust pointers gracefully to permit RCU readlock-holding
- * accesses to continue.  On the other hand, no memory allocation is required.
- */
-void assoc_array_destroy(struct assoc_array *array,
-			 const struct assoc_array_ops *ops)
-{
-	assoc_array_destroy_subtree(array->root, ops);
-	array->root = NULL;
-}
-
-/*
- * Handle insertion into an empty tree.
- */
-static bool assoc_array_insert_in_empty_tree(struct assoc_array_edit *edit)
-{
-	struct assoc_array_node *new_n0;
-
-	pr_devel("-->%s()\n", __func__);
-
-	new_n0 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n0)
-		return false;
-
-	edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-	edit->leaf_p = &new_n0->slots[0];
-	edit->adjust_count_on = new_n0;
-	edit->set[0].ptr = &edit->array->root;
-	edit->set[0].to = assoc_array_node_to_ptr(new_n0);
-
-	pr_devel("<--%s() = ok [no root]\n", __func__);
-	return true;
-}
-
-/*
- * Handle insertion into a terminal node.
- */
-static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit,
-						  const struct assoc_array_ops *ops,
-						  const void *index_key,
-						  struct assoc_array_walk_result *result)
-{
-	struct assoc_array_shortcut *shortcut, *new_s0;
-	struct assoc_array_node *node, *new_n0, *new_n1, *side;
-	struct assoc_array_ptr *ptr;
-	unsigned long dissimilarity, base_seg, blank;
-	size_t keylen;
-	bool have_meta;
-	int level, diff;
-	int slot, next_slot, free_slot, i, j;
-
-	node	= result->terminal_node.node;
-	level	= result->terminal_node.level;
-	edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot;
-
-	pr_devel("-->%s()\n", __func__);
-
-	/* We arrived at a node which doesn't have an onward node or shortcut
-	 * pointer that we have to follow.  This means that (a) the leaf we
-	 * want must go here (either by insertion or replacement) or (b) we
-	 * need to split this node and insert in one of the fragments.
-	 */
-	free_slot = -1;
-
-	/* Firstly, we have to check the leaves in this node to see if there's
-	 * a matching one we should replace in place.
-	 */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		ptr = node->slots[i];
-		if (!ptr) {
-			free_slot = i;
-			continue;
-		}
-		if (assoc_array_ptr_is_leaf(ptr) &&
-		    ops->compare_object(assoc_array_ptr_to_leaf(ptr),
-					index_key)) {
-			pr_devel("replace in slot %d\n", i);
-			edit->leaf_p = &node->slots[i];
-			edit->dead_leaf = node->slots[i];
-			pr_devel("<--%s() = ok [replace]\n", __func__);
-			return true;
-		}
-	}
-
-	/* If there is a free slot in this node then we can just insert the
-	 * leaf here.
-	 */
-	if (free_slot >= 0) {
-		pr_devel("insert in free slot %d\n", free_slot);
-		edit->leaf_p = &node->slots[free_slot];
-		edit->adjust_count_on = node;
-		pr_devel("<--%s() = ok [insert]\n", __func__);
-		return true;
-	}
-
-	/* The node has no spare slots - so we're either going to have to split
-	 * it or insert another node before it.
-	 *
-	 * Whatever, we're going to need at least two new nodes - so allocate
-	 * those now.  We may also need a new shortcut, but we deal with that
-	 * when we need it.
-	 */
-	new_n0 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n0)
-		return false;
-	edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-	new_n1 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n1)
-		return false;
-	edit->new_meta[1] = assoc_array_node_to_ptr(new_n1);
-
-	/* We need to find out how similar the leaves are. */
-	pr_devel("no spare slots\n");
-	have_meta = false;
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		ptr = node->slots[i];
-		if (assoc_array_ptr_is_meta(ptr)) {
-			edit->segment_cache[i] = 0xff;
-			have_meta = true;
-			continue;
-		}
-		base_seg = ops->get_object_key_chunk(
-			assoc_array_ptr_to_leaf(ptr), level);
-		base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-		edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
-	}
-
-	if (have_meta) {
-		pr_devel("have meta\n");
-		goto split_node;
-	}
-
-	/* The node contains only leaves */
-	dissimilarity = 0;
-	base_seg = edit->segment_cache[0];
-	for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++)
-		dissimilarity |= edit->segment_cache[i] ^ base_seg;
-
-	pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity);
-
-	if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) {
-		/* The old leaves all cluster in the same slot.  We will need
-		 * to insert a shortcut if the new node wants to cluster with them.
-		 */
-		if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0)
-			goto all_leaves_cluster_together;
-
-		/* Otherwise all the old leaves cluster in the same slot, but
-		 * the new leaf wants to go into a different slot - so we
-		 * create a new node (n0) to hold the new leaf and a pointer to
-		 * a new node (n1) holding all the old leaves.
-		 *
-		 * This can be done by falling through to the node splitting
-		 * path.
-		 */
-		pr_devel("present leaves cluster but not new leaf\n");
-	}
-
-split_node:
-	pr_devel("split node\n");
-
-	/* We need to split the current node.  The node must contain anything
-	 * from a single leaf (in the one leaf case, this leaf will cluster
-	 * with the new leaf) and the rest meta-pointers, to all leaves, some
-	 * of which may cluster.
-	 *
-	 * It won't contain the case in which all the current leaves plus the
-	 * new leaves want to cluster in the same slot.
-	 *
-	 * We need to expel at least two leaves out of a set consisting of the
-	 * leaves in the node and the new leaf.  The current meta pointers can
-	 * just be copied as they shouldn't cluster with any of the leaves.
-	 *
-	 * We need a new node (n0) to replace the current one and a new node to
-	 * take the expelled nodes (n1).
-	 */
-	edit->set[0].to = assoc_array_node_to_ptr(new_n0);
-	new_n0->back_pointer = node->back_pointer;
-	new_n0->parent_slot = node->parent_slot;
-	new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
-	new_n1->parent_slot = -1; /* Need to calculate this */
-
-do_split_node:
-	pr_devel("do_split_node\n");
-
-	new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
-	new_n1->nr_leaves_on_branch = 0;
-
-	/* Begin by finding two matching leaves.  There have to be at least two
-	 * that match - even if there are meta pointers - because any leaf that
-	 * would match a slot with a meta pointer in it must be somewhere
-	 * behind that meta pointer and cannot be here.  Further, given N
-	 * remaining leaf slots, we now have N+1 leaves to go in them.
-	 */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		slot = edit->segment_cache[i];
-		if (slot != 0xff)
-			for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++)
-				if (edit->segment_cache[j] == slot)
-					goto found_slot_for_multiple_occupancy;
-	}
-found_slot_for_multiple_occupancy:
-	pr_devel("same slot: %x %x [%02x]\n", i, j, slot);
-	BUG_ON(i >= ASSOC_ARRAY_FAN_OUT);
-	BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1);
-	BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT);
-
-	new_n1->parent_slot = slot;
-
-	/* Metadata pointers cannot change slot */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
-		if (assoc_array_ptr_is_meta(node->slots[i]))
-			new_n0->slots[i] = node->slots[i];
-		else
-			new_n0->slots[i] = NULL;
-	BUG_ON(new_n0->slots[slot] != NULL);
-	new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1);
-
-	/* Filter the leaf pointers between the new nodes */
-	free_slot = -1;
-	next_slot = 0;
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		if (assoc_array_ptr_is_meta(node->slots[i]))
-			continue;
-		if (edit->segment_cache[i] == slot) {
-			new_n1->slots[next_slot++] = node->slots[i];
-			new_n1->nr_leaves_on_branch++;
-		} else {
-			do {
-				free_slot++;
-			} while (new_n0->slots[free_slot] != NULL);
-			new_n0->slots[free_slot] = node->slots[i];
-		}
-	}
-
-	pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot);
-
-	if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) {
-		do {
-			free_slot++;
-		} while (new_n0->slots[free_slot] != NULL);
-		edit->leaf_p = &new_n0->slots[free_slot];
-		edit->adjust_count_on = new_n0;
-	} else {
-		edit->leaf_p = &new_n1->slots[next_slot++];
-		edit->adjust_count_on = new_n1;
-	}
-
-	BUG_ON(next_slot <= 1);
-
-	edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0);
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		if (edit->segment_cache[i] == 0xff) {
-			ptr = node->slots[i];
-			BUG_ON(assoc_array_ptr_is_leaf(ptr));
-			if (assoc_array_ptr_is_node(ptr)) {
-				side = assoc_array_ptr_to_node(ptr);
-				edit->set_backpointers[i] = &side->back_pointer;
-			} else {
-				shortcut = assoc_array_ptr_to_shortcut(ptr);
-				edit->set_backpointers[i] = &shortcut->back_pointer;
-			}
-		}
-	}
-
-	ptr = node->back_pointer;
-	if (!ptr)
-		edit->set[0].ptr = &edit->array->root;
-	else if (assoc_array_ptr_is_node(ptr))
-		edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot];
-	else
-		edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node;
-	edit->excised_meta[0] = assoc_array_node_to_ptr(node);
-	pr_devel("<--%s() = ok [split node]\n", __func__);
-	return true;
-
-all_leaves_cluster_together:
-	/* All the leaves, new and old, want to cluster together in this node
-	 * in the same slot, so we have to replace this node with a shortcut to
-	 * skip over the identical parts of the key and then place a pair of
-	 * nodes, one inside the other, at the end of the shortcut and
-	 * distribute the keys between them.
-	 *
-	 * Firstly we need to work out where the leaves start diverging as a
-	 * bit position into their keys so that we know how big the shortcut
-	 * needs to be.
-	 *
-	 * We only need to make a single pass of N of the N+1 leaves because if
-	 * any keys differ between themselves at bit X then at least one of
-	 * them must also differ with the base key at bit X or before.
-	 */
-	pr_devel("all leaves cluster together\n");
-	diff = INT_MAX;
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]),
-					  index_key);
-		if (x < diff) {
-			BUG_ON(x < 0);
-			diff = x;
-		}
-	}
-	BUG_ON(diff == INT_MAX);
-	BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP);
-
-	keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-	keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-
-	new_s0 = kzalloc_flex(*new_s0, index_key, keylen);
-	if (!new_s0)
-		return false;
-	edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0);
-
-	edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
-	new_s0->back_pointer = node->back_pointer;
-	new_s0->parent_slot = node->parent_slot;
-	new_s0->next_node = assoc_array_node_to_ptr(new_n0);
-	new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
-	new_n0->parent_slot = 0;
-	new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
-	new_n1->parent_slot = -1; /* Need to calculate this */
-
-	new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK;
-	pr_devel("skip_to_level = %d [diff %d]\n", level, diff);
-	BUG_ON(level <= 0);
-
-	for (i = 0; i < keylen; i++)
-		new_s0->index_key[i] =
-			ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE);
-
-	if (level & ASSOC_ARRAY_KEY_CHUNK_MASK) {
-		blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
-		pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank);
-		new_s0->index_key[keylen - 1] &= ~blank;
-	}
-
-	/* This now reduces to a node splitting exercise for which we'll need
-	 * to regenerate the disparity table.
-	 */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		ptr = node->slots[i];
-		base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr),
-						     level);
-		base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-		edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
-	}
-
-	base_seg = ops->get_key_chunk(index_key, level);
-	base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-	edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK;
-	goto do_split_node;
-}
-
-/*
- * Handle insertion into the middle of a shortcut.
- */
-static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit,
-					    const struct assoc_array_ops *ops,
-					    struct assoc_array_walk_result *result)
-{
-	struct assoc_array_shortcut *shortcut, *new_s0, *new_s1;
-	struct assoc_array_node *node, *new_n0, *side;
-	unsigned long sc_segments, dissimilarity, blank;
-	size_t keylen;
-	int level, sc_level, diff;
-	int sc_slot;
-
-	shortcut	= result->wrong_shortcut.shortcut;
-	level		= result->wrong_shortcut.level;
-	sc_level	= result->wrong_shortcut.sc_level;
-	sc_segments	= result->wrong_shortcut.sc_segments;
-	dissimilarity	= result->wrong_shortcut.dissimilarity;
-
-	pr_devel("-->%s(ix=%d dis=%lx scix=%d)\n",
-		 __func__, level, dissimilarity, sc_level);
-
-	/* We need to split a shortcut and insert a node between the two
-	 * pieces.  Zero-length pieces will be dispensed with entirely.
-	 *
-	 * First of all, we need to find out in which level the first
-	 * difference was.
-	 */
-	diff = __ffs(dissimilarity);
-	diff &= ~ASSOC_ARRAY_LEVEL_STEP_MASK;
-	diff += sc_level & ~ASSOC_ARRAY_KEY_CHUNK_MASK;
-	pr_devel("diff=%d\n", diff);
-
-	if (!shortcut->back_pointer) {
-		edit->set[0].ptr = &edit->array->root;
-	} else if (assoc_array_ptr_is_node(shortcut->back_pointer)) {
-		node = assoc_array_ptr_to_node(shortcut->back_pointer);
-		edit->set[0].ptr = &node->slots[shortcut->parent_slot];
-	} else {
-		BUG();
-	}
-
-	edit->excised_meta[0] = assoc_array_shortcut_to_ptr(shortcut);
-
-	/* Create a new node now since we're going to need it anyway */
-	new_n0 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n0)
-		return false;
-	edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-	edit->adjust_count_on = new_n0;
-
-	/* Insert a new shortcut before the new node if this segment isn't of
-	 * zero length - otherwise we just connect the new node directly to the
-	 * parent.
-	 */
-	level += ASSOC_ARRAY_LEVEL_STEP;
-	if (diff > level) {
-		pr_devel("pre-shortcut %d...%d\n", level, diff);
-		keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-
-		new_s0 = kzalloc_flex(*new_s0, index_key, keylen);
-		if (!new_s0)
-			return false;
-		edit->new_meta[1] = assoc_array_shortcut_to_ptr(new_s0);
-		edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
-		new_s0->back_pointer = shortcut->back_pointer;
-		new_s0->parent_slot = shortcut->parent_slot;
-		new_s0->next_node = assoc_array_node_to_ptr(new_n0);
-		new_s0->skip_to_level = diff;
-
-		new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
-		new_n0->parent_slot = 0;
-
-		memcpy(new_s0->index_key, shortcut->index_key,
-		       flex_array_size(new_s0, index_key, keylen));
-
-		blank = ULONG_MAX << (diff & ASSOC_ARRAY_KEY_CHUNK_MASK);
-		pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, diff, blank);
-		new_s0->index_key[keylen - 1] &= ~blank;
-	} else {
-		pr_devel("no pre-shortcut\n");
-		edit->set[0].to = assoc_array_node_to_ptr(new_n0);
-		new_n0->back_pointer = shortcut->back_pointer;
-		new_n0->parent_slot = shortcut->parent_slot;
-	}
-
-	side = assoc_array_ptr_to_node(shortcut->next_node);
-	new_n0->nr_leaves_on_branch = side->nr_leaves_on_branch;
-
-	/* We need to know which slot in the new node is going to take a
-	 * metadata pointer.
-	 */
-	sc_slot = sc_segments >> (diff & ASSOC_ARRAY_KEY_CHUNK_MASK);
-	sc_slot &= ASSOC_ARRAY_FAN_MASK;
-
-	pr_devel("new slot %lx >> %d -> %d\n",
-		 sc_segments, diff & ASSOC_ARRAY_KEY_CHUNK_MASK, sc_slot);
-
-	/* Determine whether we need to follow the new node with a replacement
-	 * for the current shortcut.  We could in theory reuse the current
-	 * shortcut if its parent slot number doesn't change - but that's a
-	 * 1-in-16 chance so not worth expending the code upon.
-	 */
-	level = diff + ASSOC_ARRAY_LEVEL_STEP;
-	if (level < shortcut->skip_to_level) {
-		pr_devel("post-shortcut %d...%d\n", level, shortcut->skip_to_level);
-		keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-
-		new_s1 = kzalloc_flex(*new_s1, index_key, keylen);
-		if (!new_s1)
-			return false;
-		edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s1);
-
-		new_s1->back_pointer = assoc_array_node_to_ptr(new_n0);
-		new_s1->parent_slot = sc_slot;
-		new_s1->next_node = shortcut->next_node;
-		new_s1->skip_to_level = shortcut->skip_to_level;
-
-		new_n0->slots[sc_slot] = assoc_array_shortcut_to_ptr(new_s1);
-
-		memcpy(new_s1->index_key, shortcut->index_key,
-		       flex_array_size(new_s1, index_key, keylen));
-
-		edit->set[1].ptr = &side->back_pointer;
-		edit->set[1].to = assoc_array_shortcut_to_ptr(new_s1);
-	} else {
-		pr_devel("no post-shortcut\n");
-
-		/* We don't have to replace the pointed-to node as long as we
-		 * use memory barriers to make sure the parent slot number is
-		 * changed before the back pointer (the parent slot number is
-		 * irrelevant to the old parent shortcut).
-		 */
-		new_n0->slots[sc_slot] = shortcut->next_node;
-		edit->set_parent_slot[0].p = &side->parent_slot;
-		edit->set_parent_slot[0].to = sc_slot;
-		edit->set[1].ptr = &side->back_pointer;
-		edit->set[1].to = assoc_array_node_to_ptr(new_n0);
-	}
-
-	/* Install the new leaf in a spare slot in the new node. */
-	if (sc_slot == 0)
-		edit->leaf_p = &new_n0->slots[1];
-	else
-		edit->leaf_p = &new_n0->slots[0];
-
-	pr_devel("<--%s() = ok [split shortcut]\n", __func__);
-	return true;
-}
-
-/**
- * assoc_array_insert - Script insertion of an object into an associative array
- * @array: The array to insert into.
- * @ops: The operations to use.
- * @index_key: The key to insert at.
- * @object: The object to insert.
- *
- * Precalculate and preallocate a script for the insertion or replacement of an
- * object in an associative array.  This results in an edit script that can
- * either be applied or cancelled.
- *
- * The function returns a pointer to an edit script or -ENOMEM.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-struct assoc_array_edit *assoc_array_insert(struct assoc_array *array,
-					    const struct assoc_array_ops *ops,
-					    const void *index_key,
-					    void *object)
-{
-	struct assoc_array_walk_result result;
-	struct assoc_array_edit *edit;
-
-	pr_devel("-->%s()\n", __func__);
-
-	/* The leaf pointer we're given must not have the bottom bit set as we
-	 * use those for type-marking the pointer.  NULL pointers are also not
-	 * allowed as they indicate an empty slot but we have to allow them
-	 * here as they can be updated later.
-	 */
-	BUG_ON(assoc_array_ptr_is_meta(object));
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return ERR_PTR(-ENOMEM);
-	edit->array = array;
-	edit->ops = ops;
-	edit->leaf = assoc_array_leaf_to_ptr(object);
-	edit->adjust_count_by = 1;
-
-	switch (assoc_array_walk(array, ops, index_key, &result)) {
-	case assoc_array_walk_tree_empty:
-		/* Allocate a root node if there isn't one yet */
-		if (!assoc_array_insert_in_empty_tree(edit))
-			goto enomem;
-		return edit;
-
-	case assoc_array_walk_found_terminal_node:
-		/* We found a node that doesn't have a node/shortcut pointer in
-		 * the slot corresponding to the index key that we have to
-		 * follow.
-		 */
-		if (!assoc_array_insert_into_terminal_node(edit, ops, index_key,
-							   &result))
-			goto enomem;
-		return edit;
-
-	case assoc_array_walk_found_wrong_shortcut:
-		/* We found a shortcut that didn't match our key in a slot we
-		 * needed to follow.
-		 */
-		if (!assoc_array_insert_mid_shortcut(edit, ops, &result))
-			goto enomem;
-		return edit;
-	}
-
-enomem:
-	/* Clean up after an out of memory error */
-	pr_devel("enomem\n");
-	assoc_array_cancel_edit(edit);
-	return ERR_PTR(-ENOMEM);
-}
-
-/**
- * assoc_array_insert_set_object - Set the new object pointer in an edit script
- * @edit: The edit script to modify.
- * @object: The object pointer to set.
- *
- * Change the object to be inserted in an edit script.  The object pointed to
- * by the old object is not freed.  This must be done prior to applying the
- * script.
- */
-void assoc_array_insert_set_object(struct assoc_array_edit *edit, void *object)
-{
-	BUG_ON(!object);
-	edit->leaf = assoc_array_leaf_to_ptr(object);
-}
-
-struct assoc_array_delete_collapse_context {
-	struct assoc_array_node	*node;
-	const void		*skip_leaf;
-	int			slot;
-};
-
-/*
- * Subtree collapse to node iterator.
- */
-static int assoc_array_delete_collapse_iterator(const void *leaf,
-						void *iterator_data)
-{
-	struct assoc_array_delete_collapse_context *collapse = iterator_data;
-
-	if (leaf == collapse->skip_leaf)
-		return 0;
-
-	BUG_ON(collapse->slot >= ASSOC_ARRAY_FAN_OUT);
-
-	collapse->node->slots[collapse->slot++] = assoc_array_leaf_to_ptr(leaf);
-	return 0;
-}
-
-/**
- * assoc_array_delete - Script deletion of an object from an associative array
- * @array: The array to search.
- * @ops: The operations to use.
- * @index_key: The key to the object.
- *
- * Precalculate and preallocate a script for the deletion of an object from an
- * associative array.  This results in an edit script that can either be
- * applied or cancelled.
- *
- * The function returns a pointer to an edit script if the object was found,
- * NULL if the object was not found or -ENOMEM.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-struct assoc_array_edit *assoc_array_delete(struct assoc_array *array,
-					    const struct assoc_array_ops *ops,
-					    const void *index_key)
-{
-	struct assoc_array_delete_collapse_context collapse;
-	struct assoc_array_walk_result result;
-	struct assoc_array_node *node, *new_n0;
-	struct assoc_array_edit *edit;
-	struct assoc_array_ptr *ptr;
-	bool has_meta;
-	int slot, i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return ERR_PTR(-ENOMEM);
-	edit->array = array;
-	edit->ops = ops;
-	edit->adjust_count_by = -1;
-
-	switch (assoc_array_walk(array, ops, index_key, &result)) {
-	case assoc_array_walk_found_terminal_node:
-		/* We found a node that should contain the leaf we've been
-		 * asked to remove - *if* it's in the tree.
-		 */
-		pr_devel("terminal_node\n");
-		node = result.terminal_node.node;
-
-		for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-			ptr = node->slots[slot];
-			if (ptr &&
-			    assoc_array_ptr_is_leaf(ptr) &&
-			    ops->compare_object(assoc_array_ptr_to_leaf(ptr),
-						index_key))
-				goto found_leaf;
-		}
-		fallthrough;
-	case assoc_array_walk_tree_empty:
-	case assoc_array_walk_found_wrong_shortcut:
-	default:
-		assoc_array_cancel_edit(edit);
-		pr_devel("not found\n");
-		return NULL;
-	}
-
-found_leaf:
-	BUG_ON(array->nr_leaves_on_tree <= 0);
-
-	/* In the simplest form of deletion we just clear the slot and release
-	 * the leaf after a suitable interval.
-	 */
-	edit->dead_leaf = node->slots[slot];
-	edit->set[0].ptr = &node->slots[slot];
-	edit->set[0].to = NULL;
-	edit->adjust_count_on = node;
-
-	/* If that concludes erasure of the last leaf, then delete the entire
-	 * internal array.
-	 */
-	if (array->nr_leaves_on_tree == 1) {
-		edit->set[1].ptr = &array->root;
-		edit->set[1].to = NULL;
-		edit->adjust_count_on = NULL;
-		edit->excised_subtree = array->root;
-		pr_devel("all gone\n");
-		return edit;
-	}
-
-	/* However, we'd also like to clear up some metadata blocks if we
-	 * possibly can.
-	 *
-	 * We go for a simple algorithm of: if this node has FAN_OUT or fewer
-	 * leaves in it, then attempt to collapse it - and attempt to
-	 * recursively collapse up the tree.
-	 *
-	 * We could also try and collapse in partially filled subtrees to take
-	 * up space in this node.
-	 */
-	if (node->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) {
-		struct assoc_array_node *parent, *grandparent;
-		struct assoc_array_ptr *ptr;
-
-		/* First of all, we need to know if this node has metadata so
-		 * that we don't try collapsing if all the leaves are already
-		 * here.
-		 */
-		has_meta = false;
-		for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-			ptr = node->slots[i];
-			if (assoc_array_ptr_is_meta(ptr)) {
-				has_meta = true;
-				break;
-			}
-		}
-
-		pr_devel("leaves: %ld [m=%d]\n",
-			 node->nr_leaves_on_branch - 1, has_meta);
-
-		/* Look further up the tree to see if we can collapse this node
-		 * into a more proximal node too.
-		 */
-		parent = node;
-	collapse_up:
-		pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch);
-
-		ptr = parent->back_pointer;
-		if (!ptr)
-			goto do_collapse;
-		if (assoc_array_ptr_is_shortcut(ptr)) {
-			struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(ptr);
-			ptr = s->back_pointer;
-			if (!ptr)
-				goto do_collapse;
-		}
-
-		grandparent = assoc_array_ptr_to_node(ptr);
-		if (grandparent->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) {
-			parent = grandparent;
-			goto collapse_up;
-		}
-
-	do_collapse:
-		/* There's no point collapsing if the original node has no meta
-		 * pointers to discard and if we didn't merge into one of that
-		 * node's ancestry.
-		 */
-		if (has_meta || parent != node) {
-			node = parent;
-
-			/* Create a new node to collapse into */
-			new_n0 = kzalloc_obj(struct assoc_array_node);
-			if (!new_n0)
-				goto enomem;
-			edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-
-			new_n0->back_pointer = node->back_pointer;
-			new_n0->parent_slot = node->parent_slot;
-			new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
-			edit->adjust_count_on = new_n0;
-
-			collapse.node = new_n0;
-			collapse.skip_leaf = assoc_array_ptr_to_leaf(edit->dead_leaf);
-			collapse.slot = 0;
-			assoc_array_subtree_iterate(assoc_array_node_to_ptr(node),
-						    node->back_pointer,
-						    assoc_array_delete_collapse_iterator,
-						    &collapse);
-			pr_devel("collapsed %d,%lu\n", collapse.slot, new_n0->nr_leaves_on_branch);
-			BUG_ON(collapse.slot != new_n0->nr_leaves_on_branch - 1);
-
-			if (!node->back_pointer) {
-				edit->set[1].ptr = &array->root;
-			} else if (assoc_array_ptr_is_leaf(node->back_pointer)) {
-				BUG();
-			} else if (assoc_array_ptr_is_node(node->back_pointer)) {
-				struct assoc_array_node *p =
-					assoc_array_ptr_to_node(node->back_pointer);
-				edit->set[1].ptr = &p->slots[node->parent_slot];
-			} else if (assoc_array_ptr_is_shortcut(node->back_pointer)) {
-				struct assoc_array_shortcut *s =
-					assoc_array_ptr_to_shortcut(node->back_pointer);
-				edit->set[1].ptr = &s->next_node;
-			}
-			edit->set[1].to = assoc_array_node_to_ptr(new_n0);
-			edit->excised_subtree = assoc_array_node_to_ptr(node);
-		}
-	}
-
-	return edit;
-
-enomem:
-	/* Clean up after an out of memory error */
-	pr_devel("enomem\n");
-	assoc_array_cancel_edit(edit);
-	return ERR_PTR(-ENOMEM);
-}
-
-/**
- * assoc_array_clear - Script deletion of all objects from an associative array
- * @array: The array to clear.
- * @ops: The operations to use.
- *
- * Precalculate and preallocate a script for the deletion of all the objects
- * from an associative array.  This results in an edit script that can either
- * be applied or cancelled.
- *
- * The function returns a pointer to an edit script if there are objects to be
- * deleted, NULL if there are no objects in the array or -ENOMEM.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-struct assoc_array_edit *assoc_array_clear(struct assoc_array *array,
-					   const struct assoc_array_ops *ops)
-{
-	struct assoc_array_edit *edit;
-
-	pr_devel("-->%s()\n", __func__);
-
-	if (!array->root)
-		return NULL;
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return ERR_PTR(-ENOMEM);
-	edit->array = array;
-	edit->ops = ops;
-	edit->set[1].ptr = &array->root;
-	edit->set[1].to = NULL;
-	edit->excised_subtree = array->root;
-	edit->ops_for_excised_subtree = ops;
-	pr_devel("all gone\n");
-	return edit;
-}
-
-/*
- * Handle the deferred destruction after an applied edit.
- */
-static void assoc_array_rcu_cleanup(struct rcu_head *head)
-{
-	struct assoc_array_edit *edit =
-		container_of(head, struct assoc_array_edit, rcu);
-	int i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	if (edit->dead_leaf)
-		edit->ops->free_object(assoc_array_ptr_to_leaf(edit->dead_leaf));
-	for (i = 0; i < ARRAY_SIZE(edit->excised_meta); i++)
-		if (edit->excised_meta[i])
-			kfree(assoc_array_ptr_to_node(edit->excised_meta[i]));
-
-	if (edit->excised_subtree) {
-		BUG_ON(assoc_array_ptr_is_leaf(edit->excised_subtree));
-		if (assoc_array_ptr_is_node(edit->excised_subtree)) {
-			struct assoc_array_node *n =
-				assoc_array_ptr_to_node(edit->excised_subtree);
-			n->back_pointer = NULL;
-		} else {
-			struct assoc_array_shortcut *s =
-				assoc_array_ptr_to_shortcut(edit->excised_subtree);
-			s->back_pointer = NULL;
-		}
-		assoc_array_destroy_subtree(edit->excised_subtree,
-					    edit->ops_for_excised_subtree);
-	}
-
-	kfree(edit);
-}
-
-/**
- * assoc_array_apply_edit - Apply an edit script to an associative array
- * @edit: The script to apply.
- *
- * Apply an edit script to an associative array to effect an insertion,
- * deletion or clearance.  As the edit script includes preallocated memory,
- * this is guaranteed not to fail.
- *
- * The edit script, dead objects and dead metadata will be scheduled for
- * destruction after an RCU grace period to permit those doing read-only
- * accesses on the array to continue to do so under the RCU read lock whilst
- * the edit is taking place.
- */
-void assoc_array_apply_edit(struct assoc_array_edit *edit)
-{
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *ptr;
-	int i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	smp_wmb();
-	if (edit->leaf_p)
-		*edit->leaf_p = edit->leaf;
-
-	smp_wmb();
-	for (i = 0; i < ARRAY_SIZE(edit->set_parent_slot); i++)
-		if (edit->set_parent_slot[i].p)
-			*edit->set_parent_slot[i].p = edit->set_parent_slot[i].to;
-
-	smp_wmb();
-	for (i = 0; i < ARRAY_SIZE(edit->set_backpointers); i++)
-		if (edit->set_backpointers[i])
-			*edit->set_backpointers[i] = edit->set_backpointers_to;
-
-	smp_wmb();
-	for (i = 0; i < ARRAY_SIZE(edit->set); i++)
-		if (edit->set[i].ptr)
-			*edit->set[i].ptr = edit->set[i].to;
-
-	if (edit->array->root == NULL) {
-		edit->array->nr_leaves_on_tree = 0;
-	} else if (edit->adjust_count_on) {
-		node = edit->adjust_count_on;
-		for (;;) {
-			node->nr_leaves_on_branch += edit->adjust_count_by;
-
-			ptr = node->back_pointer;
-			if (!ptr)
-				break;
-			if (assoc_array_ptr_is_shortcut(ptr)) {
-				shortcut = assoc_array_ptr_to_shortcut(ptr);
-				ptr = shortcut->back_pointer;
-				if (!ptr)
-					break;
-			}
-			BUG_ON(!assoc_array_ptr_is_node(ptr));
-			node = assoc_array_ptr_to_node(ptr);
-		}
-
-		edit->array->nr_leaves_on_tree += edit->adjust_count_by;
-	}
-
-	call_rcu(&edit->rcu, assoc_array_rcu_cleanup);
-}
-
-/**
- * assoc_array_cancel_edit - Discard an edit script.
- * @edit: The script to discard.
- *
- * Free an edit script and all the preallocated data it holds without making
- * any changes to the associative array it was intended for.
- *
- * NOTE!  In the case of an insertion script, this does _not_ release the leaf
- * that was to be inserted.  That is left to the caller.
- */
-void assoc_array_cancel_edit(struct assoc_array_edit *edit)
-{
-	struct assoc_array_ptr *ptr;
-	int i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	/* Clean up after an out of memory error */
-	for (i = 0; i < ARRAY_SIZE(edit->new_meta); i++) {
-		ptr = edit->new_meta[i];
-		if (ptr) {
-			if (assoc_array_ptr_is_node(ptr))
-				kfree(assoc_array_ptr_to_node(ptr));
-			else
-				kfree(assoc_array_ptr_to_shortcut(ptr));
-		}
-	}
-	kfree(edit);
-}
-
-/**
- * assoc_array_gc - Garbage collect an associative array.
- * @array: The array to clean.
- * @ops: The operations to use.
- * @iterator: A callback function to pass judgement on each object.
- * @iterator_data: Private data for the callback function.
- *
- * Collect garbage from an associative array and pack down the internal tree to
- * save memory.
- *
- * The iterator function is asked to pass judgement upon each object in the
- * array.  If it returns false, the object is discard and if it returns true,
- * the object is kept.  If it returns true, it must increment the object's
- * usage count (or whatever it needs to do to retain it) before returning.
- *
- * This function returns 0 if successful or -ENOMEM if out of memory.  In the
- * latter case, the array is not changed.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-int assoc_array_gc(struct assoc_array *array,
-		   const struct assoc_array_ops *ops,
-		   bool (*iterator)(void *object, void *iterator_data),
-		   void *iterator_data)
-{
-	struct assoc_array_shortcut *shortcut, *new_s;
-	struct assoc_array_node *node, *new_n;
-	struct assoc_array_edit *edit;
-	struct assoc_array_ptr *cursor, *ptr;
-	struct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp;
-	unsigned long nr_leaves_on_tree;
-	bool retained;
-	int keylen, slot, nr_free, next_slot, i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	if (!array->root)
-		return 0;
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return -ENOMEM;
-	edit->array = array;
-	edit->ops = ops;
-	edit->ops_for_excised_subtree = ops;
-	edit->set[0].ptr = &array->root;
-	edit->excised_subtree = array->root;
-
-	new_root = new_parent = NULL;
-	new_ptr_pp = &new_root;
-	cursor = array->root;
-
-descend:
-	/* If this point is a shortcut, then we need to duplicate it and
-	 * advance the target cursor.
-	 */
-	if (assoc_array_ptr_is_shortcut(cursor)) {
-		shortcut = assoc_array_ptr_to_shortcut(cursor);
-		keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-		new_s = kmalloc_flex(*new_s, index_key, keylen);
-		if (!new_s)
-			goto enomem;
-		pr_devel("dup shortcut %p -> %p\n", shortcut, new_s);
-		memcpy(new_s, shortcut, struct_size(new_s, index_key, keylen));
-		new_s->back_pointer = new_parent;
-		new_s->parent_slot = shortcut->parent_slot;
-		*new_ptr_pp = new_parent = assoc_array_shortcut_to_ptr(new_s);
-		new_ptr_pp = &new_s->next_node;
-		cursor = shortcut->next_node;
-	}
-
-	/* Duplicate the node at this position */
-	node = assoc_array_ptr_to_node(cursor);
-	new_n = kzalloc_obj(struct assoc_array_node);
-	if (!new_n)
-		goto enomem;
-	pr_devel("dup node %p -> %p\n", node, new_n);
-	new_n->back_pointer = new_parent;
-	new_n->parent_slot = node->parent_slot;
-	*new_ptr_pp = new_parent = assoc_array_node_to_ptr(new_n);
-	new_ptr_pp = NULL;
-	slot = 0;
-
-continue_node:
-	/* Filter across any leaves and gc any subtrees */
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = node->slots[slot];
-		if (!ptr)
-			continue;
-
-		if (assoc_array_ptr_is_leaf(ptr)) {
-			if (iterator(assoc_array_ptr_to_leaf(ptr),
-				     iterator_data))
-				/* The iterator will have done any reference
-				 * counting on the object for us.
-				 */
-				new_n->slots[slot] = ptr;
-			continue;
-		}
-
-		new_ptr_pp = &new_n->slots[slot];
-		cursor = ptr;
-		goto descend;
-	}
-
-retry_compress:
-	pr_devel("-- compress node %p --\n", new_n);
-
-	/* Count up the number of empty slots in this node and work out the
-	 * subtree leaf count.
-	 */
-	new_n->nr_leaves_on_branch = 0;
-	nr_free = 0;
-	for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = new_n->slots[slot];
-		if (!ptr)
-			nr_free++;
-		else if (assoc_array_ptr_is_leaf(ptr))
-			new_n->nr_leaves_on_branch++;
-	}
-	pr_devel("free=%d, leaves=%lu\n", nr_free, new_n->nr_leaves_on_branch);
-
-	/* See what we can fold in */
-	retained = false;
-	next_slot = 0;
-	for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		struct assoc_array_shortcut *s;
-		struct assoc_array_node *child;
-
-		ptr = new_n->slots[slot];
-		if (!ptr || assoc_array_ptr_is_leaf(ptr))
-			continue;
-
-		s = NULL;
-		if (assoc_array_ptr_is_shortcut(ptr)) {
-			s = assoc_array_ptr_to_shortcut(ptr);
-			ptr = s->next_node;
-		}
-
-		child = assoc_array_ptr_to_node(ptr);
-		new_n->nr_leaves_on_branch += child->nr_leaves_on_branch;
-
-		if (child->nr_leaves_on_branch <= nr_free + 1) {
-			/* Fold the child node into this one */
-			pr_devel("[%d] fold node %lu/%d [nx %d]\n",
-				 slot, child->nr_leaves_on_branch, nr_free + 1,
-				 next_slot);
-
-			/* We would already have reaped an intervening shortcut
-			 * on the way back up the tree.
-			 */
-			BUG_ON(s);
-
-			new_n->slots[slot] = NULL;
-			nr_free++;
-			if (slot < next_slot)
-				next_slot = slot;
-			for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-				struct assoc_array_ptr *p = child->slots[i];
-				if (!p)
-					continue;
-				BUG_ON(assoc_array_ptr_is_meta(p));
-				while (new_n->slots[next_slot])
-					next_slot++;
-				BUG_ON(next_slot >= ASSOC_ARRAY_FAN_OUT);
-				new_n->slots[next_slot++] = p;
-				nr_free--;
-			}
-			kfree(child);
-		} else {
-			pr_devel("[%d] retain node %lu/%d [nx %d]\n",
-				 slot, child->nr_leaves_on_branch, nr_free + 1,
-				 next_slot);
-			retained = true;
-		}
-	}
-
-	if (retained && new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) {
-		pr_devel("internal nodes remain despite enough space, retrying\n");
-		goto retry_compress;
-	}
-	pr_devel("after: %lu\n", new_n->nr_leaves_on_branch);
-
-	nr_leaves_on_tree = new_n->nr_leaves_on_branch;
-
-	/* Excise this node if it is singly occupied by a shortcut */
-	if (nr_free == ASSOC_ARRAY_FAN_OUT - 1) {
-		for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++)
-			if ((ptr = new_n->slots[slot]))
-				break;
-
-		if (assoc_array_ptr_is_meta(ptr) &&
-		    assoc_array_ptr_is_shortcut(ptr)) {
-			pr_devel("excise node %p with 1 shortcut\n", new_n);
-			new_s = assoc_array_ptr_to_shortcut(ptr);
-			new_parent = new_n->back_pointer;
-			slot = new_n->parent_slot;
-			kfree(new_n);
-			if (!new_parent) {
-				new_s->back_pointer = NULL;
-				new_s->parent_slot = 0;
-				new_root = ptr;
-				goto gc_complete;
-			}
-
-			if (assoc_array_ptr_is_shortcut(new_parent)) {
-				/* We can discard any preceding shortcut also */
-				struct assoc_array_shortcut *s =
-					assoc_array_ptr_to_shortcut(new_parent);
-
-				pr_devel("excise preceding shortcut\n");
-
-				new_parent = new_s->back_pointer = s->back_pointer;
-				slot = new_s->parent_slot = s->parent_slot;
-				kfree(s);
-				if (!new_parent) {
-					new_s->back_pointer = NULL;
-					new_s->parent_slot = 0;
-					new_root = ptr;
-					goto gc_complete;
-				}
-			}
-
-			new_s->back_pointer = new_parent;
-			new_s->parent_slot = slot;
-			new_n = assoc_array_ptr_to_node(new_parent);
-			new_n->slots[slot] = ptr;
-			goto ascend_old_tree;
-		}
-	}
-
-	/* Excise any shortcuts we might encounter that point to nodes that
-	 * only contain leaves.
-	 */
-	ptr = new_n->back_pointer;
-	if (!ptr)
-		goto gc_complete;
-
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		new_s = assoc_array_ptr_to_shortcut(ptr);
-		new_parent = new_s->back_pointer;
-		slot = new_s->parent_slot;
-
-		if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) {
-			struct assoc_array_node *n;
-
-			pr_devel("excise shortcut\n");
-			new_n->back_pointer = new_parent;
-			new_n->parent_slot = slot;
-			kfree(new_s);
-			if (!new_parent) {
-				new_root = assoc_array_node_to_ptr(new_n);
-				goto gc_complete;
-			}
-
-			n = assoc_array_ptr_to_node(new_parent);
-			n->slots[slot] = assoc_array_node_to_ptr(new_n);
-		}
-	} else {
-		new_parent = ptr;
-	}
-	new_n = assoc_array_ptr_to_node(new_parent);
-
-ascend_old_tree:
-	ptr = node->back_pointer;
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		slot = shortcut->parent_slot;
-		cursor = shortcut->back_pointer;
-		if (!cursor)
-			goto gc_complete;
-	} else {
-		slot = node->parent_slot;
-		cursor = ptr;
-	}
-	BUG_ON(!cursor);
-	node = assoc_array_ptr_to_node(cursor);
-	slot++;
-	goto continue_node;
-
-gc_complete:
-	edit->set[0].to = new_root;
-	assoc_array_apply_edit(edit);
-	array->nr_leaves_on_tree = nr_leaves_on_tree;
-	return 0;
-
-enomem:
-	pr_devel("enomem\n");
-	assoc_array_destroy_subtree(new_root, edit->ops);
-	kfree(edit);
-	return -ENOMEM;
-}
diff --git a/security/keys/Kconfig b/security/keys/Kconfig
index f4510d8cb485f4..3f64d60d0f8a69 100644
--- a/security/keys/Kconfig
+++ b/security/keys/Kconfig
@@ -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.
diff --git a/security/keys/internal.h b/security/keys/internal.h
index b7b622bc36a137..c452d71cce038d 100644
--- a/security/keys/internal.h
+++ b/security/keys/internal.h
@@ -21,6 +21,12 @@
 #include <linux/vmalloc.h>
 
 struct iovec;
+struct keyring_link;
+
+struct keyring_edit {
+	struct keyring_link *new;
+	struct keyring_link *old;
+};
 
 #ifdef __KDEBUG
 #define kenter(FMT, ...) \
@@ -98,13 +104,13 @@ extern int __key_move_lock(struct key *l_keyring, struct key *u_keyring,
 			   const struct keyring_index_key *index_key);
 extern int __key_link_begin(struct key *keyring,
 			    const struct keyring_index_key *index_key,
-			    struct assoc_array_edit **_edit);
+			    struct keyring_edit *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_edit *edit);
 extern void __key_link_end(struct key *keyring,
 			   const struct keyring_index_key *index_key,
-			   struct assoc_array_edit *edit);
+			   struct keyring_edit *edit);
 
 extern key_ref_t find_key_to_update(key_ref_t keyring_ref,
 				    const struct keyring_index_key *index_key);
@@ -122,7 +128,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;
diff --git a/security/keys/key.c b/security/keys/key.c
index 3f1f0fc137109a..20cf273cf4a3de 100644
--- a/security/keys/key.c
+++ b/security/keys/key.c
@@ -430,7 +430,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_edit *edit)
 {
 	int ret, awaken;
 
@@ -461,7 +461,7 @@ static int __key_instantiate_and_link(struct key *key,
 				if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
 					set_bit(KEY_FLAG_KEEP, &key->flags);
 
-				__key_link(keyring, key, _edit);
+				__key_link(keyring, key, edit);
 			}
 
 			/* disable the authorisation key */
@@ -505,7 +505,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_edit edit = {};
 	int ret;
 
 	memset(&prep, 0, sizeof(prep));
@@ -543,7 +543,7 @@ int key_instantiate_and_link(struct key *key,
 
 error_link_end:
 	if (keyring)
-		__key_link_end(keyring, &key->index_key, edit);
+		__key_link_end(keyring, &key->index_key, &edit);
 
 error:
 	if (key->type->preparse)
@@ -580,7 +580,7 @@ int key_reject_and_link(struct key *key,
 			struct key *keyring,
 			struct key *authkey)
 {
-	struct assoc_array_edit *edit = NULL;
+	struct keyring_edit edit = {};
 	int ret, awaken, link_ret = 0;
 
 	key_check(key);
@@ -599,12 +599,12 @@ int key_reject_and_link(struct key *key,
 			 * concurrent restriction install.
 			 */
 			if (keyring->restrict_link) {
-				__key_link_end(keyring, &key->index_key, edit);
+				__key_link_end(keyring, &key->index_key, &edit);
 				return -EPERM;
 			}
 			link_ret = __key_link_begin(keyring, &key->index_key, &edit);
 			if (link_ret < 0)
-				__key_link_end(keyring, &key->index_key, edit);
+				__key_link_end(keyring, &key->index_key, &edit);
 		}
 	}
 
@@ -635,7 +635,7 @@ int key_reject_and_link(struct key *key,
 	mutex_unlock(&key_construction_mutex);
 
 	if (keyring && link_ret == 0)
-		__key_link_end(keyring, &key->index_key, edit);
+		__key_link_end(keyring, &key->index_key, &edit);
 
 	/* wake up anyone waiting for a key to be constructed */
 	if (awaken)
@@ -825,7 +825,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_edit edit = {};
 	const struct cred *cred = current_cred();
 	struct key *keyring, *key = NULL;
 	key_ref_t key_ref;
@@ -966,7 +966,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
 	key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
 
 error_link_end:
-	__key_link_end(keyring, &index_key, edit);
+	__key_link_end(keyring, &index_key, &edit);
 error_free_prep:
 	if (index_key.type->preparse)
 		index_key.type->free_preparse(&prep);
@@ -979,7 +979,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
 	/* we found a matching key, so we're going to try to update it
 	 * - we can drop the locks first as we have the key pinned
 	 */
-	__key_link_end(keyring, &index_key, edit);
+	__key_link_end(keyring, &index_key, &edit);
 
 	key = key_ref_to_ptr(key_ref);
 	if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) {
diff --git a/security/keys/keyring.c b/security/keys/keyring.c
index 5281da9d5bf750..6761c6801edcd8 100644
--- a/security/keys/keyring.c
+++ b/security/keys/keyring.c
@@ -12,14 +12,15 @@
 #include <linux/security.h>
 #include <linux/seq_file.h>
 #include <linux/err.h>
+#include <linux/jhash.h>
 #include <linux/user_namespace.h>
 #include <linux/nsproxy.h>
 #include <linux/once.h>
 #include <linux/random.h>
+#include <linux/rhashtable.h>
 #include <linux/siphash.h>
+#include <linux/workqueue.h>
 #include <keys/keyring-type.h>
-#include <keys/user-type.h>
-#include <linux/assoc_array_priv.h>
 #include <linux/uaccess.h>
 #include <net/net_namespace.h>
 #include "internal.h"
@@ -31,25 +32,153 @@
 #define KEYRING_SEARCH_MAX_DEPTH 6
 
 /*
- * We mark pointers we pass to the associative array with bit 1 set if
- * they're keyrings and clear otherwise.
+ * Keyrings are inserted at the head of @list, other keys at the tail, so
+ * recursive search can stop at the first non-keyring.
  */
-#define KEYRING_PTR_SUBTYPE	0x2UL
+struct keyring_index {
+	struct rhashtable	ht;
+	struct list_head	list;		/* Active keys */
+	unsigned long		nr;		/* Number of active keys */
+	struct rcu_work		rcu_work;
+};
+
+/*
+ * __key_link_begin() inserts new links with @key NULL so allocation happens
+ * before __key_link().  @hash is cached so resizing can hash links while @key
+ * is NULL.
+ */
+struct keyring_link {
+	struct rcu_head		rcu;
+	struct rhash_head	node;
+	struct key __rcu	*key;		/* NULL while inactive */
+	struct list_head	list;
+	u32			hash;
+};
+
+static u32 keyring_hashfn(const void *data, u32 len, u32 seed)
+{
+	const struct keyring_index_key *index_key = data;
+
+	return jhash_1word(index_key->hash, seed);
+}
 
-static inline bool keyring_ptr_is_keyring(const struct assoc_array_ptr *x)
+static u32 keyring_obj_hashfn(const void *data, u32 len, u32 seed)
 {
-	return (unsigned long)x & KEYRING_PTR_SUBTYPE;
+	const struct keyring_link *link = data;
+
+	return jhash_1word(link->hash, seed);
 }
-static inline struct key *keyring_ptr_to_key(const struct assoc_array_ptr *x)
+
+static bool keyring_index_key_equal(const struct keyring_index_key *a,
+				    const struct keyring_index_key *b)
 {
-	void *object = assoc_array_ptr_to_leaf(x);
-	return (struct key *)((unsigned long)object & ~KEYRING_PTR_SUBTYPE);
+	return a->type == b->type &&
+		a->domain_tag == b->domain_tag &&
+		a->desc_len == b->desc_len &&
+		memcmp(a->description, b->description, a->desc_len) == 0;
 }
-static inline void *keyring_key_to_ptr(struct key *key)
+
+static struct key *keyring_link_key(const struct keyring_link *link)
 {
-	if (key->type == &key_type_keyring)
-		return (void *)((unsigned long)key | KEYRING_PTR_SUBTYPE);
-	return key;
+	return rcu_dereference_check(link->key, true);
+}
+
+static int keyring_obj_cmpfn(struct rhashtable_compare_arg *arg,
+			     const void *obj)
+{
+	const struct keyring_link *link = obj;
+	const struct key *key = keyring_link_key(link);
+
+	return !key || !keyring_index_key_equal(&key->index_key, arg->key);
+}
+
+static const struct rhashtable_params keyring_link_params = {
+	.head_offset		= offsetof(struct keyring_link, node),
+	.hashfn			= keyring_hashfn,
+	.obj_hashfn		= keyring_obj_hashfn,
+	.obj_cmpfn		= keyring_obj_cmpfn,
+	.min_size		= 4,
+	.nelem_hint		= 3,
+	.automatic_shrinking	= true,
+	.insecure_elasticity	= true,
+};
+
+static struct keyring_index *keyring_index_locked(const struct key *keyring)
+{
+	return rcu_dereference_protected(keyring->index,
+					 lockdep_is_held(&keyring->sem));
+}
+
+static struct keyring_link *keyring_find_link(struct keyring_index *index,
+					      const struct keyring_index_key *index_key)
+{
+	if (!index)
+		return NULL;
+
+	return rhashtable_lookup_fast(&index->ht, index_key, keyring_link_params);
+}
+
+static int keyring_iterate(const struct key *keyring,
+			   int (*iterator)(const struct key *key, void *data),
+			   void *data)
+{
+	struct keyring_index *index;
+	struct keyring_link *link;
+	int ret;
+
+	guard(rcu)();
+	index = rcu_dereference(keyring->index);
+	if (index) {
+		list_for_each_entry_rcu(link, &index->list, list) {
+			ret = iterator(keyring_link_key(link), data);
+			if (ret)
+				return ret;
+		}
+	}
+
+	return 0;
+}
+
+static void keyring_link_free_rcu(struct rcu_head *rcu)
+{
+	struct keyring_link *link = container_of(rcu, struct keyring_link, rcu);
+
+	key_put(rcu_dereference_raw(link->key));
+	kfree(link);
+}
+
+static void __keyring_index_free(struct keyring_index *index)
+{
+	struct keyring_link *link, *tmp;
+
+	rhashtable_destroy(&index->ht);
+
+	list_for_each_entry_safe(link, tmp, &index->list, list) {
+		key_put(rcu_dereference_protected(link->key, true));
+		kfree(link);
+	}
+
+	kfree(index);
+}
+
+static void keyring_index_free_work(struct work_struct *work)
+{
+	struct keyring_index *index = container_of(to_rcu_work(work),
+						 struct keyring_index, rcu_work);
+
+	__keyring_index_free(index);
+}
+
+static void keyring_index_free(struct key *keyring)
+{
+	struct keyring_index *index = keyring_index_locked(keyring);
+
+	if (!index)
+		return;
+
+	rcu_assign_pointer(keyring->index, NULL);
+	/* rhashtable_destroy() may sleep, so defer via rcu_work. */
+	queue_rcu_work(system_dfl_wq, &index->rcu_work);
 }
 
 static DEFINE_RWLOCK(keyring_name_lock);
@@ -143,80 +272,44 @@ static void keyring_free_preparse(struct key_preparsed_payload *prep)
 static int keyring_instantiate(struct key *keyring,
 			       struct key_preparsed_payload *prep)
 {
-	assoc_array_init(&keyring->keys);
+	RCU_INIT_POINTER(keyring->index, NULL);
 	/* make the keyring available by name if it has one */
 	keyring_publish_name(keyring);
 	return 0;
 }
 
 /*
- * Give key types and domains address-independent identities.  Zero means that
- * an ID has not yet been allocated.  As with inode sequence numbers used by
- * futexes, this relies on the 64-bit counter not wrapping in a machine's
- * lifetime.
- */
-static u64 key_index_id(atomic64_t *id)
-{
-	static atomic64_t next_id;
-	u64 old, new;
-
-	old = atomic64_read(id);
-	if (likely(old))
-		return old;
-
-	do {
-		new = atomic64_inc_return(&next_id);
-	} while (WARN_ON_ONCE(!new));
-
-	old = 0;
-	if (!atomic64_try_cmpxchg_relaxed(id, &old, new))
-		return old;
-	return new;
-}
-
-/*
- * Hash a key type, domain and description.  KEYCTL_READ exposes the tree's
- * traversal order, so no part of the index may contain kernel addresses.
+ * Hash a key type, domain and description.
  */
 static void hash_key_type_and_desc(struct keyring_index_key *index_key)
 {
-	const unsigned level_shift = ASSOC_ARRAY_LEVEL_STEP;
-	const unsigned long fan_mask = ASSOC_ARRAY_FAN_MASK;
 	static siphash_key_t hash_key __read_mostly;
-	unsigned long hash;
 	u64 acc;
 
+	/*
+	 * 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.
+	 */
 	get_random_once(&hash_key, sizeof(hash_key));
 	acc = siphash(index_key->description, index_key->desc_len, &hash_key);
-	acc = siphash_3u64(index_key->type_id, index_key->domain_id, acc,
-			   &hash_key);
-
-	/* Fold the hash down to 32 bits if need be. */
-	hash = acc;
-	if (ASSOC_ARRAY_KEY_CHUNK_SIZE == 32)
-		hash ^= acc >> 32;
-
-	/* Squidge all the keyrings into a separate part of the tree to
-	 * ordinary keys by making sure the lowest level segment in the hash is
-	 * zero for keyrings and non-zero otherwise.
-	 */
-	if (index_key->type != &key_type_keyring && (hash & fan_mask) == 0)
-		hash |= (hash >> (ASSOC_ARRAY_KEY_CHUNK_SIZE - level_shift)) | 1;
-	else if (index_key->type == &key_type_keyring && (hash & fan_mask) != 0)
-		hash = (hash + (hash << level_shift)) & ~fan_mask;
-	index_key->hash = hash;
+	index_key->hash = siphash_3u64((uintptr_t)index_key->type,
+				       (uintptr_t)index_key->domain_tag,
+				       acc, &hash_key);
 }
 
 /*
- * Finalise an index key to include a part of the description actually in the
- * index key, to set the domain tag and index IDs, and to calculate the hash.
+ * Finalise an index key to 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), };
-	size_t n = min_t(size_t, index_key->desc_len, sizeof(index_key->desc));
-
-	memcpy(index_key->desc, index_key->description, n);
 
 	if (!index_key->domain_tag) {
 		if (index_key->type->flags & KEY_TYPE_NET_DOMAIN)
@@ -225,14 +318,6 @@ void key_set_index_key(struct keyring_index_key *index_key)
 			index_key->domain_tag = &default_domain_tag;
 	}
 
-	/* Preserve the IDs when copying an existing key's index.  In
-	 * particular, its type may already have been unregistered.
-	 */
-	if (!index_key->type_id)
-		index_key->type_id = key_index_id(&index_key->type->index_id);
-	if (!index_key->domain_id)
-		index_key->domain_id = key_index_id(&index_key->domain_tag->index_id);
-
 	hash_key_type_and_desc(index_key);
 }
 
@@ -268,150 +353,6 @@ void key_remove_domain(struct key_tag *domain_tag)
 		key_schedule_gc_links();
 }
 
-/*
- * 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;
-	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;
-
-	d = index_key->description + offset;
-	desc_len -= offset;
-	if (desc_len > n)
-		desc_len = n;
-	d += desc_len;
-	do {
-		chunk <<= 8;
-		chunk |= *--d;
-	} while (--desc_len > 0);
-	return chunk;
-}
-
-static unsigned long keyring_get_object_key_chunk(const void *object, int level)
-{
-	const struct key *key = keyring_ptr_to_key(object);
-	return keyring_get_key_chunk(&key->index_key, level);
-}
-
-static bool keyring_compare_object(const void *object, const void *data)
-{
-	const struct keyring_index_key *index_key = data;
-	const struct key *key = keyring_ptr_to_key(object);
-
-	return key->index_key.type == index_key->type &&
-		key->index_key.domain_tag == index_key->domain_tag &&
-		key->index_key.desc_len == index_key->desc_len &&
-		memcmp(key->index_key.description, index_key->description,
-		       index_key->desc_len) == 0;
-}
-
-/*
- * Compare the index keys of a pair of objects and determine the bit position
- * at which they differ - if they differ.
- */
-static int keyring_diff_objects(const void *object, const void *data)
-{
-	const struct key *key_a = keyring_ptr_to_key(object);
-	const struct keyring_index_key *a = &key_a->index_key;
-	const struct keyring_index_key *b = data;
-	unsigned long seg_a, seg_b;
-	int level, i;
-	u64 diff;
-
-	level = 0;
-	seg_a = a->hash;
-	seg_b = b->hash;
-	if ((seg_a ^ seg_b) != 0)
-		goto differ;
-	level += ASSOC_ARRAY_KEY_CHUNK_SIZE / 8;
-
-	/* The inline description contributes one machine-word-sized chunk. */
-	seg_a = a->x;
-	seg_b = b->x;
-	if ((seg_a ^ seg_b) != 0)
-		goto differ;
-	level += sizeof(unsigned long);
-
-	diff = a->type_id ^ b->type_id;
-	if (diff)
-		return level * 8 + __ffs64(diff);
-	level += sizeof(u64);
-
-	diff = a->domain_id ^ b->domain_id;
-	if (diff)
-		return level * 8 + __ffs64(diff);
-	level += sizeof(u64);
-
-	i = sizeof(a->desc);
-	if (a->desc_len <= i)
-		goto same;
-
-	for (; i < a->desc_len; i++) {
-		seg_a = *(unsigned char *)(a->description + i);
-		seg_b = *(unsigned char *)(b->description + i);
-		if ((seg_a ^ seg_b) != 0)
-			goto differ_plus_i;
-	}
-
-same:
-	return -1;
-
-differ_plus_i:
-	level += i - (int)sizeof(a->desc);
-differ:
-	i = level * 8 + __ffs(seg_a ^ seg_b);
-	return i;
-}
-
-/*
- * Free an object after stripping the keyring flag off of the pointer.
- */
-static void keyring_free_object(void *object)
-{
-	key_put(keyring_ptr_to_key(object));
-}
-
-/*
- * Operations for keyring management by the index-tree routines.
- */
-static const struct assoc_array_ops keyring_assoc_array_ops = {
-	.get_key_chunk		= keyring_get_key_chunk,
-	.get_object_key_chunk	= keyring_get_object_key_chunk,
-	.compare_object		= keyring_compare_object,
-	.diff_objects		= keyring_diff_objects,
-	.free_object		= keyring_free_object,
-};
-
 /*
  * Clean up a keyring when it is destroyed.  Unpublish its name if it had one
  * and dispose of its data.
@@ -423,6 +364,8 @@ static const struct assoc_array_ops keyring_assoc_array_ops = {
  */
 static void keyring_destroy(struct key *keyring)
 {
+	struct keyring_index *index;
+
 	if (keyring->description) {
 		write_lock(&keyring_name_lock);
 
@@ -440,49 +383,51 @@ static void keyring_destroy(struct key *keyring)
 		kfree(keyres);
 	}
 
-	assoc_array_destroy(&keyring->keys, &keyring_assoc_array_ops);
+	index = rcu_dereference_protected(keyring->index, true);
+	if (index)
+		__keyring_index_free(index);
+}
+
+static unsigned long keyring_nr_links(const struct key *keyring)
+{
+	const struct keyring_index *index;
+
+	guard(rcu)();
+	index = rcu_dereference(keyring->index);
+	return index ? READ_ONCE(index->nr) : 0;
+}
+
+/**
+ * keyring_is_empty - Check whether a keyring is empty
+ * @keyring: The keyring to check.
+ */
+bool keyring_is_empty(const struct key *keyring)
+{
+	return keyring_nr_links(keyring) == 0;
 }
+EXPORT_SYMBOL(keyring_is_empty);
 
 /*
  * Describe a keyring for /proc.
  */
 static void keyring_describe(const struct key *keyring, struct seq_file *m)
 {
+	unsigned long nr;
+
 	if (keyring->description)
 		seq_puts(m, keyring->description);
 	else
 		seq_puts(m, "[anon]");
 
 	if (key_is_positive(keyring)) {
-		if (keyring->keys.nr_leaves_on_tree != 0)
-			seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree);
+		nr = keyring_nr_links(keyring);
+		if (nr != 0)
+			seq_printf(m, ": %lu", nr);
 		else
 			seq_puts(m, ": empty");
 	}
 }
 
-struct keyring_read_iterator_context {
-	size_t			buflen;
-	size_t			count;
-	key_serial_t		*buffer;
-};
-
-static int keyring_read_iterator(const void *object, void *data)
-{
-	struct keyring_read_iterator_context *ctx = data;
-	const struct key *key = keyring_ptr_to_key(object);
-
-	kenter("{%s,%d},,{%zu/%zu}",
-	       key->type->name, key->serial, ctx->count, ctx->buflen);
-
-	if (ctx->count >= ctx->buflen)
-		return 1;
-
-	*ctx->buffer++ = key->serial;
-	ctx->count += sizeof(key->serial);
-	return 0;
-}
-
 /*
  * Read a list of key IDs from the keyring's contents in binary form
  *
@@ -493,7 +438,10 @@ static int keyring_read_iterator(const void *object, void *data)
 static long keyring_read(const struct key *keyring,
 			 char *buffer, size_t buflen)
 {
-	struct keyring_read_iterator_context ctx;
+	struct keyring_index *links = keyring_index_locked(keyring);
+	key_serial_t *serials = (key_serial_t *)buffer;
+	struct keyring_link *link;
+	size_t count = 0;
 	long ret;
 
 	kenter("{%d},,%zu", key_serial(keyring), buflen);
@@ -501,25 +449,22 @@ static long keyring_read(const struct key *keyring,
 	if (buflen & (sizeof(key_serial_t) - 1))
 		return -EINVAL;
 
-	/* Copy as many key IDs as fit into the buffer */
-	if (buffer && buflen) {
-		ctx.buffer = (key_serial_t *)buffer;
-		ctx.buflen = buflen;
-		ctx.count = 0;
-		ret = assoc_array_iterate(&keyring->keys,
-					  keyring_read_iterator, &ctx);
-		if (ret < 0) {
-			kleave(" = %ld [iterate]", ret);
-			return ret;
+	if (buffer && buflen && links) {
+		list_for_each_entry(link, &links->list, list) {
+			if (count == buflen / sizeof(*serials))
+				break;
+
+			serials[count++] = keyring_link_key(link)->serial;
+			cond_resched();
 		}
 	}
 
-	/* Return the size of the buffer needed */
-	ret = keyring->keys.nr_leaves_on_tree * sizeof(key_serial_t);
+	ret = links ? links->nr * sizeof(key_serial_t) : 0;
 	if (ret <= buflen)
 		kleave("= %ld [ok]", ret);
 	else
 		kleave("= %ld [buffer too small]", ret);
+
 	return ret;
 }
 
@@ -583,10 +528,9 @@ bool key_default_cmp(const struct key *key,
 /*
  * Iteration function to consider each key found.
  */
-static int keyring_search_iterator(const void *object, void *iterator_data)
+static int keyring_search_iterator(const struct key *key, void *iterator_data)
 {
 	struct keyring_search_context *ctx = iterator_data;
-	const struct key *key = keyring_ptr_to_key(object);
 	unsigned long kflags = READ_ONCE(key->flags);
 	short state = key_read_state(key);
 
@@ -653,19 +597,78 @@ static int keyring_search_iterator(const void *object, void *iterator_data)
 /*
  * 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.
+ * list looking for it, based on the match function.
  */
 static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)
 {
 	if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) {
-		const void *object;
+		struct keyring_link *link;
+		struct key *key;
+
+		link = keyring_find_link(rcu_dereference(keyring->index),
+					 &ctx->index_key);
+		if (!link)
+			return 0;
+		key = keyring_link_key(link);
+		return ctx->iterator(key, ctx);
+	}
+
+	return keyring_iterate(keyring, ctx->iterator, ctx);
+}
 
-		object = assoc_array_find(&keyring->keys,
-					  &keyring_assoc_array_ops,
-					  &ctx->index_key);
-		return object ? ctx->iterator(object, ctx) : 0;
+/*
+ * Depth-first search of @keyring and its nested keyrings.
+ */
+static int search_keyring_tree(struct key *keyring,
+			       struct keyring_search_context *ctx, int depth)
+{
+	struct keyring_index *links;
+	struct keyring_link *link;
+	int ret;
+
+	if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
+			      (1 << KEY_FLAG_REVOKED)))
+		return 0;
+
+	if (search_keyring(keyring, ctx))
+		goto found;
+
+	if (!(ctx->flags & KEYRING_SEARCH_RECURSE))
+		return 0;
+	links = rcu_dereference(keyring->index);
+	if (!links)
+		return 0;
+
+	list_for_each_entry_rcu(link, &links->list, list) {
+		struct key *key = keyring_link_key(link);
+
+		if (key->type != &key_type_keyring)
+			break;
+		if (depth >= KEYRING_SEARCH_MAX_DEPTH) {
+			if (!(ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP))
+				return 0;
+			ctx->result = ERR_PTR(-ELOOP);
+			return -ELOOP;
+		}
+
+		if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
+		    key_task_permission(make_key_ref(key, ctx->possessed),
+					ctx->cred, KEY_NEED_SEARCH) < 0)
+			continue;
+
+		ret = search_keyring_tree(key, ctx, depth + 1);
+		if (ret < 0)
+			return ret;
+		if (ret)
+			goto found;
 	}
-	return assoc_array_iterate(&keyring->keys, ctx->iterator, ctx);
+
+	return 0;
+
+found:
+	if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME))
+		keyring->last_used_at = ctx->now;
+	return 1;
 }
 
 /*
@@ -675,17 +678,7 @@ static int search_keyring(struct key *keyring, struct keyring_search_context *ct
 static bool search_nested_keyrings(struct key *keyring,
 				   struct keyring_search_context *ctx)
 {
-	struct {
-		struct key *keyring;
-		struct assoc_array_node *node;
-		int slot;
-	} stack[KEYRING_SEARCH_MAX_DEPTH];
-
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *ptr;
 	struct key *key;
-	int sp = 0, slot;
 
 	kenter("{%d},{%s,%s}",
 	       keyring->serial,
@@ -703,9 +696,9 @@ static bool search_nested_keyrings(struct key *keyring,
 	 * and whether it is valid or not.
 	 */
 	if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||
-	    keyring_compare_object(keyring, &ctx->index_key)) {
+	    keyring_index_key_equal(&keyring->index_key, &ctx->index_key)) {
 		ctx->skipped_ret = 2;
-		switch (ctx->iterator(keyring_key_to_ptr(keyring), ctx)) {
+		switch (ctx->iterator(keyring, ctx)) {
 		case 1:
 			goto found;
 		case 2:
@@ -717,152 +710,11 @@ static bool search_nested_keyrings(struct key *keyring,
 
 	ctx->skipped_ret = 0;
 
-	/* Start processing a new keyring */
-descend_to_keyring:
-	kdebug("descend to %d", keyring->serial);
-	if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
-			      (1 << KEY_FLAG_REVOKED)))
-		goto not_this_keyring;
-
-	/* Search through the keys in this keyring before its searching its
-	 * subtrees.
-	 */
-	if (search_keyring(keyring, ctx))
-		goto found;
-
-	/* Then manually iterate through the keyrings nested in this one.
-	 *
-	 * Start from the root node of the index tree.  Because of the way the
-	 * hash function has been set up, keyrings cluster on the leftmost
-	 * branch of the root node (root slot 0) or in the root node itself.
-	 * Non-keyrings avoid the leftmost branch of the root entirely (root
-	 * slots 1-15).
-	 */
-	if (!(ctx->flags & KEYRING_SEARCH_RECURSE))
-		goto not_this_keyring;
-
-	ptr = READ_ONCE(keyring->keys.root);
-	if (!ptr)
-		goto not_this_keyring;
-
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		/* If the root is a shortcut, either the keyring only contains
-		 * keyring pointers (everything clusters behind root slot 0) or
-		 * doesn't contain any keyring pointers.
-		 */
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		if ((shortcut->index_key[0] & ASSOC_ARRAY_FAN_MASK) != 0)
-			goto not_this_keyring;
-
-		ptr = READ_ONCE(shortcut->next_node);
-		node = assoc_array_ptr_to_node(ptr);
-		goto begin_node;
-	}
-
-	node = assoc_array_ptr_to_node(ptr);
-	ptr = node->slots[0];
-	if (!assoc_array_ptr_is_meta(ptr))
-		goto begin_node;
-
-descend_to_node:
-	/* Descend to a more distal node in this keyring's content tree and go
-	 * through that.
-	 */
-	kdebug("descend");
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		ptr = READ_ONCE(shortcut->next_node);
-		BUG_ON(!assoc_array_ptr_is_node(ptr));
-	}
-	node = assoc_array_ptr_to_node(ptr);
-
-begin_node:
-	kdebug("begin_node");
-	slot = 0;
-ascend_to_node:
-	/* Go through the slots in a node */
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]);
-
-		if (assoc_array_ptr_is_meta(ptr)) {
-			if (node->back_pointer ||
-			    assoc_array_ptr_is_shortcut(ptr))
-				goto descend_to_node;
-		}
-
-		if (!keyring_ptr_is_keyring(ptr))
-			continue;
-
-		key = keyring_ptr_to_key(ptr);
-
-		if (sp >= KEYRING_SEARCH_MAX_DEPTH) {
-			if (ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP) {
-				ctx->result = ERR_PTR(-ELOOP);
-				return false;
-			}
-			goto not_this_keyring;
-		}
-
-		/* Search a nested keyring */
-		if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
-		    key_task_permission(make_key_ref(key, ctx->possessed),
-					ctx->cred, KEY_NEED_SEARCH) < 0)
-			continue;
-
-		/* stack the current position */
-		stack[sp].keyring = keyring;
-		stack[sp].node = node;
-		stack[sp].slot = slot;
-		sp++;
-
-		/* begin again with the new keyring */
-		keyring = key;
-		goto descend_to_keyring;
-	}
-
-	/* We've dealt with all the slots in the current node, so now we need
-	 * to ascend to the parent and continue processing there.
-	 */
-	ptr = READ_ONCE(node->back_pointer);
-	slot = node->parent_slot;
-
-	if (ptr && assoc_array_ptr_is_shortcut(ptr)) {
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		ptr = READ_ONCE(shortcut->back_pointer);
-		slot = shortcut->parent_slot;
-	}
-	if (!ptr)
-		goto not_this_keyring;
-	node = assoc_array_ptr_to_node(ptr);
-	slot++;
-
-	/* If we've ascended to the root (zero backpointer), we must have just
-	 * finished processing the leftmost branch rather than the root slots -
-	 * so there can't be any more keyrings for us to find.
-	 */
-	if (node->back_pointer) {
-		kdebug("ascend %d", slot);
-		goto ascend_to_node;
-	}
-
-	/* The keyring we're looking at was disqualified or didn't contain a
-	 * matching key.
-	 */
-not_this_keyring:
-	kdebug("not_this_keyring %d", sp);
-	if (sp <= 0) {
+	if (search_keyring_tree(keyring, ctx, 0) <= 0) {
 		kleave(" = false");
 		return false;
 	}
 
-	/* Resume the processing of a keyring higher up in the tree */
-	sp--;
-	keyring = stack[sp].keyring;
-	node = stack[sp].node;
-	slot = stack[sp].slot + 1;
-	kdebug("ascend to %d [%d]", keyring->serial, slot);
-	goto ascend_to_node;
-
 	/* We found a viable match */
 found:
 	key = key_ref_to_ptr(ctx->result);
@@ -870,8 +722,6 @@ static bool search_nested_keyrings(struct key *keyring,
 	if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) {
 		key->last_used_at = ctx->now;
 		keyring->last_used_at = ctx->now;
-		while (sp > 0)
-			stack[--sp].keyring->last_used_at = ctx->now;
 	}
 	kleave(" = true");
 	return true;
@@ -1118,8 +968,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);
 
@@ -1127,17 +977,16 @@ key_ref_t find_key_to_update(key_ref_t keyring_ref,
 	       keyring->serial, index_key->type->name, index_key->description);
 
 	guard(rcu)();
-	object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
-				  index_key);
+	link = keyring_find_link(rcu_dereference(keyring->index), index_key);
 
-	if (object)
+	if (link)
 		goto found;
 
 	kleave(" = NULL");
 	return NULL;
 
 found:
-	key = keyring_ptr_to_key(object);
+	key = keyring_link_key(link);
 	if (key->flags & ((1 << KEY_FLAG_INVALIDATED) |
 			  (1 << KEY_FLAG_REVOKED))) {
 		kleave(" = NULL [x]");
@@ -1207,11 +1056,10 @@ struct key *find_keyring_by_name(const char *name, bool uid_keyring)
 	return keyring;
 }
 
-static int keyring_detect_cycle_iterator(const void *object,
+static int keyring_detect_cycle_iterator(const struct key *key,
 					 void *iterator_data)
 {
 	struct keyring_search_context *ctx = iterator_data;
-	const struct key *key = keyring_ptr_to_key(object);
 
 	kenter("{%d}", key->serial);
 
@@ -1307,56 +1155,90 @@ int __key_move_lock(struct key *l_keyring, struct key *u_keyring,
 	return 0;
 }
 
+static struct keyring_index *keyring_get_index(struct key *keyring)
+{
+	struct keyring_index *links = keyring_index_locked(keyring);
+	int ret;
+
+	if (links)
+		return links;
+
+	links = kzalloc_obj(struct keyring_index);
+	if (!links)
+		return ERR_PTR(-ENOMEM);
+	ret = rhashtable_init(&links->ht, &keyring_link_params);
+	if (ret < 0) {
+		kfree(links);
+		return ERR_PTR(ret);
+	}
+
+	INIT_LIST_HEAD(&links->list);
+	INIT_RCU_WORK(&links->rcu_work, keyring_index_free_work);
+	rcu_assign_pointer(keyring->index, links);
+	return links;
+}
+
 /*
  * Preallocate memory so that a key can be linked into to a keyring.
  */
 int __key_link_begin(struct key *keyring,
 		     const struct keyring_index_key *index_key,
-		     struct assoc_array_edit **_edit)
+		     struct keyring_edit *edit)
 {
-	struct assoc_array_edit *edit;
+	struct keyring_link *link __free(kfree) = NULL;
+	struct keyring_link *replace;
+	struct keyring_index *links;
 	int ret;
 
 	kenter("%d,%s,%s,",
 	       keyring->serial, index_key->type->name, index_key->description);
 
-	BUG_ON(index_key->desc_len == 0);
-	BUG_ON(*_edit != NULL);
+	if (WARN_ON(index_key->desc_len == 0) || WARN_ON(edit->new))
+		return -EINVAL;
 
-	*_edit = NULL;
+	edit->new = NULL;
+	edit->old = NULL;
 
 	ret = -EKEYREVOKED;
 	if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
 		goto error;
 
-	/* Create an edit script that will insert/replace the key in the
-	 * keyring tree.
-	 */
-	edit = assoc_array_insert(&keyring->keys,
-				  &keyring_assoc_array_ops,
-				  index_key,
-				  NULL);
-	if (IS_ERR(edit)) {
-		ret = PTR_ERR(edit);
+	links = keyring_get_index(keyring);
+	if (IS_ERR(links)) {
+		ret = PTR_ERR(links);
 		goto error;
 	}
 
+	ret = -ENOMEM;
+	link = kzalloc_obj(struct keyring_link);
+	if (!link)
+		goto error;
+	link->hash = index_key->hash;
+
+	replace = keyring_find_link(links, index_key);
 	/* If we're not replacing a link in-place then we're going to need some
 	 * extra quota.
 	 */
-	if (!edit->dead_leaf) {
+	if (!replace) {
 		ret = key_payload_reserve(keyring,
 					  keyring->datalen + KEYQUOTA_LINK_BYTES);
 		if (ret < 0)
-			goto error_cancel;
+			goto error;
+
+		ret = rhashtable_insert_fast(&links->ht, &link->node,
+					     keyring_link_params);
+		if (ret < 0) {
+			key_payload_reserve(keyring,
+					    keyring->datalen - KEYQUOTA_LINK_BYTES);
+			goto error;
+		}
 	}
 
-	*_edit = edit;
+	edit->new = no_free_ptr(link);
+	edit->old = replace;
 	kleave(" = 0");
 	return 0;
 
-error_cancel:
-	assoc_array_cancel_edit(edit);
 error:
 	kleave(" = %d", ret);
 	return ret;
@@ -1385,13 +1267,35 @@ int __key_link_check_live_key(struct key *keyring, struct key *key)
  * holds at most one link to any given key of a particular type+description
  * combination.
  */
-void __key_link(struct key *keyring, struct key *key,
-		struct assoc_array_edit **_edit)
+void __key_link(struct key *keyring, struct key *key, struct keyring_edit *edit)
 {
+	struct keyring_index *index = keyring_index_locked(keyring);
+	int ret;
+
 	__key_get(key);
-	assoc_array_insert_set_object(*_edit, keyring_key_to_ptr(key));
-	assoc_array_apply_edit(*_edit);
-	*_edit = NULL;
+	rcu_assign_pointer(edit->new->key, key);
+
+	if (edit->old) {
+		ret = rhashtable_replace_fast(&index->ht, &edit->old->node,
+					      &edit->new->node, keyring_link_params);
+		if (WARN_ON(ret)) {
+			key_put(key);
+			return;
+		}
+
+		list_replace_rcu(&edit->old->list, &edit->new->list);
+		call_rcu(&edit->old->rcu, keyring_link_free_rcu);
+	} else {
+		if (key->type == &key_type_keyring)
+			list_add_rcu(&edit->new->list, &index->list);
+		else
+			list_add_tail_rcu(&edit->new->list, &index->list);
+
+		WRITE_ONCE(index->nr, index->nr + 1);
+	}
+
+	edit->new = NULL;
+	edit->old = NULL;
 	notify_key(keyring, NOTIFY_KEY_LINKED, key_serial(key));
 }
 
@@ -1402,20 +1306,31 @@ void __key_link(struct key *keyring, struct key *key,
  */
 void __key_link_end(struct key *keyring,
 		    const struct keyring_index_key *index_key,
-		    struct assoc_array_edit *edit)
+		    struct keyring_edit *edit)
 	__releases(&keyring->sem)
 	__releases(&keyring_serialise_link_lock)
 {
+	struct keyring_link *link = edit->new;
+
 	BUG_ON(index_key->type == NULL);
 	kenter("%d,%s,", keyring->serial, index_key->type->name);
 
-	if (edit) {
-		if (!edit->dead_leaf) {
+	if (link) {
+		if (!edit->old) {
 			key_payload_reserve(keyring,
 				keyring->datalen - KEYQUOTA_LINK_BYTES);
+			WARN_ON(rhashtable_remove_fast(&keyring_index_locked(keyring)->ht,
+						       &link->node,
+						       keyring_link_params));
+			call_rcu(&link->rcu, keyring_link_free_rcu);
+		} else {
+			kfree(link);
 		}
-		assoc_array_cancel_edit(edit);
+
+		edit->new = NULL;
+		edit->old = NULL;
 	}
+
 	up_write(&keyring->sem);
 
 	if (index_key->type == &key_type_keyring)
@@ -1445,9 +1360,9 @@ static int __key_link_check_restriction(struct key *keyring, struct key *key)
  * of the user's key data quota to hold the link.
  *
  * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring,
- * -EKEYREVOKED if the keyring has been revoked, -ENFILE if the keyring is
- * full, -EDQUOT if there is insufficient key data quota remaining to add
- * another link or -ENOMEM if there's insufficient memory.
+ * -EKEYREVOKED if the keyring has been revoked, -EDQUOT if there is insufficient
+ * key data quota remaining to add another link or -ENOMEM if there's
+ * insufficient memory.
  *
  * It is assumed that the caller has checked that it is permitted for a link to
  * be made (the keyring should have Write permission and the key Link
@@ -1455,7 +1370,7 @@ static int __key_link_check_restriction(struct key *keyring, struct key *key)
  */
 int key_link(struct key *keyring, struct key *key)
 {
-	struct assoc_array_edit *edit = NULL;
+	struct keyring_edit edit = {};
 	int ret;
 
 	kenter("{%d,%d}", keyring->serial, refcount_read(&keyring->usage));
@@ -1479,7 +1394,7 @@ int key_link(struct key *keyring, struct key *key)
 		__key_link(keyring, key, &edit);
 
 error_end:
-	__key_link_end(keyring, &key->index_key, edit);
+	__key_link_end(keyring, &key->index_key, &edit);
 error:
 	kleave(" = %d {%d,%d}", ret, keyring->serial, refcount_read(&keyring->usage));
 	return ret;
@@ -1503,27 +1418,21 @@ static int __key_unlink_lock(struct key *keyring)
  * Begin the process of unlinking a key from a keyring.
  */
 static int __key_unlink_begin(struct key *keyring, struct key *key,
-			      struct assoc_array_edit **_edit)
+			      struct keyring_link **edit)
 {
-	struct assoc_array_edit *edit;
-	const void *object;
+	struct keyring_link *link;
 
-	BUG_ON(*_edit != NULL);
+	if (WARN_ON(*edit))
+		return -EINVAL;
 
-	object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
-				  &key->index_key);
-	if (!object || keyring_ptr_to_key(object) != key)
+	link = keyring_find_link(keyring_index_locked(keyring), &key->index_key);
+	if (!link)
 		return -ENOENT;
 
-	edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops,
-				  &key->index_key);
-	if (IS_ERR(edit))
-		return PTR_ERR(edit);
-
-	if (!edit)
+	if (keyring_link_key(link) != key)
 		return -ENOENT;
 
-	*_edit = edit;
+	*edit = link;
 	return 0;
 }
 
@@ -1531,27 +1440,22 @@ static int __key_unlink_begin(struct key *keyring, struct key *key,
  * Apply an unlink change.
  */
 static void __key_unlink(struct key *keyring, struct key *key,
-			 struct assoc_array_edit **_edit)
+			 struct keyring_link *link)
 {
-	assoc_array_apply_edit(*_edit);
+	struct keyring_index *index = keyring_index_locked(keyring);
+	int ret;
+
+	ret = rhashtable_remove_fast(&index->ht, &link->node, keyring_link_params);
+	if (WARN_ON(ret))
+		return;
+
+	list_del_rcu(&link->list);
+	WRITE_ONCE(index->nr, index->nr - 1);
+	call_rcu(&link->rcu, keyring_link_free_rcu);
 	notify_key(keyring, NOTIFY_KEY_UNLINKED, key_serial(key));
-	*_edit = NULL;
 	key_payload_reserve(keyring, keyring->datalen - KEYQUOTA_LINK_BYTES);
 }
 
-/*
- * 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);
-}
-
 /**
  * key_unlink - Unlink the first link to a key from a keyring.
  * @keyring: The keyring to remove the link from.
@@ -1561,9 +1465,8 @@ static void __key_unlink_end(struct key *keyring,
  *
  * This function will write-lock the keyring's semaphore.
  *
- * 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.
+ * Returns 0 if successful, -ENOTDIR if the keyring isn't a keyring or -ENOENT if
+ * the key isn't linked to by the keyring.
  *
  * It is assumed that the caller has checked that it is permitted for a link to
  * be removed (the keyring should have Write permission; no permissions are
@@ -1571,7 +1474,7 @@ static void __key_unlink_end(struct key *keyring,
  */
 int key_unlink(struct key *keyring, struct key *key)
 {
-	struct assoc_array_edit *edit = NULL;
+	struct keyring_link *edit = NULL;
 	int ret;
 
 	key_check(keyring);
@@ -1583,8 +1486,8 @@ int key_unlink(struct key *keyring, struct key *key)
 
 	ret = __key_unlink_begin(keyring, key, &edit);
 	if (ret == 0)
-		__key_unlink(keyring, key, &edit);
-	__key_unlink_end(keyring, key, edit);
+		__key_unlink(keyring, key, edit);
+	up_write(&keyring->sem);
 	return ret;
 }
 EXPORT_SYMBOL(key_unlink);
@@ -1604,11 +1507,10 @@ EXPORT_SYMBOL(key_unlink);
  * some of the user's key data quota to hold the link on @to_keyring.
  *
  * Returns 0 if successful, -ENOTDIR if either keyring isn't a keyring,
- * -EKEYREVOKED if either keyring has been revoked, -ENFILE if the second
- * keyring is full, -EDQUOT if there is insufficient key data quota remaining
- * to add another link or -ENOMEM if there's insufficient memory.  If
- * KEYCTL_MOVE_EXCL is set, then -EEXIST will be returned if there's already a
- * matching key in @to_keyring.
+ * -EKEYREVOKED if either keyring has been revoked, -EDQUOT if there is
+ * insufficient key data quota remaining to add another link or -ENOMEM if
+ * there's insufficient memory.  If KEYCTL_MOVE_EXCL is set, then -EEXIST will
+ * be returned if there's already a matching key in @to_keyring.
  *
  * It is assumed that the caller has checked that it is permitted for a link to
  * be made (the keyring should have Write permission and the key Link
@@ -1619,7 +1521,8 @@ int key_move(struct key *key,
 	     struct key *to_keyring,
 	     unsigned int flags)
 {
-	struct assoc_array_edit *from_edit = NULL, *to_edit = NULL;
+	struct keyring_link *from_edit = NULL;
+	struct keyring_edit to_edit = {};
 	int ret;
 
 	kenter("%d,%d,%d", key->serial, from_keyring->serial, to_keyring->serial);
@@ -1642,7 +1545,7 @@ int key_move(struct key *key,
 		goto error;
 
 	ret = -EEXIST;
-	if (to_edit->dead_leaf && (flags & KEYCTL_MOVE_EXCL))
+	if (to_edit.old && (flags & KEYCTL_MOVE_EXCL))
 		goto error;
 
 	ret = __key_link_check_restriction(to_keyring, key);
@@ -1652,11 +1555,11 @@ int key_move(struct key *key,
 	if (ret < 0)
 		goto error;
 
-	__key_unlink(from_keyring, key, &from_edit);
+	__key_unlink(from_keyring, key, from_edit);
 	__key_link(to_keyring, key, &to_edit);
 error:
-	__key_link_end(to_keyring, &key->index_key, to_edit);
-	__key_unlink_end(from_keyring, key, from_edit);
+	__key_link_end(to_keyring, &key->index_key, &to_edit);
+	up_write(&from_keyring->sem);
 out:
 	kleave(" = %d", ret);
 	return ret;
@@ -1673,27 +1576,17 @@ EXPORT_SYMBOL(key_move);
  */
 int keyring_clear(struct key *keyring)
 {
-	struct assoc_array_edit *edit;
-	int ret;
-
 	if (keyring->type != &key_type_keyring)
 		return -ENOTDIR;
 
 	down_write(&keyring->sem);
 
-	edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
-	if (IS_ERR(edit)) {
-		ret = PTR_ERR(edit);
-	} else {
-		if (edit)
-			assoc_array_apply_edit(edit);
-		notify_key(keyring, NOTIFY_KEY_CLEARED, 0);
-		key_payload_reserve(keyring, 0);
-		ret = 0;
-	}
+	keyring_index_free(keyring);
+	notify_key(keyring, NOTIFY_KEY_CLEARED, 0);
+	key_payload_reserve(keyring, 0);
 
 	up_write(&keyring->sem);
-	return ret;
+	return 0;
 }
 EXPORT_SYMBOL(keyring_clear);
 
@@ -1704,30 +1597,12 @@ EXPORT_SYMBOL(keyring_clear);
  */
 static void keyring_revoke(struct key *keyring)
 {
-	struct assoc_array_edit *edit;
-
-	edit = assoc_array_clear(&keyring->keys, &keyring_assoc_array_ops);
-	if (!IS_ERR(edit)) {
-		if (edit)
-			assoc_array_apply_edit(edit);
-		key_payload_reserve(keyring, 0);
-	}
+	keyring_index_free(keyring);
+	key_payload_reserve(keyring, 0);
 }
 
-static bool keyring_gc_select_iterator(void *object, void *iterator_data)
+static int keyring_gc_check_iterator(const struct key *key, void *iterator_data)
 {
-	struct key *key = keyring_ptr_to_key(object);
-	time64_t *limit = iterator_data;
-
-	if (key_is_dead(key, *limit))
-		return false;
-	key_get(key);
-	return true;
-}
-
-static int keyring_gc_check_iterator(const void *object, void *iterator_data)
-{
-	const struct key *key = keyring_ptr_to_key(object);
 	time64_t *limit = iterator_data;
 
 	key_check(key);
@@ -1742,7 +1617,9 @@ static int keyring_gc_check_iterator(const void *object, void *iterator_data)
  */
 void keyring_gc(struct key *keyring, time64_t limit)
 {
-	int result;
+	struct keyring_link *link, *tmp;
+	struct keyring_index *index;
+	int ret;
 
 	kenter("%x{%s}", keyring->serial, keyring->description ?: "");
 
@@ -1751,11 +1628,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();
-	if (result == true)
+	if (keyring_iterate(keyring, keyring_gc_check_iterator, &limit))
 		goto do_gc;
 
 dont_gc:
@@ -1764,8 +1637,23 @@ 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);
+	index = keyring_index_locked(keyring);
+	if (index) {
+		list_for_each_entry_safe(link, tmp, &index->list, list) {
+			if (!key_is_dead(keyring_link_key(link), limit))
+				continue;
+
+			ret = rhashtable_remove_fast(&index->ht, &link->node,
+						     keyring_link_params);
+			if (WARN_ON(ret))
+				break;
+
+			list_del_rcu(&link->list);
+			WRITE_ONCE(index->nr, index->nr - 1);
+			call_rcu(&link->rcu, keyring_link_free_rcu);
+		}
+	}
+
 	up_write(&keyring->sem);
 	kleave(" [gc]");
 }
diff --git a/security/keys/request_key.c b/security/keys/request_key.c
index 22cd66a44da562..40fbcd15be4308 100644
--- a/security/keys/request_key.c
+++ b/security/keys/request_key.c
@@ -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_edit edit = {};
 	struct key *key;
 	key_perm_t perm;
 	key_ref_t key_ref;
@@ -433,7 +433,7 @@ static int construct_alloc_key(struct keyring_search_context *ctx,
 
 	mutex_unlock(&key_construction_mutex);
 	if (dest_keyring)
-		__key_link_end(dest_keyring, &key->index_key, edit);
+		__key_link_end(dest_keyring, &key->index_key, &edit);
 	mutex_unlock(&user->cons_lock);
 	*_key = key;
 	kleave(" = 0 [%d]", key_serial(key));
@@ -452,7 +452,7 @@ static int construct_alloc_key(struct keyring_search_context *ctx,
 		ret = __key_link_check_live_key(dest_keyring, key);
 		if (ret == 0)
 			__key_link(dest_keyring, key, &edit);
-		__key_link_end(dest_keyring, &key->index_key, edit);
+		__key_link_end(dest_keyring, &key->index_key, &edit);
 		if (ret < 0)
 			goto link_check_failed;
 	}
@@ -470,7 +470,7 @@ static int construct_alloc_key(struct keyring_search_context *ctx,
 link_alloc_failed:
 	mutex_unlock(&key_construction_mutex);
 link_alloc_failed_unlocked:
-	__key_link_end(dest_keyring, &key->index_key, edit);
+	__key_link_end(dest_keyring, &key->index_key, &edit);
 link_lock_failed:
 	mutex_unlock(&user->cons_lock);
 	key_put(key);
diff --git a/tools/testing/selftests/dm-verity/test-dm-verity-keyring.sh b/tools/testing/selftests/dm-verity/test-dm-verity-keyring.sh
index 1f9601ef22f859..792449d356cf56 100755
--- a/tools/testing/selftests/dm-verity/test-dm-verity-keyring.sh
+++ b/tools/testing/selftests/dm-verity/test-dm-verity-keyring.sh
@@ -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

17/3 2026/11/10 21:41 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 58995
							output: 18
							thoughts: 1496
						

Thoughts:
**KMSAN Fuzzing Analysis: Keyring Implementation Rewrite**

Okay, let's dive into this patch series. My initial goal is to determine if this refactoring of the keyring implementation warrants a dedicated KMSAN fuzzing session. The target architecture is amd64, so I'll be focused on that.

The core of the patch is the wholesale replacement of `assoc_array` with `rhashtable` combined with `list_head` structures within the keyring implementation. This seems like a significant structural change. It looks like `security/keys/keyring.c`, and related files are the focus of this rewrite.

My first impression is that this is a fairly contained change, but it touches a lot of files. The patch deletes several `assoc_array` related files (`Documentation/core-api/assoc_array.rst`, `include/linux/assoc_array.h` and several others in the `lib` directory) and modifies quite a few others across the kernel tree. I see changes in key management functions and data structures. It's also modifying checks in the dm-verity code, which is interesting, because it will be good to understand the implications of using `rhashtable` in these checks.

Now, let's go deeper and carefully examine the changes to the relevant data structures. I'm focusing on the changes to `include/linux/key.h`, `security/keys/internal.h`, `security/keys/key.c`, and `security/keys/keyring.c` because they define the core data structures. In `include/linux/key.h`, I see that the `keyring_index_key` and `key` structures have been updated. The `hash` field is now a `u32` instead of `unsigned long`, and the `desc_len` is now a separate field rather than embedded in a union. Also the `assoc_array` has been replaced with `rhashtable`. This points to a change in how keys are indexed and managed.

In `security/keys/keyring.c`, I'm looking at the core data structures used for the new `rhashtable` implementation. I can see the new `keyring_index`, which now contains a `struct rhashtable ht`, and the `keyring_link` structure which seems to handle the linking of the keys within the rhashtable.

Now, I want to understand how this is used in the kernel. Let's see how keys are read out of the keyring, or added to the keyring. I am specifically interested in how `keyring_read` is implemented. I'm trying to understand any potential side-effects that this data structure change might have. In `keyring_read`, I'm seeing that the code is iterating through a list, using `list_for_each_entry`, and returning serial numbers. I need to figure out what happens, and what calls `keyring_read`. I'm going to use a tool to check who calls this function, or when the `.read = keyring_read` method is used.

Based on these initial observations, I am starting to think that, because of the fundamental nature of the keyring code, and the far-reaching nature of the modifications in the filesystem, it *might* warrant further inspection. KMSAN should catch any issues relating to uninitialized memory access, so I'll use it to ensure everything is working correctly.



18/3 2026/11/10 21:41 tool grepper
0m Args:
{
  "Expression": "keyring_read"
}

Results:
{
  "Output": "security/keys/keyring.c=212=static void keyring_describe(const struct key *keyring, struct seq_file *m);\nsecurity/keys/keyring.c:213:static long keyring_read(const struct key *keyring,\nsecurity/keys/keyring.c-214-\t\t\t char *buffer, size_t buflen);\n--\nsecurity/keys/keyring.c=216=struct key_type key_type_keyring = {\n--\nsecurity/keys/keyring.c-224-\t.describe\t= keyring_describe,\nsecurity/keys/keyring.c:225:\t.read\t\t= keyring_read,\nsecurity/keys/keyring.c-226-};\n--\nsecurity/keys/keyring.c=413=static void keyring_describe(const struct key *keyring, struct seq_file *m)\n--\nsecurity/keys/keyring.c-437- */\nsecurity/keys/keyring.c:438:static long keyring_read(const struct key *keyring,\nsecurity/keys/keyring.c-439-\t\t\t char *buffer, size_t buflen)\n"
}

19/3 2026/11/10 21:41 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 61533
							output: 19
							thoughts: 26
						

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

**Analyzing `.read` Calls within the Key Subsystem**

Right, let's dive in. My immediate thought is to trace the execution of the `.read` function across the keys subsystem. Specifically, I want to understand how it's being invoked, what contexts are triggering these calls, and perhaps most importantly, to determine if there are any unusual patterns. A logical starting point is to examine calls to `keyctl_read_key`. I'll be looking for cross-key subsystem interactions and data flow. I want to identify any potential bottlenecks, vulnerabilities, or areas ripe for optimization within this critical function. From this trace, I can formulate testable hypotheses and begin to formulate refactors. The goal is a deeper understanding of the code.



20/3 2026/11/10 21:41 tool grepper
0m Args:
{
  "Expression": "key_type.*read"
}

Results:
{
  "Output": "arch/s390/kernel/cert_store.c=315=static int invalidate_keyring_keys(struct key *keyring)\n--\narch/s390/kernel/cert_store.c-322-\narch/s390/kernel/cert_store.c:323:\tkeyring_payload_len = key_type_keyring.read(keyring, NULL, 0);\narch/s390/kernel/cert_store.c-324-\tnum_keys = keyring_payload_len / sizeof(key_serial_t);\n--\narch/s390/kernel/cert_store.c-328-\narch/s390/kernel/cert_store.c:329:\trc = key_type_keyring.read(keyring, (char *)key_array, keyring_payload_len);\narch/s390/kernel/cert_store.c-330-\tif (rc != keyring_payload_len) {\n--\nfs/btrfs/verity.c=225=static int write_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset,\n--\nfs/btrfs/verity.c-283- * @inode:      inode to read items of\nfs/btrfs/verity.c:284: * @key_type:   key type to read\nfs/btrfs/verity.c-285- * @offset:     item offset to read from\n"
}

21/3 2026/11/10 21:41 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 62132
							output: 20
							thoughts: 12
						

Thoughts:
Okay, here's my attempt at summarizing that thought process, keeping in mind the expert user:

**Deep Dive: Checking `keyctl_read_key`**

Alright, let's take a look at `keyctl_read_key`. Given the context, I'm probably dealing with some low-level kernel key management, or perhaps a user-space application interacting with the kernel's keyrings. My initial thought is to refresh my memory on the system call itself. What are the key details? I need to quickly recall the function signature: arguments like the key ID, a buffer to read into, and the buffer's size. I need to make sure I understand the purpose of each argument.

I'll be thinking about potential pitfalls here as well. I need to remember the return values – what does a successful read look like, and what kind of errors am I likely to encounter? I should double-check for any gotchas with buffer management – common errors are related to potential buffer overflows or incorrect size calculations. The key size may be larger than I'm expecting, so I must take that into account.

Are there any race conditions here? I’m thinking about how the key might be modified concurrently by other processes, and I'll need to consider the implications of that for the data I retrieve.
And, finally, I want to confirm what my access rights are and that I can actually *see* the key in the first place. I will need to verify my current security context and the key's permissions. This will dictate whether the read will even succeed.



22/3 2026/11/10 21:41 tool grepper
0m Args:
{
  "Expression": "keyctl_read_key"
}

Results:
{
  "Output": "security/keys/compat.c=17=COMPAT_SYSCALL_DEFINE5(keyctl, u32, option,\n--\nsecurity/keys/compat.c-49-\tcase KEYCTL_READ:\nsecurity/keys/compat.c:50:\t\treturn keyctl_read_key(arg2, compat_ptr(arg3), arg4);\nsecurity/keys/compat.c-51-\n--\nsecurity/keys/internal.h=254=extern long keyctl_keyring_search(key_serial_t, const char __user *,\nsecurity/keys/internal.h-255-\t\t\t\t  const char __user *, key_serial_t);\nsecurity/keys/internal.h:256:extern long keyctl_read_key(key_serial_t, char __user *, size_t);\nsecurity/keys/internal.h-257-extern long keyctl_chown_key(key_serial_t, uid_t, gid_t);\n--\nsecurity/keys/keyctl.c=716=long keyctl_keyring_search(key_serial_t ringid,\n--\nsecurity/keys/keyctl.c-802- */\nsecurity/keys/keyctl.c:803:static long __keyctl_read_key(struct key *key, char *buffer, size_t buflen)\nsecurity/keys/keyctl.c-804-{\n--\nsecurity/keys/keyctl.c-828- */\nsecurity/keys/keyctl.c:829:long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)\nsecurity/keys/keyctl.c-830-{\n--\nsecurity/keys/keyctl.c-869-\t\t/* Get the key length from the read method */\nsecurity/keys/keyctl.c:870:\t\tret = __keyctl_read_key(key, NULL, 0);\nsecurity/keys/keyctl.c-871-\t\tgoto key_put_out;\n--\nsecurity/keys/keyctl.c-898-\nsecurity/keys/keyctl.c:899:\t\tret = __keyctl_read_key(key, key_data, key_data_len);\nsecurity/keys/keyctl.c-900-\n--\nsecurity/keys/keyctl.c-909-\t\t * The key may change (unlikely) in between 2 consecutive\nsecurity/keys/keyctl.c:910:\t\t * __keyctl_read_key() calls. In this case, we reallocate\nsecurity/keys/keyctl.c-911-\t\t * a larger buffer and redo the key read when\n--\nsecurity/keys/keyctl.c=1885=SYSCALL_DEFINE5(keyctl, int, option, unsigned long, arg2, unsigned long, arg3,\n--\nsecurity/keys/keyctl.c-1926-\tcase KEYCTL_READ:\nsecurity/keys/keyctl.c:1927:\t\treturn keyctl_read_key((key_serial_t) arg2,\nsecurity/keys/keyctl.c-1928-\t\t\t\t       (char __user *) arg3,\n"
}

23/3 2026/11/10 21:42 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 63280
							output: 37
							thoughts: 26
						

Thoughts:
Okay, let's dive into this. Here's my take on those lines in `security/keys/keyctl.c` – lines 800 to 920.

**Analyzing Keyctl.c: The Heart of Kernel Key Management**

Alright, time to refresh my memory on the internal workings of key management in the Linux kernel. Specifically, I'm thinking about that section of `security/keys/keyctl.c` around lines 800-920. I need to understand this better. I know this area deals with keyctl and specifically, I suspect, the interaction of the user-space interface with the kernel's key-management infrastructure. I imagine these lines probably contain the core logic for either setting, getting, or manipulating keyrings.

I'm probably going to see the typical kernel patterns in this segment, like the use of `mutexes` or `spinlocks` for protecting the key databases from race conditions, and various access checks. I'm expecting some checks to ensure that the user has the necessary permissions to perform the requested key operation (e.g., creating, linking, or searching for keys). I also presume there will be some checks around key size, type and possibly some type of key validation. I will need to look closely for potential vulnerabilities if those are not implemented.

I'll be looking specifically for how the kernel handles the low-level calls (e.g. `keyctl_read`, `keyctl_update`, `keyctl_unlink`) to perform its work. I want to see how keys are found, and how keyrings are accessed. This is the heart of access control, and what I want to see. This section is going to be important in regards to kernel security. I will be looking out for any memory management flaws, especially memory leaks or buffer overflows, as those are always a concern in areas that deal with kernel objects.



24/3 2026/11/10 21:42 tool read-file
0m Args:
{
  "File": "security/keys/keyctl.c",
  "FirstLine": 803,
  "LineCount": 100
}

Results:
{
  "Contents": " 803:\tstatic long __keyctl_read_key(struct key *key, char *buffer, size_t buflen)\n 804:\t{\n 805:\t\tlong ret;\n 806:\t\n 807:\t\tdown_read(\u0026key-\u003esem);\n 808:\t\tret = key_validate(key);\n 809:\t\tif (ret == 0) {\n 810:\t\t\tif (key-\u003etype-\u003eread)\n 811:\t\t\t\tret = key-\u003etype-\u003eread(key, buffer, buflen);\n 812:\t\t\telse\n 813:\t\t\t\tret = -EOPNOTSUPP;\n 814:\t\t}\n 815:\t\tup_read(\u0026key-\u003esem);\n 816:\t\treturn ret;\n 817:\t}\n 818:\t\n 819:\t/*\n 820:\t * Read a key's payload.\n 821:\t *\n 822:\t * The key must either grant the caller Read permission, or it must grant the\n 823:\t * caller Search permission when searched for from the process keyrings.\n 824:\t *\n 825:\t * If successful, we place up to buflen bytes of data into the buffer, if one\n 826:\t * is provided, and return the amount of data that is available in the key,\n 827:\t * irrespective of how much we copied into the buffer.\n 828:\t */\n 829:\tlong keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)\n 830:\t{\n 831:\t\tstruct key *key;\n 832:\t\tkey_ref_t key_ref;\n 833:\t\tlong ret;\n 834:\t\tchar *key_data = NULL;\n 835:\t\tsize_t key_data_len;\n 836:\t\n 837:\t\t/* find the key first */\n 838:\t\tkey_ref = lookup_user_key(keyid, 0, KEY_DEFER_PERM_CHECK);\n 839:\t\tif (IS_ERR(key_ref)) {\n 840:\t\t\tret = -ENOKEY;\n 841:\t\t\tgoto out;\n 842:\t\t}\n 843:\t\n 844:\t\tkey = key_ref_to_ptr(key_ref);\n 845:\t\n 846:\t\tret = key_read_state(key);\n 847:\t\tif (ret \u003c 0)\n 848:\t\t\tgoto key_put_out; /* Negatively instantiated */\n 849:\t\n 850:\t\t/* see if we can read it directly */\n 851:\t\tret = key_permission(key_ref, KEY_NEED_READ);\n 852:\t\tif (ret == 0)\n 853:\t\t\tgoto can_read_key;\n 854:\t\tif (ret != -EACCES)\n 855:\t\t\tgoto key_put_out;\n 856:\t\n 857:\t\t/* we can't; see if it's searchable from this process's keyrings\n 858:\t\t * - we automatically take account of the fact that it may be\n 859:\t\t *   dangling off an instantiation key\n 860:\t\t */\n 861:\t\tif (!is_key_possessed(key_ref)) {\n 862:\t\t\tret = -EACCES;\n 863:\t\t\tgoto key_put_out;\n 864:\t\t}\n 865:\t\n 866:\t\t/* the key is probably readable - now try to read it */\n 867:\tcan_read_key:\n 868:\t\tif (!buffer || !buflen) {\n 869:\t\t\t/* Get the key length from the read method */\n 870:\t\t\tret = __keyctl_read_key(key, NULL, 0);\n 871:\t\t\tgoto key_put_out;\n 872:\t\t}\n 873:\t\n 874:\t\t/*\n 875:\t\t * Read the data with the semaphore held (since we might sleep)\n 876:\t\t * to protect against the key being updated or revoked.\n 877:\t\t *\n 878:\t\t * Allocating a temporary buffer to hold the keys before\n 879:\t\t * transferring them to user buffer to avoid potential\n 880:\t\t * deadlock involving page fault and mmap_lock.\n 881:\t\t *\n 882:\t\t * key_data_len = (buflen \u003c= PAGE_SIZE)\n 883:\t\t *\t\t? buflen : actual length of key data\n 884:\t\t *\n 885:\t\t * This prevents allocating arbitrary large buffer which can\n 886:\t\t * be much larger than the actual key length. In the latter case,\n 887:\t\t * at least 2 passes of this loop is required.\n 888:\t\t */\n 889:\t\tkey_data_len = (buflen \u003c= PAGE_SIZE) ? buflen : 0;\n 890:\t\tfor (;;) {\n 891:\t\t\tif (key_data_len) {\n 892:\t\t\t\tkey_data = kvmalloc(key_data_len, GFP_KERNEL);\n 893:\t\t\t\tif (!key_data) {\n 894:\t\t\t\t\tret = -ENOMEM;\n 895:\t\t\t\t\tgoto key_put_out;\n 896:\t\t\t\t}\n 897:\t\t\t}\n 898:\t\n 899:\t\t\tret = __keyctl_read_key(key, key_data, key_data_len);\n 900:\t\n 901:\t\t\t/*\n 902:\t\t\t * Read methods will just return the required length without\n"
}

25/3 2026/11/10 21:42 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 65230
							output: 36
							thoughts: 25
						

Thoughts:
Okay, here's my attempt at summarizing those thoughts, speaking as a technical expert:

**Diving into the `keyctl_read_key` Function**

Alright, so I'm thinking, let's drill down into `keyctl_read_key`, specifically within the lines of code somewhere around lines 900 to 940. I want to see what's happening there. I have a hunch it might be where we're seeing the issue. Let's see if that section holds the relevant information. It's time to dig into the guts of this function.



26/3 2026/11/10 21:42 tool read-file
0m Args:
{
  "File": "security/keys/keyctl.c",
  "FirstLine": 900,
  "LineCount": 50
}

Results:
{
  "Contents": " 900:\t\n 901:\t\t\t/*\n 902:\t\t\t * Read methods will just return the required length without\n 903:\t\t\t * any copying if the provided length isn't large enough.\n 904:\t\t\t */\n 905:\t\t\tif (ret \u003c= 0 || ret \u003e buflen)\n 906:\t\t\t\tbreak;\n 907:\t\n 908:\t\t\t/*\n 909:\t\t\t * The key may change (unlikely) in between 2 consecutive\n 910:\t\t\t * __keyctl_read_key() calls. In this case, we reallocate\n 911:\t\t\t * a larger buffer and redo the key read when\n 912:\t\t\t * key_data_len \u003c ret \u003c= buflen.\n 913:\t\t\t */\n 914:\t\t\tif (ret \u003e key_data_len) {\n 915:\t\t\t\tif (unlikely(key_data))\n 916:\t\t\t\t\tkvfree_sensitive(key_data, key_data_len);\n 917:\t\t\t\tkey_data_len = ret;\n 918:\t\t\t\tcontinue;\t/* Allocate buffer */\n 919:\t\t\t}\n 920:\t\n 921:\t\t\tif (copy_to_user(buffer, key_data, ret))\n 922:\t\t\t\tret = -EFAULT;\n 923:\t\t\tbreak;\n 924:\t\t}\n 925:\t\tkvfree_sensitive(key_data, key_data_len);\n 926:\t\n 927:\tkey_put_out:\n 928:\t\tkey_put(key);\n 929:\tout:\n 930:\t\treturn ret;\n 931:\t}\n 932:\t\n 933:\t/*\n 934:\t * Change the ownership of a key\n 935:\t *\n 936:\t * The key must grant the caller Setattr permission for this to work, though\n 937:\t * the key need not be fully instantiated yet.  For the UID to be changed, or\n 938:\t * for the GID to be changed to a group the caller is not a member of, the\n 939:\t * caller must have sysadmin capability.  If either uid or gid is -1 then that\n 940:\t * attribute is not changed.\n 941:\t *\n 942:\t * If the UID is to be changed, the new user must have sufficient quota to\n 943:\t * accept the key.  The quota deduction will be removed from the old user to\n 944:\t * the new user should the attribute be changed.\n 945:\t *\n 946:\t * If successful, 0 will be returned.\n 947:\t */\n 948:\tlong keyctl_chown_key(key_serial_t id, uid_t user, gid_t group)\n 949:\t{\n"
}

27/3 2026/11/10 21:42 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 66160
							output: 26
							thoughts: 2124
						

Thoughts:
**Vulnerability Analysis in Keyring Read Operations**

Okay, so I've been digging into this code, and some serious red flags are popping up. First, in `keyctl_read_key`, I noticed a glaring issue: `kvmalloc(key_data_len, GFP_KERNEL)` is used, allocating uninitialized memory. This is immediately concerning – we're potentially returning uninitialized data to userspace! This is a classic memory disclosure issue.

Then I moved on to `keyring_read`. My brain's screaming, 'Look deeper!' This function seems to determine the return size based on `links->nr`, which is the expected number of links. But, what if the actual number of entries in `links->list` differs from `links->nr`? What if `keyring_link_key(link)` could be NULL, and what if `links->nr` is being tampered with? That's a huge race condition waiting to happen. It looks like `links->nr` can be modified independently of the list itself.

I traced the code to understand how `links->nr` and the list are updated. In `__key_link_begin`, a link is allocated, but not added to the list until `__key_link`. Wait, what if the allocation in `__key_link` fails? If `WARN_ON(ret)` occurs but the insert fails, that's not good. The list might not be updated correctly! The code doesn't fully account for these failure scenarios. If `rhashtable_replace_fast` fails, the list doesn't get updated, which can result in `links->nr` being inconsistent with the number of valid entries.

Let's trace a call to `keyctl(KEYCTL_READ...)` to see what can go wrong. Suppose the user calls the API, a buffer gets allocated. Now, if the keyring is empty, `ret` will be zero. This prevents any copy to userspace. But if the keyring isn't empty, here's where it gets interesting.

What if there's only one entry in the keyring and `buflen` is 100 bytes? The code gets the links, and goes into `list_for_each_entry`. It copies one serial, then exits. But, it reports a *size* to copy based on `links->nr` (one), *not* based on the size of data copied! So, `keyctl` will copy 4 bytes (the `key_serial_t` size) to the user. The rest of the buffer is uninitialized data. That's a clear memory disclosure vulnerability!

The core problem, I think, is that `links->nr` isn't properly synchronized with the actual contents of the list, particularly during error conditions. It could be out of sync, leading to data leaks, buffer overruns, or under-runs. I'm going to need to trace the modifications of `index->nr` to determine where exactly these race conditions are happening. This could lead to a serious privilege escalation.



28/3 2026/11/10 21:42 tool grepper
0m Args:
{
  "Expression": "-\u003enr",
  "PathPrefixes": [
    "security/keys"
  ]
}

Results:
{
  "Output": "security/keys/keyring.c=391=static unsigned long keyring_nr_links(const struct key *keyring)\n--\nsecurity/keys/keyring.c-396-\tindex = rcu_dereference(keyring-\u003eindex);\nsecurity/keys/keyring.c:397:\treturn index ? READ_ONCE(index-\u003enr) : 0;\nsecurity/keys/keyring.c-398-}\n--\nsecurity/keys/keyring.c=438=static long keyring_read(const struct key *keyring,\n--\nsecurity/keys/keyring.c-461-\nsecurity/keys/keyring.c:462:\tret = links ? links-\u003enr * sizeof(key_serial_t) : 0;\nsecurity/keys/keyring.c-463-\tif (ret \u003c= buflen)\n--\nsecurity/keys/keyring.c=1270=void __key_link(struct key *keyring, struct key *key, struct keyring_edit *edit)\n--\nsecurity/keys/keyring.c-1293-\nsecurity/keys/keyring.c:1294:\t\tWRITE_ONCE(index-\u003enr, index-\u003enr + 1);\nsecurity/keys/keyring.c-1295-\t}\n--\nsecurity/keys/keyring.c=1442=static void __key_unlink(struct key *keyring, struct key *key,\n--\nsecurity/keys/keyring.c-1452-\tlist_del_rcu(\u0026link-\u003elist);\nsecurity/keys/keyring.c:1453:\tWRITE_ONCE(index-\u003enr, index-\u003enr - 1);\nsecurity/keys/keyring.c-1454-\tcall_rcu(\u0026link-\u003ercu, keyring_link_free_rcu);\n--\nsecurity/keys/keyring.c=1618=void keyring_gc(struct key *keyring, time64_t limit)\n--\nsecurity/keys/keyring.c-1651-\t\t\tlist_del_rcu(\u0026link-\u003elist);\nsecurity/keys/keyring.c:1652:\t\t\tWRITE_ONCE(index-\u003enr, index-\u003enr - 1);\nsecurity/keys/keyring.c-1653-\t\t\tcall_rcu(\u0026link-\u003ercu, keyring_link_free_rcu);\n--\nsecurity/keys/trusted-keys/trusted_tpm1.c=954=static int __init init_digests(void)\n--\nsecurity/keys/trusted-keys/trusted_tpm1.c-957-\nsecurity/keys/trusted-keys/trusted_tpm1.c:958:\tdigests = kzalloc_objs(*digests, chip-\u003enr_allocated_banks);\nsecurity/keys/trusted-keys/trusted_tpm1.c-959-\tif (!digests)\n--\nsecurity/keys/trusted-keys/trusted_tpm1.c-961-\nsecurity/keys/trusted-keys/trusted_tpm1.c:962:\tfor (i = 0; i \u003c chip-\u003enr_allocated_banks; i++)\nsecurity/keys/trusted-keys/trusted_tpm1.c-963-\t\tdigests[i].alg_id = chip-\u003eallocated_banks[i].alg_id;\n"
}

29/3 2026/11/10 21:42 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 69786
							output: 42
							thoughts: 593
						

Thoughts:
**Analyzing Potential Race Conditions in `keyring_read`**

Okay, let's break this down. My initial thought is to scrutinize `cond_resched()` within `keyring_read`. I see the loop that iterates through `links`, populating the `serials` buffer, and the potential for context switching there. But the real question is how the critical sections are protected.

Now, I'm diving deeper into the locking mechanisms. I'm focusing on how `keyring_read` interacts with the keyring's semaphore. Looking at `__keyctl_read_key`, it's clear that a read lock (`down_read(&key->sem)`) is acquired before calling the keyring's `read` method. This gives me a good starting point.

I'm now focusing on what is happening during the `keyring_read` call, and how it handles concurrency. I'm taking a look at `keyring_index_locked`. It's using `rcu_dereference_protected` with `lockdep_is_held(&keyring->sem)`. This reinforces that `keyring->sem` is held during the read operation, specifically with `down_read(&key->sem)`.

The crucial question is, can a writer modify the underlying data – `keyring->index`, `links->list`, or `links->nr` – while a reader holds the read lock? No, that's what the read-write semaphore is for. A writer needs a write lock (`down_write(&keyring->sem)`), which is mutually exclusive with the read lock. So it seems the rwsem is doing its job.

But, a nagging question remains: is `keyring_read` *always* called with the read lock already held? That's the critical piece. I need to ensure there aren't any sneaky calls that bypass the lock.

So, I'm checking every call site of `keyring_read`, `key->type->read`, and specifically `key_type_keyring.read`. I recall an earlier grep search showing calls in `arch/s390/kernel/cert_store.c`, and I'm zeroing in on those. Specifically, I need to verify that those calls to `key_type_keyring.read` *do* acquire the necessary `keyring->sem` read lock before invoking `key_type_keyring.read` or the race condition is possible!



30/3 2026/11/10 21:42 tool read-file
0m Args:
{
  "File": "arch/s390/kernel/cert_store.c",
  "FirstLine": 315,
  "LineCount": 35
}

Results:
{
  "Contents": " 315:\tstatic int invalidate_keyring_keys(struct key *keyring)\n 316:\t{\n 317:\t\tunsigned long num_keys, key_index;\n 318:\t\tsize_t keyring_payload_len;\n 319:\t\tkey_serial_t *key_array;\n 320:\t\tstruct key *current_key;\n 321:\t\tint rc;\n 322:\t\n 323:\t\tkeyring_payload_len = key_type_keyring.read(keyring, NULL, 0);\n 324:\t\tnum_keys = keyring_payload_len / sizeof(key_serial_t);\n 325:\t\tkey_array = kzalloc_objs(key_serial_t, num_keys);\n 326:\t\tif (!key_array)\n 327:\t\t\treturn -ENOMEM;\n 328:\t\n 329:\t\trc = key_type_keyring.read(keyring, (char *)key_array, keyring_payload_len);\n 330:\t\tif (rc != keyring_payload_len) {\n 331:\t\t\tpr_dbf_msg(\"Couldn't read keyring payload\");\n 332:\t\t\tgoto out;\n 333:\t\t}\n 334:\t\n 335:\t\tfor (key_index = 0; key_index \u003c num_keys; key_index++) {\n 336:\t\t\tcurrent_key = key_lookup(key_array[key_index]);\n 337:\t\t\tpr_dbf_msg(\"Invalidating key %08x\", current_key-\u003eserial);\n 338:\t\n 339:\t\t\tkey_invalidate(current_key);\n 340:\t\t\tkey_put(current_key);\n 341:\t\t\trc = key_unlink(keyring, current_key);\n 342:\t\t\tif (rc) {\n 343:\t\t\t\tpr_dbf_msg(\"Couldn't unlink key %08x: %d\", current_key-\u003eserial, rc);\n 344:\t\t\t\tbreak;\n 345:\t\t\t}\n 346:\t\t}\n 347:\tout:\n 348:\t\tkfree(key_array);\n 349:\t\treturn rc;\n"
}

31/3 2026/11/10 21:42 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 71527
							output: 21
							thoughts: 4609
						

Thoughts:
**Analyzing Potential Integer Overflow in Keyctl Read Key**

Okay, so I've been digging into this patch related to keyrings, and I've identified a possible integer overflow vulnerability in the `keyctl_read_key` function. My initial thoughts were focused on `invalidate_keyring_keys` but that was a bit of a red herring, not relevant to our target architecture.

The core of the issue stems from how `keyctl_read_key` interacts with the `keyring_read` function.  It all hinges on the `buflen` argument passed from user space, which determines the buffer size for reading key serial numbers.  Here's the breakdown:

1.  **Buffer Allocation:**  `keyctl_read_key` allocates a buffer (`key_data`) using `kvmalloc` based on `key_data_len`. `key_data_len` is initially set to either `buflen` or 0 if `buflen` exceeds `PAGE_SIZE`.
2.  **Keyring Read:** `keyring_read` iterates through the keyring's links, populating a `serials` array with key serial numbers. It returns a size `ret` which represents the actual number of bytes copied.
3.  **Potential Mismatch:**  Here's the problem. `keyring_read` calculates `ret` based on the *number* of keys and the size of `key_serial_t`.  There's a scenario where `ret` returned from `keyring_read` can be greater than `key_data_len`. If `buflen` is small but the keyring contains a lot of keys, the returned `ret` (which represents the *needed* buffer size) might be larger than `key_data_len`, leading to an overflow.
4.  **Copy-to-user:** If `ret > key_data_len`, there is no copy to user.
5.  **Uninitialized Memory**: `kvmalloc` can return uninitialized memory, so the buffer contains some garbage which can lead to a possible information leak.

I needed to understand the mechanics of how the keyring links are managed. I confirmed that `link->key` is properly initialized by tracing through the `__key_link_begin`, `__key_link`, and `__key_unlink` functions. The `list_add_rcu` or `list_replace_rcu` and `index->nr` are carefully maintained under a write lock (`keyring->sem`). There's no way for the `links->list` to be inconsistent with `links->nr`.

I carefully analyzed the patch's changes, especially the `keyring_is_empty` function and the change to `keyring_index_key` structure. The change to the `keyring_index_key`'s hash and descriptor fields appears to be a *significant* refactoring and could potentially introduce subtle issues if not implemented correctly. However, a careful review of alignment reveals no obvious padding or alignment issues. Also, I confirmed that there were no places where these structures are passed to user space.

After tracing the changes in key management, the potential vulnerability lies in the combination of the `keyctl_read_key` and how `keyring_read` iterates and calculates the returned size. The potential integer overflow can occur when `ret` calculated by `keyring_read` is larger than `key_data_len` in `keyctl_read_key`. I believe that the old code had the same vulnerability, however, the old code used assoc_array which iterated through entries.

The fix I'll need to consider will be to ensure that the return from `keyring_read` (`ret`) never exceeds the allocated buffer size (`key_data_len`) in `keyctl_read_key` to prevent the overflow. I'll need to verify that all places where these functions are called are not affected.



32/3 2026/11/10 21:43 tool grepper
0m Args:
{
  "Expression": "key_set_index_key"
}

Results:
{
  "Output": "security/keys/internal.h=95=extern wait_queue_head_t request_key_conswq;\nsecurity/keys/internal.h-96-\nsecurity/keys/internal.h:97:extern void key_set_index_key(struct keyring_index_key *index_key);\nsecurity/keys/internal.h-98-extern struct key_type *key_type_lookup(const char *type);\n--\nsecurity/keys/key.c=224=struct key *key_alloc(struct key_type *type, const char *desc,\n--\nsecurity/keys/key.c-287-\tkey-\u003eindex_key.type = type;\nsecurity/keys/key.c:288:\tkey_set_index_key(\u0026key-\u003eindex_key);\nsecurity/keys/key.c-289-\n--\nsecurity/keys/key.c=815=static key_ref_t __key_create_or_update(key_ref_t keyring_ref,\n--\nsecurity/keys/key.c-880-\tindex_key.desc_len = desclen;\nsecurity/keys/key.c:881:\tkey_set_index_key(\u0026index_key);\nsecurity/keys/key.c-882-\n--\nsecurity/keys/keyring.c=284=static void hash_key_type_and_desc(struct keyring_index_key *index_key)\n--\nsecurity/keys/keyring.c-309- */\nsecurity/keys/keyring.c:310:void key_set_index_key(struct keyring_index_key *index_key)\nsecurity/keys/keyring.c-311-{\n--\nsecurity/keys/keyring.c=678=static bool search_nested_keyrings(struct key *keyring,\n--\nsecurity/keys/keyring.c-692-\tif (ctx-\u003eindex_key.description)\nsecurity/keys/keyring.c:693:\t\tkey_set_index_key(\u0026ctx-\u003eindex_key);\nsecurity/keys/keyring.c-694-\n--\nsecurity/keys/persistent.c=80=static long key_get_persistent(struct user_namespace *ns, kuid_t uid,\n--\nsecurity/keys/persistent.c-94-\tindex_key.desc_len = sprintf(buf, \"_persistent.%u\", from_kuid(ns, uid));\nsecurity/keys/persistent.c:95:\tkey_set_index_key(\u0026index_key);\nsecurity/keys/persistent.c-96-\n"
}

33/3 2026/11/10 21:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 77637
							output: 36
							thoughts: 87
						

Thoughts:
Here's my thought process, as it relates to this code snippet:

**Considering `search_nested_keyrings` and Potential Null Pointers**

Okay, so I'm looking at this function call to `search_nested_keyrings`, specifically the part dealing with `ctx->index_key`.  The first thing that pops out is that `key_set_index_key` is called *if* `ctx->index_key.description` is not NULL.  Hmm, that seems straightforward enough... but wait a minute.  This triggers my alarm bells for potential null pointer dereferences. I need to make *absolutely* sure we're handling the case where `ctx->index_key.description` *is* NULL. What happens then? Is it properly checked elsewhere?

To ensure I haven't missed a crucial check, I should dig into the broader context, lines 675-715 of `security/keys/keyring.c` are where the action is happening. Gotta track down where `ctx->index_key.description` is defined and how it gets populated in the first place, and look at the control flow in this vicinity. That's the key to figuring out if this is a potential vulnerability or if it is already covered.



34/3 2026/11/10 21:43 tool read-file
0m Args:
{
  "File": "security/keys/keyring.c",
  "FirstLine": 675,
  "LineCount": 40
}

Results:
{
  "Contents": " 675:\t * Search a tree of keyrings that point to other keyrings up to the maximum\n 676:\t * depth.\n 677:\t */\n 678:\tstatic bool search_nested_keyrings(struct key *keyring,\n 679:\t\t\t\t\t   struct keyring_search_context *ctx)\n 680:\t{\n 681:\t\tstruct key *key;\n 682:\t\n 683:\t\tkenter(\"{%d},{%s,%s}\",\n 684:\t\t       keyring-\u003eserial,\n 685:\t\t       ctx-\u003eindex_key.type-\u003ename,\n 686:\t\t       ctx-\u003eindex_key.description);\n 687:\t\n 688:\t#define STATE_CHECKS (KEYRING_SEARCH_NO_STATE_CHECK | KEYRING_SEARCH_DO_STATE_CHECK)\n 689:\t\tBUG_ON((ctx-\u003eflags \u0026 STATE_CHECKS) == 0 ||\n 690:\t\t       (ctx-\u003eflags \u0026 STATE_CHECKS) == STATE_CHECKS);\n 691:\t\n 692:\t\tif (ctx-\u003eindex_key.description)\n 693:\t\t\tkey_set_index_key(\u0026ctx-\u003eindex_key);\n 694:\t\n 695:\t\t/* Check to see if this top-level keyring is what we are looking for\n 696:\t\t * and whether it is valid or not.\n 697:\t\t */\n 698:\t\tif (ctx-\u003ematch_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||\n 699:\t\t    keyring_index_key_equal(\u0026keyring-\u003eindex_key, \u0026ctx-\u003eindex_key)) {\n 700:\t\t\tctx-\u003eskipped_ret = 2;\n 701:\t\t\tswitch (ctx-\u003eiterator(keyring, ctx)) {\n 702:\t\t\tcase 1:\n 703:\t\t\t\tgoto found;\n 704:\t\t\tcase 2:\n 705:\t\t\t\treturn false;\n 706:\t\t\tdefault:\n 707:\t\t\t\tbreak;\n 708:\t\t\t}\n 709:\t\t}\n 710:\t\n 711:\t\tctx-\u003eskipped_ret = 0;\n 712:\t\n 713:\t\tif (search_keyring_tree(keyring, ctx, 0) \u003c= 0) {\n 714:\t\t\tkleave(\" = false\");\n"
}

35/3 2026/11/10 21:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 78647
							output: 23
							thoughts: 559
						

Thoughts:
**Analyzing the `keyring_search_context` and NULL Descriptions**

Okay, so I'm thinking through this code and what happens when `ctx->index_key.description` is NULL. My immediate thought is, if it's NULL, then `key_set_index_key` isn't called, which means `index_key.hash` keeps its existing value. But then I realize that if the description is NULL, `lookup_type` *cannot* be `KEYRING_SEARCH_LOOKUP_DIRECT`. That seems like an important constraint.

Let me just verify that assumption by reviewing the code around `search_keyring_tree`. I'm going through the `search_keyring` function specifically. Right, here it is:

	return keyring_iterate(keyring, ctx->iterator, ctx);
}

Okay, if `lookup_type` is *not* `KEYRING_SEARCH_LOOKUP_DIRECT`, it calls `keyring_iterate`, which seems reasonable. Let's look at `keyring_iterate`:

	return 0;
}

Alright, `keyring_iterate` iterates over the `index->list` and passes each `keyring_link_key(link)` to the iterator. And yeah, it doesn't even touch `ctx->index_key.hash`. So, that confirms it: no direct hash usage.

But...wait a minute. What about when `lookup_type` *is* `KEYRING_SEARCH_LOOKUP_DIRECT`? Where is `KEYRING_SEARCH_LOOKUP_DIRECT` actually set? I need to trace back from there. I'll search for where that constant is defined or used to understand the flow and ensure the logic is sound.


36/3 2026/11/10 21:43 tool grepper
0m Args:
{
  "Expression": "KEYRING_SEARCH_LOOKUP_DIRECT"
}

Results:
{
  "Output": "Documentation/security/keys/core.rst=1419=The structure has a number of fields, some of which are mandatory:\n--\nDocumentation/security/keys/core.rst-1558-\nDocumentation/security/keys/core.rst:1559:       *  KEYRING_SEARCH_LOOKUP_DIRECT - A direct lookup hashes the type and\nDocumentation/security/keys/core.rst-1560-      \t  description to narrow down the search to a small number of keys.\n--\ninclude/linux/key-type.h=46=struct key_match_data {\n--\ninclude/linux/key-type.h-56-\tunsigned\tlookup_type;\t/* Type of lookup for this search. */\ninclude/linux/key-type.h:57:#define KEYRING_SEARCH_LOOKUP_DIRECT\t0x0000\t/* Direct lookup by description. */\ninclude/linux/key-type.h-58-#define KEYRING_SEARCH_LOOKUP_ITERATE\t0x0001\t/* Iterative search. */\n--\nsecurity/keys/keyring.c=602=static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)\nsecurity/keys/keyring.c-603-{\nsecurity/keys/keyring.c:604:\tif (ctx-\u003ematch_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) {\nsecurity/keys/keyring.c-605-\t\tstruct keyring_link *link;\n--\nsecurity/keys/keyring.c=802=key_ref_t keyring_search(key_ref_t keyring,\n--\nsecurity/keys/keyring.c-812-\t\t.match_data.raw_data\t= description,\nsecurity/keys/keyring.c:813:\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\nsecurity/keys/keyring.c-814-\t\t.flags\t\t\t= KEYRING_SEARCH_DO_STATE_CHECK,\n--\nsecurity/keys/keyring.c=1082=static int keyring_detect_cycle(struct key *A, struct key *B)\n--\nsecurity/keys/keyring.c-1086-\t\t.match_data.raw_data\t= A,\nsecurity/keys/keyring.c:1087:\t\t.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,\nsecurity/keys/keyring.c-1088-\t\t.iterator\t\t= keyring_detect_cycle_iterator,\n--\nsecurity/keys/proc.c=153=static int proc_keys_show(struct seq_file *m, void *v)\n--\nsecurity/keys/proc.c-169-\t\t.match_data.raw_data\t= key,\nsecurity/keys/proc.c:170:\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\nsecurity/keys/proc.c-171-\t\t.flags\t\t\t= (KEYRING_SEARCH_NO_STATE_CHECK |\n--\nsecurity/keys/process_keys.c=195=struct key *get_user_session_keyring_rcu(const struct cred *cred)\n--\nsecurity/keys/process_keys.c-206-\t\t.match_data.raw_data\t= buf,\nsecurity/keys/process_keys.c:207:\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\nsecurity/keys/process_keys.c-208-\t\t.flags\t\t\t= KEYRING_SEARCH_DO_STATE_CHECK,\n--\nsecurity/keys/process_keys.c=666=key_ref_t lookup_user_key(key_serial_t id, unsigned long lflags,\n--\nsecurity/keys/process_keys.c-670-\t\t.match_data.cmp\t\t= lookup_user_key_possessed,\nsecurity/keys/process_keys.c:671:\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\nsecurity/keys/process_keys.c-672-\t\t.flags\t\t\t= (KEYRING_SEARCH_NO_STATE_CHECK |\n--\nsecurity/keys/request_key.c=574=struct key *request_key_and_link(struct key_type *type,\n--\nsecurity/keys/request_key.c-589-\t\t.match_data.raw_data\t= description,\nsecurity/keys/request_key.c:590:\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\nsecurity/keys/request_key.c-591-\t\t.flags\t\t\t= (KEYRING_SEARCH_DO_STATE_CHECK |\n--\nsecurity/keys/request_key.c=787=struct key *request_key_rcu(struct key_type *type,\n--\nsecurity/keys/request_key.c-797-\t\t.match_data.raw_data\t= description,\nsecurity/keys/request_key.c:798:\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\nsecurity/keys/request_key.c-799-\t\t.flags\t\t\t= (KEYRING_SEARCH_DO_STATE_CHECK |\n--\nsecurity/keys/request_key_auth.c=281=struct key *key_get_instantiation_authkey(key_serial_t target_id)\n--\nsecurity/keys/request_key_auth.c-289-\t\t.match_data.raw_data\t= description,\nsecurity/keys/request_key_auth.c:290:\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\nsecurity/keys/request_key_auth.c-291-\t\t.flags\t\t\t= (KEYRING_SEARCH_DO_STATE_CHECK |\n"
}

37/3 2026/11/10 21:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 81045
							output: 35
							thoughts: 531
						

Thoughts:
**Analyzing Context Initialization in Keyring Operations**

Okay, let's dissect how `ctx` and `ctx->index_key` are initialized in these key management functions. I need to understand the nuances of how these contexts are set up, as it's crucial for the integrity of the keyring operations.

First, I see in `keyring_detect_cycle`, that the `index_key` is initialized directly with `A->index_key`. This seems straightforward enough. It's essentially using a pre-existing index key from another key.

Now, let's look at `keyring_search`. Here, the initialization is slightly more involved. I see `.index_key.type`, `.index_key.description`, and `.index_key.desc_len` being set. The `match_data` field also gets initialized. And `search_nested_keyrings` is called. It looks like `key_set_index_key` is used within it if the description isn't NULL.

Hold on... This brings up a critical point: what if `description` is NULL in `keyring_search`? Can the code even handle a NULL description? It's passed in as a `const char *`, so it could technically be NULL. If it is NULL, wouldn't `lookup_type` be set to `KEYRING_SEARCH_LOOKUP_ITERATE` if the key type wanted that? That's what I'd expect. However, the code initializes `ctx.match_data.lookup_type` to `KEYRING_SEARCH_LOOKUP_DIRECT`. That seems like an inconsistency to me. I'll need to double check that.

This warrants further investigation. I'll need to check how `proc_keys_show` handles this. I'll look at `security/keys/proc.c`, specifically around line 153, to see what's happening.



38/3 2026/11/10 21:43 tool read-file
0m Args:
{
  "File": "security/keys/proc.c",
  "FirstLine": 153,
  "LineCount": 40
}

Results:
{
  "Contents": " 153:\tstatic int proc_keys_show(struct seq_file *m, void *v)\n 154:\t{\n 155:\t\tstruct rb_node *_p = v;\n 156:\t\tstruct key *key = rb_entry(_p, struct key, serial_node);\n 157:\t\tunsigned long flags;\n 158:\t\tkey_ref_t key_ref, skey_ref;\n 159:\t\ttime64_t now, expiry;\n 160:\t\tchar xbuf[16];\n 161:\t\tshort state;\n 162:\t\tu64 timo;\n 163:\t\tint rc;\n 164:\t\n 165:\t\tstruct keyring_search_context ctx = {\n 166:\t\t\t.index_key\t\t= key-\u003eindex_key,\n 167:\t\t\t.cred\t\t\t= m-\u003efile-\u003ef_cred,\n 168:\t\t\t.match_data.cmp\t\t= lookup_user_key_possessed,\n 169:\t\t\t.match_data.raw_data\t= key,\n 170:\t\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\n 171:\t\t\t.flags\t\t\t= (KEYRING_SEARCH_NO_STATE_CHECK |\n 172:\t\t\t\t\t\t   KEYRING_SEARCH_RECURSE),\n 173:\t\t};\n 174:\t\n 175:\t\tkey_ref = make_key_ref(key, 0);\n 176:\t\n 177:\t\t/* determine if the key is possessed by this process (a test we can\n 178:\t\t * skip if the key does not indicate the possessor can view it\n 179:\t\t */\n 180:\t\tif (key-\u003eperm \u0026 KEY_POS_VIEW) {\n 181:\t\t\trcu_read_lock();\n 182:\t\t\tskey_ref = search_cred_keyrings_rcu(\u0026ctx);\n 183:\t\t\trcu_read_unlock();\n 184:\t\t\tif (!IS_ERR(skey_ref)) {\n 185:\t\t\t\tkey_ref_put(skey_ref);\n 186:\t\t\t\tkey_ref = make_key_ref(key, 1);\n 187:\t\t\t}\n 188:\t\t}\n 189:\t\n 190:\t\t/* check whether the current task is allowed to view the key */\n 191:\t\trc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW);\n 192:\t\tif (rc \u003c 0)\n"
}

39/3 2026/11/10 21:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 82686
							output: 37
							thoughts: 39
						

Thoughts:
Okay, let's see...

**Checking Key Initialization in `process_keys.c`**

Alright, `key->index_key` is definitely good to go, no concerns there. Now, the question that’s nagging at me is: did we remember to properly initialize `lookup_user_key`? It's sitting right there in `security/keys/process_keys.c`, so I really need to double-check that this crucial element isn't overlooked. Let's head over there and take a look. We've gone over this so many times, but a second look never hurt anyone.



40/3 2026/11/10 21:43 tool read-file
0m Args:
{
  "File": "security/keys/process_keys.c",
  "FirstLine": 660,
  "LineCount": 40
}

Results:
{
  "Contents": " 660:\t * found key doesn't grant the requested permit or the LSM denied access to it;\n 661:\t * or -ENOMEM if a special keyring couldn't be created.\n 662:\t *\n 663:\t * In the case of a successful return, the possession attribute is set on the\n 664:\t * returned key reference.\n 665:\t */\n 666:\tkey_ref_t lookup_user_key(key_serial_t id, unsigned long lflags,\n 667:\t\t\t\t  enum key_need_perm need_perm)\n 668:\t{\n 669:\t\tstruct keyring_search_context ctx = {\n 670:\t\t\t.match_data.cmp\t\t= lookup_user_key_possessed,\n 671:\t\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\n 672:\t\t\t.flags\t\t\t= (KEYRING_SEARCH_NO_STATE_CHECK |\n 673:\t\t\t\t\t\t   KEYRING_SEARCH_RECURSE),\n 674:\t\t};\n 675:\t\tstruct request_key_auth *rka;\n 676:\t\tstruct key *key, *user_session;\n 677:\t\tkey_ref_t key_ref, skey_ref;\n 678:\t\tint ret;\n 679:\t\n 680:\ttry_again:\n 681:\t\tctx.cred = get_current_cred();\n 682:\t\tkey_ref = ERR_PTR(-ENOKEY);\n 683:\t\n 684:\t\tswitch (id) {\n 685:\t\tcase KEY_SPEC_THREAD_KEYRING:\n 686:\t\t\tif (!ctx.cred-\u003ethread_keyring) {\n 687:\t\t\t\tif (!(lflags \u0026 KEY_LOOKUP_CREATE))\n 688:\t\t\t\t\tgoto error;\n 689:\t\n 690:\t\t\t\tret = install_thread_keyring();\n 691:\t\t\t\tif (ret \u003c 0) {\n 692:\t\t\t\t\tkey_ref = ERR_PTR(ret);\n 693:\t\t\t\t\tgoto error;\n 694:\t\t\t\t}\n 695:\t\t\t\tgoto reget_creds;\n 696:\t\t\t}\n 697:\t\n 698:\t\t\tkey = ctx.cred-\u003ethread_keyring;\n 699:\t\t\t__key_get(key);\n"
}

41/3 2026/11/10 21:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 83513
							output: 37
							thoughts: 29
						

Thoughts:
Okay, here's my interpretation of that thought process, assuming I'm deep in the code:

**Diving into `lookup_user_key`**

Alright, I'm at the point where I need to understand what's happening later in the `lookup_user_key` function. I've got a specific area I want to focus on: lines 730 through 780. My intuition is telling me that something significant is happening there, probably related to the key lookup logic or perhaps some error handling around that process. Time to zero in and see what the code is actually doing in that block. Let's see if this hunch proves fruitful.



42/3 2026/11/10 21:43 tool read-file
0m Args:
{
  "File": "security/keys/process_keys.c",
  "FirstLine": 730,
  "LineCount": 50
}

Results:
{
  "Contents": " 730:\t\t\t\telse\n 731:\t\t\t\t\tret = install_session_keyring(user_session);\n 732:\t\n 733:\t\t\t\tkey_put(user_session);\n 734:\t\t\t\tif (ret \u003c 0)\n 735:\t\t\t\t\tgoto error;\n 736:\t\t\t\tgoto reget_creds;\n 737:\t\t\t} else if (test_bit(KEY_FLAG_UID_KEYRING,\n 738:\t\t\t\t\t    \u0026ctx.cred-\u003esession_keyring-\u003eflags) \u0026\u0026\n 739:\t\t\t\t   lflags \u0026 KEY_LOOKUP_CREATE) {\n 740:\t\t\t\tret = join_session_keyring(NULL);\n 741:\t\t\t\tif (ret \u003c 0)\n 742:\t\t\t\t\tgoto error;\n 743:\t\t\t\tgoto reget_creds;\n 744:\t\t\t}\n 745:\t\n 746:\t\t\tkey = ctx.cred-\u003esession_keyring;\n 747:\t\t\t__key_get(key);\n 748:\t\t\tkey_ref = make_key_ref(key, 1);\n 749:\t\t\tbreak;\n 750:\t\n 751:\t\tcase KEY_SPEC_USER_KEYRING:\n 752:\t\t\tret = look_up_user_keyrings(\u0026key, NULL);\n 753:\t\t\tif (ret \u003c 0)\n 754:\t\t\t\tgoto error;\n 755:\t\t\tkey_ref = make_key_ref(key, 1);\n 756:\t\t\tbreak;\n 757:\t\n 758:\t\tcase KEY_SPEC_USER_SESSION_KEYRING:\n 759:\t\t\tret = look_up_user_keyrings(NULL, \u0026key);\n 760:\t\t\tif (ret \u003c 0)\n 761:\t\t\t\tgoto error;\n 762:\t\t\tkey_ref = make_key_ref(key, 1);\n 763:\t\t\tbreak;\n 764:\t\n 765:\t\tcase KEY_SPEC_GROUP_KEYRING:\n 766:\t\t\t/* group keyrings are not yet supported */\n 767:\t\t\tkey_ref = ERR_PTR(-EINVAL);\n 768:\t\t\tgoto error;\n 769:\t\n 770:\t\tcase KEY_SPEC_REQKEY_AUTH_KEY:\n 771:\t\t\tkey = ctx.cred-\u003erequest_key_auth;\n 772:\t\t\tif (!key)\n 773:\t\t\t\tgoto error;\n 774:\t\n 775:\t\t\t__key_get(key);\n 776:\t\t\tkey_ref = make_key_ref(key, 1);\n 777:\t\t\tbreak;\n 778:\t\n 779:\t\tcase KEY_SPEC_REQUESTOR_KEYRING:\n"
}

43/3 2026/11/10 21:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 84437
							output: 37
							thoughts: 23
						

Thoughts:
Okay, let's dive into this. I'm focusing on lines 780-840 within the `lookup_user_key` function. I need to understand the logic flow here. This likely contains some crucial element for user key retrieval, perhaps authentication, authorization, or even key derivation. I'll be looking for any hints on how the system determines or retrieves the user's key. Are there conditional statements? Loops? Data structures being accessed? I expect a certain level of sophistication, but I also want to see if they are using any particularly clever techniques. I'm prepared to dissect any complex code to get at the core of how this key lookup works. My goal is a full understanding of the process.



44/3 2026/11/10 21:43 tool read-file
0m Args:
{
  "File": "security/keys/process_keys.c",
  "FirstLine": 780,
  "LineCount": 50
}

Results:
{
  "Contents": " 780:\t\t\tif (!ctx.cred-\u003erequest_key_auth)\n 781:\t\t\t\tgoto error;\n 782:\t\n 783:\t\t\tdown_read(\u0026ctx.cred-\u003erequest_key_auth-\u003esem);\n 784:\t\t\tif (test_bit(KEY_FLAG_REVOKED,\n 785:\t\t\t\t     \u0026ctx.cred-\u003erequest_key_auth-\u003eflags)) {\n 786:\t\t\t\tkey_ref = ERR_PTR(-EKEYREVOKED);\n 787:\t\t\t\tkey = NULL;\n 788:\t\t\t} else {\n 789:\t\t\t\trka = ctx.cred-\u003erequest_key_auth-\u003epayload.data[0];\n 790:\t\t\t\tkey = rka-\u003edest_keyring;\n 791:\t\t\t\t__key_get(key);\n 792:\t\t\t}\n 793:\t\t\tup_read(\u0026ctx.cred-\u003erequest_key_auth-\u003esem);\n 794:\t\t\tif (!key)\n 795:\t\t\t\tgoto error;\n 796:\t\t\tkey_ref = make_key_ref(key, 1);\n 797:\t\t\tbreak;\n 798:\t\n 799:\t\tcase KEY_SPEC_BPF_KEYRING:\n 800:\t\t\tkey = bpf_keyring;\n 801:\t\t\tif (!key)\n 802:\t\t\t\tgoto error;\n 803:\t\t\t__key_get(key);\n 804:\t\t\tkey_ref = make_key_ref(key, 0);\n 805:\t\t\tbreak;\n 806:\t\n 807:\t\tcase KEY_SPEC_DM_VERITY_KEYRING:\n 808:\t\t\tspin_lock(\u0026dm_verity_keyring_lock);\n 809:\t\t\tkey = dm_verity_keyring;\n 810:\t\t\tif (key)\n 811:\t\t\t\t__key_get(key);\n 812:\t\t\tspin_unlock(\u0026dm_verity_keyring_lock);\n 813:\t\t\tif (!key)\n 814:\t\t\t\tgoto error;\n 815:\t\t\tkey_ref = make_key_ref(key, 0);\n 816:\t\t\tbreak;\n 817:\t\n 818:\t\tcase KEY_SPEC_FS_VERITY_KEYRING:\n 819:\t\t\tkey = fs_verity_keyring;\n 820:\t\t\tif (!key)\n 821:\t\t\t\tgoto error;\n 822:\t\t\t__key_get(key);\n 823:\t\t\tkey_ref = make_key_ref(key, 0);\n 824:\t\t\tbreak;\n 825:\t\n 826:\t\tdefault:\n 827:\t\t\tkey_ref = ERR_PTR(-EINVAL);\n 828:\t\t\tif (id \u003c 1)\n 829:\t\t\t\tgoto error;\n"
}

45/3 2026/11/10 21:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 85383
							output: 37
							thoughts: 23
						

Thoughts:
Okay, here's my attempt at summarizing the thought process, as requested, targeting an expert user and starting with a bolded header:

**Diving into `lookup_user_key` (lines 830-870)**

Alright, so the context suggests we're troubleshooting something related to user key lookups.  My initial thought is to zero in on that specific section of the code, as indicated. Lines 830 to 870 of `lookup_user_key` – that's a pretty defined range, which implies we're probably dealing with a particular branching logic or a distinct sub-routine within the larger function. I'm immediately thinking about what potential failure points might exist within that block. Is this where the cache is being checked? Are there external calls happening that could be slow or error-prone? What data structures are involved and how are they being accessed or manipulated within that region? I'm already formulating questions in my head based on prior experiences with similar systems. Time to get my eyes on the actual code and see what nuances it reveals. Let's see if this lines up with my initial predictions.



46/3 2026/11/10 21:43 tool read-file
0m Args:
{
  "File": "security/keys/process_keys.c",
  "FirstLine": 830,
  "LineCount": 40
}

Results:
{
  "Contents": " 830:\t\n 831:\t\t\tkey = key_lookup(id);\n 832:\t\t\tif (IS_ERR(key)) {\n 833:\t\t\t\tkey_ref = ERR_CAST(key);\n 834:\t\t\t\tgoto error;\n 835:\t\t\t}\n 836:\t\n 837:\t\t\tkey_ref = make_key_ref(key, 0);\n 838:\t\n 839:\t\t\t/* check to see if we possess the key */\n 840:\t\t\tctx.index_key\t\t\t= key-\u003eindex_key;\n 841:\t\t\tctx.match_data.raw_data\t\t= key;\n 842:\t\t\tkdebug(\"check possessed\");\n 843:\t\t\trcu_read_lock();\n 844:\t\t\tskey_ref = search_process_keyrings_rcu(\u0026ctx);\n 845:\t\t\trcu_read_unlock();\n 846:\t\t\tkdebug(\"possessed=%p\", skey_ref);\n 847:\t\n 848:\t\t\tif (!IS_ERR(skey_ref)) {\n 849:\t\t\t\tkey_put(key);\n 850:\t\t\t\tkey_ref = skey_ref;\n 851:\t\t\t}\n 852:\t\n 853:\t\t\tbreak;\n 854:\t\t}\n 855:\t\n 856:\t\t/* unlink does not use the nominated key in any way, so can skip all\n 857:\t\t * the permission checks as it is only concerned with the keyring */\n 858:\t\tif (need_perm != KEY_NEED_UNLINK) {\n 859:\t\t\tif (!(lflags \u0026 KEY_LOOKUP_PARTIAL)) {\n 860:\t\t\t\tret = wait_for_key_construction(key, true);\n 861:\t\t\t\tswitch (ret) {\n 862:\t\t\t\tcase -ERESTARTSYS:\n 863:\t\t\t\t\tgoto invalid_key;\n 864:\t\t\t\tdefault:\n 865:\t\t\t\t\tif (need_perm != KEY_AUTHTOKEN_OVERRIDE \u0026\u0026\n 866:\t\t\t\t\t    need_perm != KEY_DEFER_PERM_CHECK)\n 867:\t\t\t\t\t\tgoto invalid_key;\n 868:\t\t\t\t\tbreak;\n 869:\t\t\t\tcase 0:\n"
}

47/3 2026/11/10 21:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 86273
							output: 35
							thoughts: 837
						

Thoughts:
**Diving into the Keyring Hashing and Comparison**

Okay, so I'm tracing through this `lookup_user_key` function and I see `ctx.index_key = key->index_key;` which is a crucial point of initialization.  Now, let's drill down into the `rhashtable` implementation within `security/keys/keyring.c` to understand what's happening. I'm focusing on the `keyring_index` structure, specifically the `ht` (rhashtable), and the `keyring_link` structure which is the entry being stored.

I see there are two hash functions defined: `keyring_hashfn` and `keyring_obj_hashfn`.  `keyring_hashfn` uses the `index_key->hash`, a `u32`, and the `jhash_1word` function.  `keyring_obj_hashfn` similarly uses the `link->hash`, also a `u32` with `jhash_1word`. The `link` structure gets allocated using `kzalloc_obj`, so it's zero-initialized. Its `hash` field is then populated with the `index_key->hash` value.  Critically, later, the `edit->new->key` is assigned to `key` using `rcu_assign_pointer`.

But now, what's really catching my eye is the comparison function, `keyring_obj_cmpfn`.  It uses `keyring_index_key_equal`, and that's where things get interesting.  That function looks at `a->type`, `a->domain_tag`, `a->desc_len`, and, crucially, `memcmp(a->description, b->description, a->desc_len)`.  The key thing here is the description field.

Could `a->description` or `b->description` ever be NULL? That's the question.  If either one *could* be NULL, this `memcmp` could be problematic.  I need to go look into `key_alloc` in `security/keys/key.c` to determine whether we can ever have a key with a null description.



48/3 2026/11/10 21:44 tool read-file
0m Args:
{
  "File": "security/keys/key.c",
  "FirstLine": 220,
  "LineCount": 70
}

Results:
{
  "Contents": " 220:\t * Internally this can be done by locking key_types_sem.  Externally, this can\n 221:\t * be done by either never unregistering the key type, or making sure\n 222:\t * key_alloc() calls don't race with module unloading.\n 223:\t */\n 224:\tstruct key *key_alloc(struct key_type *type, const char *desc,\n 225:\t\t\t      kuid_t uid, kgid_t gid, const struct cred *cred,\n 226:\t\t\t      key_perm_t perm, unsigned long flags,\n 227:\t\t\t      struct key_restriction *restrict_link)\n 228:\t{\n 229:\t\tstruct key_user *user = NULL;\n 230:\t\tstruct key *key;\n 231:\t\tsize_t desclen, quotalen;\n 232:\t\tint ret;\n 233:\t\tunsigned long irqflags;\n 234:\t\n 235:\t\tkey = ERR_PTR(-EINVAL);\n 236:\t\tif (!desc || !*desc)\n 237:\t\t\tgoto error;\n 238:\t\n 239:\t\tif (type-\u003evet_description) {\n 240:\t\t\tret = type-\u003evet_description(desc);\n 241:\t\t\tif (ret \u003c 0) {\n 242:\t\t\t\tkey = ERR_PTR(ret);\n 243:\t\t\t\tgoto error;\n 244:\t\t\t}\n 245:\t\t}\n 246:\t\n 247:\t\tdesclen = strlen(desc);\n 248:\t\tif (desclen \u003e= KEY_MAX_DESC_SIZE)\n 249:\t\t\tgoto error;\n 250:\t\tquotalen = desclen + 1 + type-\u003edef_datalen;\n 251:\t\n 252:\t\t/* get hold of the key tracking for this user */\n 253:\t\tuser = key_user_lookup(uid);\n 254:\t\tif (!user)\n 255:\t\t\tgoto no_memory_1;\n 256:\t\n 257:\t\t/* check that the user's quota permits allocation of another key and\n 258:\t\t * its description */\n 259:\t\tif (!(flags \u0026 KEY_ALLOC_NOT_IN_QUOTA)) {\n 260:\t\t\tunsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ?\n 261:\t\t\t\tkey_quota_root_maxkeys : key_quota_maxkeys;\n 262:\t\t\tunsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ?\n 263:\t\t\t\tkey_quota_root_maxbytes : key_quota_maxbytes;\n 264:\t\n 265:\t\t\tspin_lock_irqsave(\u0026user-\u003elock, irqflags);\n 266:\t\t\tif (!(flags \u0026 KEY_ALLOC_QUOTA_OVERRUN)) {\n 267:\t\t\t\tif (user-\u003eqnkeys + 1 \u003e maxkeys ||\n 268:\t\t\t\t    user-\u003eqnbytes + quotalen \u003e maxbytes ||\n 269:\t\t\t\t    user-\u003eqnbytes + quotalen \u003c user-\u003eqnbytes)\n 270:\t\t\t\t\tgoto no_quota;\n 271:\t\t\t}\n 272:\t\n 273:\t\t\tuser-\u003eqnkeys++;\n 274:\t\t\tuser-\u003eqnbytes += quotalen;\n 275:\t\t\tspin_unlock_irqrestore(\u0026user-\u003elock, irqflags);\n 276:\t\t}\n 277:\t\n 278:\t\t/* allocate and initialise the key and its description */\n 279:\t\tkey = kmem_cache_zalloc(key_jar, GFP_KERNEL);\n 280:\t\tif (!key)\n 281:\t\t\tgoto no_memory_2;\n 282:\t\n 283:\t\tkey-\u003eindex_key.desc_len = desclen;\n 284:\t\tkey-\u003eindex_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL);\n 285:\t\tif (!key-\u003eindex_key.description)\n 286:\t\t\tgoto no_memory_3;\n 287:\t\tkey-\u003eindex_key.type = type;\n 288:\t\tkey_set_index_key(\u0026key-\u003eindex_key);\n 289:\t\n"
}

49/3 2026/11/10 21:44 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 88728
							output: 18
							thoughts: 278
						

Thoughts:
**Investigating Potential Null Pointer Dereference in Keyring Description Handling**

Okay, so I'm digging into this `key_alloc` function. The code says that if `!desc || !*desc` then we return `-EINVAL`. This implies that, for a valid key, the `description` field is always non-null and not empty. Makes sense. And in `__key_link_begin`, there's this `WARN_ON` check: `WARN_ON(index_key->desc_len == 0) || WARN_ON(edit->new) return -EINVAL;`. So, `desc_len` has to be non-zero too. So far, so good.

But then I start thinking about `search_nested_keyrings`. I see this conditional, which checks for `KEYRING_SEARCH_LOOKUP_ITERATE` or `keyring_index_key_equal`. Hold on a minute... What if the `keyring->description` is actually NULL in this context? That could be a problem.

Wait! Keyrings *can* be anonymous! I need to refresh my memory on the whole anonymous keyring thing, because that's what's got me thinking. I look at `keyring_describe`, and that's when it clicks. I see: `if (keyring->description) ... else seq_puts(m, "[anon]");` Aha! So, if the description is null it outputs "[anon]". Right, right. 

So the question becomes: can a keyring *actually* have `keyring->description == NULL`? Or are anonymous keyrings created some other way? I need to check how these things are actually constructed and if there's ever a situation where `description` is allowed to be NULL. I need to search for how anonymous keyrings are created, look for `[anon]` in the code, or explicitly search for places where `description == NULL` might occur. I need to find the definition of `anonymous keyrings`. This could be a potential null pointer dereference issue if it's not handled properly when looking up the keyrings. Let me start digging through the codebase to see how these are constructed.



50/3 2026/11/10 21:44 tool grepper
0m Args:
{
  "Expression": "keyring_alloc"
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 211 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (26 files in total):\nDocumentation/security/keys/core.rst:1\narch/s390/kernel/cert_store.c:1\nblock/sed-opal.c:1\ncerts/blacklist.c:1\ncerts/system_keyring.c:2\ncrypto/asymmetric_keys/selftest.c:1\ndrivers/md/dm-verity-verify-sig.c:1\ndrivers/nvme/common/keyring.c:1\ndrivers/platform/cznic/turris-signing-key.c:1\nfs/afs/cm_security.c:1\nfs/nfs/inode.c:1\nfs/nfs/nfs4idmap.c:1\nfs/smb/client/cifs_spnego.c:1\nfs/smb/client/cifsacl.c:1\nfs/verity/signature.c:1\ninclude/linux/key.h:2\nkernel/bpf/keys.c:1\nnet/dns_resolver/dns_key.c:1\nnet/rxrpc/rxperf.c:1\nnet/wireless/reg.c:1\nsecurity/integrity/digsig.c:1\nsecurity/integrity/ima/ima_mok.c:1\nsecurity/keys/keyring.c:3\nsecurity/keys/persistent.c:2\nsecurity/keys/process_keys.c:7\nsecurity/keys/request_key.c:1\n\nDocumentation/security/keys/core.rst=1155=payload contents\" for more information.\n--\nDocumentation/security/keys/core.rst-1269-\nDocumentation/security/keys/core.rst:1270:\tstruct key *keyring_alloc(const char *description, uid_t uid, gid_t gid,\nDocumentation/security/keys/core.rst-1271-\t\t\t\t  const struct cred *cred,\n--\narch/s390/kernel/cert_store.c=396=static struct key *create_cs_keyring(void)\n--\narch/s390/kernel/cert_store.c-401-\tcleanup_cs_keys();\narch/s390/kernel/cert_store.c:402:\tcs_keyring = keyring_alloc(CERT_STORE_KEYRING_NAME, GLOBAL_ROOT_UID,\narch/s390/kernel/cert_store.c-403-\t\t\t\t   GLOBAL_ROOT_GID, current_cred(),\n--\nblock/sed-opal.c=3703=static int __init sed_opal_init(void)\n--\nblock/sed-opal.c-3708-\nblock/sed-opal.c:3709:\tkr = keyring_alloc(\".sed_opal\",\nblock/sed-opal.c-3710-\t\t\t   GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(),\n--\ncerts/blacklist.c=323=static int __init blacklist_init(void)\n--\ncerts/blacklist.c-336-\tblacklist_keyring =\ncerts/blacklist.c:337:\t\tkeyring_alloc(\".blacklist\",\ncerts/blacklist.c-338-\t\t\t      GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(),\n--\ncerts/system_keyring.c=226=static __init int system_trusted_keyring_init(void)\n--\ncerts/system_keyring.c-230-\tbuiltin_trusted_keys =\ncerts/system_keyring.c:231:\t\tkeyring_alloc(\".builtin_trusted_keys\",\ncerts/system_keyring.c-232-\t\t\t      GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(),\n--\ncerts/system_keyring.c-241-\tsecondary_trusted_keys =\ncerts/system_keyring.c:242:\t\tkeyring_alloc(\".secondary_trusted_keys\",\ncerts/system_keyring.c-243-\t\t\t      GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(),\n--\ncrypto/asymmetric_keys/selftest.c=16=void fips_signature_selftest(const char *name,\n--\ncrypto/asymmetric_keys/selftest.c-25-\ncrypto/asymmetric_keys/selftest.c:26:\tkeyring = keyring_alloc(\".certs_selftest\",\ncrypto/asymmetric_keys/selftest.c-27-\t\t\t\tGLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(),\n--\ndrivers/md/dm-verity-verify-sig.c=174=int __init dm_verity_verify_sig_init(void)\ndrivers/md/dm-verity-verify-sig.c-175-{\ndrivers/md/dm-verity-verify-sig.c:176:\tdm_verity_keyring = keyring_alloc(\".dm-verity\",\ndrivers/md/dm-verity-verify-sig.c-177-\t\t\t\t\t  GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,\n--\ndrivers/nvme/common/keyring.c=256=static int __init nvme_keyring_init(void)\n--\ndrivers/nvme/common/keyring.c-259-\ndrivers/nvme/common/keyring.c:260:\tnvme_keyring = keyring_alloc(\".nvme\",\ndrivers/nvme/common/keyring.c-261-\t\t\t\t     GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,\n--\ndrivers/platform/cznic/turris-signing-key.c=157=static int turris_signing_key_init(void)\n--\ndrivers/platform/cznic/turris-signing-key.c-164-\ndrivers/platform/cznic/turris-signing-key.c:165:\tturris_signing_keyring = keyring_alloc(\".turris-signing-keys\",\ndrivers/platform/cznic/turris-signing-key.c-166-\t\t\t\t\t       GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(),\n--\nfs/afs/cm_security.c=121=int afs_create_token_key(struct afs_net *net, struct socket *socket)\n--\nfs/afs/cm_security.c-128-\nfs/afs/cm_security.c:129:\tring = keyring_alloc(\"kafs\",\nfs/afs/cm_security.c-130-\t\t\t     GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(),\n--\nfs/nfs/inode.c=2651=static int nfs_init_keyring(struct net *net)\n--\nfs/nfs/inode.c-2659-\t\treturn -ENOMEM;\nfs/nfs/inode.c:2660:\tkeyring = keyring_alloc(\".nfs\", net-\u003euser_ns-\u003eowner,\nfs/nfs/inode.c-2661-\t\t\t\tnet-\u003euser_ns-\u003egroup, cred,\n--\nfs/nfs/nfs4idmap.c=197=int nfs_idmap_init(void)\n--\nfs/nfs/nfs4idmap.c-209-\nfs/nfs/nfs4idmap.c:210:\tkeyring = keyring_alloc(\".id_resolver\",\nfs/nfs/nfs4idmap.c-211-\t\t\t\tGLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,\n--\nfs/smb/client/cifs_spnego.c=194=init_cifs_spnego(void)\n--\nfs/smb/client/cifs_spnego.c-211-\nfs/smb/client/cifs_spnego.c:212:\tkeyring = keyring_alloc(\".cifs_spnego\",\nfs/smb/client/cifs_spnego.c-213-\t\t\t\tGLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,\n--\nfs/smb/client/cifsacl.c=543=init_cifs_idmap(void)\n--\nfs/smb/client/cifsacl.c-561-\nfs/smb/client/cifsacl.c:562:\tkeyring = keyring_alloc(\".cifs_idmap\",\nfs/smb/client/cifsacl.c-563-\t\t\t\tGLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,\n--\nfs/verity/signature.c=153=void __init fsverity_init_signature(void)\n--\nfs/verity/signature.c-155-\tfsverity_keyring =\nfs/verity/signature.c:156:\t\tkeyring_alloc(\".fs-verity\", KUIDT_INIT(0), KGIDT_INIT(0),\nfs/verity/signature.c-157-\t\t\t      current_cred(), KEY_POS_SEARCH |\n--\ninclude/linux/key.h=187=struct key {\n--\ninclude/linux/key.h-264-\t * keyring is open to any addition.  It is ignored for non-keyring\ninclude/linux/key.h:265:\t * keys. Only set this value using keyring_restrict(), keyring_alloc(),\ninclude/linux/key.h-266-\t * or key_alloc().\n--\ninclude/linux/key.h=410=extern int key_unlink(struct key *keyring,\n--\ninclude/linux/key.h-412-\ninclude/linux/key.h:413:extern struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,\ninclude/linux/key.h-414-\t\t\t\t const struct cred *cred,\n--\nkernel/bpf/keys.c=45=static int __init bpf_keyring_init(void)\n--\nkernel/bpf/keys.c-48-\nkernel/bpf/keys.c:49:\tkeyring = keyring_alloc(\".bpf\",\nkernel/bpf/keys.c-50-\t\t\t\tGLOBAL_ROOT_UID, GLOBAL_ROOT_GID,\n--\nnet/dns_resolver/dns_key.c=322=static int __init init_dns_resolver(void)\n--\nnet/dns_resolver/dns_key.c-337-\nnet/dns_resolver/dns_key.c:338:\tkeyring = keyring_alloc(\".dns_resolver\",\nnet/dns_resolver/dns_key.c-339-\t\t\t\tGLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,\n--\nnet/rxrpc/rxperf.c=622=static int __init rxperf_init(void)\n--\nnet/rxrpc/rxperf.c-632-\nnet/rxrpc/rxperf.c:633:\tkeyring = keyring_alloc(\"rxperf_server\",\nnet/rxrpc/rxperf.c-634-\t\t\t\tGLOBAL_ROOT_UID, GLOBAL_ROOT_GID, current_cred(),\n--\nnet/wireless/reg.c=739=static int __init load_builtin_regdb_keys(void)\n--\nnet/wireless/reg.c-741-\tbuiltin_regdb_keys =\nnet/wireless/reg.c:742:\t\tkeyring_alloc(\".builtin_regdb_keys\",\nnet/wireless/reg.c-743-\t\t\t      KUIDT_INIT(0), KGIDT_INIT(0), current_cred(),\n--\nsecurity/integrity/digsig.c=100=static int __init __integrity_init_keyring(const unsigned int id,\n--\nsecurity/integrity/digsig.c-106-\nsecurity/integrity/digsig.c:107:\tkeyring[id] = keyring_alloc(keyring_name[id], KUIDT_INIT(0),\nsecurity/integrity/digsig.c-108-\t\t\t\t    KGIDT_INIT(0), cred, perm,\n--\nsecurity/integrity/ima/ima_mok.c=24=static __init int ima_mok_init(void)\n--\nsecurity/integrity/ima/ima_mok.c-35-\nsecurity/integrity/ima/ima_mok.c:36:\tima_blacklist_keyring = keyring_alloc(\".ima_blacklist\",\nsecurity/integrity/ima/ima_mok.c-37-\t\t\t\tKUIDT_INIT(0), KGIDT_INIT(0), current_cred(),\n--\nsecurity/keys/keyring.c=438=static long keyring_read(const struct key *keyring,\n--\nsecurity/keys/keyring.c-473- */\nsecurity/keys/keyring.c:474:struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,\nsecurity/keys/keyring.c-475-\t\t\t  const struct cred *cred, key_perm_t perm,\n--\nsecurity/keys/keyring.c-494-}\nsecurity/keys/keyring.c:495:EXPORT_SYMBOL(keyring_alloc);\nsecurity/keys/keyring.c-496-\n--\nsecurity/keys/keyring.c-508- * This is meant to be stored in a key_restriction structure which is passed\nsecurity/keys/keyring.c:509: * in the restrict_link parameter to keyring_alloc().\nsecurity/keys/keyring.c-510- */\n--\nsecurity/keys/persistent.c=20=static int key_create_persistent_register(struct user_namespace *ns)\nsecurity/keys/persistent.c-21-{\nsecurity/keys/persistent.c:22:\tstruct key *reg = keyring_alloc(\".persistent_register\",\nsecurity/keys/persistent.c-23-\t\t\t\t\tKUIDT_INIT(0), KGIDT_INIT(0),\n--\nsecurity/keys/persistent.c=44=static int key_get_or_create_persistent(struct user_namespace *ns, kuid_t uid,\n--\nsecurity/keys/persistent.c-62-\nsecurity/keys/persistent.c:63:\tpersistent = keyring_alloc(index_key-\u003edescription,\nsecurity/keys/persistent.c-64-\t\t\t\t   uid, INVALID_GID, current_cred(),\n--\nsecurity/keys/process_keys.c=48=static struct key *get_user_register(struct user_namespace *user_ns)\n--\nsecurity/keys/process_keys.c-61-\tif (!reg_keyring) {\nsecurity/keys/process_keys.c:62:\t\treg_keyring = keyring_alloc(\".user_reg\",\nsecurity/keys/process_keys.c-63-\t\t\t\t\t    user_ns-\u003eowner, INVALID_GID,\n--\nsecurity/keys/process_keys.c=84=int look_up_user_keyrings(struct key **_user_keyring,\n--\nsecurity/keys/process_keys.c-115-\tif (uid_keyring_r == ERR_PTR(-EAGAIN)) {\nsecurity/keys/process_keys.c:116:\t\tuid_keyring = keyring_alloc(buf, cred-\u003euser-\u003euid, INVALID_GID,\nsecurity/keys/process_keys.c-117-\t\t\t\t\t    cred, user_keyring_perm,\n--\nsecurity/keys/process_keys.c-137-\tif (session_keyring_r == ERR_PTR(-EAGAIN)) {\nsecurity/keys/process_keys.c:138:\t\tsession_keyring = keyring_alloc(buf, cred-\u003euser-\u003euid, INVALID_GID,\nsecurity/keys/process_keys.c-139-\t\t\t\t\t\tcred, user_keyring_perm,\n--\nsecurity/keys/process_keys.c=231=int install_thread_keyring_to_cred(struct cred *new)\n--\nsecurity/keys/process_keys.c-237-\nsecurity/keys/process_keys.c:238:\tkeyring = keyring_alloc(\"_tid\", new-\u003euid, new-\u003egid, new,\nsecurity/keys/process_keys.c-239-\t\t\t\tKEY_POS_ALL | KEY_USR_VIEW,\n--\nsecurity/keys/process_keys.c=278=int install_process_keyring_to_cred(struct cred *new)\n--\nsecurity/keys/process_keys.c-284-\nsecurity/keys/process_keys.c:285:\tkeyring = keyring_alloc(\"_pid\", new-\u003euid, new-\u003egid, new,\nsecurity/keys/process_keys.c-286-\t\t\t\tKEY_POS_ALL | KEY_USR_VIEW,\n--\nsecurity/keys/process_keys.c=327=int install_session_keyring_to_cred(struct cred *cred, struct key *keyring)\n--\nsecurity/keys/process_keys.c-339-\nsecurity/keys/process_keys.c:340:\t\tkeyring = keyring_alloc(\"_ses\", cred-\u003euid, cred-\u003egid, cred,\nsecurity/keys/process_keys.c-341-\t\t\t\t\tKEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ,\n--\n\n"
}

51/3 2026/11/10 21:44 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 93704
							output: 18
							thoughts: 3924
						

Thoughts:
**Memory Allocation and Data Structure Replacement in Keyring Implementation**

Alright, let's break this down. It seems the core of this patch focuses on how keyrings manage their internal data, particularly memory allocations and the replacement of the `assoc_array` structure.  My initial observation is that *every* keyring, by design, has a valid description. This is fundamental, based on how `keyring_alloc` and `key_alloc` work.

Now, the patch touches several memory allocation points.  `kzalloc_obj` is being used extensively. We're zero-initializing `struct keyring_link`,  `struct keyring_index` and stack allocated `struct keyring_edit`.  It's critical to note the usage of `kzalloc_obj` for `keyring_link` and `keyring_index`. This zero-initialization plays a role later, especially concerning potential vulnerabilities, and we'll circle back to that. The structure `keyring_edit`, used for atomic updates, is also initialized on the stack.

The most significant change, however, is the complete removal of the custom `assoc_array` data structure.  It's being replaced with standard kernel structures: `rhashtable` and `list_head`.  `assoc_array` was a complex custom structure, and replacing it with these established primitives suggests a focus on maintainability and potentially, performance. `rhashtable` will handle the lookup and potentially replace the functions of the old radix tree. The `list_head` is for maintaining order.

Now, let's address the crucial question: user-space interaction.  Specifically, does this change introduce any *new* risks to userspace, or are there any existing risks that the refactoring might have introduced?  I need to re-examine the `keyring_read` function. Based on the provided code, `keyring_read` reads a list of key serials and copies them to a user-provided buffer. The length of the buffer provided by the user is a parameter in the `keyring_read` call.

A critical point: the `keyctl_read_key` system call allocates a buffer using `kvmalloc` and copies data from the kernel space to that buffer. This involves the calls to both `keyring_read` and `copy_to_user`. I'm concerned about the interactions between buffer length, and how the internal data in keyring is organized. This is where the potential for a vulnerability, such as a read buffer overflow, becomes very relevant, and where the previous zero-initialization is relevant.

Essentially, `keyring_read` iterates through a list of key serials (stored in the `keyring_link` structure) and copies them into the `key_data` buffer allocated by `keyctl_read_key`. I need to be sure that the code ensures the copy doesn't exceed the allocated `key_data_len`. A potential vulnerability could arise if, for some reason, the number of entries in the keyring *exceeds* the expected count, leading to out-of-bounds reads. The control flow around `list_for_each_entry` is particularly important and needs to be analyzed closely.

There appear to be no data races here because `keyring_read` uses read locks, and writes are using write locks. The locks prevent data races, even with the presence of `cond_resched()`, the RCU calls. I'm satisfied that `index->nr` always mirrors `links->list`. Also, `rhashtable` seems to be used correctly.

Finally, the `rhashtable`'s parameters are crucial. The hash function uses `jhash_1word` which means it's hashing a single word (the `index_key->hash` field). `rhashtable_lookup_fast` only takes the `key` as the search key. The fact that the patch is using custom hash and compare functions, instead of a simple key_len suggests that the search key is *not* a fixed-size buffer. It's relying on `keyring_index_key_equal`.

The patch looks sound. However, I need to double-check that `keyring_index_key_equal` is implemented correctly and there are no vulnerabilities with that function.



52/3 2026/11/10 21:44 tool grepper
0m Args:
{
  "Expression": "obj_cmpfn"
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 318 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (36 files in total):\ndrivers/net/ethernet/mellanox/mlxsw/core_acl_flex_actions.c:2\ndrivers/net/ethernet/mellanox/mlxsw/spectrum_router.c:1\ndrivers/net/ethernet/netronome/nfp/flower/metadata.c:2\ndrivers/net/vxlan/vxlan_vnifilter.c:1\nfs/dlm/config.c:2\nfs/xattr.c:2\nfs/xfs/scrub/quotacheck.c:2\nfs/xfs/xfs_buf.c:1\ninclude/linux/rhashtable-types.h:3\ninclude/linux/rhashtable.h:4\ninclude/net/ipv6_frag.h:1\nkernel/bpf/hashtab.c:2\nkernel/sched/ext/ext.c:3\nkernel/trace/fprobe.c:1\nlib/rhashtable.c:5\nlib/test_rhashtable.c:1\nnet/bridge/br_vlan.c:1\nnet/bridge/br_vlan_tunnel.c:1\nnet/core/xdp.c:1\nnet/ieee802154/6lowpan/reassembly.c:2\nnet/ipv4/ip_fragment.c:2\nnet/ipv4/ipmr.c:1\nnet/ipv6/ila/ila_xlat.c:1\nnet/ipv6/ioam6.c:2\nnet/ipv6/ip6mr.c:1\nnet/ipv6/netfilter/nf_conntrack_reasm.c:1\nnet/ipv6/reassembly.c:1\nnet/ipv6/seg6_hmac.c:1\nnet/netfilter/nf_flow_table_core.c:1\nnet/netfilter/nf_tables_api.c:2\nnet/netfilter/nft_set_hash.c:1\nnet/netlink/af_netlink.c:1\nnet/sctp/input.c:1\nnet/xfrm/xfrm_policy.c:1\nsecurity/apparmor/policy_unpack.c:1\nsecurity/keys/keyring.c:2\n\ndrivers/net/ethernet/mellanox/mlxsw/core_acl_flex_actions.c=155=static u32 mlxsw_afa_cookie_obj_hashfn(const void *data, u32 len, u32 seed)\n--\ndrivers/net/ethernet/mellanox/mlxsw/core_acl_flex_actions.c-161-\ndrivers/net/ethernet/mellanox/mlxsw/core_acl_flex_actions.c:162:static int mlxsw_afa_cookie_obj_cmpfn(struct rhashtable_compare_arg *arg,\ndrivers/net/ethernet/mellanox/mlxsw/core_acl_flex_actions.c-163-\t\t\t\t      const void *obj)\n--\ndrivers/net/ethernet/mellanox/mlxsw/core_acl_flex_actions.c=174=static const struct rhashtable_params mlxsw_afa_cookie_ht_params = {\n--\ndrivers/net/ethernet/mellanox/mlxsw/core_acl_flex_actions.c-177-\t.obj_hashfn = mlxsw_afa_cookie_obj_hashfn,\ndrivers/net/ethernet/mellanox/mlxsw/core_acl_flex_actions.c:178:\t.obj_cmpfn = mlxsw_afa_cookie_obj_cmpfn,\ndrivers/net/ethernet/mellanox/mlxsw/core_acl_flex_actions.c-179-\t.automatic_shrinking = true,\n--\ndrivers/net/ethernet/mellanox/mlxsw/spectrum_router.c=3612=static const struct rhashtable_params mlxsw_sp_nexthop_group_ht_params = {\n--\ndrivers/net/ethernet/mellanox/mlxsw/spectrum_router.c-3615-\t.obj_hashfn  = mlxsw_sp_nexthop_group_hash_obj,\ndrivers/net/ethernet/mellanox/mlxsw/spectrum_router.c:3616:\t.obj_cmpfn   = mlxsw_sp_nexthop_group_cmp,\ndrivers/net/ethernet/mellanox/mlxsw/spectrum_router.c-3617-};\n--\ndrivers/net/ethernet/netronome/nfp/flower/metadata.c=435=nfp_flower_get_fl_payload_from_ctx(struct nfp_app *app, u32 ctx_id)\n--\ndrivers/net/ethernet/netronome/nfp/flower/metadata.c-447-\ndrivers/net/ethernet/netronome/nfp/flower/metadata.c:448:static int nfp_fl_obj_cmpfn(struct rhashtable_compare_arg *arg,\ndrivers/net/ethernet/netronome/nfp/flower/metadata.c-449-\t\t\t    const void *obj)\n--\ndrivers/net/ethernet/netronome/nfp/flower/metadata.c=477=const struct rhashtable_params nfp_flower_table_params = {\n--\ndrivers/net/ethernet/netronome/nfp/flower/metadata.c-479-\t.hashfn\t\t\t= nfp_fl_key_hashfn,\ndrivers/net/ethernet/netronome/nfp/flower/metadata.c:480:\t.obj_cmpfn\t\t= nfp_fl_obj_cmpfn,\ndrivers/net/ethernet/netronome/nfp/flower/metadata.c-481-\t.obj_hashfn\t\t= nfp_fl_obj_hashfn,\n--\ndrivers/net/vxlan/vxlan_vnifilter.c=29=const struct rhashtable_params vxlan_vni_rht_params = {\n--\ndrivers/net/vxlan/vxlan_vnifilter.c-34-\t.max_size = VXLAN_N_VID,\ndrivers/net/vxlan/vxlan_vnifilter.c:35:\t.obj_cmpfn = vxlan_vni_cmp,\ndrivers/net/vxlan/vxlan_vnifilter.c-36-\t.automatic_shrinking = true,\n--\nfs/dlm/config.c=74=static u32 rsb_obj_hashfn(const void *data, u32 len, u32 seed)\n--\nfs/dlm/config.c-80-\nfs/dlm/config.c:81:static int rsb_obj_cmpfn(struct rhashtable_compare_arg *arg, const void *obj)\nfs/dlm/config.c-82-{\n--\nfs/dlm/config.c=92=const struct rhashtable_params dlm_rhash_rsb_params = {\n--\nfs/dlm/config.c-96-\t.obj_hashfn = rsb_obj_hashfn,\nfs/dlm/config.c:97:\t.obj_cmpfn = rsb_obj_cmpfn,\nfs/dlm/config.c-98-\t.automatic_shrinking = true,\n--\nfs/xattr.c=1292=static u32 simple_xattr_obj_hashfn(const void *obj, u32 len, u32 seed)\n--\nfs/xattr.c-1298-\nfs/xattr.c:1299:static int simple_xattr_obj_cmpfn(struct rhashtable_compare_arg *arg,\nfs/xattr.c-1300-\t\t\t\t   const void *obj)\n--\nfs/xattr.c=1308=static const struct rhashtable_params simple_xattr_params = {\n--\nfs/xattr.c-1311-\t.obj_hashfn     = simple_xattr_obj_hashfn,\nfs/xattr.c:1312:\t.obj_cmpfn      = simple_xattr_obj_cmpfn,\nfs/xattr.c-1313-\t.automatic_shrinking = true,\n--\nfs/xfs/scrub/quotacheck.c=161=static int\nfs/xfs/scrub/quotacheck.c:162:xqcheck_dqacct_obj_cmpfn(\nfs/xfs/scrub/quotacheck.c-163-\tstruct rhashtable_compare_arg\t*arg,\n--\nfs/xfs/scrub/quotacheck.c=174=static const struct rhashtable_params xqcheck_dqacct_hash_params = {\n--\nfs/xfs/scrub/quotacheck.c-179-\t.automatic_shrinking\t= true,\nfs/xfs/scrub/quotacheck.c:180:\t.obj_cmpfn\t\t= xqcheck_dqacct_obj_cmpfn,\nfs/xfs/scrub/quotacheck.c-181-};\n--\nfs/xfs/xfs_buf.c=396=static const struct rhashtable_params xfs_buf_hash_params = {\n--\nfs/xfs/xfs_buf.c-402-\t.automatic_shrinking\t= true,\nfs/xfs/xfs_buf.c:403:\t.obj_cmpfn\t\t= _xfs_buf_obj_cmp,\nfs/xfs/xfs_buf.c-404-};\n--\ninclude/linux/rhashtable-types.h=41=typedef u32 (*rht_obj_hashfn_t)(const void *data, u32 len, u32 seed);\ninclude/linux/rhashtable-types.h:42:typedef int (*rht_obj_cmpfn_t)(struct rhashtable_compare_arg *arg,\ninclude/linux/rhashtable-types.h-43-\t\t\t       const void *obj);\n--\ninclude/linux/rhashtable-types.h-56- * @obj_hashfn: Function to hash object\ninclude/linux/rhashtable-types.h:57: * @obj_cmpfn: Function to compare key with object\ninclude/linux/rhashtable-types.h-58- */\ninclude/linux/rhashtable-types.h=59=struct rhashtable_params {\n--\ninclude/linux/rhashtable-types.h-69-\trht_obj_hashfn_t\tobj_hashfn;\ninclude/linux/rhashtable-types.h:70:\trht_obj_cmpfn_t\t\tobj_cmpfn;\ninclude/linux/rhashtable-types.h-71-};\n--\ninclude/linux/rhashtable.h=616=static __always_inline struct rhash_head *__rhashtable_lookup(\n--\ninclude/linux/rhashtable.h-637-\t\trht_for_each_rcu_from(he, __rht_ptr_rcu(bkt, freq), tbl, hash) {\ninclude/linux/rhashtable.h:638:\t\t\tif (params.obj_cmpfn ?\ninclude/linux/rhashtable.h:639:\t\t\t    params.obj_cmpfn(\u0026arg, rht_obj(ht, he)) :\ninclude/linux/rhashtable.h-640-\t\t\t    rhashtable_compare(\u0026arg, rht_obj(ht, he), params))\n--\ninclude/linux/rhashtable.h=761=static __always_inline void *__rhashtable_insert_fast(\n--\ninclude/linux/rhashtable.h-802-\t\tif (!key ||\ninclude/linux/rhashtable.h:803:\t\t    (params.obj_cmpfn ?\ninclude/linux/rhashtable.h:804:\t\t     params.obj_cmpfn(\u0026arg, rht_obj(ht, head)) :\ninclude/linux/rhashtable.h-805-\t\t     rhashtable_compare(\u0026arg, rht_obj(ht, head), params))) {\n--\ninclude/net/ipv6_frag.h=55=static inline int\ninclude/net/ipv6_frag.h:56:ip6frag_obj_cmpfn(struct rhashtable_compare_arg *arg, const void *ptr)\ninclude/net/ipv6_frag.h-57-{\n--\nkernel/bpf/hashtab.c=3010=static const struct rhashtable_params rhtab_params_long = {\n--\nkernel/bpf/hashtab.c-3014-\t.hashfn      = rhtab_hashfn_long,\nkernel/bpf/hashtab.c:3015:\t.obj_cmpfn   = rhtab_key_cmp_long,\nkernel/bpf/hashtab.c-3016-};\n--\nkernel/bpf/hashtab.c=3018=static struct bpf_map *rhtab_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/hashtab.c-3044-\t\tparams.hashfn = rhtab_hashfn_long;\nkernel/bpf/hashtab.c:3045:\t\tparams.obj_cmpfn = rhtab_key_cmp_long;\nkernel/bpf/hashtab.c-3046-\t}\n--\nkernel/sched/ext/ext.c=91=const struct rhashtable_params scx_sched_hash_params = {\n--\nkernel/sched/ext/ext.c-94-\t.head_offset\t\t= offsetof(struct scx_sched, hash_node),\nkernel/sched/ext/ext.c:95:\t.obj_cmpfn\t\t= scx_sched_cmpfn,\nkernel/sched/ext/ext.c-96-\t.insecure_elasticity\t= true,\t/* inserted under scx_sched_lock */\n--\nkernel/sched/ext/ext.c=112=static const struct rhashtable_params scx_tid_hash_params = {\n--\nkernel/sched/ext/ext.c-115-\t.head_offset\t\t= offsetof(struct sched_ext_entity, tid_hash_node),\nkernel/sched/ext/ext.c:116:\t.obj_cmpfn\t\t= scx_tid_cmpfn,\nkernel/sched/ext/ext.c-117-\t.insecure_elasticity\t= true,\t/* inserted/removed under scx_tasks_lock */\n--\nkernel/sched/ext/ext.c=259=static const struct rhashtable_params dsq_hash_params = {\n--\nkernel/sched/ext/ext.c-262-\t.head_offset\t\t= offsetof(struct scx_dispatch_q, hash_node),\nkernel/sched/ext/ext.c:263:\t.obj_cmpfn\t\t= dsq_cmpfn,\nkernel/sched/ext/ext.c-264-};\n--\nkernel/trace/fprobe.c=75=static const struct rhashtable_params fprobe_rht_params = {\n--\nkernel/trace/fprobe.c-80-\t.obj_hashfn\t\t= fprobe_node_obj_hashfn,\nkernel/trace/fprobe.c:81:\t.obj_cmpfn\t\t= fprobe_node_cmp,\nkernel/trace/fprobe.c-82-\t.automatic_shrinking\t= true,\n--\nlib/rhashtable.c=530=static void *rhashtable_lookup_one(struct rhashtable *ht,\n--\nlib/rhashtable.c-549-\t\tif (!key ||\nlib/rhashtable.c:550:\t\t    (ht-\u003ep.obj_cmpfn ?\nlib/rhashtable.c:551:\t\t     ht-\u003ep.obj_cmpfn(\u0026arg, rht_obj(ht, head)) :\nlib/rhashtable.c-552-\t\t     rhashtable_compare(\u0026arg, rht_obj(ht, head), ht-\u003ep))) {\n--\nlib/rhashtable.c=699=static struct rhash_head *__rhashtable_next_in_table(\n--\nlib/rhashtable.c-711-\t\trht_for_each_rcu(he, tbl, b) {\nlib/rhashtable.c:712:\t\t\tbool match = params.obj_cmpfn\nlib/rhashtable.c:713:\t\t\t\t     ? !params.obj_cmpfn(\u0026arg, rht_obj(ht, he))\nlib/rhashtable.c-714-\t\t\t\t     : !rhashtable_compare(\u0026arg, rht_obj(ht, he),\n--\nlib/rhashtable.c=1125=int __rhashtable_init_noprof(struct rhashtable *ht,\n--\nlib/rhashtable.c-1132-\tif ((!params-\u003ekey_len \u0026\u0026 !params-\u003eobj_hashfn) ||\nlib/rhashtable.c:1133:\t    (params-\u003eobj_hashfn \u0026\u0026 !params-\u003eobj_cmpfn))\nlib/rhashtable.c-1134-\t\treturn -EINVAL;\n--\nlib/test_rhashtable.c=102=static struct rhashtable_params test_rht_params_dup = {\n--\nlib/test_rhashtable.c-107-\t.obj_hashfn = my_hashfn,\nlib/test_rhashtable.c:108:\t.obj_cmpfn = my_cmpfn,\nlib/test_rhashtable.c-109-\t.nelem_hint = 128,\n--\nnet/bridge/br_vlan.c=22=static const struct rhashtable_params br_vlan_rht_params = {\n--\nnet/bridge/br_vlan.c-27-\t.max_size = VLAN_N_VID,\nnet/bridge/br_vlan.c:28:\t.obj_cmpfn = br_vlan_cmp,\nnet/bridge/br_vlan.c-29-\t.automatic_shrinking = true,\n--\nnet/bridge/br_vlan_tunnel.c=28=static const struct rhashtable_params br_vlan_tunnel_rht_params = {\n--\nnet/bridge/br_vlan_tunnel.c-32-\t.nelem_hint = 3,\nnet/bridge/br_vlan_tunnel.c:33:\t.obj_cmpfn = br_vlan_tunid_cmp,\nnet/bridge/br_vlan_tunnel.c-34-\t.automatic_shrinking = true,\n--\nnet/core/xdp.c=61=static const struct rhashtable_params mem_id_rht_params = {\n--\nnet/core/xdp.c-69-\t.hashfn    = xdp_mem_id_hashfn,\nnet/core/xdp.c:70:\t.obj_cmpfn = xdp_mem_id_cmp,\nnet/core/xdp.c-71-};\n--\nnet/ieee802154/6lowpan/reassembly.c=499=static u32 lowpan_obj_hashfn(const void *data, u32 len, u32 seed)\n--\nnet/ieee802154/6lowpan/reassembly.c-506-\nnet/ieee802154/6lowpan/reassembly.c:507:static int lowpan_obj_cmpfn(struct rhashtable_compare_arg *arg, const void *ptr)\nnet/ieee802154/6lowpan/reassembly.c-508-{\n--\nnet/ieee802154/6lowpan/reassembly.c=515=static const struct rhashtable_params lowpan_rhash_params = {\n--\nnet/ieee802154/6lowpan/reassembly.c-518-\t.obj_hashfn\t\t= lowpan_obj_hashfn,\nnet/ieee802154/6lowpan/reassembly.c:519:\t.obj_cmpfn\t\t= lowpan_obj_cmpfn,\nnet/ieee802154/6lowpan/reassembly.c-520-\t.automatic_shrinking\t= true,\n--\nnet/ipv4/ip_fragment.c=713=static u32 ip4_obj_hashfn(const void *data, u32 len, u32 seed)\n\n"
}

53/3 2026/11/10 21:44 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 103685
							output: 440
							thoughts: 2328
						

Thoughts:
**KMSAN Assessment: Keyring Data Structure Migration**

Okay, let's break this down. We're looking at a patch that fundamentally changes the keyring subsystem's internal data structures, replacing the old `assoc_array` with `rhashtable` and standard linked lists. My initial focus, as always, is on potential uninitialized memory reads – the KMSAN trigger.

First, I need to understand the data structures involved and how they're handled.  `keyring_obj_cmpfn`, `keyring_hashfn`, and `keyring_obj_hashfn` are all related to how the new `rhashtable` performs lookups and hashing.  Crucially, `link->hash` is derived from `index_key->hash` and `keyring_index_key_equal` is used in the comparison. Now, `keyring_index_key` is a *key* structure, and ensuring that the keys are initialized is key to avoiding KMSAN issues.

Now, let's apply the KMSAN rules. The core idea is: don't run KMSAN unless *necessary*. If KASAN, LOCKDEP, or standard debuggers catch the problem, we're good. So I need to meticulously go through each point in the KMSAN guidelines.

1.  **Kernel Structures to User Space:** Does this patch *send* anything to userspace that might have uninitialized fields? The `keyring_read` function, called by `keyctl_read_key`, writes key serials to a user buffer. I checked, and the code iterates through a list, assigning *fully* initialized `key_serial_t` values. No structs with padding are involved. There is no risk of uninitialized memory in `serials` is returned or leaked to userspace. The `keyring_describe()` function uses `seq_file` operations (like `seq_puts` and `seq_printf`) for printing, so again, there's no transfer of raw, potentially uninitialized data.

2.  **Conditional Logic/Branching:** Are there any *branching* decisions that rely on uninitialized values? No, all the relevant `struct keyring_edit` variables are initialized via `= {}` which are zero-initialized. I made sure to note this is done in a lot of places. Heap allocations with `kzalloc_obj` guarantee zero-initialization.

3.  **Complex Data Structures:** What about allocating structures where uninitialized fields *could* be read later?  Nope. Every new allocation, whether it's `struct keyring_index` or `struct keyring_link`, uses `kzalloc_obj`. Stack structures are zero-initialized.

4.  **Bounds Checks/Length Logic:** Does anything allow access to uninitialized bytes of existing buffers?  No, the code doesn't seem to introduce any new vulnerabilities in that area.

Now, let's consider the kinds of bugs this patch *could* introduce: Concurrency/RCU bugs (rhashtable races, list manipulations, `call_rcu`), memory leaks/refcount issues (`key_get`/`key_put`), and NULL pointer dereferences. But, these are *not* KMSAN issues. These types of bugs are handled by KASAN, LOCKDEP, or standard debuggers.

Specifically, I thoroughly investigated that all the old packing issues associated with `keyring_index_key` are gone, and that we now have clean hashing.

Therefore, because there are *no* situations where uninitialized memory is read or leaked, KMSAN is not necessary here.  This change doesn't introduce any new risks that only KMSAN could detect.

So, the conclusion is clear.  `NeedsKMSAN=false`. The refactoring is clean in that it ensures proper initialization, thus avoiding KMSAN concerns.



54/3 2026/11/10 21:45 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series completely removes the generic associative array (`assoc_array`) data structure and replaces its usage in the keys subsystem (`security/keys/keyring.c`) with a combination of `rhashtable` and `list_head`.\n\nEvaluation of uninitialized memory and info-leak risks:\n1. Memory Allocation: All newly introduced heap structures (`struct keyring_index` and `struct keyring_link`) are allocated using `kzalloc_obj()`, ensuring all fields and padding are zero-initialized before insertion into the hash table or list.\n2. Stack Initialization: All stack variables of `struct keyring_edit` and link pointers introduced across `key.c`, `keyring.c`, and `request_key.c` are explicitly zero-initialized (`= {}` or `= NULL`).\n3. User-space Exposure: Keyring listing (`keyring_read`) iterates through active keys and writes `key_serial_t` scalars into the provided buffer up to `links-\u003enr` entries, leaving no uninitialized buffer bytes or padding copied to user space.\n4. Structure Redesign: The simplified `struct keyring_index_key` removes the previous union containing partial description bytes and replaces ad-hoc index IDs with direct SipHash hashing of initialized pointers and description data.\n\nKASAN vs. KMSAN Applicability:\n- The risks introduced by this change involve concurrent RCU iteration and mutation (`rhashtable_replace_fast`, `list_replace_rcu`, `call_rcu`), rwsem lock synchronization (`keyring-\u003esem`), key reference counting (`key_get`, `key_put`), and pointer dereferences.\n- These issues are comprehensively covered by standard KASAN (use-after-free, double-free), LOCKDEP (locking violations), and general kernel assertions.\n- There are no uninitialized memory reads, uninitialized branch conditions, or kernel-to-user info-leaks that would necessitate a dedicated KMSAN fuzzing session.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series completely removes the generic associative array (`assoc_array`) data structure and replaces its usage in the keys subsystem (`security/keys/keyring.c`) with a combination of `rhashtable` and `list_head`.\n\nEvaluation of uninitialized memory and info-leak risks:\n1. Memory Allocation: All newly introduced heap structures (`struct keyring_index` and `struct keyring_link`) are allocated using `kzalloc_obj()`, ensuring all fields and padding are zero-initialized before insertion into the hash table or list.\n2. Stack Initialization: All stack variables of `struct keyring_edit` and link pointers introduced across `key.c`, `keyring.c`, and `request_key.c` are explicitly zero-initialized (`= {}` or `= NULL`).\n3. User-space Exposure: Keyring listing (`keyring_read`) iterates through active keys and writes `key_serial_t` scalars into the provided buffer up to `links-\u003enr` entries, leaving no uninitialized buffer bytes or padding copied to user space.\n4. Structure Redesign: The simplified `struct keyring_index_key` removes the previous union containing partial description bytes and replaces ad-hoc index IDs with direct SipHash hashing of initialized pointers and description data.\n\nKASAN vs. KMSAN Applicability:\n- The risks introduced by this change involve concurrent RCU iteration and mutation (`rhashtable_replace_fast`, `list_replace_rcu`, `call_rcu`), rwsem lock synchronization (`keyring-\u003esem`), key reference counting (`key_get`, `key_put`), and pointer dereferences.\n- These issues are comprehensively covered by standard KASAN (use-after-free, double-free), LOCKDEP (locking violations), and general kernel assertions.\n- There are no uninitialized memory reads, uninitialized branch conditions, or kernel-to-user info-leaks that would necessitate a dedicated KMSAN fuzzing session.",
  "NeedsKMSAN": false
}

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