AI Trajectory


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

Results:
{
  "EnableConfigs": [
    "KEYS"
  ],
  "FocusSymbols": [
    "key_link",
    "key_unlink",
    "key_move",
    "keyring_clear",
    "keyring_gc",
    "keyring_read",
    "search_keyring_tree",
    "find_key_to_update",
    "keyring_is_empty"
  ],
  "KMSANReasoning": "The patch series replaces the associative array (`assoc_array`) data structure used for keyring indexing in the Linux keys subsystem with a combination of `rhashtable` and an RCU-protected linked list (`struct keyring_index` and `struct keyring_link`), while removing the unused generic `assoc_array` implementation and fixing reference counting / error handling in s390 `cert_store.c`.\n\nKMSAN vs. KASAN analysis:\n1. Memory Allocation and Initialization: All newly introduced kernel structures (`struct keyring_index`, `struct keyring_link`) are allocated with `kzalloc_obj()`, ensuring all fields are zero-initialized upon allocation. Stack instances of `struct keyring_edit`, `struct keyring_read_context`, and `struct keyring_search_context` are zero-initialized using designated initializers (`= {}`), leaving no uninitialized fields or padding.\n2. User Space Data Exposure: `keyring_read()` exports an array of 32-bit `key_serial_t` IDs via `keyctl(KEYCTL_READ)`. The iterator writes exact serial values for active keys (`ctx.serials[ctx.count++] = key-\u003eserial`), and the returned byte length directly corresponds to the number of active entries (`index-\u003enr * sizeof(key_serial_t)`), preventing any uninitialized kernel memory from being copied to user space.\n3. Bug Profile: The architectural changes introduce potential risks around RCU concurrency, list/hash table synchronization, reference count management (`key_get`/`key_put`), locking deadlocks, or use-after-free conditions. These classes of bugs are thoroughly covered by KASAN, LOCKDEP, and existing kernel debuggers.\n\nBecause no uninitialized memory reads or information leaks are exposed or introduced by this series, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch completely replaces the associative array (assoc_array) implementation used for kernel keyrings with an rhashtable and linked list (keyring_index) data structure, altering insertion, deletion, lookup, iteration, garbage collection, and RCU lifetime management. It also adds several new WARN_ON assertions in reachable code paths. The affected code in security/keys/ is fully reachable via standard keyctl, add_key, and request_key system calls in virtualized environments.",
  "WorthFuzzing": true
}

1/1 2026/11/18 16:41 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 50084e4806939522d31a77da9a8d49de5932b15a\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Wed Nov 18 16:41:42 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/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c\nindex 998f2da5617500..bc682216fa7fdd 100644\n--- a/arch/s390/kernel/cert_store.c\n+++ b/arch/s390/kernel/cert_store.c\n@@ -307,7 +307,6 @@ static struct key *get_user_session_keyring(void)\n \t\t\t   PTR_ERR(us_keyring_ref));\n \t\treturn ERR_PTR(-ENOKEY);\n \t}\n-\tkey_ref_put(us_keyring_ref);\n \treturn key_ref_to_ptr(us_keyring_ref);\n }\n \n@@ -334,6 +333,9 @@ static int invalidate_keyring_keys(struct key *keyring)\n \n \tfor (key_index = 0; key_index \u003c num_keys; key_index++) {\n \t\tcurrent_key = key_lookup(key_array[key_index]);\n+\t\tif (!current_key)\n+\t\t\tcontinue;\n+\n \t\tpr_dbf_msg(\"Invalidating key %08x\", current_key-\u003eserial);\n \n \t\tkey_invalidate(current_key);\n@@ -352,27 +354,30 @@ static int invalidate_keyring_keys(struct key *keyring)\n static struct key *find_cs_keyring(void)\n {\n \tkey_ref_t cs_keyring_ref;\n+\tstruct key *us_keyring;\n \tstruct key *cs_keyring;\n \n-\tcs_keyring_ref = keyring_search(make_key_ref(get_user_session_keyring(), true),\n+\tus_keyring = get_user_session_keyring();\n+\tif (IS_ERR(us_keyring))\n+\t\treturn NULL;\n+\n+\tcs_keyring_ref = keyring_search(make_key_ref(us_keyring, true),\n \t\t\t\t\t\u0026key_type_keyring, CERT_STORE_KEYRING_NAME,\n \t\t\t\t\tfalse);\n-\tif (!IS_ERR(cs_keyring_ref)) {\n-\t\tcs_keyring = key_ref_to_ptr(cs_keyring_ref);\n-\t\tkey_ref_put(cs_keyring_ref);\n-\t\tgoto found;\n-\t}\n+\tkey_put(us_keyring);\n+\tif (!IS_ERR(cs_keyring_ref))\n+\t\treturn key_ref_to_ptr(cs_keyring_ref);\n+\n \t/* Search default locations: thread, process, session keyrings */\n \tcs_keyring = request_key(\u0026key_type_keyring, CERT_STORE_KEYRING_NAME, NULL);\n \tif (IS_ERR(cs_keyring))\n \t\treturn NULL;\n-\tkey_put(cs_keyring);\n-found:\n \treturn cs_keyring;\n }\n \n static void cleanup_cs_keys(void)\n {\n+\tstruct key *us_keyring;\n \tstruct key *cs_keyring;\n \n \tcs_keyring = find_cs_keyring();\n@@ -389,21 +394,36 @@ static void cleanup_cs_keys(void)\n \n \tkeyring_clear(cs_keyring);\n \tkey_invalidate(cs_keyring);\n+\n+\tus_keyring = get_user_session_keyring();\n+\tif (IS_ERR(us_keyring)) {\n+\t\tkey_put(cs_keyring);\n+\t\treturn;\n+\t}\n+\n+\tkey_unlink(us_keyring, cs_keyring);\n+\tkey_put(us_keyring);\n \tkey_put(cs_keyring);\n-\tkey_unlink(get_user_session_keyring(), cs_keyring);\n }\n \n static struct key *create_cs_keyring(void)\n {\n \tstatic struct key *cs_keyring;\n+\tstruct key *us_keyring;\n \n \t/* Cleanup previous cs_keyring and all associated keys if any. */\n \tcleanup_cs_keys();\n+\n+\tus_keyring = get_user_session_keyring();\n+\tif (IS_ERR(us_keyring))\n+\t\treturn NULL;\n+\n \tcs_keyring = keyring_alloc(CERT_STORE_KEYRING_NAME, GLOBAL_ROOT_UID,\n \t\t\t\t   GLOBAL_ROOT_GID, current_cred(),\n \t\t\t\t   (KEY_POS_ALL \u0026 ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ,\n \t\t\t\t   KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_SET_KEEP,\n-\t\t\t\t   NULL, get_user_session_keyring());\n+\t\t\t\t   NULL, us_keyring);\n+\tkey_put(us_keyring);\n \tif (IS_ERR(cs_keyring)) {\n \t\tpr_dbf_msg(\"Can't allocate cert_store keyring\");\n \t\treturn NULL;\n@@ -710,13 +730,12 @@ static int fill_cs_keyring(void)\n \t\tgoto cleanup_keys;\n \n \trc = add_certificates_to_keyring(vcssb, cs_keyring);\n+\tkey_put(cs_keyring);\n \tif (rc)\n-\t\tgoto cleanup_cs_keyring;\n+\t\tgoto cleanup_keys;\n \n \tgoto out;\n \n-cleanup_cs_keyring:\n-\tkey_put(cs_keyring);\n cleanup_keys:\n \tcleanup_cs_keys();\n out:\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 357f5636081055..8794f47da9f505 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 inline bool keyring_ptr_is_keyring(const struct assoc_array_ptr *x)\n+static u32 keyring_hashfn(const void *data, u32 len, u32 seed)\n {\n-\treturn (unsigned long)x \u0026 KEYRING_PTR_SUBTYPE;\n+\tconst struct keyring_index_key *index_key = data;\n+\n+\treturn jhash_1word(index_key-\u003ehash, seed);\n }\n-static inline struct key *keyring_ptr_to_key(const struct assoc_array_ptr *x)\n+\n+static u32 keyring_obj_hashfn(const void *data, u32 len, u32 seed)\n {\n-\tvoid *object = assoc_array_ptr_to_leaf(x);\n-\treturn (struct key *)((unsigned long)object \u0026 ~KEYRING_PTR_SUBTYPE);\n+\tconst struct keyring_link *link = data;\n+\n+\treturn jhash_1word(link-\u003ehash, seed);\n }\n-static inline void *keyring_key_to_ptr(struct key *key)\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-\tif (key-\u003etype == \u0026key_type_keyring)\n-\t\treturn (void *)((unsigned long)key | KEYRING_PTR_SUBTYPE);\n-\treturn key;\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+\n+static struct key *keyring_link_key(const struct keyring_link *link)\n+{\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,60 +383,75 @@ 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+struct keyring_read_context {\n+\tkey_serial_t\t*serials;\n+\tsize_t\t\tmax;\n+\tsize_t\t\tcount;\n };\n \n-static int keyring_read_iterator(const void *object, void *data)\n+static int keyring_read_iterator(const struct key *key, void *iterator_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+\tstruct keyring_read_context *ctx = iterator_data;\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+\tctx-\u003eserials[ctx-\u003ecount++] = key-\u003eserial;\n+\treturn ctx-\u003ecount == ctx-\u003emax;\n }\n \n /*\n  * Read a list of key IDs from the keyring's contents in binary form\n  *\n- * The keyring's semaphore is read-locked by the caller.  This prevents someone\n- * from modifying it under us - which could cause us to read key IDs multiple\n- * times.\n+ * The walk is RCU-protected, so the keyring's semaphore is not required.  A\n+ * keyring modified concurrently may list a key twice or miss one, but it can\n+ * never have a link freed under the walk.\n  */\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 \tlong ret;\n \n \tkenter(\"{%d},,%zu\", key_serial(keyring), buflen);\n@@ -501,25 +459,23 @@ 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\tstruct keyring_read_context ctx = {\n+\t\t\t.serials\t= (key_serial_t *)buffer,\n+\t\t\t.max\t\t= buflen / sizeof(key_serial_t),\n+\t\t};\n+\n+\t\tret = keyring_iterate(keyring, keyring_read_iterator, \u0026ctx);\n+\t\tif (ret \u003c 0)\n \t\t\treturn ret;\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 = keyring_nr_links(keyring) * sizeof(key_serial_t);\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 +539,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 +608,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 +689,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 +707,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 +721,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 +733,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 +979,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 +988,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 +1067,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,57 +1166,98 @@ 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 = 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\tret = -EINVAL;\n+\t\tgoto out;\n+\t}\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+\tif (test_bit(KEY_FLAG_REVOKED, \u0026keyring-\u003eflags)) {\n+\t\tret = -EKEYREVOKED;\n+\t\tgoto out;\n+\t}\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-\t\tgoto error;\n+\tlinks = keyring_get_index(keyring);\n+\tif (IS_ERR(links)) {\n+\t\tret = PTR_ERR(links);\n+\t\tgoto out;\n \t}\n \n-\t/* If we're not replacing a link in-place then we're going to need some\n+\tlink = kzalloc_obj(struct keyring_link);\n+\tif (!link) {\n+\t\tret = -ENOMEM;\n+\t\tgoto out;\n+\t}\n+\tlink-\u003ehash = index_key-\u003ehash;\n+\n+\treplace = keyring_find_link(links, index_key);\n+\n+\t/*\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 out;\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 out;\n+\t\t}\n \t}\n \n-\t*_edit = edit;\n-\tkleave(\" = 0\");\n-\treturn 0;\n+\tedit-\u003enew = link;\n+\tedit-\u003eold = replace;\n+\tret = 0;\n \n-error_cancel:\n-\tassoc_array_cancel_edit(edit);\n-error:\n+out:\n+\tif (ret \u0026\u0026 link)\n+\t\tkfree(link);\n \tkleave(\" = %d\", ret);\n \treturn ret;\n }\n@@ -1385,13 +1285,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 +1324,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 +1378,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 +1388,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 +1412,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 +1436,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 +1458,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 +1483,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 +1492,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 +1504,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 +1525,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 +1539,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 +1563,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 +1573,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 +1594,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 +1615,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-}\n-\n-static bool keyring_gc_select_iterator(void *object, 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+\tkeyring_index_free(keyring);\n+\tkey_payload_reserve(keyring, 0);\n }\n \n-static int keyring_gc_check_iterator(const void *object, void *iterator_data)\n+static int keyring_gc_check_iterator(const struct key *key, 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 +1635,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 +1646,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 +1655,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/18 16:41 agent patch-evaluator
16m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "KEYS"
  ],
  "FocusSymbols": [
    "key_link",
    "key_unlink",
    "key_move",
    "keyring_clear",
    "keyring_gc",
    "keyring_read",
    "search_keyring_tree",
    "find_key_to_update",
    "keyring_is_empty"
  ],
  "Reasoning": "The patch completely replaces the associative array (assoc_array) implementation used for kernel keyrings with an rhashtable and linked list (keyring_index) data structure, altering insertion, deletion, lookup, iteration, garbage collection, and RCU lifetime management. It also adds several new WARN_ON assertions in reachable code paths. The affected code in security/keys/ is fully reachable via standard keyctl, add_key, and request_key system calls in virtualized environments.",
  "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 50084e4806939522d31a77da9a8d49de5932b15a
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Nov 18 16:41:42 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/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c
index 998f2da5617500..bc682216fa7fdd 100644
--- a/arch/s390/kernel/cert_store.c
+++ b/arch/s390/kernel/cert_store.c
@@ -307,7 +307,6 @@ static struct key *get_user_session_keyring(void)
 			   PTR_ERR(us_keyring_ref));
 		return ERR_PTR(-ENOKEY);
 	}
-	key_ref_put(us_keyring_ref);
 	return key_ref_to_ptr(us_keyring_ref);
 }
 
@@ -334,6 +333,9 @@ static int invalidate_keyring_keys(struct key *keyring)
 
 	for (key_index = 0; key_index < num_keys; key_index++) {
 		current_key = key_lookup(key_array[key_index]);
+		if (!current_key)
+			continue;
+
 		pr_dbf_msg("Invalidating key %08x", current_key->serial);
 
 		key_invalidate(current_key);
@@ -352,27 +354,30 @@ static int invalidate_keyring_keys(struct key *keyring)
 static struct key *find_cs_keyring(void)
 {
 	key_ref_t cs_keyring_ref;
+	struct key *us_keyring;
 	struct key *cs_keyring;
 
-	cs_keyring_ref = keyring_search(make_key_ref(get_user_session_keyring(), true),
+	us_keyring = get_user_session_keyring();
+	if (IS_ERR(us_keyring))
+		return NULL;
+
+	cs_keyring_ref = keyring_search(make_key_ref(us_keyring, true),
 					&key_type_keyring, CERT_STORE_KEYRING_NAME,
 					false);
-	if (!IS_ERR(cs_keyring_ref)) {
-		cs_keyring = key_ref_to_ptr(cs_keyring_ref);
-		key_ref_put(cs_keyring_ref);
-		goto found;
-	}
+	key_put(us_keyring);
+	if (!IS_ERR(cs_keyring_ref))
+		return key_ref_to_ptr(cs_keyring_ref);
+
 	/* Search default locations: thread, process, session keyrings */
 	cs_keyring = request_key(&key_type_keyring, CERT_STORE_KEYRING_NAME, NULL);
 	if (IS_ERR(cs_keyring))
 		return NULL;
-	key_put(cs_keyring);
-found:
 	return cs_keyring;
 }
 
 static void cleanup_cs_keys(void)
 {
+	struct key *us_keyring;
 	struct key *cs_keyring;
 
 	cs_keyring = find_cs_keyring();
@@ -389,21 +394,36 @@ static void cleanup_cs_keys(void)
 
 	keyring_clear(cs_keyring);
 	key_invalidate(cs_keyring);
+
+	us_keyring = get_user_session_keyring();
+	if (IS_ERR(us_keyring)) {
+		key_put(cs_keyring);
+		return;
+	}
+
+	key_unlink(us_keyring, cs_keyring);
+	key_put(us_keyring);
 	key_put(cs_keyring);
-	key_unlink(get_user_session_keyring(), cs_keyring);
 }
 
 static struct key *create_cs_keyring(void)
 {
 	static struct key *cs_keyring;
+	struct key *us_keyring;
 
 	/* Cleanup previous cs_keyring and all associated keys if any. */
 	cleanup_cs_keys();
+
+	us_keyring = get_user_session_keyring();
+	if (IS_ERR(us_keyring))
+		return NULL;
+
 	cs_keyring = keyring_alloc(CERT_STORE_KEYRING_NAME, GLOBAL_ROOT_UID,
 				   GLOBAL_ROOT_GID, current_cred(),
 				   (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ,
 				   KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_SET_KEEP,
-				   NULL, get_user_session_keyring());
+				   NULL, us_keyring);
+	key_put(us_keyring);
 	if (IS_ERR(cs_keyring)) {
 		pr_dbf_msg("Can't allocate cert_store keyring");
 		return NULL;
@@ -710,13 +730,12 @@ static int fill_cs_keyring(void)
 		goto cleanup_keys;
 
 	rc = add_certificates_to_keyring(vcssb, cs_keyring);
+	key_put(cs_keyring);
 	if (rc)
-		goto cleanup_cs_keyring;
+		goto cleanup_keys;
 
 	goto out;
 
-cleanup_cs_keyring:
-	key_put(cs_keyring);
 cleanup_keys:
 	cleanup_cs_keys();
 out:
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 357f5636081055..8794f47da9f505 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 inline bool keyring_ptr_is_keyring(const struct assoc_array_ptr *x)
+static u32 keyring_hashfn(const void *data, u32 len, u32 seed)
 {
-	return (unsigned long)x & KEYRING_PTR_SUBTYPE;
+	const struct keyring_index_key *index_key = data;
+
+	return jhash_1word(index_key->hash, seed);
 }
-static inline struct key *keyring_ptr_to_key(const struct assoc_array_ptr *x)
+
+static u32 keyring_obj_hashfn(const void *data, u32 len, u32 seed)
 {
-	void *object = assoc_array_ptr_to_leaf(x);
-	return (struct key *)((unsigned long)object & ~KEYRING_PTR_SUBTYPE);
+	const struct keyring_link *link = data;
+
+	return jhash_1word(link->hash, seed);
 }
-static inline void *keyring_key_to_ptr(struct key *key)
+
+static bool keyring_index_key_equal(const struct keyring_index_key *a,
+				    const struct keyring_index_key *b)
 {
-	if (key->type == &key_type_keyring)
-		return (void *)((unsigned long)key | KEYRING_PTR_SUBTYPE);
-	return key;
+	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 struct key *keyring_link_key(const struct keyring_link *link)
+{
+	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,60 +383,75 @@ 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;
+struct keyring_read_context {
+	key_serial_t	*serials;
+	size_t		max;
+	size_t		count;
 };
 
-static int keyring_read_iterator(const void *object, void *data)
+static int keyring_read_iterator(const struct key *key, void *iterator_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);
+	struct keyring_read_context *ctx = iterator_data;
 
-	if (ctx->count >= ctx->buflen)
-		return 1;
-
-	*ctx->buffer++ = key->serial;
-	ctx->count += sizeof(key->serial);
-	return 0;
+	ctx->serials[ctx->count++] = key->serial;
+	return ctx->count == ctx->max;
 }
 
 /*
  * Read a list of key IDs from the keyring's contents in binary form
  *
- * The keyring's semaphore is read-locked by the caller.  This prevents someone
- * from modifying it under us - which could cause us to read key IDs multiple
- * times.
+ * The walk is RCU-protected, so the keyring's semaphore is not required.  A
+ * keyring modified concurrently may list a key twice or miss one, but it can
+ * never have a link freed under the walk.
  */
 static long keyring_read(const struct key *keyring,
 			 char *buffer, size_t buflen)
 {
-	struct keyring_read_iterator_context ctx;
 	long ret;
 
 	kenter("{%d},,%zu", key_serial(keyring), buflen);
@@ -501,25 +459,23 @@ 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);
+		struct keyring_read_context ctx = {
+			.serials	= (key_serial_t *)buffer,
+			.max		= buflen / sizeof(key_serial_t),
+		};
+
+		ret = keyring_iterate(keyring, keyring_read_iterator, &ctx);
+		if (ret < 0)
 			return ret;
-		}
 	}
 
-	/* Return the size of the buffer needed */
-	ret = keyring->keys.nr_leaves_on_tree * sizeof(key_serial_t);
+	ret = keyring_nr_links(keyring) * sizeof(key_serial_t);
 	if (ret <= buflen)
 		kleave("= %ld [ok]", ret);
 	else
 		kleave("= %ld [buffer too small]", ret);
+
 	return ret;
 }
 
@@ -583,10 +539,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 +608,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 +689,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 +707,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 +721,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 +733,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 +979,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 +988,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 +1067,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,57 +1166,98 @@ 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 = 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)) {
+		ret = -EINVAL;
+		goto out;
+	}
 
-	*_edit = NULL;
+	edit->new = NULL;
+	edit->old = NULL;
 
-	ret = -EKEYREVOKED;
-	if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
-		goto error;
+	if (test_bit(KEY_FLAG_REVOKED, &keyring->flags)) {
+		ret = -EKEYREVOKED;
+		goto out;
+	}
 
-	/* 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);
-		goto error;
+	links = keyring_get_index(keyring);
+	if (IS_ERR(links)) {
+		ret = PTR_ERR(links);
+		goto out;
 	}
 
-	/* If we're not replacing a link in-place then we're going to need some
+	link = kzalloc_obj(struct keyring_link);
+	if (!link) {
+		ret = -ENOMEM;
+		goto out;
+	}
+	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 out;
+
+		ret = rhashtable_insert_fast(&links->ht, &link->node,
+					     keyring_link_params);
+		if (ret < 0) {
+			key_payload_reserve(keyring,
+					    keyring->datalen - KEYQUOTA_LINK_BYTES);
+			goto out;
+		}
 	}
 
-	*_edit = edit;
-	kleave(" = 0");
-	return 0;
+	edit->new = link;
+	edit->old = replace;
+	ret = 0;
 
-error_cancel:
-	assoc_array_cancel_edit(edit);
-error:
+out:
+	if (ret && link)
+		kfree(link);
 	kleave(" = %d", ret);
 	return ret;
 }
@@ -1385,13 +1285,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 +1324,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 +1378,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 +1388,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 +1412,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 +1436,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 +1458,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 +1483,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 +1492,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 +1504,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 +1525,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 +1539,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 +1563,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 +1573,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 +1594,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 +1615,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);
-	}
-}
-
-static bool keyring_gc_select_iterator(void *object, 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;
+	keyring_index_free(keyring);
+	key_payload_reserve(keyring, 0);
 }
 
-static int keyring_gc_check_iterator(const void *object, void *iterator_data)
+static int keyring_gc_check_iterator(const struct key *key, void *iterator_data)
 {
-	const struct key *key = keyring_ptr_to_key(object);
 	time64_t *limit = iterator_data;
 
 	key_check(key);
@@ -1742,7 +1635,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 +1646,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 +1655,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/18 16:41 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 61432
							output: 29
							thoughts: 757
						

Thoughts:
**Patch Analysis: Assoc Array Removal and Keyring Implementation Replacement**

Okay, let's break this down. My initial assessment is that this patch is definitely worth a deep dive for fuzzing with syzkaller. The triage philosophy is clear: Reachability is key. Given my expertise, the criteria are second nature. Let's see...

First, the patch itself. This is significant. It's not some minor tweak; it's a complete removal of `assoc_array` from the kernel and a *substantial* rewrite of the keyring index implementation.  They're nuking it!  Goodbye, `assoc_array`.  Hello, `rhashtable` + linked list!  The change isn't just about replacing a data structure; it's a complete rethink of how keys are stored and managed within the `security/keys/` subsystem. That's a huge shift.

Specifically:

*   `assoc_array` is gone. Completely deleted, along with its documentation. That's a clean sweep. This means everything that *used* that implementation has been rewritten.
*   The old `struct assoc_array keys;` is now `struct keyring_index __rcu *index;`, which leverages `rhashtable` and a linked list. All the key operations - search, insertion, deletion, garbage collection, everything - are now built on this new foundation.
*   It's not just isolated to `keyring.c`. This touch includes changes to `internal.h`, `key.c`, and `request_key.c`.
*   A new function, `keyring_is_empty`, is introduced and exported. And it's used in *other* parts of the kernel, including drivers. That is important.

Now, does this meet the "WorthFuzzing" criteria? Absolutely.  `security/keys/` is a core kernel subsystem. It's directly accessible from userspace via syscalls like `keyctl`, `add_key`, and `request_key`. These are standard, reachable in standard environments. It's not some obscure, conditionally compiled module. This touches critical security aspects of the kernel. This is *definitely* a core subsystem, and it's being substantially refactored. The potential for introducing subtle vulnerabilities during such a fundamental change is high. The "no functional change" rule applies doubly here.

Reachability is not an issue: this should work in QEMU/GCE, amd64 is my focus.

Now I need to determine exactly which CONFIG options come into play. Let's double-check `security/keys/Kconfig` and any callers to determine the specific configurations that make this code active. This is an all-hands-on-deck situation for fuzzing!



4/2 2026/11/18 16:43 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/18 16:43 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 62928
							output: 34
							thoughts: 26
						

Thoughts:
Here's my thought process, as if I were considering this myself:

**Investigating the Build Process for Key Management Components**

Okay, so I want to understand exactly how the `keyring.c` file and other related files in the security/keys directory are being compiled. That means I need to dive into the build system, and the first place I'd look is the `Makefile` within that specific directory: `security/keys/Makefile`. It's almost certain that's where the compilation rules and dependencies for this part of the kernel are defined. I expect to find the compiler flags, include paths, object file dependencies, and linking instructions that ultimately produce the final, linked object. I'll be looking specifically for any rules that target `keyring.c` and its associated files, making sure to pay attention to any dependencies on other modules or libraries. This should give me a solid understanding of the build process and how these key management components fit into the larger kernel image.



6/2 2026/11/18 16:43 tool grepper
0m Args:
{
  "Expression": "keyring\\.o|key\\.o",
  "PathPrefixes": [
    "security/keys/Makefile"
  ]
}

Results:
{
  "Output": "security/keys/Makefile=9=obj-y := \\\nsecurity/keys/Makefile-10-\tgc.o \\\nsecurity/keys/Makefile:11:\tkey.o \\\nsecurity/keys/Makefile:12:\tkeyring.o \\\nsecurity/keys/Makefile-13-\tkeyctl.o \\\n--\nsecurity/keys/Makefile-15-\tprocess_keys.o \\\nsecurity/keys/Makefile:16:\trequest_key.o \\\nsecurity/keys/Makefile-17-\trequest_key_auth.o \\\n--\nsecurity/keys/Makefile=24=obj-$(CONFIG_KEY_DH_OPERATIONS) += dh.o\nsecurity/keys/Makefile:25:obj-$(CONFIG_ASYMMETRIC_KEY_TYPE) += keyctl_pkey.o\nsecurity/keys/Makefile-26-\n--\nsecurity/keys/Makefile-29-#\nsecurity/keys/Makefile:30:obj-$(CONFIG_BIG_KEYS) += big_key.o\nsecurity/keys/Makefile-31-obj-$(CONFIG_TRUSTED_KEYS) += trusted-keys/\n"
}

7/2 2026/11/18 16:43 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 63468
							output: 25
							thoughts: 22
						

Thoughts:
Here's my thought process, as if I were considering this issue:

**Reviewing the Security Module Entry Point**

Okay, so we're tracking down when the `security/keys` module is actually initialized within the system. My first thought is to dig into the `security/Makefile`. That's usually the place where the build process for the security-related components is defined, and it should contain the dependencies and likely, the points where `security/keys` gets pulled in. I expect to find some logic or include statements that control its compilation and linking. That's the logical starting point for understanding its integration. I'll need to scrutinize that `Makefile` carefully.



8/2 2026/11/18 16:45 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"
}

9/2 2026/11/18 16:45 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 63703
							output: 23
							thoughts: 275
						

Thoughts:
**My Initial Thoughts on Keyring Changes**

Okay, so `CONFIG_KEYS` seems to pull in the core keyring infrastructure, compiling the files in `security/keys/` along with `keyring.o`, `key.o`, and `request_key.o`. My initial thought is to pause and consider the implications for related security features. What about dm-verity, fs-verity, and even BPF? Let's quickly verify where these features interface with the keyrings.

Right, let's look at the source files `drivers/md/dm-verity-verify-sig.c`, `fs/verity/signature.c`, and `kernel/bpf/keys.c`. The code confirms my suspicion. I see checks for empty keyrings, as expected. Specifically, the verity code uses `dm_verity_keyring` and `fsverity_keyring` and BPF uses `bpf_keyring`.

Now, the main focus of this is on the core of the keyring implementation itself, and this particular commit, from what I can see here, seems quite significant. The major rewrite involved replacing the entire `assoc_array` data structure in the keyring subsystem with an rhashtable and linked list (`keyring_index`). This suggests a complete overhaul of how keys are indexed, searched, linked, unlinked, read, cleared, and garbage collected within the keyrings. That's a fundamental change to the data structures involved, and the performance and scalability aspects are definitely worth thinking about.

To get a full understanding, I need to dig into the git log and review the commit message. The commit message should give me the full context, the rationale behind this fundamental architectural change, and potentially provide insights into any performance benefits or compatibility concerns introduced.



10/2 2026/11/18 16:46 tool grepper
0m Args:
{
  "Expression": "syz-cluster: applied patch under review"
}

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

11/2 2026/11/18 16:46 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 64393
							output: 35
							thoughts: 84
						

Thoughts:
Okay, let's break this down.

**Investigating Recent Changes in `security/keys/keyring.c`**

Alright, I need to pinpoint the most recent changes affecting the keyring functionality, but I don't have direct access to a `git log` command. No worries. I can always work around that. Since I can analyze the diff or read the files directly, I will start by focusing on `security/keys/keyring.c`. The goal here is to identify exactly which functions were added or substantially altered in recent commits. Once I identify those changes, I will then zoom in on the specific code segments in `security/keys/keyring.c` that are around those modified areas. It is the most sensible way to get to the information I need, given the limited tools at my disposal.



12/2 2026/11/18 16:48 tool read-file
0m Args:
{
  "File": "security/keys/keyring.c",
  "FirstLine": 35,
  "LineCount": 90
}

Results:
{
  "Contents": "  35:\t * Keyrings are inserted at the head of @list, other keys at the tail, so\n  36:\t * recursive search can stop at the first non-keyring.\n  37:\t */\n  38:\tstruct keyring_index {\n  39:\t\tstruct rhashtable\tht;\n  40:\t\tstruct list_head\tlist;\t\t/* Active keys */\n  41:\t\tunsigned long\t\tnr;\t\t/* Number of active keys */\n  42:\t\tstruct rcu_work\t\trcu_work;\n  43:\t};\n  44:\t\n  45:\t/*\n  46:\t * __key_link_begin() inserts new links with @key NULL so allocation happens\n  47:\t * before __key_link().  @hash is cached so resizing can hash links while @key\n  48:\t * is NULL.\n  49:\t */\n  50:\tstruct keyring_link {\n  51:\t\tstruct rcu_head\t\trcu;\n  52:\t\tstruct rhash_head\tnode;\n  53:\t\tstruct key __rcu\t*key;\t\t/* NULL while inactive */\n  54:\t\tstruct list_head\tlist;\n  55:\t\tu32\t\t\thash;\n  56:\t};\n  57:\t\n  58:\tstatic u32 keyring_hashfn(const void *data, u32 len, u32 seed)\n  59:\t{\n  60:\t\tconst struct keyring_index_key *index_key = data;\n  61:\t\n  62:\t\treturn jhash_1word(index_key-\u003ehash, seed);\n  63:\t}\n  64:\t\n  65:\tstatic u32 keyring_obj_hashfn(const void *data, u32 len, u32 seed)\n  66:\t{\n  67:\t\tconst struct keyring_link *link = data;\n  68:\t\n  69:\t\treturn jhash_1word(link-\u003ehash, seed);\n  70:\t}\n  71:\t\n  72:\tstatic bool keyring_index_key_equal(const struct keyring_index_key *a,\n  73:\t\t\t\t\t    const struct keyring_index_key *b)\n  74:\t{\n  75:\t\treturn a-\u003etype == b-\u003etype \u0026\u0026\n  76:\t\t\ta-\u003edomain_tag == b-\u003edomain_tag \u0026\u0026\n  77:\t\t\ta-\u003edesc_len == b-\u003edesc_len \u0026\u0026\n  78:\t\t\tmemcmp(a-\u003edescription, b-\u003edescription, a-\u003edesc_len) == 0;\n  79:\t}\n  80:\t\n  81:\tstatic struct key *keyring_link_key(const struct keyring_link *link)\n  82:\t{\n  83:\t\treturn rcu_dereference_check(link-\u003ekey, true);\n  84:\t}\n  85:\t\n  86:\tstatic int keyring_obj_cmpfn(struct rhashtable_compare_arg *arg,\n  87:\t\t\t\t     const void *obj)\n  88:\t{\n  89:\t\tconst struct keyring_link *link = obj;\n  90:\t\tconst struct key *key = keyring_link_key(link);\n  91:\t\n  92:\t\treturn !key || !keyring_index_key_equal(\u0026key-\u003eindex_key, arg-\u003ekey);\n  93:\t}\n  94:\t\n  95:\tstatic const struct rhashtable_params keyring_link_params = {\n  96:\t\t.head_offset\t\t= offsetof(struct keyring_link, node),\n  97:\t\t.hashfn\t\t\t= keyring_hashfn,\n  98:\t\t.obj_hashfn\t\t= keyring_obj_hashfn,\n  99:\t\t.obj_cmpfn\t\t= keyring_obj_cmpfn,\n 100:\t\t.min_size\t\t= 4,\n 101:\t\t.nelem_hint\t\t= 3,\n 102:\t\t.automatic_shrinking\t= true,\n 103:\t\t.insecure_elasticity\t= true,\n 104:\t};\n 105:\t\n 106:\tstatic struct keyring_index *keyring_index_locked(const struct key *keyring)\n 107:\t{\n 108:\t\treturn rcu_dereference_protected(keyring-\u003eindex,\n 109:\t\t\t\t\t\t lockdep_is_held(\u0026keyring-\u003esem));\n 110:\t}\n 111:\t\n 112:\tstatic struct keyring_link *keyring_find_link(struct keyring_index *index,\n 113:\t\t\t\t\t\t      const struct keyring_index_key *index_key)\n 114:\t{\n 115:\t\tif (!index)\n 116:\t\t\treturn NULL;\n 117:\t\n 118:\t\treturn rhashtable_lookup_fast(\u0026index-\u003eht, index_key, keyring_link_params);\n 119:\t}\n 120:\t\n 121:\tstatic int keyring_iterate(const struct key *keyring,\n 122:\t\t\t\t   int (*iterator)(const struct key *key, void *data),\n 123:\t\t\t\t   void *data)\n 124:\t{\n"
}

13/2 2026/11/18 16:48 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 65998
							output: 36
							thoughts: 27
						

Thoughts:
Okay, let's dive into this. I'm focusing on `security/keys/keyring.c`, specifically lines 125-250. My expert eye immediately wants to understand what's happening in this segment. I'm expecting this section to deal with the core functionalities of the keyring system – perhaps initialization, key management, or maybe access control and permission handling. I'll need to look for key data structures that represent keyrings, probably some function calls that allocate, free, or search for keys within a keyring structure, and hopefully some security-related checks. I want to quickly identify the main control flow and any potential areas that might be performance bottlenecks. Ultimately, I'm aiming to understand the role this section plays in the overall security architecture, looking for anything that might impact the robustness or performance of the key management system. My goal is a high-level comprehension, a mental map of this code segment in relation to the larger, more extensive codebase.



14/2 2026/11/18 16:50 tool read-file
0m Args:
{
  "File": "security/keys/keyring.c",
  "FirstLine": 125,
  "LineCount": 80
}

Results:
{
  "Contents": " 125:\t\tstruct keyring_index *index;\n 126:\t\tstruct keyring_link *link;\n 127:\t\tint ret;\n 128:\t\n 129:\t\tguard(rcu)();\n 130:\t\tindex = rcu_dereference(keyring-\u003eindex);\n 131:\t\tif (index) {\n 132:\t\t\tlist_for_each_entry_rcu(link, \u0026index-\u003elist, list) {\n 133:\t\t\t\tret = iterator(keyring_link_key(link), data);\n 134:\t\t\t\tif (ret)\n 135:\t\t\t\t\treturn ret;\n 136:\t\t\t}\n 137:\t\t}\n 138:\t\n 139:\t\treturn 0;\n 140:\t}\n 141:\t\n 142:\tstatic void keyring_link_free_rcu(struct rcu_head *rcu)\n 143:\t{\n 144:\t\tstruct keyring_link *link = container_of(rcu, struct keyring_link, rcu);\n 145:\t\n 146:\t\tkey_put(rcu_dereference_raw(link-\u003ekey));\n 147:\t\tkfree(link);\n 148:\t}\n 149:\t\n 150:\tstatic void __keyring_index_free(struct keyring_index *index)\n 151:\t{\n 152:\t\tstruct keyring_link *link, *tmp;\n 153:\t\n 154:\t\trhashtable_destroy(\u0026index-\u003eht);\n 155:\t\n 156:\t\tlist_for_each_entry_safe(link, tmp, \u0026index-\u003elist, list) {\n 157:\t\t\tkey_put(rcu_dereference_protected(link-\u003ekey, true));\n 158:\t\t\tkfree(link);\n 159:\t\t}\n 160:\t\n 161:\t\tkfree(index);\n 162:\t}\n 163:\t\n 164:\tstatic void keyring_index_free_work(struct work_struct *work)\n 165:\t{\n 166:\t\tstruct keyring_index *index = container_of(to_rcu_work(work),\n 167:\t\t\t\t\t\t\t struct keyring_index, rcu_work);\n 168:\t\n 169:\t\t__keyring_index_free(index);\n 170:\t}\n 171:\t\n 172:\tstatic void keyring_index_free(struct key *keyring)\n 173:\t{\n 174:\t\tstruct keyring_index *index = keyring_index_locked(keyring);\n 175:\t\n 176:\t\tif (!index)\n 177:\t\t\treturn;\n 178:\t\n 179:\t\trcu_assign_pointer(keyring-\u003eindex, NULL);\n 180:\t\t/* rhashtable_destroy() may sleep, so defer via rcu_work. */\n 181:\t\tqueue_rcu_work(system_dfl_wq, \u0026index-\u003ercu_work);\n 182:\t}\n 183:\t\n 184:\tstatic DEFINE_RWLOCK(keyring_name_lock);\n 185:\t\n 186:\t/*\n 187:\t * Clean up the bits of user_namespace that belong to us.\n 188:\t */\n 189:\tvoid key_free_user_ns(struct user_namespace *ns)\n 190:\t{\n 191:\t\twrite_lock(\u0026keyring_name_lock);\n 192:\t\tlist_del_init(\u0026ns-\u003ekeyring_name_list);\n 193:\t\twrite_unlock(\u0026keyring_name_lock);\n 194:\t\n 195:\t\tkey_put(ns-\u003euser_keyring_register);\n 196:\t#ifdef CONFIG_PERSISTENT_KEYRINGS\n 197:\t\tkey_put(ns-\u003epersistent_keyring_register);\n 198:\t#endif\n 199:\t}\n 200:\t\n 201:\t/*\n 202:\t * The keyring key type definition.  Keyrings are simply keys of this type and\n 203:\t * can be treated as ordinary keys in addition to having their own special\n 204:\t * operations.\n"
}

15/2 2026/11/18 16:50 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 67394
							output: 36
							thoughts: 40
						

Thoughts:
Okay, let's dive into this.

**Examining Keyring Implementation in the Linux Kernel**

Right, I need to get a handle on how keyrings are being handled, specifically the search functions. My immediate focus is on the `search_keyring_tree` function and any related functions within `security/keys/keyring.c`. I'll want to carefully examine the code in the region of lines 600-750. This is likely where the core search logic resides, and I anticipate that's where I'll find the details of how key lookups are performed and how the keyring tree is traversed. I'll be looking for things like the data structures used, any caching mechanisms, potential bottlenecks, and any subtle concurrency issues that might be lurking. Time to start digging!



16/2 2026/11/18 16:51 tool read-file
0m Args:
{
  "File": "security/keys/keyring.c",
  "FirstLine": 600,
  "LineCount": 90
}

Results:
{
  "Contents": " 600:\t\tctx-\u003eresult = make_key_ref(key, ctx-\u003epossessed);\n 601:\t\tkleave(\" = 1 [found]\");\n 602:\t\treturn 1;\n 603:\t\n 604:\tskipped:\n 605:\t\treturn ctx-\u003eskipped_ret;\n 606:\t}\n 607:\t\n 608:\t/*\n 609:\t * Search inside a keyring for a key.  We can search by walking to it\n 610:\t * directly based on its index-key or we can iterate over the entire\n 611:\t * list looking for it, based on the match function.\n 612:\t */\n 613:\tstatic int search_keyring(struct key *keyring, struct keyring_search_context *ctx)\n 614:\t{\n 615:\t\tif (ctx-\u003ematch_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) {\n 616:\t\t\tstruct keyring_link *link;\n 617:\t\t\tstruct key *key;\n 618:\t\n 619:\t\t\tlink = keyring_find_link(rcu_dereference(keyring-\u003eindex),\n 620:\t\t\t\t\t\t \u0026ctx-\u003eindex_key);\n 621:\t\t\tif (!link)\n 622:\t\t\t\treturn 0;\n 623:\t\t\tkey = keyring_link_key(link);\n 624:\t\t\treturn ctx-\u003eiterator(key, ctx);\n 625:\t\t}\n 626:\t\n 627:\t\treturn keyring_iterate(keyring, ctx-\u003eiterator, ctx);\n 628:\t}\n 629:\t\n 630:\t/*\n 631:\t * Depth-first search of @keyring and its nested keyrings.\n 632:\t */\n 633:\tstatic int search_keyring_tree(struct key *keyring,\n 634:\t\t\t\t       struct keyring_search_context *ctx, int depth)\n 635:\t{\n 636:\t\tstruct keyring_index *links;\n 637:\t\tstruct keyring_link *link;\n 638:\t\tint ret;\n 639:\t\n 640:\t\tif (keyring-\u003eflags \u0026 ((1 \u003c\u003c KEY_FLAG_INVALIDATED) |\n 641:\t\t\t\t      (1 \u003c\u003c KEY_FLAG_REVOKED)))\n 642:\t\t\treturn 0;\n 643:\t\n 644:\t\tif (search_keyring(keyring, ctx))\n 645:\t\t\tgoto found;\n 646:\t\n 647:\t\tif (!(ctx-\u003eflags \u0026 KEYRING_SEARCH_RECURSE))\n 648:\t\t\treturn 0;\n 649:\t\tlinks = rcu_dereference(keyring-\u003eindex);\n 650:\t\tif (!links)\n 651:\t\t\treturn 0;\n 652:\t\n 653:\t\tlist_for_each_entry_rcu(link, \u0026links-\u003elist, list) {\n 654:\t\t\tstruct key *key = keyring_link_key(link);\n 655:\t\n 656:\t\t\tif (key-\u003etype != \u0026key_type_keyring)\n 657:\t\t\t\tbreak;\n 658:\t\t\tif (depth \u003e= KEYRING_SEARCH_MAX_DEPTH) {\n 659:\t\t\t\tif (!(ctx-\u003eflags \u0026 KEYRING_SEARCH_DETECT_TOO_DEEP))\n 660:\t\t\t\t\treturn 0;\n 661:\t\t\t\tctx-\u003eresult = ERR_PTR(-ELOOP);\n 662:\t\t\t\treturn -ELOOP;\n 663:\t\t\t}\n 664:\t\n 665:\t\t\tif (!(ctx-\u003eflags \u0026 KEYRING_SEARCH_NO_CHECK_PERM) \u0026\u0026\n 666:\t\t\t    key_task_permission(make_key_ref(key, ctx-\u003epossessed),\n 667:\t\t\t\t\t\tctx-\u003ecred, KEY_NEED_SEARCH) \u003c 0)\n 668:\t\t\t\tcontinue;\n 669:\t\n 670:\t\t\tret = search_keyring_tree(key, ctx, depth + 1);\n 671:\t\t\tif (ret \u003c 0)\n 672:\t\t\t\treturn ret;\n 673:\t\t\tif (ret)\n 674:\t\t\t\tgoto found;\n 675:\t\t}\n 676:\t\n 677:\t\treturn 0;\n 678:\t\n 679:\tfound:\n 680:\t\tif (!(ctx-\u003eflags \u0026 KEYRING_SEARCH_NO_UPDATE_TIME))\n 681:\t\t\tkeyring-\u003elast_used_at = ctx-\u003enow;\n 682:\t\treturn 1;\n 683:\t}\n 684:\t\n 685:\t/*\n 686:\t * Search a tree of keyrings that point to other keyrings up to the maximum\n 687:\t * depth.\n 688:\t */\n 689:\tstatic bool search_nested_keyrings(struct key *keyring,\n"
}

17/2 2026/11/18 16:51 llm patch-evaluator
2m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 68918
							output: 37
							thoughts: 67
						

Thoughts:
Okay, let's dive into this. Here's how I'm processing this task, as if I were considering the implications of the provided thoughts:

**Analyzing Key Management and Garbage Collection**

Alright, my immediate thought is to take a closer look at the mechanisms being referenced. Specifically, I need to understand how the system interacts with and manages these "key" elements: `__key_link_begin`, `__key_link`, `__key_link_end`, `__key_unlink_begin`, and `__key_unlink`. These hints suggest a connection to managing some kind of linked data structure, probably related to authorization or cryptographic keys. The presence of `keyring_gc` is particularly intriguing. It strongly implies the existence of a garbage collection process specifically for these keys. This requires careful consideration because this is usually where the critical failure points are located.

Given the context, I think it will be wise to read lines 1160-1280. That chunk probably contains the relevant code dealing with these linking and unlinking operations, and the garbage collection itself. I'm going to pay close attention to the data structures involved, the synchronization mechanisms used (if any), and any error handling related to these key-related tasks. I need to get a clear picture of the whole lifecycle and how it manages potentially sensitive data.



18/2 2026/11/18 16:53 tool read-file
0m Args:
{
  "File": "security/keys/keyring.c",
  "FirstLine": 1160,
  "LineCount": 90
}

Results:
{
  "Contents": "1160:\t\t/* Serialise link/link calls to prevent parallel calls causing a cycle\n1161:\t\t * when linking two keyring in opposite orders.\n1162:\t\t */\n1163:\t\tif (index_key-\u003etype == \u0026key_type_keyring)\n1164:\t\t\tmutex_lock(\u0026keyring_serialise_link_lock);\n1165:\t\n1166:\t\treturn 0;\n1167:\t}\n1168:\t\n1169:\tstatic struct keyring_index *keyring_get_index(struct key *keyring)\n1170:\t{\n1171:\t\tstruct keyring_index *links = keyring_index_locked(keyring);\n1172:\t\tint ret;\n1173:\t\n1174:\t\tif (links)\n1175:\t\t\treturn links;\n1176:\t\n1177:\t\tlinks = kzalloc_obj(struct keyring_index);\n1178:\t\tif (!links)\n1179:\t\t\treturn ERR_PTR(-ENOMEM);\n1180:\t\tret = rhashtable_init(\u0026links-\u003eht, \u0026keyring_link_params);\n1181:\t\tif (ret \u003c 0) {\n1182:\t\t\tkfree(links);\n1183:\t\t\treturn ERR_PTR(ret);\n1184:\t\t}\n1185:\t\n1186:\t\tINIT_LIST_HEAD(\u0026links-\u003elist);\n1187:\t\tINIT_RCU_WORK(\u0026links-\u003ercu_work, keyring_index_free_work);\n1188:\t\trcu_assign_pointer(keyring-\u003eindex, links);\n1189:\t\treturn links;\n1190:\t}\n1191:\t\n1192:\t/*\n1193:\t * Preallocate memory so that a key can be linked into to a keyring.\n1194:\t */\n1195:\tint __key_link_begin(struct key *keyring,\n1196:\t\t\t     const struct keyring_index_key *index_key,\n1197:\t\t\t     struct keyring_edit *edit)\n1198:\t{\n1199:\t\tstruct keyring_link *link = NULL;\n1200:\t\tstruct keyring_link *replace;\n1201:\t\tstruct keyring_index *links;\n1202:\t\tint ret;\n1203:\t\n1204:\t\tkenter(\"%d,%s,%s,\",\n1205:\t\t       keyring-\u003eserial, index_key-\u003etype-\u003ename, index_key-\u003edescription);\n1206:\t\n1207:\t\tif (WARN_ON(index_key-\u003edesc_len == 0) || WARN_ON(edit-\u003enew)) {\n1208:\t\t\tret = -EINVAL;\n1209:\t\t\tgoto out;\n1210:\t\t}\n1211:\t\n1212:\t\tedit-\u003enew = NULL;\n1213:\t\tedit-\u003eold = NULL;\n1214:\t\n1215:\t\tif (test_bit(KEY_FLAG_REVOKED, \u0026keyring-\u003eflags)) {\n1216:\t\t\tret = -EKEYREVOKED;\n1217:\t\t\tgoto out;\n1218:\t\t}\n1219:\t\n1220:\t\tlinks = keyring_get_index(keyring);\n1221:\t\tif (IS_ERR(links)) {\n1222:\t\t\tret = PTR_ERR(links);\n1223:\t\t\tgoto out;\n1224:\t\t}\n1225:\t\n1226:\t\tlink = kzalloc_obj(struct keyring_link);\n1227:\t\tif (!link) {\n1228:\t\t\tret = -ENOMEM;\n1229:\t\t\tgoto out;\n1230:\t\t}\n1231:\t\tlink-\u003ehash = index_key-\u003ehash;\n1232:\t\n1233:\t\treplace = keyring_find_link(links, index_key);\n1234:\t\n1235:\t\t/*\n1236:\t\t * If we're not replacing a link in-place then we're going to need some\n1237:\t\t * extra quota.\n1238:\t\t */\n1239:\t\tif (!replace) {\n1240:\t\t\tret = key_payload_reserve(keyring,\n1241:\t\t\t\t\t\t  keyring-\u003edatalen + KEYQUOTA_LINK_BYTES);\n1242:\t\t\tif (ret \u003c 0)\n1243:\t\t\t\tgoto out;\n1244:\t\n1245:\t\t\tret = rhashtable_insert_fast(\u0026links-\u003eht, \u0026link-\u003enode,\n1246:\t\t\t\t\t\t     keyring_link_params);\n1247:\t\t\tif (ret \u003c 0) {\n1248:\t\t\t\tkey_payload_reserve(keyring,\n1249:\t\t\t\t\t\t    keyring-\u003edatalen - KEYQUOTA_LINK_BYTES);\n"
}

19/2 2026/11/18 16:53 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 70571
							output: 32
							thoughts: 563
						

Thoughts:
**My Assessment of the Keyring Refactoring Patch**

Okay, so I'm looking at this patch and immediately, my spidey-sense is tingling. I'm seeing a flurry of `WARN_ON` assertions popping up, specifically at lines 1207, 1299, 1340, 1443, 1467, and 1666. That's a red flag right there – new assertions always warrant extra scrutiny, especially when they're sprinkled throughout what looks like a significant code change.

This isn't just a minor tweak; this is a full-blown architectural shift within `security/keys`. They're ripping out the old `assoc_array` implementation for keyrings and replacing it with an `rhashtable` combined with `list_head`, all while incorporating RCU and locking. That's a major redesign! This `keyring` code is exposed through syscalls like `keyctl`, `add_key`, and `request_key`, meaning it's absolutely reachable and critical.

Now, as per my standard practices, this screams for fuzzing. The guidelines state it explicitly: "NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED." This patch checks multiple boxes. Not only are there new runtime checks, but it's also a fundamental restructuring of data structures in a very exposed area. 

Therefore, I'm marking this patch as `WorthFuzzing = true`, no question.

Now, let's drill down into the details. I need to figure out the necessary configurations for testing. Clearly, `CONFIG_KEYS` is involved, and that's standard. I'll need to double-check `security/keys/Kconfig` to see if there are any other dependencies, selects, or enables. I'll have to investigate those settings to form my strategy for comprehensive testing.



20/2 2026/11/18 16:55 tool read-file
0m Args:
{
  "File": "security/keys/Kconfig",
  "FirstLine": 1,
  "LineCount": 40
}

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  36:\t\n  37:\t\t  An example of such a process is a pathwalk through a network\n  38:\t\t  filesystem in which each method needs to request an authentication\n  39:\t\t  key.  Pathwalk will call multiple methods for each dentry traversed\n  40:\t\t  (permission, d_revalidate, lookup, getxattr, getacl, ...).\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 72142
							output: 30
							thoughts: 55
						

Thoughts:
Okay, let's see, no explicit dependencies listed for `KEYS`... that's a bit unusual. My immediate thought is, what *else* is potentially impacted when `KEYS` is activated? This requires a bit of cross-referencing. Specifically, in `kernel/bpf/keys.c`, it’s clear we are dealing with BPF keys here. Okay, so where's the most likely place to find information about its broader context, its build configuration? Given the location, my instinct is to check either `kernel/bpf/Makefile` or `kernel/bpf/Kconfig`. Those are the usual suspects. I'll start with the Makefile, but Kconfig is probably the key!



22/2 2026/11/18 16:55 tool grepper
0m Args:
{
  "Expression": "keys\\.o",
  "PathPrefixes": [
    "kernel/bpf/Makefile"
  ]
}

Results:
{
  "Output": "kernel/bpf/Makefile=30=ifeq ($(CONFIG_KEYS),y)\nkernel/bpf/Makefile:31:obj-$(CONFIG_BPF_SYSCALL) += keys.o\nkernel/bpf/Makefile-32-endif\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 72449
							output: 45
							thoughts: 1907
						

Thoughts:
**Focusing on Keyring Modifications**

Okay, so I'm diving into this patch related to keyrings.  My initial assessment is that `CONFIG_KEYS` is the key enabler here, and `CONFIG_BPF_SYSCALL` is standard for BPF. No other configs seem relevant, I've checked. The code modifications look concentrated in `security/keys/` directory.

I've scanned through the code changes in `arch/s390/kernel/cert_store.c`, `drivers/md/dm-verity-verify-sig.c`, and `fs/verity/signature.c`. The most significant alterations appear to be the replacement of checks related to `nr_leaves_on_tree` with calls to `keyring_is_empty()`. This indicates a core shift in the way keyrings are checked, hinting at modifications to the underlying keyring data structure, and the associated logic.

Now, let's get down to the function-level details. I've gone through the modified and added functions, both static and global, in `security/keys/keyring.c`, `security/keys/key.c`, and `security/keys/request_key.c`.

I'm trying to identify the *most* relevant symbols. I need to avoid listing ubiquitous lifecycle functions. I need to focus on the specific feature logic being added or altered, or direct API entrypoints for this subsystem. I know that compiler-inlined static functions lack distinct symbol addresses.

After reviewing the list, I'm thinking, are `key_link`, `key_unlink`, `key_move`, `keyring_clear`, `keyring_gc`, `keyring_read`, `search_keyring_tree`, `keyring_is_empty`, and `find_key_to_update` the best focus symbols? Yes, these aren't ubiquitous and are specific to keyring operations. 

Of the above list, here are the functions I've selected as my primary focus.

1.  **`key_link`**: Links a key into a keyring. It's an entry point which exercises `__key_link_begin`, `__key_link`, and `rhashtable_insert_fast` as well as list operations.
2.  **`key_unlink`**: Unlinks a key from a keyring. This calls `__key_unlink_begin`, `__key_unlink`, and `rhashtable_remove_fast`.
3.  **`key_move`**: This moves a key between keyrings and exercises both linking and unlinking with atomicity.
4.  **`keyring_clear`**: This clears a keyring and calls `keyring_index_free` and `rcu_work`.
5.  **`keyring_gc`**:  This garbage collects dead keys from a keyring and exercises rhashtable removals and iteration.
6.  **`keyring_read`**: Reads keys from a keyring, exercising `keyring_iterate`, and RCU traversal.
7.  **`keyring_is_empty`**: This is a newly introduced API to determine if a keyring is empty.
8.  **`search_keyring_tree`**: This recursively searches nested keyrings. Important, it replaces an older traversal method. It's static, but I'm expecting the compiler not to inline it due to recursion.

Okay, let me just confirm that `search_keyring_tree` is *not* inlined. Confirmed. Then I had a look at `key_set_index_key` which has had a hash change. Finally, I'm going to quickly check `security/keys/keyctl.c` to see how those syscalls use these functions I'm selecting.



24/2 2026/11/18 16:56 tool grepper
0m Args:
{
  "Expression": "key_link|key_unlink|key_move|keyring_clear",
  "PathPrefixes": [
    "security/keys/keyctl.c"
  ]
}

Results:
{
  "Output": "security/keys/keyctl.c=418=long keyctl_invalidate_key(key_serial_t id)\n--\nsecurity/keys/keyctl.c-464- */\nsecurity/keys/keyctl.c:465:long keyctl_keyring_clear(key_serial_t ringid)\nsecurity/keys/keyctl.c-466-{\n--\nsecurity/keys/keyctl.c-494-\telse\nsecurity/keys/keyctl.c:495:\t\tret = keyring_clear(keyring);\nsecurity/keys/keyctl.c-496-error_put:\n--\nsecurity/keys/keyctl.c=513=long keyctl_keyring_link(key_serial_t id, key_serial_t ringid)\n--\nsecurity/keys/keyctl.c-529-\nsecurity/keys/keyctl.c:530:\tret = key_link(key_ref_to_ptr(keyring_ref), key_ref_to_ptr(key_ref));\nsecurity/keys/keyctl.c-531-\n--\nsecurity/keys/keyctl.c=550=long keyctl_keyring_unlink(key_serial_t id, key_serial_t ringid)\n--\nsecurity/keys/keyctl.c-573-\telse\nsecurity/keys/keyctl.c:574:\t\tret = key_unlink(keyring, key);\nsecurity/keys/keyctl.c-575-\n--\nsecurity/keys/keyctl.c=593=long keyctl_keyring_move(key_serial_t id, key_serial_t from_ringid,\n--\nsecurity/keys/keyctl.c-617-\nsecurity/keys/keyctl.c:618:\tret = key_move(key_ref_to_ptr(key_ref), key_ref_to_ptr(from_ref),\nsecurity/keys/keyctl.c-619-\t\t       key_ref_to_ptr(to_ref), flags);\n--\nsecurity/keys/keyctl.c=716=long keyctl_keyring_search(key_serial_t ringid,\n--\nsecurity/keys/keyctl.c-778-\nsecurity/keys/keyctl.c:779:\t\tret = key_link(key_ref_to_ptr(dest_ref), key_ref_to_ptr(key_ref));\nsecurity/keys/keyctl.c-780-\t\tif (ret \u003c 0)\n--\nsecurity/keys/keyctl.c=1885=SYSCALL_DEFINE5(keyctl, int, option, unsigned long, arg2, unsigned long, arg3,\n--\nsecurity/keys/keyctl.c-1909-\tcase KEYCTL_CLEAR:\nsecurity/keys/keyctl.c:1910:\t\treturn keyctl_keyring_clear((key_serial_t) arg2);\nsecurity/keys/keyctl.c-1911-\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 75958
							output: 20
							thoughts: 433
						

Thoughts:
**Kernel Keyring Internals: A Quick Dive**

Okay, so I'm looking at how `keyctl` interacts with the kernel keyring implementation. It's pretty straightforward, actually. `keyctl` commands map directly to specific kernel functions: `KEYCTL_LINK` calls `keyctl_keyring_link` which ultimately calls `key_link`; `KEYCTL_UNLINK` goes to `keyctl_keyring_unlink` and then `key_unlink`; `KEYCTL_MOVE` to `keyctl_keyring_move` then `key_move`, and so on.  `KEYCTL_CLEAR` hits `keyctl_keyring_clear` which then triggers `keyring_clear`. `KEYCTL_READ` hits `keyctl_read_key`, calling `keyring_read`. `KEYCTL_SEARCH` is a bit more involved; it's `keyctl_keyring_search` then `search_nested_keyrings` and finally `search_keyring_tree`. And of course, the garbage collection mechanism (`keyring_gc`) runs in the background via the workqueue when keys expire. Oh, and `find_key_to_update` is called when adding keys with existing names.

Now, my next question is, are any of these functions *ubiquitous*?  No, it looks like they are not. They are exclusively invoked when actively managing kernel keyrings, whether it's through `keyctl`, `add_key`, `request_key`, or other key management operations. That helps narrow down the scope.

Let's switch gears and focus on the `EnableConfigs`.  We need `KEYS` to compile the `security/keys` subsystem, obviously. Are there other relevant configurations? I should check the `security/keys/Kconfig` file and other potentially relevant files.

`KEYS` seems to be the main configuration needed, but what about `SECURITY`? I want to make sure I don't miss something. I'll need to double-check if `KEYS` depends on anything else within the Kconfig system.

Okay, I see that the `menuconfig KEYS` in `security/keys/Kconfig` has no `depends on`. Now, let's see how `security/keys/Kconfig` is even sourced from `init/Kconfig` and `security/Kconfig`. Time to grep!



26/2 2026/11/18 16:56 tool grepper
0m Args:
{
  "Expression": "security/keys/Kconfig"
}

Results:
{
  "Output": "security/Kconfig=6=menu \"Security options\"\nsecurity/Kconfig-7-\nsecurity/Kconfig:8:source \"security/keys/Kconfig\"\nsecurity/Kconfig-9-\n"
}

27/2 2026/11/18 16:56 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 76980
							output: 199
							thoughts: 341
						

Thoughts:
**My Assessment of the Linux Keyrings Subsystem for Fuzzing**

Okay, so looking at `security/Kconfig`, it directly sources `security/keys/Kconfig` without any conditional checks. This means the `KEYS` config option is the only one we actually need. Simple enough.

Now, let's do a quick sanity check to see if this is all correct:

*   **Subsystem:** It's the `security/keys` subsystem, which is the Linux Keyrings, a core feature related to security, crypto, and credential management. Checks out.
*   **Reachability:** We can interact with this via standard syscalls – `keyctl`, `add_key`, `request_key` – so it's fully accessible. This is great for fuzzing.
*   **Architecture:** It's generic C code, but this version replaces the old `assoc_array` tree with `rhashtable` and `list_head`, which affects the key ring data structure on all architectures. This makes it relevant across the board, in terms of impact, even if some parts only affect x86.
*   **Assertions:** There are a bunch of new `WARN_ON(...)` calls sprinkled around in `__key_link_begin`, `__key_link`, `__key_link_end`, `__key_unlink_begin`, `__key_unlink`, and `keyring_gc`. That suggests they've put in an effort to identify potential issues, which is a good sign for fuzzing. More assertions mean more chances to catch bugs.
*   **Refactoring/Redesign:** It's a *complete* replacement of the internal data structure and concurrency/RCU model. That's a huge change! This is prime territory for finding memory corruption, race conditions, or logic errors.

Looks like we're in good shape. WorthFuzzing is definitely **true**.

Based on the code changes, these are the key symbols to focus on:
*   `key_link` and `key_unlink`
*   `key_move`
*   `keyring_clear` and `keyring_gc`
*   `keyring_read`
*   `search_keyring_tree`
*   `find_key_to_update`
*   `keyring_is_empty`

So, let's activate the `KEYS` config option and call `set-results`. We're ready to start fuzzing.



28/2 2026/11/18 16:58 tool set-results
0m Args:
{
  "EnableConfigs": [
    "KEYS"
  ],
  "FocusSymbols": [
    "key_link",
    "key_unlink",
    "key_move",
    "keyring_clear",
    "keyring_gc",
    "keyring_read",
    "search_keyring_tree",
    "find_key_to_update",
    "keyring_is_empty"
  ],
  "Reasoning": "The patch completely replaces the associative array (assoc_array) implementation used for kernel keyrings with an rhashtable and linked list (keyring_index) data structure, altering insertion, deletion, lookup, iteration, garbage collection, and RCU lifetime management. It also adds several new WARN_ON assertions in reachable code paths. The affected code in security/keys/ is fully reachable via standard keyctl, add_key, and request_key system calls in virtualized environments.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "KEYS"
  ],
  "FocusSymbols": [
    "key_link",
    "key_unlink",
    "key_move",
    "keyring_clear",
    "keyring_gc",
    "keyring_read",
    "search_keyring_tree",
    "find_key_to_update",
    "keyring_is_empty"
  ],
  "Reasoning": "The patch completely replaces the associative array (assoc_array) implementation used for kernel keyrings with an rhashtable and linked list (keyring_index) data structure, altering insertion, deletion, lookup, iteration, garbage collection, and RCU lifetime management. It also adds several new WARN_ON assertions in reachable code paths. The affected code in security/keys/ is fully reachable via standard keyctl, add_key, and request_key system calls in virtualized environments.",
  "WorthFuzzing": true
}

29/1 2026/11/18 16:58 action If
14m Args:
{
  "WorthFuzzing": true
}

Results:
null

30/2 2026/11/18 16:58 agent kmsan-evaluator
14m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series replaces the associative array (`assoc_array`) data structure used for keyring indexing in the Linux keys subsystem with a combination of `rhashtable` and an RCU-protected linked list (`struct keyring_index` and `struct keyring_link`), while removing the unused generic `assoc_array` implementation and fixing reference counting / error handling in s390 `cert_store.c`.\n\nKMSAN vs. KASAN analysis:\n1. Memory Allocation and Initialization: All newly introduced kernel structures (`struct keyring_index`, `struct keyring_link`) are allocated with `kzalloc_obj()`, ensuring all fields are zero-initialized upon allocation. Stack instances of `struct keyring_edit`, `struct keyring_read_context`, and `struct keyring_search_context` are zero-initialized using designated initializers (`= {}`), leaving no uninitialized fields or padding.\n2. User Space Data Exposure: `keyring_read()` exports an array of 32-bit `key_serial_t` IDs via `keyctl(KEYCTL_READ)`. The iterator writes exact serial values for active keys (`ctx.serials[ctx.count++] = key-\u003eserial`), and the returned byte length directly corresponds to the number of active entries (`index-\u003enr * sizeof(key_serial_t)`), preventing any uninitialized kernel memory from being copied to user space.\n3. Bug Profile: The architectural changes introduce potential risks around RCU concurrency, list/hash table synchronization, reference count management (`key_get`/`key_put`), locking deadlocks, or use-after-free conditions. These classes of bugs are thoroughly covered by KASAN, LOCKDEP, and existing kernel debuggers.\n\nBecause no uninitialized memory reads or information leaks are exposed or introduced by this series, a dedicated KMSAN fuzzing session is not warranted.",
  "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 50084e4806939522d31a77da9a8d49de5932b15a
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Nov 18 16:41:42 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/arch/s390/kernel/cert_store.c b/arch/s390/kernel/cert_store.c
index 998f2da5617500..bc682216fa7fdd 100644
--- a/arch/s390/kernel/cert_store.c
+++ b/arch/s390/kernel/cert_store.c
@@ -307,7 +307,6 @@ static struct key *get_user_session_keyring(void)
 			   PTR_ERR(us_keyring_ref));
 		return ERR_PTR(-ENOKEY);
 	}
-	key_ref_put(us_keyring_ref);
 	return key_ref_to_ptr(us_keyring_ref);
 }
 
@@ -334,6 +333,9 @@ static int invalidate_keyring_keys(struct key *keyring)
 
 	for (key_index = 0; key_index < num_keys; key_index++) {
 		current_key = key_lookup(key_array[key_index]);
+		if (!current_key)
+			continue;
+
 		pr_dbf_msg("Invalidating key %08x", current_key->serial);
 
 		key_invalidate(current_key);
@@ -352,27 +354,30 @@ static int invalidate_keyring_keys(struct key *keyring)
 static struct key *find_cs_keyring(void)
 {
 	key_ref_t cs_keyring_ref;
+	struct key *us_keyring;
 	struct key *cs_keyring;
 
-	cs_keyring_ref = keyring_search(make_key_ref(get_user_session_keyring(), true),
+	us_keyring = get_user_session_keyring();
+	if (IS_ERR(us_keyring))
+		return NULL;
+
+	cs_keyring_ref = keyring_search(make_key_ref(us_keyring, true),
 					&key_type_keyring, CERT_STORE_KEYRING_NAME,
 					false);
-	if (!IS_ERR(cs_keyring_ref)) {
-		cs_keyring = key_ref_to_ptr(cs_keyring_ref);
-		key_ref_put(cs_keyring_ref);
-		goto found;
-	}
+	key_put(us_keyring);
+	if (!IS_ERR(cs_keyring_ref))
+		return key_ref_to_ptr(cs_keyring_ref);
+
 	/* Search default locations: thread, process, session keyrings */
 	cs_keyring = request_key(&key_type_keyring, CERT_STORE_KEYRING_NAME, NULL);
 	if (IS_ERR(cs_keyring))
 		return NULL;
-	key_put(cs_keyring);
-found:
 	return cs_keyring;
 }
 
 static void cleanup_cs_keys(void)
 {
+	struct key *us_keyring;
 	struct key *cs_keyring;
 
 	cs_keyring = find_cs_keyring();
@@ -389,21 +394,36 @@ static void cleanup_cs_keys(void)
 
 	keyring_clear(cs_keyring);
 	key_invalidate(cs_keyring);
+
+	us_keyring = get_user_session_keyring();
+	if (IS_ERR(us_keyring)) {
+		key_put(cs_keyring);
+		return;
+	}
+
+	key_unlink(us_keyring, cs_keyring);
+	key_put(us_keyring);
 	key_put(cs_keyring);
-	key_unlink(get_user_session_keyring(), cs_keyring);
 }
 
 static struct key *create_cs_keyring(void)
 {
 	static struct key *cs_keyring;
+	struct key *us_keyring;
 
 	/* Cleanup previous cs_keyring and all associated keys if any. */
 	cleanup_cs_keys();
+
+	us_keyring = get_user_session_keyring();
+	if (IS_ERR(us_keyring))
+		return NULL;
+
 	cs_keyring = keyring_alloc(CERT_STORE_KEYRING_NAME, GLOBAL_ROOT_UID,
 				   GLOBAL_ROOT_GID, current_cred(),
 				   (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ,
 				   KEY_ALLOC_NOT_IN_QUOTA | KEY_ALLOC_SET_KEEP,
-				   NULL, get_user_session_keyring());
+				   NULL, us_keyring);
+	key_put(us_keyring);
 	if (IS_ERR(cs_keyring)) {
 		pr_dbf_msg("Can't allocate cert_store keyring");
 		return NULL;
@@ -710,13 +730,12 @@ static int fill_cs_keyring(void)
 		goto cleanup_keys;
 
 	rc = add_certificates_to_keyring(vcssb, cs_keyring);
+	key_put(cs_keyring);
 	if (rc)
-		goto cleanup_cs_keyring;
+		goto cleanup_keys;
 
 	goto out;
 
-cleanup_cs_keyring:
-	key_put(cs_keyring);
 cleanup_keys:
 	cleanup_cs_keys();
 out:
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 357f5636081055..8794f47da9f505 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 inline bool keyring_ptr_is_keyring(const struct assoc_array_ptr *x)
+static u32 keyring_hashfn(const void *data, u32 len, u32 seed)
 {
-	return (unsigned long)x & KEYRING_PTR_SUBTYPE;
+	const struct keyring_index_key *index_key = data;
+
+	return jhash_1word(index_key->hash, seed);
 }
-static inline struct key *keyring_ptr_to_key(const struct assoc_array_ptr *x)
+
+static u32 keyring_obj_hashfn(const void *data, u32 len, u32 seed)
 {
-	void *object = assoc_array_ptr_to_leaf(x);
-	return (struct key *)((unsigned long)object & ~KEYRING_PTR_SUBTYPE);
+	const struct keyring_link *link = data;
+
+	return jhash_1word(link->hash, seed);
 }
-static inline void *keyring_key_to_ptr(struct key *key)
+
+static bool keyring_index_key_equal(const struct keyring_index_key *a,
+				    const struct keyring_index_key *b)
 {
-	if (key->type == &key_type_keyring)
-		return (void *)((unsigned long)key | KEYRING_PTR_SUBTYPE);
-	return key;
+	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 struct key *keyring_link_key(const struct keyring_link *link)
+{
+	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,60 +383,75 @@ 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;
+struct keyring_read_context {
+	key_serial_t	*serials;
+	size_t		max;
+	size_t		count;
 };
 
-static int keyring_read_iterator(const void *object, void *data)
+static int keyring_read_iterator(const struct key *key, void *iterator_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);
+	struct keyring_read_context *ctx = iterator_data;
 
-	if (ctx->count >= ctx->buflen)
-		return 1;
-
-	*ctx->buffer++ = key->serial;
-	ctx->count += sizeof(key->serial);
-	return 0;
+	ctx->serials[ctx->count++] = key->serial;
+	return ctx->count == ctx->max;
 }
 
 /*
  * Read a list of key IDs from the keyring's contents in binary form
  *
- * The keyring's semaphore is read-locked by the caller.  This prevents someone
- * from modifying it under us - which could cause us to read key IDs multiple
- * times.
+ * The walk is RCU-protected, so the keyring's semaphore is not required.  A
+ * keyring modified concurrently may list a key twice or miss one, but it can
+ * never have a link freed under the walk.
  */
 static long keyring_read(const struct key *keyring,
 			 char *buffer, size_t buflen)
 {
-	struct keyring_read_iterator_context ctx;
 	long ret;
 
 	kenter("{%d},,%zu", key_serial(keyring), buflen);
@@ -501,25 +459,23 @@ 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);
+		struct keyring_read_context ctx = {
+			.serials	= (key_serial_t *)buffer,
+			.max		= buflen / sizeof(key_serial_t),
+		};
+
+		ret = keyring_iterate(keyring, keyring_read_iterator, &ctx);
+		if (ret < 0)
 			return ret;
-		}
 	}
 
-	/* Return the size of the buffer needed */
-	ret = keyring->keys.nr_leaves_on_tree * sizeof(key_serial_t);
+	ret = keyring_nr_links(keyring) * sizeof(key_serial_t);
 	if (ret <= buflen)
 		kleave("= %ld [ok]", ret);
 	else
 		kleave("= %ld [buffer too small]", ret);
+
 	return ret;
 }
 
@@ -583,10 +539,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 +608,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 +689,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 +707,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 +721,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 +733,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 +979,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 +988,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 +1067,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,57 +1166,98 @@ 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 = 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)) {
+		ret = -EINVAL;
+		goto out;
+	}
 
-	*_edit = NULL;
+	edit->new = NULL;
+	edit->old = NULL;
 
-	ret = -EKEYREVOKED;
-	if (test_bit(KEY_FLAG_REVOKED, &keyring->flags))
-		goto error;
+	if (test_bit(KEY_FLAG_REVOKED, &keyring->flags)) {
+		ret = -EKEYREVOKED;
+		goto out;
+	}
 
-	/* 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);
-		goto error;
+	links = keyring_get_index(keyring);
+	if (IS_ERR(links)) {
+		ret = PTR_ERR(links);
+		goto out;
 	}
 
-	/* If we're not replacing a link in-place then we're going to need some
+	link = kzalloc_obj(struct keyring_link);
+	if (!link) {
+		ret = -ENOMEM;
+		goto out;
+	}
+	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 out;
+
+		ret = rhashtable_insert_fast(&links->ht, &link->node,
+					     keyring_link_params);
+		if (ret < 0) {
+			key_payload_reserve(keyring,
+					    keyring->datalen - KEYQUOTA_LINK_BYTES);
+			goto out;
+		}
 	}
 
-	*_edit = edit;
-	kleave(" = 0");
-	return 0;
+	edit->new = link;
+	edit->old = replace;
+	ret = 0;
 
-error_cancel:
-	assoc_array_cancel_edit(edit);
-error:
+out:
+	if (ret && link)
+		kfree(link);
 	kleave(" = %d", ret);
 	return ret;
 }
@@ -1385,13 +1285,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 +1324,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 +1378,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 +1388,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 +1412,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 +1436,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 +1458,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 +1483,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 +1492,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 +1504,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 +1525,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 +1539,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 +1563,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 +1573,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 +1594,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 +1615,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);
-	}
-}
-
-static bool keyring_gc_select_iterator(void *object, 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;
+	keyring_index_free(keyring);
+	key_payload_reserve(keyring, 0);
 }
 
-static int keyring_gc_check_iterator(const void *object, void *iterator_data)
+static int keyring_gc_check_iterator(const struct key *key, void *iterator_data)
 {
-	const struct key *key = keyring_ptr_to_key(object);
 	time64_t *limit = iterator_data;
 
 	key_check(key);
@@ -1742,7 +1635,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 +1646,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 +1655,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

31/3 2026/11/18 16:58 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 60644
							output: 29
							thoughts: 1356
						

Thoughts:
**KMSAN Fuzzing Justification: Analyzing the assoc_array Replacement**

Alright, let's dive into this patch series. My initial assessment is focused on determining if these code changes warrant a dedicated KMSAN fuzzing session, beyond our standard KASAN efforts. The core of this patch seems to be a significant refactoring: replacing the `assoc_array` data structure within the kernel's key management system with `rhashtable` and `list_head` structures. This is a big shift, and it has implications for memory safety, so a deep dive is required.

First, let me summarize the changes: the patch series is essentially gutting the old `assoc_array` implementation and replacing it across several subsystems. It looks like we're saying goodbye to the `Documentation/core-api/assoc_array.rst` file, and all the corresponding code. The `assoc_array` is removed completely. They're replacing it within `security/keys`, which I'll need to pay close attention to. There are several other changes including:

*   Replaced checks on `keys.nr_leaves_on_tree` with `keyring_is_empty()`.
*   Changes to `struct keyring_index_key`
    *   `hash` changed from `unsigned long` to `u32`
    *   `desc_len` changed from `u16` to `unsigned int`
    *   removed union with `desc`, `x`
    *   removed `type_id`, `domain_id`
    *   In `struct key`:
        *   matching changes in the union with `struct keyring_index_key`.
        *   `struct assoc_array keys;` replaced by `struct keyring_index __rcu *index;`.
*   `struct keyring_edit` replaces `struct assoc_array_edit *`.
*   Keyring search, link, unlink, move, clear, gc, read operations rewritten to use `struct keyring_index` (rhashtable + linked list) instead of `assoc_array`.

My primary concern right now is to identify potential uninitialized memory reads or information leaks to user space that may result from this change. Given the critical nature of the key management subsystem, even subtle flaws could be exploited. I must carefully scrutinize the data structure replacements, paying particular attention to how these new structures are initialized and accessed, especially the `keyring_read()` function.

Let's dissect `keyring_read()`. The new implementation has a significant change in how it iterates through and exposes key serials: the `keyring_read_iterator_context` structure is gone. Instead, we have a `keyring_read_context` that is very similar. The change is replacing a `assoc_array_iterate` call with `keyring_iterate`, a similar function, but with a different internal implementation. I will note the change in how the iterator handles buffer limits, but I don't see any obvious new risks immediately.

*   Old `keyring_read()` code:


32/3 2026/11/18 16:59 tool grepper
0m Args:
{
  "Expression": "keyring_read",
  "PathPrefixes": [
    "security/keys/"
  ]
}

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-430-\nsecurity/keys/keyring.c:431:struct keyring_read_context {\nsecurity/keys/keyring.c-432-\tkey_serial_t\t*serials;\n--\nsecurity/keys/keyring.c-436-\nsecurity/keys/keyring.c:437:static int keyring_read_iterator(const struct key *key, void *iterator_data)\nsecurity/keys/keyring.c-438-{\nsecurity/keys/keyring.c:439:\tstruct keyring_read_context *ctx = iterator_data;\nsecurity/keys/keyring.c-440-\n--\nsecurity/keys/keyring.c-451- */\nsecurity/keys/keyring.c:452:static long keyring_read(const struct key *keyring,\nsecurity/keys/keyring.c-453-\t\t\t char *buffer, size_t buflen)\n--\nsecurity/keys/keyring.c-462-\tif (buffer \u0026\u0026 buflen) {\nsecurity/keys/keyring.c:463:\t\tstruct keyring_read_context ctx = {\nsecurity/keys/keyring.c-464-\t\t\t.serials\t= (key_serial_t *)buffer,\n--\nsecurity/keys/keyring.c-467-\nsecurity/keys/keyring.c:468:\t\tret = keyring_iterate(keyring, keyring_read_iterator, \u0026ctx);\nsecurity/keys/keyring.c-469-\t\tif (ret \u003c 0)\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 63299
							output: 29
							thoughts: 47
						

Thoughts:
**Investigating the Key Retrieval Mechanism**

Okay, so I need to dive into how the `keyctl_read_key` system call actually *works* under the hood. My primary question is how it retrieves the actual key data, and I suspect that either `keyring_read` or the `key->type->read` function pointer is the key to that. I'm going to quickly check if `keyctl_read_key` calls either of those functions.

My next step, and this is where I'll get the real information, is a simple grep command. Let's see if I can find all instances of `keyctl_read` within the `security/keys/` directory. That should give me a good overview of the surrounding code and potentially reveal the data path. I expect to find some interesting results!



34/3 2026/11/18 16:59 tool grepper
0m Args:
{
  "Expression": "keyctl_read",
  "PathPrefixes": [
    "security/keys/"
  ]
}

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"
}

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

Args:
null

Results:
null

Tokens:
							input: 64336
							output: 36
							thoughts: 25
						

Thoughts:
Here's a first-person summary, tailored for an expert audience, of the requested code section.

**Diving into `keyctl.c` for Context**

Okay, time to get a bit more granular. I'm going to jump into `security/keys/keyctl.c` and focus on lines 800 to 920. That range usually encompasses a critical piece of the keyring management, likely the heart of a key operation or access control decision. Given the focus on `keyctl`, I'm expecting to find core functions related to key manipulation – creating, linking, searching, and maybe some permission checking in that segment. My initial hypothesis is that I'll probably encounter a function responsible for the handling of a specific key operation from user space. I'll need to pay close attention to the arguments passed to the function, how it interacts with the keyring structures, what sort of locking is being employed, and, critically, how any errors are handled and propagated. I am interested to see how it's dealing with user input and if there is a potential for vulnerabilities if input isn't validated correctly. I anticipate seeing conditional logic reflecting the intricacies of key attributes, permissions, and possible access control lists. It is also of great interest to me whether any of this could be a security risk and if I can better understand its architecture for improving its safety.



36/3 2026/11/18 17:00 tool read-file
0m Args:
{
  "File": "security/keys/keyctl.c",
  "FirstLine": 800,
  "LineCount": 80
}

Results:
{
  "Contents": " 800:\t/*\n 801:\t * Call the read method\n 802:\t */\n 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"
}

37/3 2026/11/18 17:00 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 65849
							output: 36
							thoughts: 24
						

Thoughts:
Okay, let's dive into this `keyctl_read_key` function, specifically lines 880-940. I need to understand the control flow and data manipulation happening within this section. Given my expertise, I'm already looking for potential areas of concern: memory allocation, buffer handling, error checking, and security implications. I'll meticulously examine each line, anticipating edge cases and potential vulnerabilities. I'm focusing on how the data is being accessed and managed during the key read operation. I'm looking for any signs of race conditions or flaws in the integrity checks. My goal is to grasp the core mechanics and identify any areas that could lead to unexpected behavior or security issues within the kernel's key management subsystem. This is where the devil lives, it's the edge of the problem that always exposes the true nature of code. So, let's get to work.



38/3 2026/11/18 17:00 tool read-file
0m Args:
{
  "File": "security/keys/keyctl.c",
  "FirstLine": 880,
  "LineCount": 60
}

Results:
{
  "Contents": " 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 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"
}

39/3 2026/11/18 17:00 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 66994
							output: 20
							thoughts: 2328
						

Thoughts:
**Vulnerability Analysis of Keyring Iteration and Data Leakage**

Okay, let's break this down. I'm looking at `security/keys/keyctl.c`, specifically how `keyctl_read_key` handles keyrings and the data it exposes. The code reads the key data, and then copies it to user space. It uses `kvmalloc`, which is fine, but it *doesn't* zero the memory. So, if the key data isn't fully initialized, you're potentially leaking uninitialized kernel memory to user space.

I see `keyring_read` being called and immediately, I'm thinking about concurrent access and synchronization. It retrieves key serials and returns the number of bytes that *should* have been written. But the crucial thing is the comment: "The walk is RCU-protected, so the keyring's semaphore is not required". It makes an important point about modifications happening concurrently, where a key may be listed twice, or even missed. Now, let's think about this a bit:

1.  **Concurrent Modification and Semaphores:** The code uses `down_read` for reading and `down_write` for modification (`keyring_gc`, `keyring_clear`, `key_unlink`, and `key_link`). But, if the iteration is RCU-protected, can modifications still be happening while the read occurs? The comment seems to say yes, but it sounds like there are ways around it.
2.  **`keyring_nr_links` vs. Iteration Count:**  `keyring_read` calculates the return value based on `keyring_nr_links`. However, what if `ctx.count` (the actual number of iterated items) is less than this? Or, what if the `keyring_nr_links` is *more* than what was actually iterated? That would indicate there are inconsistent results from how the keyring looks *during* read, versus how it looks at the end.
3.  **Invalid or Revoked Keys:** `keyring_read_iterator` iterates through the keyring and calls `keyring_link_key`, adding the key's serial. But this routine *doesn't* skip any keys, even if they are invalid or revoked.  This seems wrong. It just puts the `key->serial`. This is *very* important.
4.  **`keyring_link_key` and Potential NULLs:** What happens if `keyring_link_key(link)` returns NULL? The code needs to handle this. It looks like it is possible during linking! This is a *major* potential flaw. Look at `__key_link_begin()`! A new link is created, inserted into an RHTABLE, and then the key is assigned. At first, the key is *null*! It looks like you can get a link without a key. This is a potential NULL pointer dereference.
5.  **Race Conditions and RCU:** The `keyring_iterate` function uses `rcu_dereference` and `list_for_each_entry_rcu`. The RCU protection means that there is a window where modifications to the keyring's links are possible while a read is occurring. I think this can lead to returning incorrect data.

This is a real problem. By exploiting the race condition during read, a malicious user could read stale keyring entries or potentially trigger a NULL pointer dereference. The combination of uninitialized memory in `kvmalloc`, potential issues with `keyring_nr_links` and iteration count, and the concurrent modification risks creates a significant information leak and potentially a denial-of-service vulnerability. This requires deeper analysis to confirm the exploitability, but the potential is *very* concerning. I need to check all callers of `key_type_keyring` to be thorough.



40/3 2026/11/18 17:02 tool grepper
0m Args:
{
  "Expression": "key_type_keyring"
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 225 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (13 files in total):\nDocumentation/security/keys/core.rst:1\narch/s390/kernel/cert_store.c:4\ncerts/system_keyring.c:3\ncrypto/asymmetric_keys/restrict.c:2\ninclude/linux/key-type.h:1\nnet/rxrpc/server_key.c:1\nsecurity/integrity/digsig.c:1\nsecurity/keys/gc.c:2\nsecurity/keys/key.c:3\nsecurity/keys/keyring.c:17\nsecurity/keys/persistent.c:2\nsecurity/keys/process_keys.c:3\nsecurity/keys/request_key.c:2\n\nDocumentation/security/keys/core.rst=1331=The facility provides access to the keyring type for managing such a bundle::\nDocumentation/security/keys/core.rst-1332-\nDocumentation/security/keys/core.rst:1333:\tstruct key_type key_type_keyring;\nDocumentation/security/keys/core.rst-1334-\n--\narch/s390/kernel/cert_store.c=314=static int invalidate_keyring_keys(struct key *keyring)\n--\narch/s390/kernel/cert_store.c-321-\narch/s390/kernel/cert_store.c:322:\tkeyring_payload_len = key_type_keyring.read(keyring, NULL, 0);\narch/s390/kernel/cert_store.c-323-\tnum_keys = keyring_payload_len / sizeof(key_serial_t);\n--\narch/s390/kernel/cert_store.c-327-\narch/s390/kernel/cert_store.c:328:\trc = key_type_keyring.read(keyring, (char *)key_array, keyring_payload_len);\narch/s390/kernel/cert_store.c-329-\tif (rc != keyring_payload_len) {\n--\narch/s390/kernel/cert_store.c=354=static struct key *find_cs_keyring(void)\n--\narch/s390/kernel/cert_store.c-364-\tcs_keyring_ref = keyring_search(make_key_ref(us_keyring, true),\narch/s390/kernel/cert_store.c:365:\t\t\t\t\t\u0026key_type_keyring, CERT_STORE_KEYRING_NAME,\narch/s390/kernel/cert_store.c-366-\t\t\t\t\tfalse);\n--\narch/s390/kernel/cert_store.c-371-\t/* Search default locations: thread, process, session keyrings */\narch/s390/kernel/cert_store.c:372:\tcs_keyring = request_key(\u0026key_type_keyring, CERT_STORE_KEYRING_NAME, NULL);\narch/s390/kernel/cert_store.c-373-\tif (IS_ERR(cs_keyring))\n--\ncerts/system_keyring.c=87=int restrict_link_by_builtin_and_secondary_trusted(\n--\ncerts/system_keyring.c-95-\t */\ncerts/system_keyring.c:96:\tif (type == \u0026key_type_keyring \u0026\u0026\ncerts/system_keyring.c-97-\t    dest_keyring == secondary_trusted_keys \u0026\u0026\n--\ncerts/system_keyring.c=117=int restrict_link_by_digsig_builtin_and_secondary(struct key *dest_keyring,\n--\ncerts/system_keyring.c-124-\t */\ncerts/system_keyring.c:125:\tif (type == \u0026key_type_keyring \u0026\u0026\ncerts/system_keyring.c-126-\t    dest_keyring == secondary_trusted_keys \u0026\u0026\n--\ncerts/system_keyring.c=206=int restrict_link_by_builtin_secondary_and_machine(\n--\ncerts/system_keyring.c-211-{\ncerts/system_keyring.c:212:\tif (machine_trusted_keys \u0026\u0026 type == \u0026key_type_keyring \u0026\u0026\ncerts/system_keyring.c-213-\t    dest_keyring == secondary_trusted_keys \u0026\u0026\n--\ncrypto/asymmetric_keys/restrict.c=209=static int key_or_keyring_common(struct key *dest_keyring,\n--\ncrypto/asymmetric_keys/restrict.c-221-\t\treturn -ENOKEY;\ncrypto/asymmetric_keys/restrict.c:222:\telse if (dest_keyring-\u003etype != \u0026key_type_keyring)\ncrypto/asymmetric_keys/restrict.c-223-\t\treturn -EOPNOTSUPP;\n--\ncrypto/asymmetric_keys/restrict.c-237-\tif (trusted) {\ncrypto/asymmetric_keys/restrict.c:238:\t\tif (trusted-\u003etype == \u0026key_type_keyring) {\ncrypto/asymmetric_keys/restrict.c-239-\t\t\t/* See if we have a key that signed this one. */\n--\ninclude/linux/key-type.h=64=struct key_type {\n--\ninclude/linux/key-type.h-167-\ninclude/linux/key-type.h:168:extern struct key_type key_type_keyring;\ninclude/linux/key-type.h-169-\n--\nnet/rxrpc/server_key.c=120=int rxrpc_server_keyring(struct rxrpc_sock *rx, sockptr_t optval, int optlen)\n--\nnet/rxrpc/server_key.c-136-\nnet/rxrpc/server_key.c:137:\tkey = request_key(\u0026key_type_keyring, description, NULL);\nnet/rxrpc/server_key.c-138-\tif (IS_ERR(key)) {\n--\nsecurity/integrity/digsig.c=42=static struct key *integrity_keyring_from_id(const unsigned int id)\n--\nsecurity/integrity/digsig.c-48-\t\tkeyring[id] =\nsecurity/integrity/digsig.c:49:\t\t\trequest_key(\u0026key_type_keyring, keyring_name[id], NULL);\nsecurity/integrity/digsig.c-50-\t\tif (IS_ERR(keyring[id])) {\n--\nsecurity/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=485=struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,\n--\nsecurity/keys/keyring.c-493-\nsecurity/keys/keyring.c:494:\tkeyring = key_alloc(\u0026key_type_keyring, description,\nsecurity/keys/keyring.c-495-\t\t\t    uid, gid, cred, perm, flags, restrict_link);\n--\nsecurity/keys/keyring.c=633=static int search_keyring_tree(struct key *keyring,\n--\nsecurity/keys/keyring.c-655-\nsecurity/keys/keyring.c:656:\t\tif (key-\u003etype != \u0026key_type_keyring)\nsecurity/keys/keyring.c-657-\t\t\tbreak;\n--\nsecurity/keys/keyring.c=775=key_ref_t keyring_search_rcu(key_ref_t keyring_ref,\n--\nsecurity/keys/keyring.c-787-\nsecurity/keys/keyring.c:788:\tif (keyring-\u003etype != \u0026key_type_keyring)\nsecurity/keys/keyring.c-789-\t\treturn ERR_PTR(-ENOTDIR);\n--\nsecurity/keys/keyring.c=878=static bool keyring_detect_restriction_cycle(const struct key *dest_keyring,\n--\nsecurity/keys/keyring.c-881-\twhile (keyres \u0026\u0026 keyres-\u003ekey \u0026\u0026\nsecurity/keys/keyring.c:882:\t       keyres-\u003ekey-\u003etype == \u0026key_type_keyring) {\nsecurity/keys/keyring.c-883-\t\tif (keyres-\u003ekey == dest_keyring)\n--\nsecurity/keys/keyring.c=902=int keyring_restrict(key_ref_t keyring_ref, const char *type,\n--\nsecurity/keys/keyring.c-912-\nsecurity/keys/keyring.c:913:\tif (keyring-\u003etype != \u0026key_type_keyring)\nsecurity/keys/keyring.c-914-\t\treturn -ENOTDIR;\n--\nsecurity/keys/keyring.c=1116=int __key_link_lock(struct key *keyring,\n--\nsecurity/keys/keyring.c-1120-{\nsecurity/keys/keyring.c:1121:\tif (keyring-\u003etype != \u0026key_type_keyring)\nsecurity/keys/keyring.c-1122-\t\treturn -ENOTDIR;\n--\nsecurity/keys/keyring.c-1128-\t */\nsecurity/keys/keyring.c:1129:\tif (index_key-\u003etype == \u0026key_type_keyring)\nsecurity/keys/keyring.c-1130-\t\tmutex_lock(\u0026keyring_serialise_link_lock);\n--\nsecurity/keys/keyring.c=1138=int __key_move_lock(struct key *l_keyring, struct key *u_keyring,\n--\nsecurity/keys/keyring.c-1143-{\nsecurity/keys/keyring.c:1144:\tif (l_keyring-\u003etype != \u0026key_type_keyring ||\nsecurity/keys/keyring.c:1145:\t    u_keyring-\u003etype != \u0026key_type_keyring)\nsecurity/keys/keyring.c-1146-\t\treturn -ENOTDIR;\n--\nsecurity/keys/keyring.c-1162-\t */\nsecurity/keys/keyring.c:1163:\tif (index_key-\u003etype == \u0026key_type_keyring)\nsecurity/keys/keyring.c-1164-\t\tmutex_lock(\u0026keyring_serialise_link_lock);\n--\nsecurity/keys/keyring.c=1271=int __key_link_check_live_key(struct key *keyring, struct key *key)\nsecurity/keys/keyring.c-1272-{\nsecurity/keys/keyring.c:1273:\tif (key-\u003etype == \u0026key_type_keyring)\nsecurity/keys/keyring.c-1274-\t\t/* check that we aren't going to create a cycle by linking one\n--\nsecurity/keys/keyring.c=1288=void __key_link(struct key *keyring, struct key *key, struct keyring_edit *edit)\n--\nsecurity/keys/keyring.c-1306-\t} else {\nsecurity/keys/keyring.c:1307:\t\tif (key-\u003etype == \u0026key_type_keyring)\nsecurity/keys/keyring.c-1308-\t\t\tlist_add_rcu(\u0026edit-\u003enew-\u003elist, \u0026index-\u003elist);\n--\nsecurity/keys/keyring.c=1325=void __key_link_end(struct key *keyring,\n--\nsecurity/keys/keyring.c-1353-\nsecurity/keys/keyring.c:1354:\tif (index_key-\u003etype == \u0026key_type_keyring)\nsecurity/keys/keyring.c-1355-\t\tmutex_unlock(\u0026keyring_serialise_link_lock);\n--\nsecurity/keys/keyring.c=1425=static int __key_unlink_lock(struct key *keyring)\n--\nsecurity/keys/keyring.c-1427-{\nsecurity/keys/keyring.c:1428:\tif (keyring-\u003etype != \u0026key_type_keyring)\nsecurity/keys/keyring.c-1429-\t\treturn -ENOTDIR;\n--\nsecurity/keys/keyring.c=1595=int keyring_clear(struct key *keyring)\nsecurity/keys/keyring.c-1596-{\nsecurity/keys/keyring.c:1597:\tif (keyring-\u003etype != \u0026key_type_keyring)\nsecurity/keys/keyring.c-1598-\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--\n\n"
}

41/3 2026/11/18 17:02 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 74228
							output: 41
							thoughts: 3141
						

Thoughts:
**Analysis of Keyring Read Vulnerability**

Okay, let's break this down. My initial observation is focused on a change in the `keyring_read` function, specifically around how the iterator interacts with the key serial numbers. The old code used a `keyring_read_iterator_context` which, when compared to the new `keyring_read_context` implementation, has a very simple approach, simply populating the buffer with key serials. The core issue revolves around the interaction between `keyring_read`, `keyctl_read_key`, and the potential for a race condition, potentially leading to information disclosure. The critical piece of this puzzle is the fact that `keyring_gc` *does* modify the keyring contents (removing entries) *while* the read operation might be in progress, without holding the read lock.

Specifically: `keyctl_read_key()` with a sufficiently large buffer calls the keyring's read method. During this read, if `keyring_gc` runs concurrently, it can remove a key from the keyring. The iterator in `keyring_read` relies on `keyring_nr_links(keyring)` to determine the size, however the iterator itself, and the count within the iterator, are updated without the lock.  So, if a key is removed after the initial `keyring_nr_links` calculation but before the iterator has completely walked the keyring, the return value `ret` from `keyring_read` may be inconsistent with what is in the buffer.  This inconsistency could expose uninitialized or stale data potentially copied into the user buffer, especially if `keyctl_read_key` returns a buffer length larger than the actual number of key serials written into the buffer. This is because the caller (e.g., `keyctl_read_key`) allocates memory for the *reported* size but might receive less data.

The older code was similar, although it used a `buflen` check, which doesn't solve the core issue of concurrent modification.  My concern is that, in a multi-threaded scenario, this inconsistency could lead to a read of potentially sensitive information beyond the bounds of the expected data or data of keys that have been de-linked.



42/3 2026/11/18 17:03 tool grepper
0m Args:
{
  "Expression": "invalidate_keyring_keys",
  "PathPrefixes": [
    "arch/s390/kernel/cert_store.c"
  ]
}

Results:
{
  "Output": "arch/s390/kernel/cert_store.c=299=static struct key *get_user_session_keyring(void)\n--\narch/s390/kernel/cert_store.c-313-/* Invalidate all keys from cert_store keyring. */\narch/s390/kernel/cert_store.c:314:static int invalidate_keyring_keys(struct key *keyring)\narch/s390/kernel/cert_store.c-315-{\n--\narch/s390/kernel/cert_store.c=378=static void cleanup_cs_keys(void)\n--\narch/s390/kernel/cert_store.c-391-\t */\narch/s390/kernel/cert_store.c:392:\tif (invalidate_keyring_keys(cs_keyring))\narch/s390/kernel/cert_store.c-393-\t\tunregister_key_type(\u0026key_type_cert_store_key);\n"
}

43/3 2026/11/18 17:03 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 78146
							output: 42
							thoughts: 30
						

Thoughts:
Okay, let's dive into this. Here's my take on those lines of code:

**Analyzing `arch/s390/kernel/cert_store.c` (Lines 314-350)**

Alright, time to get into the nitty-gritty of that certificate store code on s390 architecture, specifically lines 314 through 350. My immediate thought is, "What's the context here? What are we looking at within this broader framework of certificate management?" I'm expecting to see something related to loading, storing, or retrieving certificates, potentially related to secure boot or cryptographic operations, given the kernel context. I need to figure out the exact function being implemented here.

I'm mentally preparing to scrutinize the data structures involved. Are there linked lists, hash tables, or some other organization for these certificates? And more importantly, how is memory being handled? Are we seeing static allocations, dynamic allocations via `kmalloc`, or something more involved, like memory pools? Given this is within kernel space, memory management is always a point of intense focus. Any potential for leaks, fragmentation, or unexpected behavior is a major red flag.

I'm particularly interested in the error handling. I'll be looking for `if` statements, return codes, and any logging or debugging information included. Are we handling various error conditions gracefully, or is there potential for crashes or security vulnerabilities if something goes wrong during certificate operations? The absence of robust error handling is always concerning, especially with something as security-critical as certificate management.

Furthermore, I'll be looking for any indications of synchronization or locking. This code is probably running in a multi-threaded or multi-CPU environment, so concurrent access to the certificate store is a real possibility. Are mutexes, spinlocks, or other synchronization primitives being used to protect the integrity of the data? Race conditions are a nightmare to debug, so I'll be meticulously checking how concurrent access is managed.

Finally, I'll try to identify any performance considerations. Is this code optimized for speed, or is it more concerned with security and robustness? Any hints of optimization techniques, such as caching, prefetching, or efficient algorithms, are worth noting. I know the s390 architecture is well-suited for cryptographic tasks, so I'll be looking for any leverage of hardware acceleration or optimized instructions. Basically, I want to understand how it performs under load and its overall efficiency.



44/3 2026/11/18 17:05 tool read-file
0m Args:
{
  "File": "arch/s390/kernel/cert_store.c",
  "FirstLine": 314,
  "LineCount": 40
}

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

45/3 2026/11/18 17:05 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 79357
							output: 35
							thoughts: 3707
						

Thoughts:
**Analyzing Potential Uninitialized Memory in Keyctl Read Operations**

Okay, so I was looking into this `invalidate_keyring_keys` function in the s390 cert store and noticed it allocates a zeroed array of keys. Then I got a bit worried about `keyctl_read_key` and whether it might be copying uninitialized memory to user space, so I started digging into that.

My first thought was, in `keyctl_read_key`, we have `key_data = kvmalloc(key_data_len, GFP_KERNEL);` – uh oh, uninitialized memory! But then it calls `__keyctl_read_key`, which in turn calls the key type's `read` method. In this case, it calls `keyring_read`.

Now, looking at `keyring_read`, it seemed okay at first, doing some buffer size checks, but then it calls `keyring_iterate`, and that calls `keyring_nr_links`. Wait, how is that number determined? It calls `index ? READ_ONCE(index->nr) : 0;` which is a count of links in the keyring, updated via `WRITE_ONCE` in `__key_link`, `__key_unlink`, and `keyring_gc`.

My concern was how that count is linked to the actual number of elements in the list. I saw that `index->nr` is incremented/decremented with each addition/removal of a link using `list_add_tail_rcu`, `list_replace_rcu`, and `list_del_rcu` respectively. It's essentially the number of elements in the `index->list`. The key thing is that these operations are protected by `down_read(&key->sem)`, so no other writer can add or remove elements while we're reading.

So, `keyring_iterate` iterates over all the elements in the list and copies the serial numbers into the `ctx.serials` array. The number of bytes written to the buffer, `ret`, is then equal to the number of links times the size of a serial.  And that `ret` value is used in the `copy_to_user` function.

Now, if `ret` is greater than `buflen`, `keyctl_read_key` would have previously checked this (`if (ret <= 0 || ret > buflen) break;`). If it breaks and returns `ret`, that value is passed back to userspace, which should know to request a larger buffer, with no memory copy happening.

But if `ret <= buflen`, there's another check, and if `ret > key_data_len`, the buffer is reallocated to be large enough for the second pass, so that the buffer size now matches the return value and the `copy_to_user` copies initialized bytes.

I need to confirm the bytes are initialized and that is happening in `keyring_read_iterator`, and whether there were any potential `NULL` dereferences in this function.

I looked closer, and now I'm thinking, wait, what if `key` is NULL in `keyring_read_iterator`? I checked `keyring_link_key(link)` and saw that that uses `rcu_dereference_check`. Can that ever be `NULL`? I checked the cases and `link->key` is initialized after the link is added to the hash table and list. So it's never NULL in the list. What if it's in the hash table with a `NULL` key? In `keyring_obj_cmpfn`, the key is checked and excluded from being looked up. The `link->hash` is always initialized when the object is created, so a concurrent resize doesn't create problems.

Finally, I carefully checked the patch file-by-file. Turns out the changes are mostly refcounting and error handling fixes in the s390 cert store. I am seeing no real issues related to uninitialized memory. There are also changes related to associative arrays in the key code, changing to `keyring_index`. I did have a look at how key is allocated to make sure there are no other regressions.



46/3 2026/11/18 17:06 tool grepper
0m Args:
{
  "Expression": "kmem_cache_zalloc|kzalloc",
  "PathPrefixes": [
    "security/keys/"
  ]
}

Results:
{
  "Output": "security/keys/dh.c=122=long __keyctl_dh_compute(struct keyctl_dh_params __user *params,\n--\nsecurity/keys/dh.c-235-\nsecurity/keys/dh.c:236:\toutbuf = kzalloc(kdfcopy ? (outlen + kdfcopy-\u003eotherinfolen) : outlen,\nsecurity/keys/dh.c-237-\t\t\t GFP_KERNEL);\n--\nsecurity/keys/encrypted-keys/encrypted.c=332=static int get_derived_key(u8 *derived_key, enum derived_key_type key_type,\n--\nsecurity/keys/encrypted-keys/encrypted.c-341-\nsecurity/keys/encrypted-keys/encrypted.c:342:\tderived_buf = kzalloc(derived_buf_len, GFP_KERNEL);\nsecurity/keys/encrypted-keys/encrypted.c-343-\tif (!derived_buf)\n--\nsecurity/keys/encrypted-keys/encrypted.c=575=static struct encrypted_key_payload *encrypted_key_alloc(struct key *key,\n--\nsecurity/keys/encrypted-keys/encrypted.c-650-\nsecurity/keys/encrypted-keys/encrypted.c:651:\tepayload = kzalloc_flex(*epayload, payload_data, payload_totallen);\nsecurity/keys/encrypted-keys/encrypted.c-652-\tif (!epayload)\n--\nsecurity/keys/key.c=224=struct key *key_alloc(struct key_type *type, const char *desc,\n--\nsecurity/keys/key.c-278-\t/* allocate and initialise the key and its description */\nsecurity/keys/key.c:279:\tkey = kmem_cache_zalloc(key_jar, GFP_KERNEL);\nsecurity/keys/key.c-280-\tif (!key)\n--\nsecurity/keys/keyctl.c=1784=long keyctl_watch_key(key_serial_t id, int watch_queue_fd, int watch_id)\n--\nsecurity/keys/keyctl.c-1809-\t\tif (!key-\u003ewatchers) {\nsecurity/keys/keyctl.c:1810:\t\t\twlist = kzalloc_obj(*wlist);\nsecurity/keys/keyctl.c-1811-\t\t\tif (!wlist)\n--\nsecurity/keys/keyctl.c-1815-\nsecurity/keys/keyctl.c:1816:\t\twatch = kzalloc_obj(*watch);\nsecurity/keys/keyctl.c-1817-\t\tif (!watch)\n--\nsecurity/keys/keyring.c=854=static struct key_restriction *keyring_restriction_alloc(\n--\nsecurity/keys/keyring.c-857-\tstruct key_restriction *keyres =\nsecurity/keys/keyring.c:858:\t\tkzalloc_obj(struct key_restriction);\nsecurity/keys/keyring.c-859-\n--\nsecurity/keys/keyring.c=1169=static struct keyring_index *keyring_get_index(struct key *keyring)\n--\nsecurity/keys/keyring.c-1176-\nsecurity/keys/keyring.c:1177:\tlinks = kzalloc_obj(struct keyring_index);\nsecurity/keys/keyring.c-1178-\tif (!links)\n--\nsecurity/keys/keyring.c=1195=int __key_link_begin(struct key *keyring,\n--\nsecurity/keys/keyring.c-1225-\nsecurity/keys/keyring.c:1226:\tlink = kzalloc_obj(struct keyring_link);\nsecurity/keys/keyring.c-1227-\tif (!link) {\n--\nsecurity/keys/request_key_auth.c=195=struct key *request_key_auth_new(struct key *target, const char *op,\n--\nsecurity/keys/request_key_auth.c-207-\t/* allocate a auth record */\nsecurity/keys/request_key_auth.c:208:\trka = kzalloc_obj(*rka);\nsecurity/keys/request_key_auth.c-209-\tif (!rka)\n--\nsecurity/keys/trusted-keys/trusted_core.c=135=static struct trusted_key_payload *trusted_payload_alloc(struct key *key)\n--\nsecurity/keys/trusted-keys/trusted_core.c-142-\t\tgoto err;\nsecurity/keys/trusted-keys/trusted_core.c:143:\tp = kzalloc_obj(*p);\nsecurity/keys/trusted-keys/trusted_core.c-144-\tif (!p)\n--\nsecurity/keys/trusted-keys/trusted_pkwm.c=60=static struct trusted_key_options *trusted_options_alloc(void)\n--\nsecurity/keys/trusted-keys/trusted_pkwm.c-64-\nsecurity/keys/trusted-keys/trusted_pkwm.c:65:\toptions = kzalloc_obj(*options);\nsecurity/keys/trusted-keys/trusted_pkwm.c-66-\nsecurity/keys/trusted-keys/trusted_pkwm.c-67-\tif (options) {\nsecurity/keys/trusted-keys/trusted_pkwm.c:68:\t\tpkwm = kzalloc_obj(*pkwm);\nsecurity/keys/trusted-keys/trusted_pkwm.c-69-\n--\nsecurity/keys/trusted-keys/trusted_tpm1.c=628=static int key_seal(struct trusted_key_payload *p,\n--\nsecurity/keys/trusted-keys/trusted_tpm1.c-633-\nsecurity/keys/trusted-keys/trusted_tpm1.c:634:\tstruct tpm_buf *tb __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);\nsecurity/keys/trusted-keys/trusted_tpm1.c-635-\tif (!tb)\n--\nsecurity/keys/trusted-keys/trusted_tpm1.c=656=static int key_unseal(struct trusted_key_payload *p,\n--\nsecurity/keys/trusted-keys/trusted_tpm1.c-661-\nsecurity/keys/trusted-keys/trusted_tpm1.c:662:\tstruct tpm_buf *tb __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);\nsecurity/keys/trusted-keys/trusted_tpm1.c-663-\tif (!tb)\n--\nsecurity/keys/trusted-keys/trusted_tpm1.c=837=static struct trusted_key_options *trusted_options_alloc(bool is_tpm2)\n--\nsecurity/keys/trusted-keys/trusted_tpm1.c-841-\nsecurity/keys/trusted-keys/trusted_tpm1.c:842:\toptions = kzalloc_obj(*options);\nsecurity/keys/trusted-keys/trusted_tpm1.c-843-\tif (options) {\n--\nsecurity/keys/trusted-keys/trusted_tpm1.c-846-\nsecurity/keys/trusted-keys/trusted_tpm1.c:847:\t\tprivate = kzalloc_obj(*private);\nsecurity/keys/trusted-keys/trusted_tpm1.c-848-\t\tif (!private) {\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_tpm2.c=239=int tpm2_seal_trusted(struct tpm_chip *chip,\n--\nsecurity/keys/trusted-keys/trusted_tpm2.c-266-\nsecurity/keys/trusted-keys/trusted_tpm2.c:267:\tbuf = kzalloc(TPM_BUFSIZE, GFP_KERNEL);\nsecurity/keys/trusted-keys/trusted_tpm2.c-268-\tif (!buf) {\n--\nsecurity/keys/trusted-keys/trusted_tpm2.c-276-\nsecurity/keys/trusted-keys/trusted_tpm2.c:277:\tsized = kzalloc(TPM_BUFSIZE, GFP_KERNEL);\nsecurity/keys/trusted-keys/trusted_tpm2.c-278-\tif (!sized) {\n--\nsecurity/keys/trusted-keys/trusted_tpm2.c=384=static int tpm2_load_cmd(struct tpm_chip *chip,\n--\nsecurity/keys/trusted-keys/trusted_tpm2.c-445-\nsecurity/keys/trusted-keys/trusted_tpm2.c:446:\tbuf = kzalloc(TPM_BUFSIZE, GFP_KERNEL);\nsecurity/keys/trusted-keys/trusted_tpm2.c-447-\tif (!buf) {\n--\nsecurity/keys/trusted-keys/trusted_tpm2.c=494=static int tpm2_unseal_cmd(struct tpm_chip *chip,\n--\nsecurity/keys/trusted-keys/trusted_tpm2.c-510-\nsecurity/keys/trusted-keys/trusted_tpm2.c:511:\tbuf = kzalloc(TPM_BUFSIZE, GFP_KERNEL);\nsecurity/keys/trusted-keys/trusted_tpm2.c-512-\tif (!buf) {\n"
}

47/3 2026/11/18 17:06 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 86446
							output: 35
							thoughts: 715
						

Thoughts:
**Memory Allocation and Key Indexing: A Deep Dive**

Okay, so I'm looking at this code and immediately noticing a pattern: everything's zero-initialized during allocation. We've got `kmem_cache_zalloc` for `key_jar`, `kzalloc_obj` for `keyring_index` and `keyring_link`, and even the `struct keyring_edit edit = {};` declarations are effectively zeroing the struct. Good, good - consistent initialization helps avoid subtle bugs.

Now, let's pivot to `key_set_index_key`. This function finalizes an index key by setting the domain tag and calculating the hash. It looks like it handles the `domain_tag` logic. If it's not already set, it checks for a `KEY_TYPE_NET_DOMAIN` flag and potentially uses the current network namespace's domain tag. If *that* fails, it falls back to a default domain tag. Nothing obviously wrong there.

The interesting part is how the hash is calculated in `hash_key_type_and_desc`. They are computing a SipHash value using the description, the type pointer, and the domain tag pointer, with a per-boot random key. They're explicitly pointing out that the pointer-based input is safe because SipHash is cryptographically secure. Truncating the SipHash value to 32 bits is also deemed safe, which aligns with my understanding of SipHash's properties.

But wait, where is `index_key` *created* in the first place? I need to track down the instantiation of `struct keyring_index_key`. Let's see... Ah, there it is in `__key_create_or_update`. It looks like it's a stack variable here. The `type` and `description` are getting set, but... hmm... where is `.desc_len` getting set? This warrants further investigation. Let me check the surrounding lines in `security/keys/key.c` around line 825.



48/3 2026/11/18 17:08 tool read-file
0m Args:
{
  "File": "security/keys/key.c",
  "FirstLine": 820,
  "LineCount": 45
}

Results:
{
  "Contents": " 820:\t\t\t\t\t\tkey_perm_t perm,\n 821:\t\t\t\t\t\tunsigned long flags,\n 822:\t\t\t\t\t\tbool allow_update)\n 823:\t{\n 824:\t\tstruct keyring_index_key index_key = {\n 825:\t\t\t.description\t= description,\n 826:\t\t};\n 827:\t\tstruct key_preparsed_payload prep;\n 828:\t\tstruct keyring_edit edit = {};\n 829:\t\tconst struct cred *cred = current_cred();\n 830:\t\tstruct key *keyring, *key = NULL;\n 831:\t\tkey_ref_t key_ref;\n 832:\t\tint ret;\n 833:\t\tstruct key_restriction *restrict_link = NULL;\n 834:\t\tsize_t desclen;\n 835:\t\n 836:\t\t/* look up the key type to see if it's one of the registered kernel\n 837:\t\t * types */\n 838:\t\tindex_key.type = key_type_lookup(type);\n 839:\t\tif (IS_ERR(index_key.type)) {\n 840:\t\t\tkey_ref = ERR_PTR(-ENODEV);\n 841:\t\t\tgoto error;\n 842:\t\t}\n 843:\t\n 844:\t\tkey_ref = ERR_PTR(-EINVAL);\n 845:\t\tif (!index_key.type-\u003einstantiate ||\n 846:\t\t    (!index_key.description \u0026\u0026 !index_key.type-\u003epreparse))\n 847:\t\t\tgoto error_put_type;\n 848:\t\n 849:\t\tkeyring = key_ref_to_ptr(keyring_ref);\n 850:\t\n 851:\t\tkey_check(keyring);\n 852:\t\n 853:\t\tkey_ref = ERR_PTR(-ENOTDIR);\n 854:\t\tif (keyring-\u003etype != \u0026key_type_keyring)\n 855:\t\t\tgoto error_put_type;\n 856:\t\n 857:\t\tmemset(\u0026prep, 0, sizeof(prep));\n 858:\t\tprep.orig_description = description;\n 859:\t\tprep.data = payload;\n 860:\t\tprep.datalen = plen;\n 861:\t\tprep.quotalen = index_key.type-\u003edef_datalen;\n 862:\t\tprep.expiry = TIME64_MAX;\n 863:\t\tif (index_key.type-\u003epreparse) {\n 864:\t\t\tret = index_key.type-\u003epreparse(\u0026prep);\n"
}

49/3 2026/11/18 17:08 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 88309
							output: 35
							thoughts: 52
						

Thoughts:
Here's my summary, as if I were thinking it:

**Digging into the `index_key.desc_len` Initialization**

Okay, so I need to track down the initialization of `index_key.desc_len`. Time to get into the weeds of the key management code. Let's see... the `__key_create_or_update` function is the most likely place. So, I'll jump right into `security/keys/key.c` and zero in on lines 865 through 905. That should be the relevant section to analyze how `index_key.desc_len` is being set, and where. Hopefully, the code is well-structured enough for a quick read-through to reveal the details. It could be directly assigned, or derived from another value in there; I need to follow the logic.



50/3 2026/11/18 17:09 tool read-file
0m Args:
{
  "File": "security/keys/key.c",
  "FirstLine": 865,
  "LineCount": 40
}

Results:
{
  "Contents": " 865:\t\t\tif (ret \u003c 0) {\n 866:\t\t\t\tkey_ref = ERR_PTR(ret);\n 867:\t\t\t\tgoto error_free_prep;\n 868:\t\t\t}\n 869:\t\t\tif (!index_key.description)\n 870:\t\t\t\tindex_key.description = prep.description;\n 871:\t\t\tkey_ref = ERR_PTR(-EINVAL);\n 872:\t\t\tif (!index_key.description)\n 873:\t\t\t\tgoto error_free_prep;\n 874:\t\t}\n 875:\t\tdesclen = strlen(index_key.description);\n 876:\t\tif (desclen \u003e= KEY_MAX_DESC_SIZE) {\n 877:\t\t\tkey_ref = ERR_PTR(-EINVAL);\n 878:\t\t\tgoto error_free_prep;\n 879:\t\t}\n 880:\t\tindex_key.desc_len = desclen;\n 881:\t\tkey_set_index_key(\u0026index_key);\n 882:\t\n 883:\t\tret = __key_link_lock(keyring, \u0026index_key);\n 884:\t\tif (ret \u003c 0) {\n 885:\t\t\tkey_ref = ERR_PTR(ret);\n 886:\t\t\tgoto error_free_prep;\n 887:\t\t}\n 888:\t\n 889:\t\tret = __key_link_begin(keyring, \u0026index_key, \u0026edit);\n 890:\t\tif (ret \u003c 0) {\n 891:\t\t\tkey_ref = ERR_PTR(ret);\n 892:\t\t\tgoto error_link_end;\n 893:\t\t}\n 894:\t\n 895:\t\tif (!(flags \u0026 KEY_ALLOC_BYPASS_RESTRICTION))\n 896:\t\t\trestrict_link = keyring-\u003erestrict_link;\n 897:\t\n 898:\t\tif (restrict_link \u0026\u0026 restrict_link-\u003echeck) {\n 899:\t\t\tret = restrict_link-\u003echeck(keyring, index_key.type,\n 900:\t\t\t\t\t\t   \u0026prep.payload, restrict_link-\u003ekey);\n 901:\t\t\tif (ret \u003c 0) {\n 902:\t\t\t\tkey_ref = ERR_PTR(ret);\n 903:\t\t\t\tgoto error_link_end;\n 904:\t\t\t}\n"
}

51/3 2026/11/18 17:09 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 89194
							output: 20
							thoughts: 90
						

Thoughts:
Here's my understanding of the situation, given my expertise:

**Analyzing `struct keyring_index_key` Initialization and Usage**

Okay, so I see that `index_key.desc_len` is being explicitly set. That's a key detail. What's clever is that the initializers are explicitly zeroing out fields not mentioned, like `domain_tag`, which, by default, sets it to NULL.  This is a good, clean approach to ensure a known state.

The core of this seems to be happening in the `key_set_index_key(&index_key)` function.  It's responsible for setting the `domain_tag` if it's currently NULL and then, most critically, calling `hash_key_type_and_desc(&index_key)`. That latter call is where the real work happens. It's likely involved with hashing or deriving some critical metadata based on the key type and description.

Now, I need to understand the implications of this approach. We've got `desc_len` set explicitly, fields zeroed in initializers (and overwritten if necessary via `key_set_index_key`), and then the crucial hashing.

I'm thinking about the different usages of this structure, trying to understand how this pattern fits into the overall keyring design.  What I need to do now is go dig into the other places where `struct keyring_index_key` is used.  That will give me the full picture. My focus will be on understanding how `desc_len`, the zero-initialization, the potential assignment of `domain_tag` (from NULL), and the hashing relate to the overall performance, security, and integrity of the keyring operations.



52/3 2026/11/18 17:10 tool grepper
0m Args:
{
  "Expression": "struct keyring_index_key"
}

Results:
{
  "Output": "include/linux/key.h=111=struct key_tag {\n--\ninclude/linux/key.h-116-\ninclude/linux/key.h:117:struct keyring_index_key {\ninclude/linux/key.h-118-\t/* [!] If this structure is altered, the union in struct key must change too! */\n--\ninclude/linux/key.h=187=struct key {\n--\ninclude/linux/key.h-238-\tunion {\ninclude/linux/key.h:239:\t\tstruct keyring_index_key index_key;\ninclude/linux/key.h-240-\t\tstruct {\n--\nsecurity/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/internal.h=101=extern int __key_link_lock(struct key *keyring,\nsecurity/keys/internal.h:102:\t\t\t   const struct keyring_index_key *index_key);\nsecurity/keys/internal.h-103-extern int __key_move_lock(struct key *l_keyring, struct key *u_keyring,\nsecurity/keys/internal.h:104:\t\t\t   const struct keyring_index_key *index_key);\nsecurity/keys/internal.h-105-extern int __key_link_begin(struct key *keyring,\nsecurity/keys/internal.h:106:\t\t\t    const struct keyring_index_key *index_key,\nsecurity/keys/internal.h-107-\t\t\t    struct keyring_edit *edit);\n--\nsecurity/keys/internal.h=111=extern void __key_link_end(struct key *keyring,\nsecurity/keys/internal.h:112:\t\t\t   const struct keyring_index_key *index_key,\nsecurity/keys/internal.h-113-\t\t\t   struct keyring_edit *edit);\n--\nsecurity/keys/internal.h=115=extern key_ref_t find_key_to_update(key_ref_t keyring_ref,\nsecurity/keys/internal.h:116:\t\t\t\t    const struct keyring_index_key *index_key);\nsecurity/keys/internal.h-117-\nsecurity/keys/internal.h=118=struct keyring_search_context {\nsecurity/keys/internal.h:119:\tstruct keyring_index_key index_key;\nsecurity/keys/internal.h-120-\tconst struct cred\t*cred;\n--\nsecurity/keys/key.c=815=static key_ref_t __key_create_or_update(key_ref_t keyring_ref,\n--\nsecurity/keys/key.c-823-{\nsecurity/keys/key.c:824:\tstruct keyring_index_key index_key = {\nsecurity/keys/key.c-825-\t\t.description\t= description,\n--\nsecurity/keys/keyring.c=58=static u32 keyring_hashfn(const void *data, u32 len, u32 seed)\nsecurity/keys/keyring.c-59-{\nsecurity/keys/keyring.c:60:\tconst struct keyring_index_key *index_key = data;\nsecurity/keys/keyring.c-61-\n--\nsecurity/keys/keyring.c=65=static u32 keyring_obj_hashfn(const void *data, u32 len, u32 seed)\n--\nsecurity/keys/keyring.c-71-\nsecurity/keys/keyring.c:72:static bool keyring_index_key_equal(const struct keyring_index_key *a,\nsecurity/keys/keyring.c:73:\t\t\t\t    const struct keyring_index_key *b)\nsecurity/keys/keyring.c-74-{\n--\nsecurity/keys/keyring.c=112=static struct keyring_link *keyring_find_link(struct keyring_index *index,\nsecurity/keys/keyring.c:113:\t\t\t\t\t      const struct keyring_index_key *index_key)\nsecurity/keys/keyring.c-114-{\n--\nsecurity/keys/keyring.c=272=static int keyring_instantiate(struct key *keyring,\n--\nsecurity/keys/keyring.c-283- */\nsecurity/keys/keyring.c:284:static void hash_key_type_and_desc(struct keyring_index_key *index_key)\nsecurity/keys/keyring.c-285-{\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=979=key_ref_t find_key_to_update(key_ref_t keyring_ref,\nsecurity/keys/keyring.c:980:\t\t\t     const struct keyring_index_key *index_key)\nsecurity/keys/keyring.c-981-{\n--\nsecurity/keys/keyring.c=1116=int __key_link_lock(struct key *keyring,\nsecurity/keys/keyring.c:1117:\t\t    const struct keyring_index_key *index_key)\nsecurity/keys/keyring.c-1118-\t__acquires(\u0026keyring-\u003esem)\n--\nsecurity/keys/keyring.c=1138=int __key_move_lock(struct key *l_keyring, struct key *u_keyring,\nsecurity/keys/keyring.c:1139:\t\t    const struct keyring_index_key *index_key)\nsecurity/keys/keyring.c-1140-\t__acquires(\u0026l_keyring-\u003esem)\n--\nsecurity/keys/keyring.c=1195=int __key_link_begin(struct key *keyring,\nsecurity/keys/keyring.c:1196:\t\t     const struct keyring_index_key *index_key,\nsecurity/keys/keyring.c-1197-\t\t     struct keyring_edit *edit)\n--\nsecurity/keys/keyring.c=1325=void __key_link_end(struct key *keyring,\nsecurity/keys/keyring.c:1326:\t\t    const struct keyring_index_key *index_key,\nsecurity/keys/keyring.c-1327-\t\t    struct keyring_edit *edit)\n--\nsecurity/keys/persistent.c=44=static int key_get_or_create_persistent(struct user_namespace *ns, kuid_t uid,\nsecurity/keys/persistent.c:45:\t\t\t\t\tstruct keyring_index_key *index_key,\nsecurity/keys/persistent.c-46-\t\t\t\t\tkey_ref_t *persistent_ref)\n--\nsecurity/keys/persistent.c=80=static long key_get_persistent(struct user_namespace *ns, kuid_t uid,\n--\nsecurity/keys/persistent.c-82-{\nsecurity/keys/persistent.c:83:\tstruct keyring_index_key index_key;\nsecurity/keys/persistent.c-84-\tstruct key *persistent;\n"
}

53/3 2026/11/18 17:10 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 91531
							output: 34
							thoughts: 22
						

Thoughts:
Here's my analysis of the provided thought process, tailored for an expert audience:

**Diving into `persistent.c`**

Okay, so the mental breadcrumb trail leads me directly to `security/keys/persistent.c`, specifically lines 80 through 110. My intuition, based on the context I *haven't* been given, is that there's a problem I need to get to the bottom of. That section of the code likely deals with some core aspect of persistent key management. Knowing the kernel's key subsystem, that's almost certainly the zone handling the persistence of keys, potentially related to storage, retrieval, or some crucial lifecycle operation. I'm immediately running through possible failure scenarios – is this around key revocation, key expiration, or a permissions problem? Or, perhaps, a memory leak or race condition? Given that section of the source file, my mind goes to the persistence and storage, is this a file-system issue? I need to quickly analyze that block to understand the precise interaction and quickly correlate that with any recent changes or reported issues that might be related.



54/3 2026/11/18 17:11 tool read-file
0m Args:
{
  "File": "security/keys/persistent.c",
  "FirstLine": 80,
  "LineCount": 35
}

Results:
{
  "Contents": "  80:\tstatic long key_get_persistent(struct user_namespace *ns, kuid_t uid,\n  81:\t\t\t\t       key_ref_t dest_ref)\n  82:\t{\n  83:\t\tstruct keyring_index_key index_key;\n  84:\t\tstruct key *persistent;\n  85:\t\tkey_ref_t reg_ref, persistent_ref;\n  86:\t\tchar buf[32];\n  87:\t\tlong ret;\n  88:\t\tbool created = false;\n  89:\t\n  90:\t\t/* Look in the register if it exists */\n  91:\t\tmemset(\u0026index_key, 0, sizeof(index_key));\n  92:\t\tindex_key.type = \u0026key_type_keyring;\n  93:\t\tindex_key.description = buf;\n  94:\t\tindex_key.desc_len = sprintf(buf, \"_persistent.%u\", from_kuid(ns, uid));\n  95:\t\tkey_set_index_key(\u0026index_key);\n  96:\t\n  97:\t\tif (ns-\u003epersistent_keyring_register) {\n  98:\t\t\treg_ref = make_key_ref(ns-\u003epersistent_keyring_register, true);\n  99:\t\t\tdown_read(\u0026ns-\u003ekeyring_sem);\n 100:\t\t\tpersistent_ref = find_key_to_update(reg_ref, \u0026index_key);\n 101:\t\t\tup_read(\u0026ns-\u003ekeyring_sem);\n 102:\t\n 103:\t\t\tif (persistent_ref)\n 104:\t\t\t\tgoto found;\n 105:\t\t}\n 106:\t\n 107:\t\t/* It wasn't in the register, so we'll need to create it.  We might\n 108:\t\t * also need to create the register.\n 109:\t\t */\n 110:\t\tdown_write(\u0026ns-\u003ekeyring_sem);\n 111:\t\tret = key_get_or_create_persistent(ns, uid, \u0026index_key,\n 112:\t\t\t\t\t\t   \u0026persistent_ref);\n 113:\t\tup_write(\u0026ns-\u003ekeyring_sem);\n 114:\t\tif (ret \u003c 0)\n"
}

55/3 2026/11/18 17:11 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 92386
							output: 31
							thoughts: 65
						

Thoughts:
Here's my analysis of the provided code snippet:

**Initialization and Context Preparation**

Okay, so I see a `memset` being used to zero out the `index_key` structure.  That's a standard initialization step, clearing the memory before we start. Now, let me dig into this. I'm going to jump straight into `security/keys/keyring.c` to see how this `index_key` is being used within the keyring search operations. I'm specifically interested in the `keyring_search` and `keyring_search_rcu` functions. I want to understand how the `struct keyring_search_context` is being set up in this context.  I'll probably trace how the `index_key` is fed into the search context and what implications that has on the overall key lookup process. I'm expecting some clever use of the context for synchronization or efficient searching, given the RCU involvement. Let's get to the bottom of this.



56/3 2026/11/18 17:12 tool grepper
0m Args:
{
  "Expression": "struct keyring_search_context",
  "PathPrefixes": [
    "security/keys/"
  ]
}

Results:
{
  "Output": "security/keys/internal.h=115=extern key_ref_t find_key_to_update(key_ref_t keyring_ref,\n--\nsecurity/keys/internal.h-117-\nsecurity/keys/internal.h:118:struct keyring_search_context {\nsecurity/keys/internal.h-119-\tstruct keyring_index_key index_key;\n--\nsecurity/keys/internal.h=142=extern key_ref_t keyring_search_rcu(key_ref_t keyring_ref,\nsecurity/keys/internal.h:143:\t\t\t\t    struct keyring_search_context *ctx);\nsecurity/keys/internal.h-144-\nsecurity/keys/internal.h:145:extern key_ref_t search_cred_keyrings_rcu(struct keyring_search_context *ctx);\nsecurity/keys/internal.h:146:extern key_ref_t search_process_keyrings_rcu(struct keyring_search_context *ctx);\nsecurity/keys/internal.h-147-\n--\nsecurity/keys/keyring.c=542=static int keyring_search_iterator(const struct key *key, void *iterator_data)\nsecurity/keys/keyring.c-543-{\nsecurity/keys/keyring.c:544:\tstruct keyring_search_context *ctx = iterator_data;\nsecurity/keys/keyring.c-545-\tunsigned long kflags = READ_ONCE(key-\u003eflags);\n--\nsecurity/keys/keyring.c-612- */\nsecurity/keys/keyring.c:613:static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)\nsecurity/keys/keyring.c-614-{\n--\nsecurity/keys/keyring.c=633=static int search_keyring_tree(struct key *keyring,\nsecurity/keys/keyring.c:634:\t\t\t       struct keyring_search_context *ctx, int depth)\nsecurity/keys/keyring.c-635-{\n--\nsecurity/keys/keyring.c=689=static bool search_nested_keyrings(struct key *keyring,\nsecurity/keys/keyring.c:690:\t\t\t\t   struct keyring_search_context *ctx)\nsecurity/keys/keyring.c-691-{\n--\nsecurity/keys/keyring.c=775=key_ref_t keyring_search_rcu(key_ref_t keyring_ref,\nsecurity/keys/keyring.c:776:\t\t\t     struct keyring_search_context *ctx)\nsecurity/keys/keyring.c-777-{\n--\nsecurity/keys/keyring.c=813=key_ref_t keyring_search(key_ref_t keyring,\n--\nsecurity/keys/keyring.c-817-{\nsecurity/keys/keyring.c:818:\tstruct keyring_search_context ctx = {\nsecurity/keys/keyring.c-819-\t\t.index_key.type\t\t= type,\n--\nsecurity/keys/keyring.c=1070=static int keyring_detect_cycle_iterator(const struct key *key,\n--\nsecurity/keys/keyring.c-1072-{\nsecurity/keys/keyring.c:1073:\tstruct keyring_search_context *ctx = iterator_data;\nsecurity/keys/keyring.c-1074-\n--\nsecurity/keys/keyring.c=1093=static int keyring_detect_cycle(struct key *A, struct key *B)\nsecurity/keys/keyring.c-1094-{\nsecurity/keys/keyring.c:1095:\tstruct keyring_search_context ctx = {\nsecurity/keys/keyring.c-1096-\t\t.index_key\t\t= A-\u003eindex_key,\n--\nsecurity/keys/proc.c=153=static int proc_keys_show(struct seq_file *m, void *v)\n--\nsecurity/keys/proc.c-164-\nsecurity/keys/proc.c:165:\tstruct keyring_search_context ctx = {\nsecurity/keys/proc.c-166-\t\t.index_key\t\t= key-\u003eindex_key,\n--\nsecurity/keys/process_keys.c=195=struct key *get_user_session_keyring_rcu(const struct cred *cred)\n--\nsecurity/keys/process_keys.c-200-\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,\n--\nsecurity/keys/process_keys.c=400=void key_fsgid_changed(struct cred *new_cred)\n--\nsecurity/keys/process_keys.c-431- */\nsecurity/keys/process_keys.c:432:key_ref_t search_cred_keyrings_rcu(struct keyring_search_context *ctx)\nsecurity/keys/process_keys.c-433-{\n--\nsecurity/keys/process_keys.c-548- */\nsecurity/keys/process_keys.c:549:key_ref_t search_process_keyrings_rcu(struct keyring_search_context *ctx)\nsecurity/keys/process_keys.c-550-{\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-668-{\nsecurity/keys/process_keys.c:669:\tstruct keyring_search_context ctx = {\nsecurity/keys/process_keys.c-670-\t\t.match_data.cmp\t\t= lookup_user_key_possessed,\n--\nsecurity/keys/request_key.c-21-\nsecurity/keys/request_key.c:22:static struct key *check_cached_key(struct keyring_search_context *ctx)\nsecurity/keys/request_key.c-23-{\n--\nsecurity/keys/request_key.c=265=static int construct_get_dest_keyring(struct key **_dest_keyring)\n--\nsecurity/keys/request_key.c-368- */\nsecurity/keys/request_key.c:369:static int construct_alloc_key(struct keyring_search_context *ctx,\nsecurity/keys/request_key.c-370-\t\t\t       struct key *dest_keyring,\n--\nsecurity/keys/request_key.c-488- */\nsecurity/keys/request_key.c:489:static struct key *construct_key_and_link(struct keyring_search_context *ctx,\nsecurity/keys/request_key.c-490-\t\t\t\t\t  const char *callout_info,\n--\nsecurity/keys/request_key.c=574=struct key *request_key_and_link(struct key_type *type,\n--\nsecurity/keys/request_key.c-582-{\nsecurity/keys/request_key.c:583:\tstruct keyring_search_context ctx = {\nsecurity/keys/request_key.c-584-\t\t.index_key.type\t\t= type,\n--\nsecurity/keys/request_key.c=787=struct key *request_key_rcu(struct key_type *type,\n--\nsecurity/keys/request_key.c-790-{\nsecurity/keys/request_key.c:791:\tstruct keyring_search_context ctx = {\nsecurity/keys/request_key.c-792-\t\t.index_key.type\t\t= type,\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-283-\tchar description[16];\nsecurity/keys/request_key_auth.c:284:\tstruct keyring_search_context ctx = {\nsecurity/keys/request_key_auth.c-285-\t\t.index_key.type\t\t= \u0026key_type_request_key_auth,\n"
}

57/3 2026/11/18 17:12 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 94742
							output: 30
							thoughts: 3104
						

Thoughts:
**Analysis of Keyring Data Structures and Potential Security Considerations**

Alright, let's break this down systematically. My initial impression is that the changes are primarily focused on performance and internal consistency within the keyring implementation. The first thing I notice is the initialization of the `struct keyring_search_context ctx`. This appears to be a standard pattern, so nothing immediately jumps out.

I then went through the `struct keyring_index_key` and its relation to the `struct key`. The key point here is the careful alignment of the `struct keyring_index_key` fields within the `union` inside `struct key`. I confirmed the layout ensures no padding on a 64-bit architecture, which is critical for efficient memory access. This matching structure implies that access to these elements will be consistent between both structures.

I moved on to `keyring_index_key_equal`, it uses `memcmp` which appears safe as the length check is done beforehand, ensuring no out-of-bounds reads. The assumption that `description` is a null-terminated string or a pre-parsed description is sound.

The next point of focus was information leaks, or any unintended data transfer to user space. It is a critical check to verify that data is not leaked to the user. I investigated `keyctl_read_key`, which copies `key_serial_t` (a 32-bit integer) to a user-space buffer. I verified that all elements of the array are properly initialized before being copied. I confirmed that the number of elements is always accurate using the `keyring_nr_links` function. A read-write lock, held by `down_read` protects against concurrent modification during the read operation. This locking mechanism prevents any data races or inconsistencies, and I checked that there are no calls to `key_type_keyring.read` without this lock being held.

Moving to the recursive search (`search_keyring_tree`) I examined the new depth-first approach. It appears to be a clean and controlled implementation, limiting the recursion depth to a maximum of six levels. The function initializes all variables before use, the use of `rcu_dereference` and the `list_for_each_entry_rcu` loop is also consistent. The "break" logic in the loop indicates that keyrings are stored at the head of the list; therefore, once a non-keyring entry is encountered, the search can stop to optimize the recursion. I also checked that there are no possibilities of non-keyrings replacing keyrings, given the key identification by (type, description).

Then I investigated the key lookup with `find_cs_keyring`, `request_key`, `key_ref_to_ptr` are standard, and the calls are safe.

Finally, I checked the new `bpf_lookup_keyring` implementation, and the `keyring_is_empty` function. Both functions look clean and do exactly what is expected.

I didn't find any kernel structures being transmitted to user space, so no uninitialized or potentially dangerous data is exposed. I also verified the usage of any `copy_to_user` calls within `security/keys` and found nothing of concern. Overall, the modifications seem safe and well-considered.



58/3 2026/11/18 17:12 tool grepper
0m Args:
{
  "Expression": "copy_to_user",
  "PathPrefixes": [
    "security/keys/"
  ]
}

Results:
{
  "Output": "security/keys/dh.c=94=static int keyctl_dh_compute_kdf(struct crypto_shash *hash,\n--\nsecurity/keys/dh.c-113-\tret = buflen;\nsecurity/keys/dh.c:114:\tif (copy_to_user(buffer, outbuf, buflen) != 0)\nsecurity/keys/dh.c-115-\t\tret = -EFAULT;\n--\nsecurity/keys/dh.c=122=long __keyctl_dh_compute(struct keyctl_dh_params __user *params,\n--\nsecurity/keys/dh.c-278-\t\t\t\t\t    req-\u003edst_len + kdfcopy-\u003eotherinfolen);\nsecurity/keys/dh.c:279:\t} else if (copy_to_user(buffer, outbuf, req-\u003edst_len) == 0) {\nsecurity/keys/dh.c-280-\t\tret = req-\u003edst_len;\n--\nsecurity/keys/keyctl.c=642=long keyctl_describe_key(key_serial_t keyid,\n--\nsecurity/keys/keyctl.c-692-\tif (buffer \u0026\u0026 buflen \u003e= ret) {\nsecurity/keys/keyctl.c:693:\t\tif (copy_to_user(buffer, infobuf, infolen) != 0 ||\nsecurity/keys/keyctl.c:694:\t\t    copy_to_user(buffer + infolen, key-\u003edescription,\nsecurity/keys/keyctl.c-695-\t\t\t\t desclen + 1) != 0)\n--\nsecurity/keys/keyctl.c=829=long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)\n--\nsecurity/keys/keyctl.c-920-\nsecurity/keys/keyctl.c:921:\t\tif (copy_to_user(buffer, key_data, ret))\nsecurity/keys/keyctl.c-922-\t\t\tret = -EFAULT;\n--\nsecurity/keys/keyctl.c=1572=long keyctl_get_security(key_serial_t keyid,\n--\nsecurity/keys/keyctl.c-1605-\t\tif (buffer \u0026\u0026 buflen \u003e 0 \u0026\u0026\nsecurity/keys/keyctl.c:1606:\t\t    copy_to_user(buffer, \"\", 1) != 0)\nsecurity/keys/keyctl.c-1607-\t\t\tret = -EFAULT;\n--\nsecurity/keys/keyctl.c-1613-\nsecurity/keys/keyctl.c:1614:\t\t\tif (copy_to_user(buffer, context, buflen) != 0)\nsecurity/keys/keyctl.c-1615-\t\t\t\tret = -EFAULT;\n--\nsecurity/keys/keyctl.c=1865=long keyctl_capabilities(unsigned char __user *_buffer, size_t buflen)\n--\nsecurity/keys/keyctl.c-1871-\t\t\tsize = sizeof(keyrings_capabilities);\nsecurity/keys/keyctl.c:1872:\t\tif (copy_to_user(_buffer, keyrings_capabilities, size) != 0)\nsecurity/keys/keyctl.c-1873-\t\t\treturn -EFAULT;\n--\nsecurity/keys/keyctl_pkey.c=208=long keyctl_pkey_query(key_serial_t id,\n--\nsecurity/keys/keyctl_pkey.c-233-\tret = -EFAULT;\nsecurity/keys/keyctl_pkey.c:234:\tif (copy_to_user(_res, \u0026res, sizeof(res)) == 0 \u0026\u0026\nsecurity/keys/keyctl_pkey.c-235-\t    clear_user(_res-\u003e__spare, sizeof(_res-\u003e__spare)) == 0)\n--\nsecurity/keys/keyctl_pkey.c=260=long keyctl_pkey_e_d_s(int op,\n--\nsecurity/keys/keyctl_pkey.c-312-\nsecurity/keys/keyctl_pkey.c:313:\tif (copy_to_user(_out, out, ret) != 0)\nsecurity/keys/keyctl_pkey.c-314-\t\tret = -EFAULT;\n"
}

59/3 2026/11/18 17:12 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 99635
							output: 415
							thoughts: 1140
						

Thoughts:
**KMSAN Assessment: NeedsKMSAN = false**

Okay, let's break this down. My goal here is to determine if this refactor warrants KMSAN (Kernel Memory Sanitizer) enabled. I need to make sure I'm not introducing any potential for uninitialized memory reads or information leaks.

First, I've got a good handle on what the patch *actually* does. It's refactoring the keyring index storage, replacing the old `assoc_array` with a `rhashtable` and `list_head` combo. It also simplifies key hashing with SipHash, tidies up keyring emptiness checks in dm-verity and fsverity, cleans up obsolete code, and fixes some reference counting and error handling in s390's `cert_store.c`.

Now, the crucial point: memory allocation and initialization. *All* the heap-allocated structures that are new or touched by this refactor – `keyring_index` and `keyring_link` – are allocated using `kzalloc_obj`. This is critical. `kzalloc_obj` guarantees that all allocated memory is zero-initialized. Zero initialization is *key*. On the stack, instances like `keyring_edit`, `keyring_search_context`, and `keyring_read_context` are zero-initialized with `= {}`. This ensures that there are no uninitialized variables being read.

Regarding data transfer to userspace, `keyring_read()` is writing `key_serial_t` integers directly into a caller's buffer. The number of entries written is controlled by `index->nr`. The buffer length calculation is precise, ensuring that no uninitialized memory gets leaked into the user space.

Okay, so what about the risks? I'm seeing potential issues with RCU synchronization, use-after-free, double-free, deadlocks, lockdep warnings, and reference counting bugs. However, these are precisely the kinds of bugs that KASAN, LOCKDEP, and the standard kernel debugging facilities (like kmemleak, DEBUG_OBJECTS, etc.) are designed to catch. This is within their scope.

Therefore, given that I've ensured zero-initialization of all structures, that no data is transferred to user space without explicit initialization, and the primary risks are already handled by existing kernel sanitizers, KMSAN fuzzing isn't justified here. The patch *does not* introduce any risk of uninitialized memory usage or info-leaks.

I'm confident in setting `NeedsKMSAN=false`. Let's move on.



60/3 2026/11/18 17:12 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series replaces the associative array (`assoc_array`) data structure used for keyring indexing in the Linux keys subsystem with a combination of `rhashtable` and an RCU-protected linked list (`struct keyring_index` and `struct keyring_link`), while removing the unused generic `assoc_array` implementation and fixing reference counting / error handling in s390 `cert_store.c`.\n\nKMSAN vs. KASAN analysis:\n1. Memory Allocation and Initialization: All newly introduced kernel structures (`struct keyring_index`, `struct keyring_link`) are allocated with `kzalloc_obj()`, ensuring all fields are zero-initialized upon allocation. Stack instances of `struct keyring_edit`, `struct keyring_read_context`, and `struct keyring_search_context` are zero-initialized using designated initializers (`= {}`), leaving no uninitialized fields or padding.\n2. User Space Data Exposure: `keyring_read()` exports an array of 32-bit `key_serial_t` IDs via `keyctl(KEYCTL_READ)`. The iterator writes exact serial values for active keys (`ctx.serials[ctx.count++] = key-\u003eserial`), and the returned byte length directly corresponds to the number of active entries (`index-\u003enr * sizeof(key_serial_t)`), preventing any uninitialized kernel memory from being copied to user space.\n3. Bug Profile: The architectural changes introduce potential risks around RCU concurrency, list/hash table synchronization, reference count management (`key_get`/`key_put`), locking deadlocks, or use-after-free conditions. These classes of bugs are thoroughly covered by KASAN, LOCKDEP, and existing kernel debuggers.\n\nBecause no uninitialized memory reads or information leaks are exposed or introduced by this series, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series replaces the associative array (`assoc_array`) data structure used for keyring indexing in the Linux keys subsystem with a combination of `rhashtable` and an RCU-protected linked list (`struct keyring_index` and `struct keyring_link`), while removing the unused generic `assoc_array` implementation and fixing reference counting / error handling in s390 `cert_store.c`.\n\nKMSAN vs. KASAN analysis:\n1. Memory Allocation and Initialization: All newly introduced kernel structures (`struct keyring_index`, `struct keyring_link`) are allocated with `kzalloc_obj()`, ensuring all fields are zero-initialized upon allocation. Stack instances of `struct keyring_edit`, `struct keyring_read_context`, and `struct keyring_search_context` are zero-initialized using designated initializers (`= {}`), leaving no uninitialized fields or padding.\n2. User Space Data Exposure: `keyring_read()` exports an array of 32-bit `key_serial_t` IDs via `keyctl(KEYCTL_READ)`. The iterator writes exact serial values for active keys (`ctx.serials[ctx.count++] = key-\u003eserial`), and the returned byte length directly corresponds to the number of active entries (`index-\u003enr * sizeof(key_serial_t)`), preventing any uninitialized kernel memory from being copied to user space.\n3. Bug Profile: The architectural changes introduce potential risks around RCU concurrency, list/hash table synchronization, reference count management (`key_get`/`key_put`), locking deadlocks, or use-after-free conditions. These classes of bugs are thoroughly covered by KASAN, LOCKDEP, and existing kernel debuggers.\n\nBecause no uninitialized memory reads or information leaks are exposed or introduced by this series, a dedicated KMSAN fuzzing session is not warranted.",
  "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)