AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/11/13 05:13 flow patch-triage
5m Args:
null

Results:
{
  "EnableConfigs": [
    "KEYS"
  ],
  "FocusSymbols": [
    "keyring_clear",
    "keyring_read",
    "keyring_gc",
    "keyring_search_rcu",
    "keyring_search",
    "keyring_destroy",
    "key_link",
    "key_unlink",
    "key_move",
    "__key_link_begin",
    "__key_link",
    "__key_link_end",
    "find_key_to_update"
  ],
  "KMSANReasoning": "The patch series replaces the associative array (`assoc_array`) data structure in the keyring subsystem with a simpler `rhashtable` and `list_head` based index (`struct keyring_index` and `struct keyring_link`), while also removing the unused `assoc_array` library code and documentation.\n\nKMSAN vs KASAN Applicability Analysis:\n1. Kernel-to-User Copy / Info-Leaks: In `keyring_read()`, keys in the keyring are iterated over and their serial numbers (`key_serial_t`, 32-bit integers) are written sequentially into the destination buffer up to `links-\u003enr * sizeof(key_serial_t)`. `keyctl_read_key()` only copies the exact number of written bytes (`ret`) to user space via `copy_to_user()`. There are no padding gaps or uninitialized bytes in this data stream.\n2. Dynamic Allocations: All newly introduced structures (`struct keyring_index`, `struct keyring_link`) are allocated using `kzalloc_obj()`, guaranteeing zero-initialization of all fields and pointers.\n3. Stack Allocations: Instances of `struct keyring_edit` used to track transaction links are zero-initialized with `{}` across all callers (`key_instantiate_and_link`, `key_reject_and_link`, `key_link`, `key_move`, `construct_alloc_key`, etc.).\n4. Data Structures and Hashing: `struct keyring_index_key` layout changes (simplification from the union with machine-word packing to `u32 hash` and `unsigned int desc_len`) remove padding rather than introducing any uninitialized gaps. Hashing via SipHash operates strictly over initialized type/tag pointers and string descriptions.\n5. Other bug classes: Any risks in this patch series involve concurrency, RCU dereferencing/freeing (`call_rcu`), list/rhashtable operations, key reference counting, or locking (`keyring-\u003esem`), which are comprehensively detected by KASAN, PROVE_RCU, and LOCKDEP.\n\nTherefore, this patch series does not introduce or expose uninitialized memory risks, and a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch removes the generic associative array (assoc_array) implementation from the kernel and completely replaces the internal keyring indexing mechanism with a resizable hash table (rhashtable) and RCU-protected linked list. This touches core key management and lookup logic, including linking, unlinking, nested keyring searching, reading, clearing, moving, and garbage collection under RCU. The code is directly reachable from userspace via the key management system calls (add_key, keyctl, request_key).",
  "WorthFuzzing": true
}

1/1 2026/11/13 05:13 action read-patch-diff
0m Args:
null

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

Args:
null

Results:
{
  "EnableConfigs": [
    "KEYS"
  ],
  "FocusSymbols": [
    "keyring_clear",
    "keyring_read",
    "keyring_gc",
    "keyring_search_rcu",
    "keyring_search",
    "keyring_destroy",
    "key_link",
    "key_unlink",
    "key_move",
    "__key_link_begin",
    "__key_link",
    "__key_link_end",
    "find_key_to_update"
  ],
  "Reasoning": "The patch removes the generic associative array (assoc_array) implementation from the kernel and completely replaces the internal keyring indexing mechanism with a resizable hash table (rhashtable) and RCU-protected linked list. This touches core key management and lookup logic, including linking, unlinking, nested keyring searching, reading, clearing, moving, and garbage collection under RCU. The code is directly reachable from userspace via the key management system calls (add_key, keyctl, request_key).",
  "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 dce3c6a27421196608214dc306f23dcbc6e60b65
Author: syz-cluster <triage@syzkaller.com>
Date:   Fri Nov 13 05:13:11 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/core-api/assoc_array.rst b/Documentation/core-api/assoc_array.rst
deleted file mode 100644
index 19d89f92bf8da8..00000000000000
--- a/Documentation/core-api/assoc_array.rst
+++ /dev/null
@@ -1,564 +0,0 @@
-========================================
-Generic Associative Array Implementation
-========================================
-
-Overview
-========
-
-This associative array implementation is an object container with the following
-properties:
-
-1. Objects are opaque pointers.  The implementation does not care where they
-   point (if anywhere) or what they point to (if anything).
-
-   .. note::
-
-      Pointers to objects _must_ be zero in the least significant bit.
-
-2. Objects do not need to contain linkage blocks for use by the array.  This
-   permits an object to be located in multiple arrays simultaneously.
-   Rather, the array is made up of metadata blocks that point to objects.
-
-3. Objects require index keys to locate them within the array.
-
-4. Index keys must be unique.  Inserting an object with the same key as one
-   already in the array will replace the old object.
-
-5. Index keys can be of any length and can be of different lengths.
-
-6. Index keys should encode the length early on, before any variation due to
-   length is seen.
-
-7. Index keys can include a hash to scatter objects throughout the array.
-
-8. The array can iterated over.  The objects will not necessarily come out in
-   key order.
-
-9. The array can be iterated over while it is being modified, provided the
-   RCU readlock is being held by the iterator.  Note, however, under these
-   circumstances, some objects may be seen more than once.  If this is a
-   problem, the iterator should lock against modification.  Objects will not
-   be missed, however, unless deleted.
-
-10. Objects in the array can be looked up by means of their index key.
-
-11. Objects can be looked up while the array is being modified, provided the
-    RCU readlock is being held by the thread doing the look up.
-
-The implementation uses a tree of 16-pointer nodes internally that are indexed
-on each level by nibbles from the index key in the same manner as in a radix
-tree.  To improve memory efficiency, shortcuts can be emplaced to skip over
-what would otherwise be a series of single-occupancy nodes.  Further, nodes
-pack leaf object pointers into spare space in the node rather than making an
-extra branch until as such time an object needs to be added to a full node.
-
-
-The Public API
-==============
-
-The public API can be found in ``<linux/assoc_array.h>``.  The associative
-array is rooted on the following structure::
-
-    struct assoc_array {
-            ...
-    };
-
-The code is selected by enabling ``CONFIG_ASSOCIATIVE_ARRAY`` with::
-
-    ./script/config -e ASSOCIATIVE_ARRAY
-
-
-Edit Script
------------
-
-The insertion and deletion functions produce an 'edit script' that can later be
-applied to effect the changes without risking ``ENOMEM``. This retains the
-preallocated metadata blocks that will be installed in the internal tree and
-keeps track of the metadata blocks that will be removed from the tree when the
-script is applied.
-
-This is also used to keep track of dead blocks and dead objects after the
-script has been applied so that they can be freed later.  The freeing is done
-after an RCU grace period has passed - thus allowing access functions to
-proceed under the RCU read lock.
-
-The script appears as outside of the API as a pointer of the type::
-
-    struct assoc_array_edit;
-
-There are two functions for dealing with the script:
-
-1. Apply an edit script::
-
-    void assoc_array_apply_edit(struct assoc_array_edit *edit);
-
-   This will perform the edit functions, interpolating various write barriers
-   to permit accesses under the RCU read lock to continue.  The edit script
-   will then be passed to ``call_rcu()`` to free it and any dead stuff it
-   points to.
-
-2. Cancel an edit script::
-
-    void assoc_array_cancel_edit(struct assoc_array_edit *edit);
-
-   This frees the edit script and all preallocated memory immediately. If
-   this was for insertion, the new object is *not* released by this function,
-   but must rather be released by the caller.
-
-These functions are guaranteed not to fail.
-
-
-Operations Table
-----------------
-
-Various functions take a table of operations::
-
-    struct assoc_array_ops {
-            ...
-    };
-
-This points to a number of methods, all of which need to be provided:
-
-1. Get a chunk of index key from caller data::
-
-    unsigned long (*get_key_chunk)(const void *index_key, int level);
-
-   This should return a chunk of caller-supplied index key starting at the
-   *bit* position given by the level argument.  The level argument will be a
-   multiple of ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` and the function should return
-   ``ASSOC_ARRAY_KEY_CHUNK_SIZE bits``.  No error is possible.
-
-
-2. Get a chunk of an object's index key::
-
-    unsigned long (*get_object_key_chunk)(const void *object, int level);
-
-   As the previous function, but gets its data from an object in the array
-   rather than from a caller-supplied index key.
-
-
-3. See if this is the object we're looking for::
-
-    bool (*compare_object)(const void *object, const void *index_key);
-
-   Compare the object against an index key and return ``true`` if it matches
-   and ``false`` if it doesn't.
-
-
-4. Diff the index keys of two objects::
-
-    int (*diff_objects)(const void *object, const void *index_key);
-
-   Return the bit position at which the index key of the specified object
-   differs from the given index key or -1 if they are the same.
-
-
-5. Free an object::
-
-    void (*free_object)(void *object);
-
-   Free the specified object.  Note that this may be called an RCU grace period
-   after ``assoc_array_apply_edit()`` was called, so ``synchronize_rcu()`` may
-   be necessary on module unloading.
-
-
-Manipulation Functions
-----------------------
-
-There are a number of functions for manipulating an associative array:
-
-1. Initialise an associative array::
-
-    void assoc_array_init(struct assoc_array *array);
-
-   This initialises the base structure for an associative array.  It can't fail.
-
-
-2. Insert/replace an object in an associative array::
-
-    struct assoc_array_edit *
-    assoc_array_insert(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       const void *index_key,
-                       void *object);
-
-   This inserts the given object into the array.  Note that the least
-   significant bit of the pointer must be zero as it's used to type-mark
-   pointers internally.
-
-   If an object already exists for that key then it will be replaced with the
-   new object and the old one will be freed automatically.
-
-   The ``index_key`` argument should hold index key information and is
-   passed to the methods in the ops table when they are called.
-
-   This function makes no alteration to the array itself, but rather returns
-   an edit script that must be applied.  ``-ENOMEM`` is returned in the case of
-   an out-of-memory error.
-
-   The caller should lock exclusively against other modifiers of the array.
-
-
-3. Delete an object from an associative array::
-
-    struct assoc_array_edit *
-    assoc_array_delete(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       const void *index_key);
-
-   This deletes an object that matches the specified data from the array.
-
-   The ``index_key`` argument should hold index key information and is
-   passed to the methods in the ops table when they are called.
-
-   This function makes no alteration to the array itself, but rather returns
-   an edit script that must be applied.  ``-ENOMEM`` is returned in the case of
-   an out-of-memory error.  ``NULL`` will be returned if the specified object
-   is not found within the array.
-
-The caller should lock exclusively against other modifiers of the array.
-
-
-4. Delete all objects from an associative array::
-
-    struct assoc_array_edit *
-    assoc_array_clear(struct assoc_array *array,
-                      const struct assoc_array_ops *ops);
-
-   This deletes all the objects from an associative array and leaves it
-   completely empty.
-
-   This function makes no alteration to the array itself, but rather returns
-   an edit script that must be applied.  ``-ENOMEM`` is returned in the case of
-   an out-of-memory error.
-
-   The caller should lock exclusively against other modifiers of the array.
-
-
-5. Destroy an associative array, deleting all objects::
-
-    void assoc_array_destroy(struct assoc_array *array,
-                             const struct assoc_array_ops *ops);
-
-   This destroys the contents of the associative array and leaves it
-   completely empty.  It is not permitted for another thread to be traversing
-   the array under the RCU read lock at the same time as this function is
-   destroying it as no RCU deferral is performed on memory release -
-   something that would require memory to be allocated.
-
-   The caller should lock exclusively against other modifiers and accessors
-   of the array.
-
-
-6. Garbage collect an associative array::
-
-    int assoc_array_gc(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       bool (*iterator)(void *object, void *iterator_data),
-                       void *iterator_data);
-
-   This iterates over the objects in an associative array and passes each one
-   to ``iterator()``.  If ``iterator()`` returns ``true``, the object is kept.
-   If it returns ``false``, the object will be freed.  If the ``iterator()``
-   function returns ``true``, it must perform any appropriate refcount
-   incrementing on the object before returning.
-
-   The internal tree will be packed down if possible as part of the iteration
-   to reduce the number of nodes in it.
-
-   The ``iterator_data`` is passed directly to ``iterator()`` and is otherwise
-   ignored by the function.
-
-   The function will return ``0`` if successful and ``-ENOMEM`` if there wasn't
-   enough memory.
-
-   It is possible for other threads to iterate over or search the array under
-   the RCU read lock while this function is in progress.  The caller should
-   lock exclusively against other modifiers of the array.
-
-
-Access Functions
-----------------
-
-There are two functions for accessing an associative array:
-
-1. Iterate over all the objects in an associative array::
-
-    int assoc_array_iterate(const struct assoc_array *array,
-                            int (*iterator)(const void *object,
-                                            void *iterator_data),
-                            void *iterator_data);
-
-   This passes each object in the array to the iterator callback function.
-   ``iterator_data`` is private data for that function.
-
-   This may be used on an array at the same time as the array is being
-   modified, provided the RCU read lock is held.  Under such circumstances,
-   it is possible for the iteration function to see some objects twice.  If
-   this is a problem, then modification should be locked against.  The
-   iteration algorithm should not, however, miss any objects.
-
-   The function will return ``0`` if no objects were in the array or else it
-   will return the result of the last iterator function called.  Iteration
-   stops immediately if any call to the iteration function results in a
-   non-zero return.
-
-
-2. Find an object in an associative array::
-
-    void *assoc_array_find(const struct assoc_array *array,
-                           const struct assoc_array_ops *ops,
-                           const void *index_key);
-
-   This walks through the array's internal tree directly to the object
-   specified by the index key.
-
-   This may be used on an array at the same time as the array is being
-   modified, provided the RCU read lock is held.
-
-   The function will return the object if found (and set ``*_type`` to the
-   object type) or will return ``NULL`` if the object was not found.
-
-
-Index Key Form
---------------
-
-The index key can be of any form, but since the algorithms aren't told how long
-the key is, it is strongly recommended that the index key includes its length
-very early on before any variation due to the length would have an effect on
-comparisons.
-
-This will cause leaves with different length keys to scatter away from each
-other - and those with the same length keys to cluster together.
-
-It is also recommended that the index key begin with a hash of the rest of the
-key to maximise scattering throughout keyspace.
-
-The better the scattering, the wider and lower the internal tree will be.
-
-Poor scattering isn't too much of a problem as there are shortcuts and nodes
-can contain mixtures of leaves and metadata pointers.
-
-The index key is read in chunks of machine word.  Each chunk is subdivided into
-one nibble (4 bits) per level, so on a 32-bit CPU this is good for 8 levels and
-on a 64-bit CPU, 16 levels.  Unless the scattering is really poor, it is
-unlikely that more than one word of any particular index key will have to be
-used.
-
-
-Internal Workings
-=================
-
-The associative array data structure has an internal tree.  This tree is
-constructed of two types of metadata blocks: nodes and shortcuts.
-
-A node is an array of slots.  Each slot can contain one of four things:
-
-* A NULL pointer, indicating that the slot is empty.
-* A pointer to an object (a leaf).
-* A pointer to a node at the next level.
-* A pointer to a shortcut.
-
-
-Basic Internal Tree Layout
---------------------------
-
-Ignoring shortcuts for the moment, the nodes form a multilevel tree.  The index
-key space is strictly subdivided by the nodes in the tree and nodes occur on
-fixed levels.  For example::
-
- Level: 0               1               2               3
-        =============== =============== =============== ===============
-                                                        NODE D
-                        NODE B          NODE C  +------>+---+
-                +------>+---+   +------>+---+   |       | 0 |
-        NODE A  |       | 0 |   |       | 0 |   |       +---+
-        +---+   |       +---+   |       +---+   |       :   :
-        | 0 |   |       :   :   |       :   :   |       +---+
-        +---+   |       +---+   |       +---+   |       | f |
-        | 1 |---+       | 3 |---+       | 7 |---+       +---+
-        +---+           +---+           +---+
-        :   :           :   :           | 8 |---+
-        +---+           +---+           +---+   |       NODE E
-        | e |---+       | f |           :   :   +------>+---+
-        +---+   |       +---+           +---+           | 0 |
-        | f |   |                       | f |           +---+
-        +---+   |                       +---+           :   :
-                |       NODE F                          +---+
-                +------>+---+                           | f |
-                        | 0 |           NODE G          +---+
-                        +---+   +------>+---+
-                        :   :   |       | 0 |
-                        +---+   |       +---+
-                        | 6 |---+       :   :
-                        +---+           +---+
-                        :   :           | f |
-                        +---+           +---+
-                        | f |
-                        +---+
-
-In the above example, there are 7 nodes (A-G), each with 16 slots (0-f).
-Assuming no other meta data nodes in the tree, the key space is divided
-thusly:
-
-    ===========     ====
-    KEY PREFIX      NODE
-    ===========     ====
-    137*            D
-    138*            E
-    13[0-69-f]*     C
-    1[0-24-f]*      B
-    e6*             G
-    e[0-57-f]*      F
-    [02-df]*        A
-    ===========     ====
-
-So, for instance, keys with the following example index keys will be found in
-the appropriate nodes:
-
-    =============== ======= ====
-    INDEX KEY       PREFIX  NODE
-    =============== ======= ====
-    13694892892489  13      C
-    13795289025897  137     D
-    13889dde88793   138     E
-    138bbb89003093  138     E
-    1394879524789   12      C
-    1458952489      1       B
-    9431809de993ba  \-      A
-    b4542910809cd   \-      A
-    e5284310def98   e       F
-    e68428974237    e6      G
-    e7fffcbd443     e       F
-    f3842239082     \-      A
-    =============== ======= ====
-
-To save memory, if a node can hold all the leaves in its portion of keyspace,
-then the node will have all those leaves in it and will not have any metadata
-pointers - even if some of those leaves would like to be in the same slot.
-
-A node can contain a heterogeneous mix of leaves and metadata pointers.
-Metadata pointers must be in the slots that match their subdivisions of key
-space.  The leaves can be in any slot not occupied by a metadata pointer.  It
-is guaranteed that none of the leaves in a node will match a slot occupied by a
-metadata pointer.  If the metadata pointer is there, any leaf whose key matches
-the metadata key prefix must be in the subtree that the metadata pointer points
-to.
-
-In the above example list of index keys, node A will contain:
-
-    ====    =============== ==================
-    SLOT    CONTENT         INDEX KEY (PREFIX)
-    ====    =============== ==================
-    1       PTR TO NODE B   1*
-    any     LEAF            9431809de993ba
-    any     LEAF            b4542910809cd
-    e       PTR TO NODE F   e*
-    any     LEAF            f3842239082
-    ====    =============== ==================
-
-and node B:
-
-    ====    =============== ==================
-    SLOT    CONTENT         INDEX KEY (PREFIX)
-    ====    =============== ==================
-    3       PTR TO NODE C   13*
-    any     LEAF            1458952489
-    ====    =============== ==================
-
-
-Shortcuts
----------
-
-Shortcuts are metadata records that jump over a piece of keyspace.  A shortcut
-is a replacement for a series of single-occupancy nodes ascending through the
-levels.  Shortcuts exist to save memory and to speed up traversal.
-
-It is possible for the root of the tree to be a shortcut - say, for example,
-the tree contains at least 17 nodes all with key prefix ``1111``.  The
-insertion algorithm will insert a shortcut to skip over the ``1111`` keyspace
-in a single bound and get to the fourth level where these actually become
-different.
-
-
-Splitting And Collapsing Nodes
-------------------------------
-
-Each node has a maximum capacity of 16 leaves and metadata pointers.  If the
-insertion algorithm finds that it is trying to insert a 17th object into a
-node, that node will be split such that at least two leaves that have a common
-key segment at that level end up in a separate node rooted on that slot for
-that common key segment.
-
-If the leaves in a full node and the leaf that is being inserted are
-sufficiently similar, then a shortcut will be inserted into the tree.
-
-When the number of objects in the subtree rooted at a node falls to 16 or
-fewer, then the subtree will be collapsed down to a single node - and this will
-ripple towards the root if possible.
-
-
-Non-Recursive Iteration
------------------------
-
-Each node and shortcut contains a back pointer to its parent and the number of
-slot in that parent that points to it.  None-recursive iteration uses these to
-proceed rootwards through the tree, going to the parent node, slot N + 1 to
-make sure progress is made without the need for a stack.
-
-The backpointers, however, make simultaneous alteration and iteration tricky.
-
-
-Simultaneous Alteration And Iteration
--------------------------------------
-
-There are a number of cases to consider:
-
-1. Simple insert/replace.  This involves simply replacing a NULL or old
-   matching leaf pointer with the pointer to the new leaf after a barrier.
-   The metadata blocks don't change otherwise.  An old leaf won't be freed
-   until after the RCU grace period.
-
-2. Simple delete.  This involves just clearing an old matching leaf.  The
-   metadata blocks don't change otherwise.  The old leaf won't be freed until
-   after the RCU grace period.
-
-3. Insertion replacing part of a subtree that we haven't yet entered.  This
-   may involve replacement of part of that subtree - but that won't affect
-   the iteration as we won't have reached the pointer to it yet and the
-   ancestry blocks are not replaced (the layout of those does not change).
-
-4. Insertion replacing nodes that we're actively processing.  This isn't a
-   problem as we've passed the anchoring pointer and won't switch onto the
-   new layout until we follow the back pointers - at which point we've
-   already examined the leaves in the replaced node (we iterate over all the
-   leaves in a node before following any of its metadata pointers).
-
-   We might, however, re-see some leaves that have been split out into a new
-   branch that's in a slot further along than we were at.
-
-5. Insertion replacing nodes that we're processing a dependent branch of.
-   This won't affect us until we follow the back pointers.  Similar to (4).
-
-6. Deletion collapsing a branch under us.  This doesn't affect us because the
-   back pointers will get us back to the parent of the new node before we
-   could see the new node.  The entire collapsed subtree is thrown away
-   unchanged - and will still be rooted on the same slot, so we shouldn't
-   process it a second time as we'll go back to slot + 1.
-
-.. note::
-
-   Under some circumstances, we need to simultaneously change the parent
-   pointer and the parent slot pointer on a node (say, for example, we
-   inserted another node before it and moved it up a level).  We cannot do
-   this without locking against a read - so we have to replace that node too.
-
-   However, when we're changing a shortcut into a node this isn't a problem
-   as shortcuts only have one slot and so the parent slot number isn't used
-   when traversing backwards over one.  This means that it's okay to change
-   the slot number first - provided suitable barriers are used to make sure
-   the parent slot number is read after the back pointer.
-
-Obsolete blocks and leaves are freed up after an RCU grace period has passed,
-so as long as anyone doing walking or iteration holds the RCU read lock, the
-old superstructure should not go away on them.
diff --git a/Documentation/core-api/index.rst b/Documentation/core-api/index.rst
index 92f91c6a0d79d6..d56c60663b0c40 100644
--- a/Documentation/core-api/index.rst
+++ b/Documentation/core-api/index.rst
@@ -38,7 +38,6 @@ Library functionality that is used throughout the kernel.
    kobject
    kref
    cleanup
-   assoc_array
    folio_queue
    xarray
    maple_tree
diff --git a/Documentation/translations/zh_CN/core-api/assoc_array.rst b/Documentation/translations/zh_CN/core-api/assoc_array.rst
deleted file mode 100644
index 3649bf0d148807..00000000000000
--- a/Documentation/translations/zh_CN/core-api/assoc_array.rst
+++ /dev/null
@@ -1,473 +0,0 @@
-.. include:: ../disclaimer-zh_CN.rst
-
-:Original: Documentation/core-api/assoc_array.rst
-
-:翻译:
-
- 司延腾 Yanteng Si <siyanteng@loongson.cn>
-
-:校译:
-
-
-
-.. _cn_core-api_assoc_array:
-
-==================
-通用关联数组的实现
-==================
-
-简介
-====
-
-这个关联数组的实现是一个具有以下属性的对象容器:
-
-1. 对象是不透明的指针。该实现不关心它们指向哪里(如果有的话)或它们指向什么(如果有的
-   话)。
-
-   .. note::
-
-      指向对象的指针 *必须* 在最小有效位为零。
-
-2. 对象不需要包含供数组使用的链接块。这允许一个对象同时位于多个数组中。相反,数组是
-   由指向对象的元数据块组成的。
-
-3. 对象需要索引键来定位它们在阵列中的位置。
-
-4. 索引键必须是唯一的。插入一个与已经在数组中的且具有相同键值的对象将取代旧的对象。
-
-5. 索引键可以是任何长度,也可以是不同的长度。
-
-6. 索引键应该在早期就对长度进行编码,即在任何由于长度引起的变化出现之前。
-
-7. 索引键可以包括一个哈希值,以便将对象分散到整个数组中。
-
-8. 该数组可以迭代。对象不一定会按索引键的顺序出现。
-
-9.  数组可以在被修改的时候进行迭代,只要RCU的读锁被迭代器持有。然而,请注意,在这种情
-    况下,一些对象可能会被看到不止一次。如果这是个问题,迭代器应该锁定以防止修改。然
-    而,除非删除,否则对象不会被错过。
-
-10. 数组中的对象可以通过其索引键进行查询。
-
-11. 当数组被修改时,对象可以被查询,前提是进行查询的线程持有RCU的读锁。
-
-该实现在内部使用了一棵由16个指针节点组成的树,这些节点在每一层都由索引键的小数点进行索
-引,其方式与基数树相同。为了提高内存效率,可以放置快捷键,以跳过本来是一系列单占节点的地
-方。此外,节点将叶子对象指针打包到节点的空闲空间中,而不是做一个额外的分支,直到有对象
-需要被添加到一个完整的节点中。
-
-公用API
-=======
-
-公用API可以在 ``<linux/assoc_array.h>`` 中找到。关联数组的根是以下结构::
-
-    struct assoc_array {
-            ...
-    };
-
-该代码是通过启用 ``CONFIG_ASSOCIATIVE_ARRAY`` 来选择的,以::
-
-    ./script/config -e ASSOCIATIVE_ARRAY
-
-
-编辑脚本
---------
-
-插入和删除功能会产生一个“编辑脚本”,以后可以应用这个脚本来实现更改,而不会造成 ``ENOMEM``
-风险。这保留了将被安装在内部树中的预分配的元数据块,并跟踪应用脚本时将从树中删除的元数
-据块。
-
-在脚本应用后,这也被用来跟踪死块和死对象,以便以后可以释放它们。释放是在RCU宽限期过后
-进行的--因此允许访问功能在RCU读锁下进行。
-
-脚本在API之外显示为一个类型为::
-
-    struct assoc_array_edit;
-
-有两个处理脚本的功能:
-
-1. 应用一个编辑脚本::
-
-    void assoc_array_apply_edit(struct assoc_array_edit *edit);
-
-这将执行编辑功能,插值各种写屏障,以允许在RCU读锁下的访问继续进行。然后,编辑脚本将被
-传递给 ``call_rcu()`` ,以释放它和它所指向的任何死的东西。
-
-2. Cancel an edit script::
-
-    void assoc_array_cancel_edit(struct assoc_array_edit *edit);
-
-这将立即释放编辑脚本和所有预分配的内存。如果这是为了插入,新的对象不会被这个函数释放,
-而是必须由调用者释放。
-
-这些函数保证不会失败。
-
-
-操作表
-------
-
-各种功能采用了一个操作表::
-
-    struct assoc_array_ops {
-            ...
-    };
-
-这指出了一些方法,所有这些方法都需要提供:
-
-1. 从调用者数据中获取索引键的一个块::
-
-    unsigned long (*get_key_chunk)(const void *index_key, int level);
-
-这应该返回一个由调用者提供的索引键的块,从level参数给出的 *比特* 位置开始。level参数将
-是 ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` 的倍数,该函数应返回 ``ASSOC_ARRAY_KEY_CHUNK_SIZE``
-位。不可能出现错误。
-
-
-2. 获取一个对象的索引键的一个块::
-
-    unsigned long (*get_object_key_chunk)(const void *object, int level);
-
-和前面的函数一样,但是从数组中的一个对象而不是从调用者提供的索引键中获取数据。
-
-
-3. 看看这是否是我们要找的对象::
-
-    bool (*compare_object)(const void *object, const void *index_key);
-
-将对象与一个索引键进行比较,如果匹配则返回 ``true`` ,不匹配则返回 ``false`` 。
-
-
-4. 对两个对象的索引键进行比较::
-
-    int (*diff_objects)(const void *object, const void *index_key);
-
-返回指定对象的索引键与给定索引键不同的比特位置,如果它们相同,则返回-1。
-
-
-5. 释放一个对象::
-
-    void (*free_object)(void *object);
-
-释放指定的对象。注意,这可能是在调用 ``assoc_array_apply_edit()`` 后的一个RCU宽限期内
-调用的,所以在模块卸载时可能需要 ``synchronize_rcu()`` 。
-
-
-操控函数
---------
-
-有一些函数用于操控关联数组:
-
-1. 初始化一个关联数组::
-
-    void assoc_array_init(struct assoc_array *array);
-
-这将初始化一个关联数组的基础结构。它不会失败。
-
-
-2. 在一个关联数组中插入/替换一个对象::
-
-    struct assoc_array_edit *
-    assoc_array_insert(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       const void *index_key,
-                       void *object);
-
-这将把给定的对象插入数组中。注意,指针的最小有效位必须是0,因为它被用来在内部标记指针的类
-型。
-
-如果该键已经存在一个对象,那么它将被新的对象所取代,旧的对象将被自动释放。
-
-``index_key`` 参数应持有索引键信息,并在调用OPP表中的方法时传递给它们。
-
-这个函数不对数组本身做任何改动,而是返回一个必须应用的编辑脚本。如果出现内存不足的错误,会
-返回 ``-ENOMEM`` 。
-
-调用者应专门锁定数组的其他修改器。
-
-
-3. 从一个关联数组中删除一个对象::
-
-    struct assoc_array_edit *
-    assoc_array_delete(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       const void *index_key);
-
-这将从数组中删除一个符合指定数据的对象。
-
-``index_key`` 参数应持有索引键信息,并在调用OPP表中的方法时传递给它们。
-
-这个函数不对数组本身做任何改动,而是返回一个必须应用的编辑脚本。 ``-ENOMEM`` 在出现内存不足
-的错误时返回。如果在数组中没有找到指定的对象,将返回 ``NULL`` 。
-
-调用者应该对数组的其他修改者进行专门锁定。
-
-
-4. 从一个关联数组中删除所有对象::
-
-    struct assoc_array_edit *
-    assoc_array_clear(struct assoc_array *array,
-                      const struct assoc_array_ops *ops);
-
-这个函数删除了一个关联数组中的所有对象,使其完全为空。
-
-这个函数没有对数组本身做任何改动,而是返回一个必须应用的编辑脚本。如果出现内存不足
-的错误,则返回 ``-ENOMEM`` 。
-
-调用者应专门锁定数组的其他修改者。
-
-
-5. 销毁一个关联数组,删除所有对象::
-
-    void assoc_array_destroy(struct assoc_array *array,
-                             const struct assoc_array_ops *ops);
-
-这将破坏关联数组的内容,使其完全为空。在这个函数销毁数组的同时,不允许另一个线程在RCU读锁
-下遍历数组,因为在内存释放时不执行RCU延迟,这需要分配内存。
-
-调用者应该专门针对数组的其他修改者和访问者进行锁定。
-
-
-6. 垃圾回收一个关联数组::
-
-    int assoc_array_gc(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       bool (*iterator)(void *object, void *iterator_data),
-                       void *iterator_data);
-
-这是对一个关联数组中的对象进行迭代,并将每个对象传递给 ``iterator()`` 。如果 ``iterator()`` 返回
-true,该对象被保留。如果它返回 ``false`` ,该对象将被释放。如果 ``iterator()`` 函数返回 ``true`` ,它必须
-在返回之前对该对象进行适当的 ``refcount`` 递增。
-
-如果可能的话,内部树将被打包下来,作为迭代的一部分,以减少其中的节点数量。
-
-``iterator_data`` 被直接传递给 ``iterator()`` ,否则会被函数忽略。
-
-如果成功,该函数将返回 ``0`` ,如果没有足够的内存,则返回 ``-ENOMEM`` 。
-
-在这个函数执行过程中,其他线程有可能在RCU读锁下迭代或搜索阵列。调用者应该专门针对数组的其他
-修改者进行锁定。
-
-
-访问函数
---------
-
-有两个函数用于访问一个关联数组:
-
-1. 遍历一个关联数组中的所有对象::
-
-    int assoc_array_iterate(const struct assoc_array *array,
-                            int (*iterator)(const void *object,
-                                            void *iterator_data),
-                            void *iterator_data);
-
-这将数组中的每个对象传递给迭代器回调函数。 ``iterator_data`` 是该函数的私有数据。
-
-在数组被修改的同时,可以在数组上使用这个方法,前提是RCU读锁被持有。在这种情况下,迭代函数有
-可能两次看到某些对象。如果这是个问题,那么修改应该被锁定。然而,迭代算法不应该错过任何对象。
-
-如果数组中没有对象,该函数将返回 ``0`` ,否则将返回最后一次调用的迭代器函数的结果。如果对迭代函数
-的任何调用导致非零返回,迭代立即停止。
-
-
-2. 在一个关联数组中寻找一个对象::
-
-    void *assoc_array_find(const struct assoc_array *array,
-                           const struct assoc_array_ops *ops,
-                           const void *index_key);
-
-这将直接穿过数组的内部树,到达索引键所指定的对象。
-
-这个函数可以在修改数组的同时用在数组上,前提是RCU读锁被持有。
-
-如果找到对象,该函数将返回对象(并将 ``*_type`` 设置为对象的类型),如果没有找到对象,将返回 ``NULL`` 。
-
-
-索引键形式
-----------
-
-索引键可以是任何形式的,但是由于算法没有被告知键有多长,所以强烈建议在任何由于长度而产生的变化
-对比较产生影响之前,索引键应该很早就包括其长度。
-
-这将导致具有不同长度键的叶子相互分散,而具有相同长度键的叶子则聚集在一起。
-
-我们还建议索引键以键的其余部分的哈希值开始,以最大限度地提高整个键空间的散布情况。
-
-分散性越好,内部树就越宽,越低。
-
-分散性差并不是一个太大的问题,因为有快捷键,节点可以包含叶子和元数据指针的混合物。
-
-索引键是以机器字的块状来读取的。每个块被细分为每层一个nibble(4比特),所以在32位CPU上这适合8层,
-在64位CPU上适合16层。除非散布情况真的很差,否则不太可能有超过一个字的任何特定索引键需要被使用。
-
-
-内部工作机制
-============
-
-关联数组数据结构有一个内部树。这个树由两种类型的元数据块构成:节点和快捷键。
-
-一个节点是一个槽的数组。每个槽可以包含以下四种东西之一:
-
-* 一个NULL的指针,表示槽是空的。
-* 一个指向对象(叶子)的指针。
-* 一个指向下一级节点的指针。
-* 一个指向快捷键的指针。
-
-
-基本的内部树形布局
-------------------
-
-暂时不考虑快捷键,节点形成一个多级树。索引键空间被树上的节点严格细分,节点出现在固定的层次上。例如::
-
- Level: 0               1               2               3
-        =============== =============== =============== ===============
-                                                        NODE D
-                        NODE B          NODE C  +------>+---+
-                +------>+---+   +------>+---+   |       | 0 |
-        NODE A  |       | 0 |   |       | 0 |   |       +---+
-        +---+   |       +---+   |       +---+   |       :   :
-        | 0 |   |       :   :   |       :   :   |       +---+
-        +---+   |       +---+   |       +---+   |       | f |
-        | 1 |---+       | 3 |---+       | 7 |---+       +---+
-        +---+           +---+           +---+
-        :   :           :   :           | 8 |---+
-        +---+           +---+           +---+   |       NODE E
-        | e |---+       | f |           :   :   +------>+---+
-        +---+   |       +---+           +---+           | 0 |
-        | f |   |                       | f |           +---+
-        +---+   |                       +---+           :   :
-                |       NODE F                          +---+
-                +------>+---+                           | f |
-                        | 0 |           NODE G          +---+
-                        +---+   +------>+---+
-                        :   :   |       | 0 |
-                        +---+   |       +---+
-                        | 6 |---+       :   :
-                        +---+           +---+
-                        :   :           | f |
-                        +---+           +---+
-                        | f |
-                        +---+
-
-在上述例子中,有7个节点(A-G),每个节点有16个槽(0-f)。假设树上没有其他元数据节点,那么密钥空间
-是这样划分的::
-
-    KEY PREFIX      NODE
-    ==========      ====
-    137*            D
-    138*            E
-    13[0-69-f]*     C
-    1[0-24-f]*      B
-    e6*             G
-    e[0-57-f]*      F
-    [02-df]*        A
-
-因此,例如,具有以下示例索引键的键将在适当的节点中被找到::
-
-    INDEX KEY       PREFIX  NODE
-    =============== ======= ====
-    13694892892489  13      C
-    13795289025897  137     D
-    13889dde88793   138     E
-    138bbb89003093  138     E
-    1394879524789   12      C
-    1458952489      1       B
-    9431809de993ba  -       A
-    b4542910809cd   -       A
-    e5284310def98   e       F
-    e68428974237    e6      G
-    e7fffcbd443     e       F
-    f3842239082     -       A
-
-为了节省内存,如果一个节点可以容纳它的那部分键空间中的所有叶子,那么这个节点将有所有这些叶子,而不
-会有任何元数据指针——即使其中一些叶子想在同一个槽中。
-
-一个节点可以包含叶子和元数据指针的异质性混合。元数据指针必须在与它们的关键空间的细分相匹配的槽中。
-叶子可以在任何没有被元数据指针占据的槽中。保证一个节点中没有一个叶子会与元数据指针占据的槽相匹配。
-如果元数据指针在那里,任何键与元数据键前缀相匹配的叶必须在元数据指针指向的子树中。
-
-在上面的索引键的例子列表中,节点A将包含::
-
-    SLOT    CONTENT         INDEX KEY (PREFIX)
-    ====    =============== ==================
-    1       PTR TO NODE B   1*
-    any     LEAF            9431809de993ba
-    any     LEAF            b4542910809cd
-    e       PTR TO NODE F   e*
-    any     LEAF            f3842239082
-
-和节点B::
-
-    3	PTR TO NODE C	13*
-    any	LEAF		1458952489
-
-
-快捷键
----------
-
-快捷键是跳过一块键空间的元数据记录。快捷键是一系列通过层次上升的单占节点的替代物。快捷键的存在是
-为了节省内存和加快遍历速度。
-
-树的根部有可能是一个快捷键——比如说,树至少包含17个节点,都有键前缀 ``1111`` 。插入算法将插入一个快捷键,
-以单次跳过 ``1111`` 的键位,并到达第四层,在这里,这些键位实际上变得不同。
-
-
-拆分和合并节点
-------------------------------
-
-每个节点的最大容量为16个叶子和元数据指针。如果插入算法发现它正试图将一个第17个对象插入到一个节点中,
-该节点将被拆分,使得至少两个在该层有一个共同的关键段的叶子最终在一个单独的节点中,该共同的关键段的根
-在该槽上。
-
-如果一个完整的节点中的叶子和被插入的叶子足够相似,那么就会在树中插入一个快捷键。
-
-当根植于某个节点的子树中的对象数量下降到16个或更少时,那么该子树将被合并成一个单独的节点——如果可能的
-话,这将向根部扩散。
-
-
-非递归式迭代
-------------
-
-每个节点和快捷键都包含一个指向其父节点的后置指针,以及该父节点中指向它的槽数。非递归迭代使用这些来
-通过树的根部进行,前往父节点,槽N+1,以确保在没有堆栈的情况下取得进展。
-
-然而,反向指针使得同时改变和迭代变得很棘手。
-
-
-同时改变和迭代
---------------
-
-有一些情况需要考虑:
-
-1. 简单的插入/替换。这涉及到简单地将一个NULL或旧的匹配叶子的指针替换为屏障后的新叶子的指针。否则元数
-   据块不会改变。一个旧的叶子直到RCU宽限期过后才会被释放。
-
-2. 简单删除。这只是涉及到清除一个旧的匹配叶子。元数据块不会有其他变化。旧的叶子直到RCU宽限期之后才会
-   被释放。
-
-3. 插入,替换我们还没有进入的子树的一部分。这可能涉及到替换该子树的一部分——但这不会影响迭代,因为我们
-   还没有到达它的指针,而且祖先块也不会被替换(这些块的布局不会改变)。
-
-4. 插入替换了我们正在处理的节点。这不是一个问题,因为我们已经通过了锚定指针,直到我们跟随后面的指针才
-   会切换到新的布局上——这时我们已经检查了被替换节点的叶子(在跟随任何元数据指针之前,我们会迭代一个节
-   点的所有叶子)。
-
-   然而,我们可能会重新看到一些叶子,这些叶子已经被分割成一个新的分支,而这个分支的位置比我们之前的位
-   置更远。
-
-5. 插入替换了我们正在处理的依赖分支的节点。这不会影响到我们,直到我们跟随后面的指针。与(4)类似。
-
-6. 删掉我们下面的一个分支。这不会影响我们,因为在我们看到新节点之前,回溯指针会让我们回到新节点的父节
-   点。整个崩溃的子树被扔掉了,没有任何变化——而且仍然会在同一个槽上生根,所以我们不应该第二次处理它,
-   因为我们会回到槽+1。
-
-.. note::
-
-    在某些情况下,我们需要同时改变一个节点的父指针和父槽指针(比如说,我们在它之前插入了另一个节点,
-    并把它往上移了一层)。我们不能在不锁定读取的情况下这样做——所以我们必须同时替换该节点。
-
-    然而,当我们把一个快捷键改成一个节点时,这不是一个问题,因为快捷键只有一个槽,所以当向后遍
-    历一个槽时,不会使用父槽号。这意味着先改变槽位号是可以的——只要使用适当的屏障来确保父槽位号在后
-    退指针之后被读取。
-
-过时的块和叶子在RCU宽限期过后会被释放,所以只要任何进行遍历或迭代的人持有RCU读锁,旧的上层建筑就不
-应该在他们身上消失。
diff --git a/Documentation/translations/zh_CN/core-api/index.rst b/Documentation/translations/zh_CN/core-api/index.rst
index 453a02cd1f4486..ec4b03b2a0a60e 100644
--- a/Documentation/translations/zh_CN/core-api/index.rst
+++ b/Documentation/translations/zh_CN/core-api/index.rst
@@ -41,7 +41,6 @@
 
    kobject
    kref
-   assoc_array
    xarray
    rbtree
    idr
diff --git a/drivers/md/dm-verity-verify-sig.c b/drivers/md/dm-verity-verify-sig.c
index 0c65c7a31da8bd..bd5143aae4fa96 100644
--- a/drivers/md/dm-verity-verify-sig.c
+++ b/drivers/md/dm-verity-verify-sig.c
@@ -153,7 +153,7 @@ int verity_verify_root_hash(const void *root_hash, size_t root_hash_len,
 	if (ret != -ENOKEY && ret != -EKEYREJECTED)
 		return ret;
 
-	if (dm_verity_keyring->keys.nr_leaves_on_tree &&
+	if (!keyring_is_empty(dm_verity_keyring) &&
 	    dm_verity_keyring->restrict_link)
 		ret = verify_pkcs7_signature(root_hash, root_hash_len,
 					     sig_data, sig_len,
diff --git a/fs/verity/signature.c b/fs/verity/signature.c
index 2f49c5d9d98705..b45b39b829b298 100644
--- a/fs/verity/signature.c
+++ b/fs/verity/signature.c
@@ -70,7 +70,7 @@ int fsverity_verify_signature(const struct fsverity_info *vi,
 		return 0;
 	}
 
-	if (fsverity_keyring->keys.nr_leaves_on_tree == 0) {
+	if (keyring_is_empty(fsverity_keyring)) {
 		/*
 		 * The ".fs-verity" keyring is empty, due to builtin signatures
 		 * being supported by the kernel but not actually being used.
diff --git a/include/keys/keyring-type.h b/include/keys/keyring-type.h
index 1dc83862f519ad..314832f5dc4a99 100644
--- a/include/keys/keyring-type.h
+++ b/include/keys/keyring-type.h
@@ -9,6 +9,5 @@
 #define _KEYS_KEYRING_TYPE_H
 
 #include <linux/key.h>
-#include <linux/assoc_array.h>
 
 #endif /* _KEYS_KEYRING_TYPE_H */
diff --git a/include/linux/assoc_array.h b/include/linux/assoc_array.h
deleted file mode 100644
index 8b3f230ce89440..00000000000000
--- a/include/linux/assoc_array.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0-or-later */
-/* Generic associative array implementation.
- *
- * See Documentation/core-api/assoc_array.rst for information.
- *
- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.
- * Written by David Howells (dhowells@redhat.com)
- */
-
-#ifndef _LINUX_ASSOC_ARRAY_H
-#define _LINUX_ASSOC_ARRAY_H
-
-#ifdef CONFIG_ASSOCIATIVE_ARRAY
-
-#include <linux/types.h>
-
-#define ASSOC_ARRAY_KEY_CHUNK_SIZE BITS_PER_LONG /* Key data retrieved in chunks of this size */
-
-/*
- * Generic associative array.
- */
-struct assoc_array {
-	struct assoc_array_ptr	*root;		/* The node at the root of the tree */
-	unsigned long		nr_leaves_on_tree;
-};
-
-/*
- * Operations on objects and index keys for use by array manipulation routines.
- */
-struct assoc_array_ops {
-	/* Method to get a chunk of an index key from caller-supplied data */
-	unsigned long (*get_key_chunk)(const void *index_key, int level);
-
-	/* Method to get a piece of an object's index key */
-	unsigned long (*get_object_key_chunk)(const void *object, int level);
-
-	/* Is this the object we're looking for? */
-	bool (*compare_object)(const void *object, const void *index_key);
-
-	/* How different is an object from an index key, to a bit position in
-	 * their keys? (or -1 if they're the same)
-	 */
-	int (*diff_objects)(const void *object, const void *index_key);
-
-	/* Method to free an object. */
-	void (*free_object)(void *object);
-};
-
-/*
- * Access and manipulation functions.
- */
-struct assoc_array_edit;
-
-static inline void assoc_array_init(struct assoc_array *array)
-{
-	array->root = NULL;
-	array->nr_leaves_on_tree = 0;
-}
-
-extern int assoc_array_iterate(const struct assoc_array *array,
-			       int (*iterator)(const void *object,
-					       void *iterator_data),
-			       void *iterator_data);
-extern void *assoc_array_find(const struct assoc_array *array,
-			      const struct assoc_array_ops *ops,
-			      const void *index_key);
-extern void assoc_array_destroy(struct assoc_array *array,
-				const struct assoc_array_ops *ops);
-extern struct assoc_array_edit *assoc_array_insert(struct assoc_array *array,
-						   const struct assoc_array_ops *ops,
-						   const void *index_key,
-						   void *object);
-extern void assoc_array_insert_set_object(struct assoc_array_edit *edit,
-					  void *object);
-extern struct assoc_array_edit *assoc_array_delete(struct assoc_array *array,
-						   const struct assoc_array_ops *ops,
-						   const void *index_key);
-extern struct assoc_array_edit *assoc_array_clear(struct assoc_array *array,
-						  const struct assoc_array_ops *ops);
-extern void assoc_array_apply_edit(struct assoc_array_edit *edit);
-extern void assoc_array_cancel_edit(struct assoc_array_edit *edit);
-extern int assoc_array_gc(struct assoc_array *array,
-			  const struct assoc_array_ops *ops,
-			  bool (*iterator)(void *object, void *iterator_data),
-			  void *iterator_data);
-
-#endif /* CONFIG_ASSOCIATIVE_ARRAY */
-#endif /* _LINUX_ASSOC_ARRAY_H */
diff --git a/include/linux/assoc_array_priv.h b/include/linux/assoc_array_priv.h
deleted file mode 100644
index dca733ef675038..00000000000000
--- a/include/linux/assoc_array_priv.h
+++ /dev/null
@@ -1,178 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0-or-later */
-/* Private definitions for the generic associative array implementation.
- *
- * See Documentation/core-api/assoc_array.rst for information.
- *
- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.
- * Written by David Howells (dhowells@redhat.com)
- */
-
-#ifndef _LINUX_ASSOC_ARRAY_PRIV_H
-#define _LINUX_ASSOC_ARRAY_PRIV_H
-
-#ifdef CONFIG_ASSOCIATIVE_ARRAY
-
-#include <linux/assoc_array.h>
-
-#define ASSOC_ARRAY_FAN_OUT		16	/* Number of slots per node */
-#define ASSOC_ARRAY_FAN_MASK		(ASSOC_ARRAY_FAN_OUT - 1)
-#define ASSOC_ARRAY_LEVEL_STEP		(ilog2(ASSOC_ARRAY_FAN_OUT))
-#define ASSOC_ARRAY_LEVEL_STEP_MASK	(ASSOC_ARRAY_LEVEL_STEP - 1)
-#define ASSOC_ARRAY_KEY_CHUNK_MASK	(ASSOC_ARRAY_KEY_CHUNK_SIZE - 1)
-#define ASSOC_ARRAY_KEY_CHUNK_SHIFT	(ilog2(BITS_PER_LONG))
-
-/*
- * Undefined type representing a pointer with type information in the bottom
- * two bits.
- */
-struct assoc_array_ptr;
-
-/*
- * An N-way node in the tree.
- *
- * Each slot contains one of four things:
- *
- *	(1) Nothing (NULL).
- *
- *	(2) A leaf object (pointer types 0).
- *
- *	(3) A next-level node (pointer type 1, subtype 0).
- *
- *	(4) A shortcut (pointer type 1, subtype 1).
- *
- * The tree is optimised for search-by-ID, but permits reasonable iteration
- * also.
- *
- * The tree is navigated by constructing an index key consisting of an array of
- * segments, where each segment is ilog2(ASSOC_ARRAY_FAN_OUT) bits in size.
- *
- * The segments correspond to levels of the tree (the first segment is used at
- * level 0, the second at level 1, etc.).
- */
-struct assoc_array_node {
-	struct assoc_array_ptr	*back_pointer;
-	u8			parent_slot;
-	struct assoc_array_ptr	*slots[ASSOC_ARRAY_FAN_OUT];
-	unsigned long		nr_leaves_on_branch;
-};
-
-/*
- * A shortcut through the index space out to where a collection of nodes/leaves
- * with the same IDs live.
- */
-struct assoc_array_shortcut {
-	struct assoc_array_ptr	*back_pointer;
-	int			parent_slot;
-	int			skip_to_level;
-	struct assoc_array_ptr	*next_node;
-	unsigned long		index_key[];
-};
-
-/*
- * Preallocation cache.
- */
-struct assoc_array_edit {
-	struct rcu_head			rcu;
-	struct assoc_array		*array;
-	const struct assoc_array_ops	*ops;
-	const struct assoc_array_ops	*ops_for_excised_subtree;
-	struct assoc_array_ptr		*leaf;
-	struct assoc_array_ptr		**leaf_p;
-	struct assoc_array_ptr		*dead_leaf;
-	struct assoc_array_ptr		*new_meta[3];
-	struct assoc_array_ptr		*excised_meta[1];
-	struct assoc_array_ptr		*excised_subtree;
-	struct assoc_array_ptr		**set_backpointers[ASSOC_ARRAY_FAN_OUT];
-	struct assoc_array_ptr		*set_backpointers_to;
-	struct assoc_array_node		*adjust_count_on;
-	long				adjust_count_by;
-	struct {
-		struct assoc_array_ptr	**ptr;
-		struct assoc_array_ptr	*to;
-	} set[2];
-	struct {
-		u8			*p;
-		u8			to;
-	} set_parent_slot[1];
-	u8				segment_cache[ASSOC_ARRAY_FAN_OUT + 1];
-};
-
-/*
- * Internal tree member pointers are marked in the bottom one or two bits to
- * indicate what type they are so that we don't have to look behind every
- * pointer to see what it points to.
- *
- * We provide functions to test type annotations and to create and translate
- * the annotated pointers.
- */
-#define ASSOC_ARRAY_PTR_TYPE_MASK 0x1UL
-#define ASSOC_ARRAY_PTR_LEAF_TYPE 0x0UL	/* Points to leaf (or nowhere) */
-#define ASSOC_ARRAY_PTR_META_TYPE 0x1UL	/* Points to node or shortcut */
-#define ASSOC_ARRAY_PTR_SUBTYPE_MASK	0x2UL
-#define ASSOC_ARRAY_PTR_NODE_SUBTYPE	0x0UL
-#define ASSOC_ARRAY_PTR_SHORTCUT_SUBTYPE 0x2UL
-
-static inline bool assoc_array_ptr_is_meta(const struct assoc_array_ptr *x)
-{
-	return (unsigned long)x & ASSOC_ARRAY_PTR_TYPE_MASK;
-}
-static inline bool assoc_array_ptr_is_leaf(const struct assoc_array_ptr *x)
-{
-	return !assoc_array_ptr_is_meta(x);
-}
-static inline bool assoc_array_ptr_is_shortcut(const struct assoc_array_ptr *x)
-{
-	return (unsigned long)x & ASSOC_ARRAY_PTR_SUBTYPE_MASK;
-}
-static inline bool assoc_array_ptr_is_node(const struct assoc_array_ptr *x)
-{
-	return !assoc_array_ptr_is_shortcut(x);
-}
-
-static inline void *assoc_array_ptr_to_leaf(const struct assoc_array_ptr *x)
-{
-	return (void *)((unsigned long)x & ~ASSOC_ARRAY_PTR_TYPE_MASK);
-}
-
-static inline
-unsigned long __assoc_array_ptr_to_meta(const struct assoc_array_ptr *x)
-{
-	return (unsigned long)x &
-		~(ASSOC_ARRAY_PTR_SUBTYPE_MASK | ASSOC_ARRAY_PTR_TYPE_MASK);
-}
-static inline
-struct assoc_array_node *assoc_array_ptr_to_node(const struct assoc_array_ptr *x)
-{
-	return (struct assoc_array_node *)__assoc_array_ptr_to_meta(x);
-}
-static inline
-struct assoc_array_shortcut *assoc_array_ptr_to_shortcut(const struct assoc_array_ptr *x)
-{
-	return (struct assoc_array_shortcut *)__assoc_array_ptr_to_meta(x);
-}
-
-static inline
-struct assoc_array_ptr *__assoc_array_x_to_ptr(const void *p, unsigned long t)
-{
-	return (struct assoc_array_ptr *)((unsigned long)p | t);
-}
-static inline
-struct assoc_array_ptr *assoc_array_leaf_to_ptr(const void *p)
-{
-	return __assoc_array_x_to_ptr(p, ASSOC_ARRAY_PTR_LEAF_TYPE);
-}
-static inline
-struct assoc_array_ptr *assoc_array_node_to_ptr(const struct assoc_array_node *p)
-{
-	return __assoc_array_x_to_ptr(
-		p, ASSOC_ARRAY_PTR_META_TYPE | ASSOC_ARRAY_PTR_NODE_SUBTYPE);
-}
-static inline
-struct assoc_array_ptr *assoc_array_shortcut_to_ptr(const struct assoc_array_shortcut *p)
-{
-	return __assoc_array_x_to_ptr(
-		p, ASSOC_ARRAY_PTR_META_TYPE | ASSOC_ARRAY_PTR_SHORTCUT_SUBTYPE);
-}
-
-#endif /* CONFIG_ASSOCIATIVE_ARRAY */
-#endif /* _LINUX_ASSOC_ARRAY_PRIV_H */
diff --git a/include/linux/key-type.h b/include/linux/key-type.h
index c4f329b6ae3fed..bb97bd3e5af4fa 100644
--- a/include/linux/key-type.h
+++ b/include/linux/key-type.h
@@ -161,7 +161,6 @@ struct key_type {
 				     const void *in, const void *in2);
 
 	/* internal fields */
-	atomic64_t		index_id;	/* Opaque keyring index ID */
 	struct list_head	link;		/* link in types list */
 	struct lock_class_key	lock_class;	/* key->sem lock class */
 } __randomize_layout;
diff --git a/include/linux/key.h b/include/linux/key.h
index 420412aab9263a..0d2d64e10f7baf 100644
--- a/include/linux/key.h
+++ b/include/linux/key.h
@@ -17,7 +17,6 @@
 #include <linux/sysctl.h>
 #include <linux/rwsem.h>
 #include <linux/atomic.h>
-#include <linux/assoc_array.h>
 #include <linux/refcount.h>
 #include <linux/time64.h>
 
@@ -107,34 +106,21 @@ struct key_owner;
 struct key_tag;
 struct keyring_list;
 struct keyring_name;
+struct keyring_index;
 
 struct key_tag {
 	struct rcu_head		rcu;
-	atomic64_t		index_id;	/* Opaque keyring index ID */
 	refcount_t		usage;
 	bool			removed;	/* T when subject removed */
 };
 
 struct keyring_index_key {
 	/* [!] If this structure is altered, the union in struct key must change too! */
-	unsigned long		hash;			/* Hash value */
-	union {
-		struct {
-#ifdef __LITTLE_ENDIAN /* Put desc_len at the LSB of x */
-			u16	desc_len;
-			char	desc[sizeof(long) - 2];	/* First few chars of description */
-#else
-			char	desc[sizeof(long) - 2];	/* First few chars of description */
-			u16	desc_len;
-#endif
-		};
-		unsigned long x;
-	};
+	u32			hash;			/* Hash value */
+	unsigned int		desc_len;
 	struct key_type		*type;
 	struct key_tag		*domain_tag;	/* Domain of operation */
 	const char		*description;
-	u64			type_id;	/* Cached index IDs */
-	u64			domain_id;
 };
 
 union key_payload {
@@ -252,13 +238,11 @@ struct key {
 	union {
 		struct keyring_index_key index_key;
 		struct {
-			unsigned long	hash;
-			unsigned long	len_desc;
+			u32		hash;
+			unsigned int	desc_len;
 			struct key_type	*type;		/* type of key */
 			struct key_tag	*domain_tag;	/* Domain of operation */
 			char		*description;
-			u64		type_id;
-			u64		domain_id;
 		};
 	};
 
@@ -271,7 +255,7 @@ struct key {
 		struct {
 			/* Keyring bits */
 			struct list_head name_link;
-			struct assoc_array keys;
+			struct keyring_index __rcu *index;
 		};
 	};
 
@@ -439,6 +423,7 @@ extern int restrict_link_reject(struct key *keyring,
 				struct key *restriction_key);
 
 extern int keyring_clear(struct key *keyring);
+bool keyring_is_empty(const struct key *keyring);
 
 extern key_ref_t keyring_search(key_ref_t keyring,
 				struct key_type *type,
diff --git a/kernel/bpf/keys.c b/kernel/bpf/keys.c
index bffc356839ac56..24e0416abc99dd 100644
--- a/kernel/bpf/keys.c
+++ b/kernel/bpf/keys.c
@@ -29,7 +29,7 @@ struct bpf_key *bpf_lookup_keyring(void)
 
 	if (!bpf_keyring)
 		return NULL;
-	if (!READ_ONCE(bpf_keyring->keys.nr_leaves_on_tree) ||
+	if (keyring_is_empty(bpf_keyring) ||
 	    !READ_ONCE(bpf_keyring->restrict_link))
 		return NULL;
 
diff --git a/lib/Kconfig b/lib/Kconfig
index 1e42f5167c68bc..f70382dbb15954 100644
--- a/lib/Kconfig
+++ b/lib/Kconfig
@@ -349,20 +349,6 @@ config XARRAY_MULTI
 	  Support entries which occupy multiple consecutive indices in the
 	  XArray.
 
-config ASSOCIATIVE_ARRAY
-	bool
-	help
-	  Generic associative array.  Can be searched and iterated over whilst
-	  it is being modified.  It is also reasonably quick to search and
-	  modify.  The algorithms are non-recursive, and the trees are highly
-	  capacious.
-
-	  See:
-
-		Documentation/core-api/assoc_array.rst
-
-	  for more information.
-
 config CLOSURES
 	bool
 
diff --git a/lib/Makefile b/lib/Makefile
index a2afe954805cb8..4777dfcc824405 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -141,7 +141,6 @@ obj-$(CONFIG_GENERIC_HWEIGHT) += hweight.o
 
 obj-$(CONFIG_BTREE) += btree.o
 obj-$(CONFIG_INTERVAL_TREE) += interval_tree.o
-obj-$(CONFIG_ASSOCIATIVE_ARRAY) += assoc_array.o
 obj-$(CONFIG_DEBUG_PREEMPT) += smp_processor_id.o
 obj-$(CONFIG_LIST_HARDENED) += list_debug.o
 obj-$(CONFIG_DEBUG_OBJECTS) += debugobjects.o
diff --git a/lib/assoc_array.c b/lib/assoc_array.c
deleted file mode 100644
index b6c9723e12ced5..00000000000000
--- a/lib/assoc_array.c
+++ /dev/null
@@ -1,1724 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0-or-later
-/* Generic associative array implementation.
- *
- * See Documentation/core-api/assoc_array.rst for information.
- *
- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.
- * Written by David Howells (dhowells@redhat.com)
- */
-//#define DEBUG
-#include <linux/rcupdate.h>
-#include <linux/slab.h>
-#include <linux/err.h>
-#include <linux/assoc_array_priv.h>
-
-/*
- * Iterate over an associative array.  The caller must hold the RCU read lock
- * or better.
- */
-static int assoc_array_subtree_iterate(const struct assoc_array_ptr *root,
-				       const struct assoc_array_ptr *stop,
-				       int (*iterator)(const void *leaf,
-						       void *iterator_data),
-				       void *iterator_data)
-{
-	const struct assoc_array_shortcut *shortcut;
-	const struct assoc_array_node *node;
-	const struct assoc_array_ptr *cursor, *ptr, *parent;
-	unsigned long has_meta;
-	int slot, ret;
-
-	cursor = root;
-
-begin_node:
-	if (assoc_array_ptr_is_shortcut(cursor)) {
-		/* Descend through a shortcut */
-		shortcut = assoc_array_ptr_to_shortcut(cursor);
-		cursor = READ_ONCE(shortcut->next_node); /* Address dependency. */
-	}
-
-	node = assoc_array_ptr_to_node(cursor);
-	slot = 0;
-
-	/* We perform two passes of each node.
-	 *
-	 * The first pass does all the leaves in this node.  This means we
-	 * don't miss any leaves if the node is split up by insertion whilst
-	 * we're iterating over the branches rooted here (we may, however, see
-	 * some leaves twice).
-	 */
-	has_meta = 0;
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-		has_meta |= (unsigned long)ptr;
-		if (ptr && assoc_array_ptr_is_leaf(ptr)) {
-			/* We need a barrier between the read of the pointer,
-			 * which is supplied by the above READ_ONCE().
-			 */
-			/* Invoke the callback */
-			ret = iterator(assoc_array_ptr_to_leaf(ptr),
-				       iterator_data);
-			if (ret)
-				return ret;
-		}
-	}
-
-	/* The second pass attends to all the metadata pointers.  If we follow
-	 * one of these we may find that we don't come back here, but rather go
-	 * back to a replacement node with the leaves in a different layout.
-	 *
-	 * We are guaranteed to make progress, however, as the slot number for
-	 * a particular portion of the key space cannot change - and we
-	 * continue at the back pointer + 1.
-	 */
-	if (!(has_meta & ASSOC_ARRAY_PTR_META_TYPE))
-		goto finished_node;
-	slot = 0;
-
-continue_node:
-	node = assoc_array_ptr_to_node(cursor);
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-		if (assoc_array_ptr_is_meta(ptr)) {
-			cursor = ptr;
-			goto begin_node;
-		}
-	}
-
-finished_node:
-	/* Move up to the parent (may need to skip back over a shortcut) */
-	parent = READ_ONCE(node->back_pointer); /* Address dependency. */
-	slot = node->parent_slot;
-	if (parent == stop)
-		return 0;
-
-	if (assoc_array_ptr_is_shortcut(parent)) {
-		shortcut = assoc_array_ptr_to_shortcut(parent);
-		cursor = parent;
-		parent = READ_ONCE(shortcut->back_pointer); /* Address dependency. */
-		slot = shortcut->parent_slot;
-		if (parent == stop)
-			return 0;
-	}
-
-	/* Ascend to next slot in parent node */
-	cursor = parent;
-	slot++;
-	goto continue_node;
-}
-
-/**
- * assoc_array_iterate - Pass all objects in the array to a callback
- * @array: The array to iterate over.
- * @iterator: The callback function.
- * @iterator_data: Private data for the callback function.
- *
- * Iterate over all the objects in an associative array.  Each one will be
- * presented to the iterator function.
- *
- * If the array is being modified concurrently with the iteration then it is
- * possible that some objects in the array will be passed to the iterator
- * callback more than once - though every object should be passed at least
- * once.  If this is undesirable then the caller must lock against modification
- * for the duration of this function.
- *
- * The function will return 0 if no objects were in the array or else it will
- * return the result of the last iterator function called.  Iteration stops
- * immediately if any call to the iteration function results in a non-zero
- * return.
- *
- * The caller should hold the RCU read lock or better if concurrent
- * modification is possible.
- */
-int assoc_array_iterate(const struct assoc_array *array,
-			int (*iterator)(const void *object,
-					void *iterator_data),
-			void *iterator_data)
-{
-	struct assoc_array_ptr *root = READ_ONCE(array->root); /* Address dependency. */
-
-	if (!root)
-		return 0;
-	return assoc_array_subtree_iterate(root, NULL, iterator, iterator_data);
-}
-
-enum assoc_array_walk_status {
-	assoc_array_walk_tree_empty,
-	assoc_array_walk_found_terminal_node,
-	assoc_array_walk_found_wrong_shortcut,
-};
-
-struct assoc_array_walk_result {
-	struct {
-		struct assoc_array_node	*node;	/* Node in which leaf might be found */
-		int		level;
-		int		slot;
-	} terminal_node;
-	struct {
-		struct assoc_array_shortcut *shortcut;
-		int		level;
-		int		sc_level;
-		unsigned long	sc_segments;
-		unsigned long	dissimilarity;
-	} wrong_shortcut;
-};
-
-/*
- * Navigate through the internal tree looking for the closest node to the key.
- */
-static enum assoc_array_walk_status
-assoc_array_walk(const struct assoc_array *array,
-		 const struct assoc_array_ops *ops,
-		 const void *index_key,
-		 struct assoc_array_walk_result *result)
-{
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *cursor, *ptr;
-	unsigned long sc_segments, dissimilarity;
-	unsigned long segments;
-	int level, sc_level, next_sc_level;
-	int slot;
-
-	pr_devel("-->%s()\n", __func__);
-
-	cursor = READ_ONCE(array->root);  /* Address dependency. */
-	if (!cursor)
-		return assoc_array_walk_tree_empty;
-
-	level = 0;
-
-	/* Use segments from the key for the new leaf to navigate through the
-	 * internal tree, skipping through nodes and shortcuts that are on
-	 * route to the destination.  Eventually we'll come to a slot that is
-	 * either empty or contains a leaf at which point we've found a node in
-	 * which the leaf we're looking for might be found or into which it
-	 * should be inserted.
-	 */
-jumped:
-	segments = ops->get_key_chunk(index_key, level);
-	pr_devel("segments[%d]: %lx\n", level, segments);
-
-	if (assoc_array_ptr_is_shortcut(cursor))
-		goto follow_shortcut;
-
-consider_node:
-	node = assoc_array_ptr_to_node(cursor);
-	slot = segments >> (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
-	slot &= ASSOC_ARRAY_FAN_MASK;
-	ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-
-	pr_devel("consider slot %x [ix=%d type=%lu]\n",
-		 slot, level, (unsigned long)ptr & 3);
-
-	if (!assoc_array_ptr_is_meta(ptr)) {
-		/* The node doesn't have a node/shortcut pointer in the slot
-		 * corresponding to the index key that we have to follow.
-		 */
-		result->terminal_node.node = node;
-		result->terminal_node.level = level;
-		result->terminal_node.slot = slot;
-		pr_devel("<--%s() = terminal_node\n", __func__);
-		return assoc_array_walk_found_terminal_node;
-	}
-
-	if (assoc_array_ptr_is_node(ptr)) {
-		/* There is a pointer to a node in the slot corresponding to
-		 * this index key segment, so we need to follow it.
-		 */
-		cursor = ptr;
-		level += ASSOC_ARRAY_LEVEL_STEP;
-		if ((level & ASSOC_ARRAY_KEY_CHUNK_MASK) != 0)
-			goto consider_node;
-		goto jumped;
-	}
-
-	/* There is a shortcut in the slot corresponding to the index key
-	 * segment.  We follow the shortcut if its partial index key matches
-	 * this leaf's.  Otherwise we need to split the shortcut.
-	 */
-	cursor = ptr;
-follow_shortcut:
-	shortcut = assoc_array_ptr_to_shortcut(cursor);
-	pr_devel("shortcut to %d\n", shortcut->skip_to_level);
-	sc_level = level + ASSOC_ARRAY_LEVEL_STEP;
-	BUG_ON(sc_level > shortcut->skip_to_level);
-
-	do {
-		/* Check the leaf against the shortcut's index key a word at a
-		 * time, trimming the final word (the shortcut stores the index
-		 * key completely from the root to the shortcut's target).
-		 */
-		if ((sc_level & ASSOC_ARRAY_KEY_CHUNK_MASK) == 0)
-			segments = ops->get_key_chunk(index_key, sc_level);
-
-		sc_segments = shortcut->index_key[sc_level >> ASSOC_ARRAY_KEY_CHUNK_SHIFT];
-		dissimilarity = segments ^ sc_segments;
-
-		if (shortcut->skip_to_level < round_down(sc_level,
-				ASSOC_ARRAY_KEY_CHUNK_SIZE) + ASSOC_ARRAY_KEY_CHUNK_SIZE) {
-			/* Trim segments that are beyond the shortcut */
-			int shift = shortcut->skip_to_level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-			dissimilarity &= ~(ULONG_MAX << shift);
-			next_sc_level = shortcut->skip_to_level;
-		} else {
-			next_sc_level = sc_level + ASSOC_ARRAY_KEY_CHUNK_SIZE;
-			next_sc_level = round_down(next_sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		}
-
-		if (dissimilarity != 0) {
-			/* This shortcut points elsewhere */
-			result->wrong_shortcut.shortcut = shortcut;
-			result->wrong_shortcut.level = level;
-			result->wrong_shortcut.sc_level = sc_level;
-			result->wrong_shortcut.sc_segments = sc_segments;
-			result->wrong_shortcut.dissimilarity = dissimilarity;
-			return assoc_array_walk_found_wrong_shortcut;
-		}
-
-		sc_level = next_sc_level;
-	} while (sc_level < shortcut->skip_to_level);
-
-	/* The shortcut matches the leaf's index to this point. */
-	cursor = READ_ONCE(shortcut->next_node); /* Address dependency. */
-	if (((level ^ sc_level) & ~ASSOC_ARRAY_KEY_CHUNK_MASK) != 0) {
-		level = sc_level;
-		goto jumped;
-	} else {
-		level = sc_level;
-		goto consider_node;
-	}
-}
-
-/**
- * assoc_array_find - Find an object by index key
- * @array: The associative array to search.
- * @ops: The operations to use.
- * @index_key: The key to the object.
- *
- * Find an object in an associative array by walking through the internal tree
- * to the node that should contain the object and then searching the leaves
- * there.  NULL is returned if the requested object was not found in the array.
- *
- * The caller must hold the RCU read lock or better.
- */
-void *assoc_array_find(const struct assoc_array *array,
-		       const struct assoc_array_ops *ops,
-		       const void *index_key)
-{
-	struct assoc_array_walk_result result;
-	const struct assoc_array_node *node;
-	const struct assoc_array_ptr *ptr;
-	const void *leaf;
-	int slot;
-
-	if (assoc_array_walk(array, ops, index_key, &result) !=
-	    assoc_array_walk_found_terminal_node)
-		return NULL;
-
-	node = result.terminal_node.node;
-
-	/* If the target key is available to us, it's has to be pointed to by
-	 * the terminal node.
-	 */
-	for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-		if (ptr && assoc_array_ptr_is_leaf(ptr)) {
-			/* We need a barrier between the read of the pointer
-			 * and dereferencing the pointer - but only if we are
-			 * actually going to dereference it.
-			 */
-			leaf = assoc_array_ptr_to_leaf(ptr);
-			if (ops->compare_object(leaf, index_key))
-				return (void *)leaf;
-		}
-	}
-
-	return NULL;
-}
-
-/*
- * Destructively iterate over an associative array.  The caller must prevent
- * other simultaneous accesses.
- */
-static void assoc_array_destroy_subtree(struct assoc_array_ptr *root,
-					const struct assoc_array_ops *ops)
-{
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *cursor, *parent = NULL;
-	int slot = -1;
-
-	pr_devel("-->%s()\n", __func__);
-
-	cursor = root;
-	if (!cursor) {
-		pr_devel("empty\n");
-		return;
-	}
-
-move_to_meta:
-	if (assoc_array_ptr_is_shortcut(cursor)) {
-		/* Descend through a shortcut */
-		pr_devel("[%d] shortcut\n", slot);
-		BUG_ON(!assoc_array_ptr_is_shortcut(cursor));
-		shortcut = assoc_array_ptr_to_shortcut(cursor);
-		BUG_ON(shortcut->back_pointer != parent);
-		BUG_ON(slot != -1 && shortcut->parent_slot != slot);
-		parent = cursor;
-		cursor = shortcut->next_node;
-		slot = -1;
-		BUG_ON(!assoc_array_ptr_is_node(cursor));
-	}
-
-	pr_devel("[%d] node\n", slot);
-	node = assoc_array_ptr_to_node(cursor);
-	BUG_ON(node->back_pointer != parent);
-	BUG_ON(slot != -1 && node->parent_slot != slot);
-	slot = 0;
-
-continue_node:
-	pr_devel("Node %p [back=%p]\n", node, node->back_pointer);
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		struct assoc_array_ptr *ptr = node->slots[slot];
-		if (!ptr)
-			continue;
-		if (assoc_array_ptr_is_meta(ptr)) {
-			parent = cursor;
-			cursor = ptr;
-			goto move_to_meta;
-		}
-
-		if (ops) {
-			pr_devel("[%d] free leaf\n", slot);
-			ops->free_object(assoc_array_ptr_to_leaf(ptr));
-		}
-	}
-
-	parent = node->back_pointer;
-	slot = node->parent_slot;
-	pr_devel("free node\n");
-	kfree(node);
-	if (!parent)
-		return; /* Done */
-
-	/* Move back up to the parent (may need to free a shortcut on
-	 * the way up) */
-	if (assoc_array_ptr_is_shortcut(parent)) {
-		shortcut = assoc_array_ptr_to_shortcut(parent);
-		BUG_ON(shortcut->next_node != cursor);
-		cursor = parent;
-		parent = shortcut->back_pointer;
-		slot = shortcut->parent_slot;
-		pr_devel("free shortcut\n");
-		kfree(shortcut);
-		if (!parent)
-			return;
-
-		BUG_ON(!assoc_array_ptr_is_node(parent));
-	}
-
-	/* Ascend to next slot in parent node */
-	pr_devel("ascend to %p[%d]\n", parent, slot);
-	cursor = parent;
-	node = assoc_array_ptr_to_node(cursor);
-	slot++;
-	goto continue_node;
-}
-
-/**
- * assoc_array_destroy - Destroy an associative array
- * @array: The array to destroy.
- * @ops: The operations to use.
- *
- * Discard all metadata and free all objects in an associative array.  The
- * array will be empty and ready to use again upon completion.  This function
- * cannot fail.
- *
- * The caller must prevent all other accesses whilst this takes place as no
- * attempt is made to adjust pointers gracefully to permit RCU readlock-holding
- * accesses to continue.  On the other hand, no memory allocation is required.
- */
-void assoc_array_destroy(struct assoc_array *array,
-			 const struct assoc_array_ops *ops)
-{
-	assoc_array_destroy_subtree(array->root, ops);
-	array->root = NULL;
-}
-
-/*
- * Handle insertion into an empty tree.
- */
-static bool assoc_array_insert_in_empty_tree(struct assoc_array_edit *edit)
-{
-	struct assoc_array_node *new_n0;
-
-	pr_devel("-->%s()\n", __func__);
-
-	new_n0 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n0)
-		return false;
-
-	edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-	edit->leaf_p = &new_n0->slots[0];
-	edit->adjust_count_on = new_n0;
-	edit->set[0].ptr = &edit->array->root;
-	edit->set[0].to = assoc_array_node_to_ptr(new_n0);
-
-	pr_devel("<--%s() = ok [no root]\n", __func__);
-	return true;
-}
-
-/*
- * Handle insertion into a terminal node.
- */
-static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit,
-						  const struct assoc_array_ops *ops,
-						  const void *index_key,
-						  struct assoc_array_walk_result *result)
-{
-	struct assoc_array_shortcut *shortcut, *new_s0;
-	struct assoc_array_node *node, *new_n0, *new_n1, *side;
-	struct assoc_array_ptr *ptr;
-	unsigned long dissimilarity, base_seg, blank;
-	size_t keylen;
-	bool have_meta;
-	int level, diff;
-	int slot, next_slot, free_slot, i, j;
-
-	node	= result->terminal_node.node;
-	level	= result->terminal_node.level;
-	edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot;
-
-	pr_devel("-->%s()\n", __func__);
-
-	/* We arrived at a node which doesn't have an onward node or shortcut
-	 * pointer that we have to follow.  This means that (a) the leaf we
-	 * want must go here (either by insertion or replacement) or (b) we
-	 * need to split this node and insert in one of the fragments.
-	 */
-	free_slot = -1;
-
-	/* Firstly, we have to check the leaves in this node to see if there's
-	 * a matching one we should replace in place.
-	 */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		ptr = node->slots[i];
-		if (!ptr) {
-			free_slot = i;
-			continue;
-		}
-		if (assoc_array_ptr_is_leaf(ptr) &&
-		    ops->compare_object(assoc_array_ptr_to_leaf(ptr),
-					index_key)) {
-			pr_devel("replace in slot %d\n", i);
-			edit->leaf_p = &node->slots[i];
-			edit->dead_leaf = node->slots[i];
-			pr_devel("<--%s() = ok [replace]\n", __func__);
-			return true;
-		}
-	}
-
-	/* If there is a free slot in this node then we can just insert the
-	 * leaf here.
-	 */
-	if (free_slot >= 0) {
-		pr_devel("insert in free slot %d\n", free_slot);
-		edit->leaf_p = &node->slots[free_slot];
-		edit->adjust_count_on = node;
-		pr_devel("<--%s() = ok [insert]\n", __func__);
-		return true;
-	}
-
-	/* The node has no spare slots - so we're either going to have to split
-	 * it or insert another node before it.
-	 *
-	 * Whatever, we're going to need at least two new nodes - so allocate
-	 * those now.  We may also need a new shortcut, but we deal with that
-	 * when we need it.
-	 */
-	new_n0 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n0)
-		return false;
-	edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-	new_n1 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n1)
-		return false;
-	edit->new_meta[1] = assoc_array_node_to_ptr(new_n1);
-
-	/* We need to find out how similar the leaves are. */
-	pr_devel("no spare slots\n");
-	have_meta = false;
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		ptr = node->slots[i];
-		if (assoc_array_ptr_is_meta(ptr)) {
-			edit->segment_cache[i] = 0xff;
-			have_meta = true;
-			continue;
-		}
-		base_seg = ops->get_object_key_chunk(
-			assoc_array_ptr_to_leaf(ptr), level);
-		base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-		edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
-	}
-
-	if (have_meta) {
-		pr_devel("have meta\n");
-		goto split_node;
-	}
-
-	/* The node contains only leaves */
-	dissimilarity = 0;
-	base_seg = edit->segment_cache[0];
-	for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++)
-		dissimilarity |= edit->segment_cache[i] ^ base_seg;
-
-	pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity);
-
-	if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) {
-		/* The old leaves all cluster in the same slot.  We will need
-		 * to insert a shortcut if the new node wants to cluster with them.
-		 */
-		if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0)
-			goto all_leaves_cluster_together;
-
-		/* Otherwise all the old leaves cluster in the same slot, but
-		 * the new leaf wants to go into a different slot - so we
-		 * create a new node (n0) to hold the new leaf and a pointer to
-		 * a new node (n1) holding all the old leaves.
-		 *
-		 * This can be done by falling through to the node splitting
-		 * path.
-		 */
-		pr_devel("present leaves cluster but not new leaf\n");
-	}
-
-split_node:
-	pr_devel("split node\n");
-
-	/* We need to split the current node.  The node must contain anything
-	 * from a single leaf (in the one leaf case, this leaf will cluster
-	 * with the new leaf) and the rest meta-pointers, to all leaves, some
-	 * of which may cluster.
-	 *
-	 * It won't contain the case in which all the current leaves plus the
-	 * new leaves want to cluster in the same slot.
-	 *
-	 * We need to expel at least two leaves out of a set consisting of the
-	 * leaves in the node and the new leaf.  The current meta pointers can
-	 * just be copied as they shouldn't cluster with any of the leaves.
-	 *
-	 * We need a new node (n0) to replace the current one and a new node to
-	 * take the expelled nodes (n1).
-	 */
-	edit->set[0].to = assoc_array_node_to_ptr(new_n0);
-	new_n0->back_pointer = node->back_pointer;
-	new_n0->parent_slot = node->parent_slot;
-	new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
-	new_n1->parent_slot = -1; /* Need to calculate this */
-
-do_split_node:
-	pr_devel("do_split_node\n");
-
-	new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
-	new_n1->nr_leaves_on_branch = 0;
-
-	/* Begin by finding two matching leaves.  There have to be at least two
-	 * that match - even if there are meta pointers - because any leaf that
-	 * would match a slot with a meta pointer in it must be somewhere
-	 * behind that meta pointer and cannot be here.  Further, given N
-	 * remaining leaf slots, we now have N+1 leaves to go in them.
-	 */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		slot = edit->segment_cache[i];
-		if (slot != 0xff)
-			for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++)
-				if (edit->segment_cache[j] == slot)
-					goto found_slot_for_multiple_occupancy;
-	}
-found_slot_for_multiple_occupancy:
-	pr_devel("same slot: %x %x [%02x]\n", i, j, slot);
-	BUG_ON(i >= ASSOC_ARRAY_FAN_OUT);
-	BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1);
-	BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT);
-
-	new_n1->parent_slot = slot;
-
-	/* Metadata pointers cannot change slot */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
-		if (assoc_array_ptr_is_meta(node->slots[i]))
-			new_n0->slots[i] = node->slots[i];
-		else
-			new_n0->slots[i] = NULL;
-	BUG_ON(new_n0->slots[slot] != NULL);
-	new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1);
-
-	/* Filter the leaf pointers between the new nodes */
-	free_slot = -1;
-	next_slot = 0;
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		if (assoc_array_ptr_is_meta(node->slots[i]))
-			continue;
-		if (edit->segment_cache[i] == slot) {
-			new_n1->slots[next_slot++] = node->slots[i];
-			new_n1->nr_leaves_on_branch++;
-		} else {
-			do {
-				free_slot++;
-			} while (new_n0->slots[free_slot] != NULL);
-			new_n0->slots[free_slot] = node->slots[i];
-		}
-	}
-
-	pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot);
-
-	if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) {
-		do {
-			free_slot++;
-		} while (new_n0->slots[free_slot] != NULL);
-		edit->leaf_p = &new_n0->slots[free_slot];
-		edit->adjust_count_on = new_n0;
-	} else {
-		edit->leaf_p = &new_n1->slots[next_slot++];
-		edit->adjust_count_on = new_n1;
-	}
-
-	BUG_ON(next_slot <= 1);
-
-	edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0);
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		if (edit->segment_cache[i] == 0xff) {
-			ptr = node->slots[i];
-			BUG_ON(assoc_array_ptr_is_leaf(ptr));
-			if (assoc_array_ptr_is_node(ptr)) {
-				side = assoc_array_ptr_to_node(ptr);
-				edit->set_backpointers[i] = &side->back_pointer;
-			} else {
-				shortcut = assoc_array_ptr_to_shortcut(ptr);
-				edit->set_backpointers[i] = &shortcut->back_pointer;
-			}
-		}
-	}
-
-	ptr = node->back_pointer;
-	if (!ptr)
-		edit->set[0].ptr = &edit->array->root;
-	else if (assoc_array_ptr_is_node(ptr))
-		edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot];
-	else
-		edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node;
-	edit->excised_meta[0] = assoc_array_node_to_ptr(node);
-	pr_devel("<--%s() = ok [split node]\n", __func__);
-	return true;
-
-all_leaves_cluster_together:
-	/* All the leaves, new and old, want to cluster together in this node
-	 * in the same slot, so we have to replace this node with a shortcut to
-	 * skip over the identical parts of the key and then place a pair of
-	 * nodes, one inside the other, at the end of the shortcut and
-	 * distribute the keys between them.
-	 *
-	 * Firstly we need to work out where the leaves start diverging as a
-	 * bit position into their keys so that we know how big the shortcut
-	 * needs to be.
-	 *
-	 * We only need to make a single pass of N of the N+1 leaves because if
-	 * any keys differ between themselves at bit X then at least one of
-	 * them must also differ with the base key at bit X or before.
-	 */
-	pr_devel("all leaves cluster together\n");
-	diff = INT_MAX;
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]),
-					  index_key);
-		if (x < diff) {
-			BUG_ON(x < 0);
-			diff = x;
-		}
-	}
-	BUG_ON(diff == INT_MAX);
-	BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP);
-
-	keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-	keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-
-	new_s0 = kzalloc_flex(*new_s0, index_key, keylen);
-	if (!new_s0)
-		return false;
-	edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0);
-
-	edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
-	new_s0->back_pointer = node->back_pointer;
-	new_s0->parent_slot = node->parent_slot;
-	new_s0->next_node = assoc_array_node_to_ptr(new_n0);
-	new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
-	new_n0->parent_slot = 0;
-	new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
-	new_n1->parent_slot = -1; /* Need to calculate this */
-
-	new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK;
-	pr_devel("skip_to_level = %d [diff %d]\n", level, diff);
-	BUG_ON(level <= 0);
-
-	for (i = 0; i < keylen; i++)
-		new_s0->index_key[i] =
-			ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE);
-
-	if (level & ASSOC_ARRAY_KEY_CHUNK_MASK) {
-		blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
-		pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank);
-		new_s0->index_key[keylen - 1] &= ~blank;
-	}
-
-	/* This now reduces to a node splitting exercise for which we'll need
-	 * to regenerate the disparity table.
-	 */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		ptr = node->slots[i];
-		base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr),
-						     level);
-		base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-		edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
-	}
-
-	base_seg = ops->get_key_chunk(index_key, level);
-	base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-	edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK;
-	goto do_split_node;
-}
-
-/*
- * Handle insertion into the middle of a shortcut.
- */
-static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit,
-					    const struct assoc_array_ops *ops,
-					    struct assoc_array_walk_result *result)
-{
-	struct assoc_array_shortcut *shortcut, *new_s0, *new_s1;
-	struct assoc_array_node *node, *new_n0, *side;
-	unsigned long sc_segments, dissimilarity, blank;
-	size_t keylen;
-	int level, sc_level, diff;
-	int sc_slot;
-
-	shortcut	= result->wrong_shortcut.shortcut;
-	level		= result->wrong_shortcut.level;
-	sc_level	= result->wrong_shortcut.sc_level;
-	sc_segments	= result->wrong_shortcut.sc_segments;
-	dissimilarity	= result->wrong_shortcut.dissimilarity;
-
-	pr_devel("-->%s(ix=%d dis=%lx scix=%d)\n",
-		 __func__, level, dissimilarity, sc_level);
-
-	/* We need to split a shortcut and insert a node between the two
-	 * pieces.  Zero-length pieces will be dispensed with entirely.
-	 *
-	 * First of all, we need to find out in which level the first
-	 * difference was.
-	 */
-	diff = __ffs(dissimilarity);
-	diff &= ~ASSOC_ARRAY_LEVEL_STEP_MASK;
-	diff += sc_level & ~ASSOC_ARRAY_KEY_CHUNK_MASK;
-	pr_devel("diff=%d\n", diff);
-
-	if (!shortcut->back_pointer) {
-		edit->set[0].ptr = &edit->array->root;
-	} else if (assoc_array_ptr_is_node(shortcut->back_pointer)) {
-		node = assoc_array_ptr_to_node(shortcut->back_pointer);
-		edit->set[0].ptr = &node->slots[shortcut->parent_slot];
-	} else {
-		BUG();
-	}
-
-	edit->excised_meta[0] = assoc_array_shortcut_to_ptr(shortcut);
-
-	/* Create a new node now since we're going to need it anyway */
-	new_n0 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n0)
-		return false;
-	edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-	edit->adjust_count_on = new_n0;
-
-	/* Insert a new shortcut before the new node if this segment isn't of
-	 * zero length - otherwise we just connect the new node directly to the
-	 * parent.
-	 */
-	level += ASSOC_ARRAY_LEVEL_STEP;
-	if (diff > level) {
-		pr_devel("pre-shortcut %d...%d\n", level, diff);
-		keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-
-		new_s0 = kzalloc_flex(*new_s0, index_key, keylen);
-		if (!new_s0)
-			return false;
-		edit->new_meta[1] = assoc_array_shortcut_to_ptr(new_s0);
-		edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
-		new_s0->back_pointer = shortcut->back_pointer;
-		new_s0->parent_slot = shortcut->parent_slot;
-		new_s0->next_node = assoc_array_node_to_ptr(new_n0);
-		new_s0->skip_to_level = diff;
-
-		new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
-		new_n0->parent_slot = 0;
-
-		memcpy(new_s0->index_key, shortcut->index_key,
-		       flex_array_size(new_s0, index_key, keylen));
-
-		blank = ULONG_MAX << (diff & ASSOC_ARRAY_KEY_CHUNK_MASK);
-		pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, diff, blank);
-		new_s0->index_key[keylen - 1] &= ~blank;
-	} else {
-		pr_devel("no pre-shortcut\n");
-		edit->set[0].to = assoc_array_node_to_ptr(new_n0);
-		new_n0->back_pointer = shortcut->back_pointer;
-		new_n0->parent_slot = shortcut->parent_slot;
-	}
-
-	side = assoc_array_ptr_to_node(shortcut->next_node);
-	new_n0->nr_leaves_on_branch = side->nr_leaves_on_branch;
-
-	/* We need to know which slot in the new node is going to take a
-	 * metadata pointer.
-	 */
-	sc_slot = sc_segments >> (diff & ASSOC_ARRAY_KEY_CHUNK_MASK);
-	sc_slot &= ASSOC_ARRAY_FAN_MASK;
-
-	pr_devel("new slot %lx >> %d -> %d\n",
-		 sc_segments, diff & ASSOC_ARRAY_KEY_CHUNK_MASK, sc_slot);
-
-	/* Determine whether we need to follow the new node with a replacement
-	 * for the current shortcut.  We could in theory reuse the current
-	 * shortcut if its parent slot number doesn't change - but that's a
-	 * 1-in-16 chance so not worth expending the code upon.
-	 */
-	level = diff + ASSOC_ARRAY_LEVEL_STEP;
-	if (level < shortcut->skip_to_level) {
-		pr_devel("post-shortcut %d...%d\n", level, shortcut->skip_to_level);
-		keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-
-		new_s1 = kzalloc_flex(*new_s1, index_key, keylen);
-		if (!new_s1)
-			return false;
-		edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s1);
-
-		new_s1->back_pointer = assoc_array_node_to_ptr(new_n0);
-		new_s1->parent_slot = sc_slot;
-		new_s1->next_node = shortcut->next_node;
-		new_s1->skip_to_level = shortcut->skip_to_level;
-
-		new_n0->slots[sc_slot] = assoc_array_shortcut_to_ptr(new_s1);
-
-		memcpy(new_s1->index_key, shortcut->index_key,
-		       flex_array_size(new_s1, index_key, keylen));
-
-		edit->set[1].ptr = &side->back_pointer;
-		edit->set[1].to = assoc_array_shortcut_to_ptr(new_s1);
-	} else {
-		pr_devel("no post-shortcut\n");
-
-		/* We don't have to replace the pointed-to node as long as we
-		 * use memory barriers to make sure the parent slot number is
-		 * changed before the back pointer (the parent slot number is
-		 * irrelevant to the old parent shortcut).
-		 */
-		new_n0->slots[sc_slot] = shortcut->next_node;
-		edit->set_parent_slot[0].p = &side->parent_slot;
-		edit->set_parent_slot[0].to = sc_slot;
-		edit->set[1].ptr = &side->back_pointer;
-		edit->set[1].to = assoc_array_node_to_ptr(new_n0);
-	}
-
-	/* Install the new leaf in a spare slot in the new node. */
-	if (sc_slot == 0)
-		edit->leaf_p = &new_n0->slots[1];
-	else
-		edit->leaf_p = &new_n0->slots[0];
-
-	pr_devel("<--%s() = ok [split shortcut]\n", __func__);
-	return true;
-}
-
-/**
- * assoc_array_insert - Script insertion of an object into an associative array
- * @array: The array to insert into.
- * @ops: The operations to use.
- * @index_key: The key to insert at.
- * @object: The object to insert.
- *
- * Precalculate and preallocate a script for the insertion or replacement of an
- * object in an associative array.  This results in an edit script that can
- * either be applied or cancelled.
- *
- * The function returns a pointer to an edit script or -ENOMEM.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-struct assoc_array_edit *assoc_array_insert(struct assoc_array *array,
-					    const struct assoc_array_ops *ops,
-					    const void *index_key,
-					    void *object)
-{
-	struct assoc_array_walk_result result;
-	struct assoc_array_edit *edit;
-
-	pr_devel("-->%s()\n", __func__);
-
-	/* The leaf pointer we're given must not have the bottom bit set as we
-	 * use those for type-marking the pointer.  NULL pointers are also not
-	 * allowed as they indicate an empty slot but we have to allow them
-	 * here as they can be updated later.
-	 */
-	BUG_ON(assoc_array_ptr_is_meta(object));
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return ERR_PTR(-ENOMEM);
-	edit->array = array;
-	edit->ops = ops;
-	edit->leaf = assoc_array_leaf_to_ptr(object);
-	edit->adjust_count_by = 1;
-
-	switch (assoc_array_walk(array, ops, index_key, &result)) {
-	case assoc_array_walk_tree_empty:
-		/* Allocate a root node if there isn't one yet */
-		if (!assoc_array_insert_in_empty_tree(edit))
-			goto enomem;
-		return edit;
-
-	case assoc_array_walk_found_terminal_node:
-		/* We found a node that doesn't have a node/shortcut pointer in
-		 * the slot corresponding to the index key that we have to
-		 * follow.
-		 */
-		if (!assoc_array_insert_into_terminal_node(edit, ops, index_key,
-							   &result))
-			goto enomem;
-		return edit;
-
-	case assoc_array_walk_found_wrong_shortcut:
-		/* We found a shortcut that didn't match our key in a slot we
-		 * needed to follow.
-		 */
-		if (!assoc_array_insert_mid_shortcut(edit, ops, &result))
-			goto enomem;
-		return edit;
-	}
-
-enomem:
-	/* Clean up after an out of memory error */
-	pr_devel("enomem\n");
-	assoc_array_cancel_edit(edit);
-	return ERR_PTR(-ENOMEM);
-}
-
-/**
- * assoc_array_insert_set_object - Set the new object pointer in an edit script
- * @edit: The edit script to modify.
- * @object: The object pointer to set.
- *
- * Change the object to be inserted in an edit script.  The object pointed to
- * by the old object is not freed.  This must be done prior to applying the
- * script.
- */
-void assoc_array_insert_set_object(struct assoc_array_edit *edit, void *object)
-{
-	BUG_ON(!object);
-	edit->leaf = assoc_array_leaf_to_ptr(object);
-}
-
-struct assoc_array_delete_collapse_context {
-	struct assoc_array_node	*node;
-	const void		*skip_leaf;
-	int			slot;
-};
-
-/*
- * Subtree collapse to node iterator.
- */
-static int assoc_array_delete_collapse_iterator(const void *leaf,
-						void *iterator_data)
-{
-	struct assoc_array_delete_collapse_context *collapse = iterator_data;
-
-	if (leaf == collapse->skip_leaf)
-		return 0;
-
-	BUG_ON(collapse->slot >= ASSOC_ARRAY_FAN_OUT);
-
-	collapse->node->slots[collapse->slot++] = assoc_array_leaf_to_ptr(leaf);
-	return 0;
-}
-
-/**
- * assoc_array_delete - Script deletion of an object from an associative array
- * @array: The array to search.
- * @ops: The operations to use.
- * @index_key: The key to the object.
- *
- * Precalculate and preallocate a script for the deletion of an object from an
- * associative array.  This results in an edit script that can either be
- * applied or cancelled.
- *
- * The function returns a pointer to an edit script if the object was found,
- * NULL if the object was not found or -ENOMEM.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-struct assoc_array_edit *assoc_array_delete(struct assoc_array *array,
-					    const struct assoc_array_ops *ops,
-					    const void *index_key)
-{
-	struct assoc_array_delete_collapse_context collapse;
-	struct assoc_array_walk_result result;
-	struct assoc_array_node *node, *new_n0;
-	struct assoc_array_edit *edit;
-	struct assoc_array_ptr *ptr;
-	bool has_meta;
-	int slot, i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return ERR_PTR(-ENOMEM);
-	edit->array = array;
-	edit->ops = ops;
-	edit->adjust_count_by = -1;
-
-	switch (assoc_array_walk(array, ops, index_key, &result)) {
-	case assoc_array_walk_found_terminal_node:
-		/* We found a node that should contain the leaf we've been
-		 * asked to remove - *if* it's in the tree.
-		 */
-		pr_devel("terminal_node\n");
-		node = result.terminal_node.node;
-
-		for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-			ptr = node->slots[slot];
-			if (ptr &&
-			    assoc_array_ptr_is_leaf(ptr) &&
-			    ops->compare_object(assoc_array_ptr_to_leaf(ptr),
-						index_key))
-				goto found_leaf;
-		}
-		fallthrough;
-	case assoc_array_walk_tree_empty:
-	case assoc_array_walk_found_wrong_shortcut:
-	default:
-		assoc_array_cancel_edit(edit);
-		pr_devel("not found\n");
-		return NULL;
-	}
-
-found_leaf:
-	BUG_ON(array->nr_leaves_on_tree <= 0);
-
-	/* In the simplest form of deletion we just clear the slot and release
-	 * the leaf after a suitable interval.
-	 */
-	edit->dead_leaf = node->slots[slot];
-	edit->set[0].ptr = &node->slots[slot];
-	edit->set[0].to = NULL;
-	edit->adjust_count_on = node;
-
-	/* If that concludes erasure of the last leaf, then delete the entire
-	 * internal array.
-	 */
-	if (array->nr_leaves_on_tree == 1) {
-		edit->set[1].ptr = &array->root;
-		edit->set[1].to = NULL;
-		edit->adjust_count_on = NULL;
-		edit->excised_subtree = array->root;
-		pr_devel("all gone\n");
-		return edit;
-	}
-
-	/* However, we'd also like to clear up some metadata blocks if we
-	 * possibly can.
-	 *
-	 * We go for a simple algorithm of: if this node has FAN_OUT or fewer
-	 * leaves in it, then attempt to collapse it - and attempt to
-	 * recursively collapse up the tree.
-	 *
-	 * We could also try and collapse in partially filled subtrees to take
-	 * up space in this node.
-	 */
-	if (node->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) {
-		struct assoc_array_node *parent, *grandparent;
-		struct assoc_array_ptr *ptr;
-
-		/* First of all, we need to know if this node has metadata so
-		 * that we don't try collapsing if all the leaves are already
-		 * here.
-		 */
-		has_meta = false;
-		for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-			ptr = node->slots[i];
-			if (assoc_array_ptr_is_meta(ptr)) {
-				has_meta = true;
-				break;
-			}
-		}
-
-		pr_devel("leaves: %ld [m=%d]\n",
-			 node->nr_leaves_on_branch - 1, has_meta);
-
-		/* Look further up the tree to see if we can collapse this node
-		 * into a more proximal node too.
-		 */
-		parent = node;
-	collapse_up:
-		pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch);
-
-		ptr = parent->back_pointer;
-		if (!ptr)
-			goto do_collapse;
-		if (assoc_array_ptr_is_shortcut(ptr)) {
-			struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(ptr);
-			ptr = s->back_pointer;
-			if (!ptr)
-				goto do_collapse;
-		}
-
-		grandparent = assoc_array_ptr_to_node(ptr);
-		if (grandparent->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) {
-			parent = grandparent;
-			goto collapse_up;
-		}
-
-	do_collapse:
-		/* There's no point collapsing if the original node has no meta
-		 * pointers to discard and if we didn't merge into one of that
-		 * node's ancestry.
-		 */
-		if (has_meta || parent != node) {
-			node = parent;
-
-			/* Create a new node to collapse into */
-			new_n0 = kzalloc_obj(struct assoc_array_node);
-			if (!new_n0)
-				goto enomem;
-			edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-
-			new_n0->back_pointer = node->back_pointer;
-			new_n0->parent_slot = node->parent_slot;
-			new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
-			edit->adjust_count_on = new_n0;
-
-			collapse.node = new_n0;
-			collapse.skip_leaf = assoc_array_ptr_to_leaf(edit->dead_leaf);
-			collapse.slot = 0;
-			assoc_array_subtree_iterate(assoc_array_node_to_ptr(node),
-						    node->back_pointer,
-						    assoc_array_delete_collapse_iterator,
-						    &collapse);
-			pr_devel("collapsed %d,%lu\n", collapse.slot, new_n0->nr_leaves_on_branch);
-			BUG_ON(collapse.slot != new_n0->nr_leaves_on_branch - 1);
-
-			if (!node->back_pointer) {
-				edit->set[1].ptr = &array->root;
-			} else if (assoc_array_ptr_is_leaf(node->back_pointer)) {
-				BUG();
-			} else if (assoc_array_ptr_is_node(node->back_pointer)) {
-				struct assoc_array_node *p =
-					assoc_array_ptr_to_node(node->back_pointer);
-				edit->set[1].ptr = &p->slots[node->parent_slot];
-			} else if (assoc_array_ptr_is_shortcut(node->back_pointer)) {
-				struct assoc_array_shortcut *s =
-					assoc_array_ptr_to_shortcut(node->back_pointer);
-				edit->set[1].ptr = &s->next_node;
-			}
-			edit->set[1].to = assoc_array_node_to_ptr(new_n0);
-			edit->excised_subtree = assoc_array_node_to_ptr(node);
-		}
-	}
-
-	return edit;
-
-enomem:
-	/* Clean up after an out of memory error */
-	pr_devel("enomem\n");
-	assoc_array_cancel_edit(edit);
-	return ERR_PTR(-ENOMEM);
-}
-
-/**
- * assoc_array_clear - Script deletion of all objects from an associative array
- * @array: The array to clear.
- * @ops: The operations to use.
- *
- * Precalculate and preallocate a script for the deletion of all the objects
- * from an associative array.  This results in an edit script that can either
- * be applied or cancelled.
- *
- * The function returns a pointer to an edit script if there are objects to be
- * deleted, NULL if there are no objects in the array or -ENOMEM.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-struct assoc_array_edit *assoc_array_clear(struct assoc_array *array,
-					   const struct assoc_array_ops *ops)
-{
-	struct assoc_array_edit *edit;
-
-	pr_devel("-->%s()\n", __func__);
-
-	if (!array->root)
-		return NULL;
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return ERR_PTR(-ENOMEM);
-	edit->array = array;
-	edit->ops = ops;
-	edit->set[1].ptr = &array->root;
-	edit->set[1].to = NULL;
-	edit->excised_subtree = array->root;
-	edit->ops_for_excised_subtree = ops;
-	pr_devel("all gone\n");
-	return edit;
-}
-
-/*
- * Handle the deferred destruction after an applied edit.
- */
-static void assoc_array_rcu_cleanup(struct rcu_head *head)
-{
-	struct assoc_array_edit *edit =
-		container_of(head, struct assoc_array_edit, rcu);
-	int i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	if (edit->dead_leaf)
-		edit->ops->free_object(assoc_array_ptr_to_leaf(edit->dead_leaf));
-	for (i = 0; i < ARRAY_SIZE(edit->excised_meta); i++)
-		if (edit->excised_meta[i])
-			kfree(assoc_array_ptr_to_node(edit->excised_meta[i]));
-
-	if (edit->excised_subtree) {
-		BUG_ON(assoc_array_ptr_is_leaf(edit->excised_subtree));
-		if (assoc_array_ptr_is_node(edit->excised_subtree)) {
-			struct assoc_array_node *n =
-				assoc_array_ptr_to_node(edit->excised_subtree);
-			n->back_pointer = NULL;
-		} else {
-			struct assoc_array_shortcut *s =
-				assoc_array_ptr_to_shortcut(edit->excised_subtree);
-			s->back_pointer = NULL;
-		}
-		assoc_array_destroy_subtree(edit->excised_subtree,
-					    edit->ops_for_excised_subtree);
-	}
-
-	kfree(edit);
-}
-
-/**
- * assoc_array_apply_edit - Apply an edit script to an associative array
- * @edit: The script to apply.
- *
- * Apply an edit script to an associative array to effect an insertion,
- * deletion or clearance.  As the edit script includes preallocated memory,
- * this is guaranteed not to fail.
- *
- * The edit script, dead objects and dead metadata will be scheduled for
- * destruction after an RCU grace period to permit those doing read-only
- * accesses on the array to continue to do so under the RCU read lock whilst
- * the edit is taking place.
- */
-void assoc_array_apply_edit(struct assoc_array_edit *edit)
-{
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *ptr;
-	int i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	smp_wmb();
-	if (edit->leaf_p)
-		*edit->leaf_p = edit->leaf;
-
-	smp_wmb();
-	for (i = 0; i < ARRAY_SIZE(edit->set_parent_slot); i++)
-		if (edit->set_parent_slot[i].p)
-			*edit->set_parent_slot[i].p = edit->set_parent_slot[i].to;
-
-	smp_wmb();
-	for (i = 0; i < ARRAY_SIZE(edit->set_backpointers); i++)
-		if (edit->set_backpointers[i])
-			*edit->set_backpointers[i] = edit->set_backpointers_to;
-
-	smp_wmb();
-	for (i = 0; i < ARRAY_SIZE(edit->set); i++)
-		if (edit->set[i].ptr)
-			*edit->set[i].ptr = edit->set[i].to;
-
-	if (edit->array->root == NULL) {
-		edit->array->nr_leaves_on_tree = 0;
-	} else if (edit->adjust_count_on) {
-		node = edit->adjust_count_on;
-		for (;;) {
-			node->nr_leaves_on_branch += edit->adjust_count_by;
-
-			ptr = node->back_pointer;
-			if (!ptr)
-				break;
-			if (assoc_array_ptr_is_shortcut(ptr)) {
-				shortcut = assoc_array_ptr_to_shortcut(ptr);
-				ptr = shortcut->back_pointer;
-				if (!ptr)
-					break;
-			}
-			BUG_ON(!assoc_array_ptr_is_node(ptr));
-			node = assoc_array_ptr_to_node(ptr);
-		}
-
-		edit->array->nr_leaves_on_tree += edit->adjust_count_by;
-	}
-
-	call_rcu(&edit->rcu, assoc_array_rcu_cleanup);
-}
-
-/**
- * assoc_array_cancel_edit - Discard an edit script.
- * @edit: The script to discard.
- *
- * Free an edit script and all the preallocated data it holds without making
- * any changes to the associative array it was intended for.
- *
- * NOTE!  In the case of an insertion script, this does _not_ release the leaf
- * that was to be inserted.  That is left to the caller.
- */
-void assoc_array_cancel_edit(struct assoc_array_edit *edit)
-{
-	struct assoc_array_ptr *ptr;
-	int i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	/* Clean up after an out of memory error */
-	for (i = 0; i < ARRAY_SIZE(edit->new_meta); i++) {
-		ptr = edit->new_meta[i];
-		if (ptr) {
-			if (assoc_array_ptr_is_node(ptr))
-				kfree(assoc_array_ptr_to_node(ptr));
-			else
-				kfree(assoc_array_ptr_to_shortcut(ptr));
-		}
-	}
-	kfree(edit);
-}
-
-/**
- * assoc_array_gc - Garbage collect an associative array.
- * @array: The array to clean.
- * @ops: The operations to use.
- * @iterator: A callback function to pass judgement on each object.
- * @iterator_data: Private data for the callback function.
- *
- * Collect garbage from an associative array and pack down the internal tree to
- * save memory.
- *
- * The iterator function is asked to pass judgement upon each object in the
- * array.  If it returns false, the object is discard and if it returns true,
- * the object is kept.  If it returns true, it must increment the object's
- * usage count (or whatever it needs to do to retain it) before returning.
- *
- * This function returns 0 if successful or -ENOMEM if out of memory.  In the
- * latter case, the array is not changed.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-int assoc_array_gc(struct assoc_array *array,
-		   const struct assoc_array_ops *ops,
-		   bool (*iterator)(void *object, void *iterator_data),
-		   void *iterator_data)
-{
-	struct assoc_array_shortcut *shortcut, *new_s;
-	struct assoc_array_node *node, *new_n;
-	struct assoc_array_edit *edit;
-	struct assoc_array_ptr *cursor, *ptr;
-	struct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp;
-	unsigned long nr_leaves_on_tree;
-	bool retained;
-	int keylen, slot, nr_free, next_slot, i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	if (!array->root)
-		return 0;
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return -ENOMEM;
-	edit->array = array;
-	edit->ops = ops;
-	edit->ops_for_excised_subtree = ops;
-	edit->set[0].ptr = &array->root;
-	edit->excised_subtree = array->root;
-
-	new_root = new_parent = NULL;
-	new_ptr_pp = &new_root;
-	cursor = array->root;
-
-descend:
-	/* If this point is a shortcut, then we need to duplicate it and
-	 * advance the target cursor.
-	 */
-	if (assoc_array_ptr_is_shortcut(cursor)) {
-		shortcut = assoc_array_ptr_to_shortcut(cursor);
-		keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-		new_s = kmalloc_flex(*new_s, index_key, keylen);
-		if (!new_s)
-			goto enomem;
-		pr_devel("dup shortcut %p -> %p\n", shortcut, new_s);
-		memcpy(new_s, shortcut, struct_size(new_s, index_key, keylen));
-		new_s->back_pointer = new_parent;
-		new_s->parent_slot = shortcut->parent_slot;
-		*new_ptr_pp = new_parent = assoc_array_shortcut_to_ptr(new_s);
-		new_ptr_pp = &new_s->next_node;
-		cursor = shortcut->next_node;
-	}
-
-	/* Duplicate the node at this position */
-	node = assoc_array_ptr_to_node(cursor);
-	new_n = kzalloc_obj(struct assoc_array_node);
-	if (!new_n)
-		goto enomem;
-	pr_devel("dup node %p -> %p\n", node, new_n);
-	new_n->back_pointer = new_parent;
-	new_n->parent_slot = node->parent_slot;
-	*new_ptr_pp = new_parent = assoc_array_node_to_ptr(new_n);
-	new_ptr_pp = NULL;
-	slot = 0;
-
-continue_node:
-	/* Filter across any leaves and gc any subtrees */
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = node->slots[slot];
-		if (!ptr)
-			continue;
-
-		if (assoc_array_ptr_is_leaf(ptr)) {
-			if (iterator(assoc_array_ptr_to_leaf(ptr),
-				     iterator_data))
-				/* The iterator will have done any reference
-				 * counting on the object for us.
-				 */
-				new_n->slots[slot] = ptr;
-			continue;
-		}
-
-		new_ptr_pp = &new_n->slots[slot];
-		cursor = ptr;
-		goto descend;
-	}
-
-retry_compress:
-	pr_devel("-- compress node %p --\n", new_n);
-
-	/* Count up the number of empty slots in this node and work out the
-	 * subtree leaf count.
-	 */
-	new_n->nr_leaves_on_branch = 0;
-	nr_free = 0;
-	for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = new_n->slots[slot];
-		if (!ptr)
-			nr_free++;
-		else if (assoc_array_ptr_is_leaf(ptr))
-			new_n->nr_leaves_on_branch++;
-	}
-	pr_devel("free=%d, leaves=%lu\n", nr_free, new_n->nr_leaves_on_branch);
-
-	/* See what we can fold in */
-	retained = false;
-	next_slot = 0;
-	for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		struct assoc_array_shortcut *s;
-		struct assoc_array_node *child;
-
-		ptr = new_n->slots[slot];
-		if (!ptr || assoc_array_ptr_is_leaf(ptr))
-			continue;
-
-		s = NULL;
-		if (assoc_array_ptr_is_shortcut(ptr)) {
-			s = assoc_array_ptr_to_shortcut(ptr);
-			ptr = s->next_node;
-		}
-
-		child = assoc_array_ptr_to_node(ptr);
-		new_n->nr_leaves_on_branch += child->nr_leaves_on_branch;
-
-		if (child->nr_leaves_on_branch <= nr_free + 1) {
-			/* Fold the child node into this one */
-			pr_devel("[%d] fold node %lu/%d [nx %d]\n",
-				 slot, child->nr_leaves_on_branch, nr_free + 1,
-				 next_slot);
-
-			/* We would already have reaped an intervening shortcut
-			 * on the way back up the tree.
-			 */
-			BUG_ON(s);
-
-			new_n->slots[slot] = NULL;
-			nr_free++;
-			if (slot < next_slot)
-				next_slot = slot;
-			for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-				struct assoc_array_ptr *p = child->slots[i];
-				if (!p)
-					continue;
-				BUG_ON(assoc_array_ptr_is_meta(p));
-				while (new_n->slots[next_slot])
-					next_slot++;
-				BUG_ON(next_slot >= ASSOC_ARRAY_FAN_OUT);
-				new_n->slots[next_slot++] = p;
-				nr_free--;
-			}
-			kfree(child);
-		} else {
-			pr_devel("[%d] retain node %lu/%d [nx %d]\n",
-				 slot, child->nr_leaves_on_branch, nr_free + 1,
-				 next_slot);
-			retained = true;
-		}
-	}
-
-	if (retained && new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) {
-		pr_devel("internal nodes remain despite enough space, retrying\n");
-		goto retry_compress;
-	}
-	pr_devel("after: %lu\n", new_n->nr_leaves_on_branch);
-
-	nr_leaves_on_tree = new_n->nr_leaves_on_branch;
-
-	/* Excise this node if it is singly occupied by a shortcut */
-	if (nr_free == ASSOC_ARRAY_FAN_OUT - 1) {
-		for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++)
-			if ((ptr = new_n->slots[slot]))
-				break;
-
-		if (assoc_array_ptr_is_meta(ptr) &&
-		    assoc_array_ptr_is_shortcut(ptr)) {
-			pr_devel("excise node %p with 1 shortcut\n", new_n);
-			new_s = assoc_array_ptr_to_shortcut(ptr);
-			new_parent = new_n->back_pointer;
-			slot = new_n->parent_slot;
-			kfree(new_n);
-			if (!new_parent) {
-				new_s->back_pointer = NULL;
-				new_s->parent_slot = 0;
-				new_root = ptr;
-				goto gc_complete;
-			}
-
-			if (assoc_array_ptr_is_shortcut(new_parent)) {
-				/* We can discard any preceding shortcut also */
-				struct assoc_array_shortcut *s =
-					assoc_array_ptr_to_shortcut(new_parent);
-
-				pr_devel("excise preceding shortcut\n");
-
-				new_parent = new_s->back_pointer = s->back_pointer;
-				slot = new_s->parent_slot = s->parent_slot;
-				kfree(s);
-				if (!new_parent) {
-					new_s->back_pointer = NULL;
-					new_s->parent_slot = 0;
-					new_root = ptr;
-					goto gc_complete;
-				}
-			}
-
-			new_s->back_pointer = new_parent;
-			new_s->parent_slot = slot;
-			new_n = assoc_array_ptr_to_node(new_parent);
-			new_n->slots[slot] = ptr;
-			goto ascend_old_tree;
-		}
-	}
-
-	/* Excise any shortcuts we might encounter that point to nodes that
-	 * only contain leaves.
-	 */
-	ptr = new_n->back_pointer;
-	if (!ptr)
-		goto gc_complete;
-
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		new_s = assoc_array_ptr_to_shortcut(ptr);
-		new_parent = new_s->back_pointer;
-		slot = new_s->parent_slot;
-
-		if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) {
-			struct assoc_array_node *n;
-
-			pr_devel("excise shortcut\n");
-			new_n->back_pointer = new_parent;
-			new_n->parent_slot = slot;
-			kfree(new_s);
-			if (!new_parent) {
-				new_root = assoc_array_node_to_ptr(new_n);
-				goto gc_complete;
-			}
-
-			n = assoc_array_ptr_to_node(new_parent);
-			n->slots[slot] = assoc_array_node_to_ptr(new_n);
-		}
-	} else {
-		new_parent = ptr;
-	}
-	new_n = assoc_array_ptr_to_node(new_parent);
-
-ascend_old_tree:
-	ptr = node->back_pointer;
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		slot = shortcut->parent_slot;
-		cursor = shortcut->back_pointer;
-		if (!cursor)
-			goto gc_complete;
-	} else {
-		slot = node->parent_slot;
-		cursor = ptr;
-	}
-	BUG_ON(!cursor);
-	node = assoc_array_ptr_to_node(cursor);
-	slot++;
-	goto continue_node;
-
-gc_complete:
-	edit->set[0].to = new_root;
-	assoc_array_apply_edit(edit);
-	array->nr_leaves_on_tree = nr_leaves_on_tree;
-	return 0;
-
-enomem:
-	pr_devel("enomem\n");
-	assoc_array_destroy_subtree(new_root, edit->ops);
-	kfree(edit);
-	return -ENOMEM;
-}
diff --git a/security/keys/Kconfig b/security/keys/Kconfig
index f4510d8cb485f4..3f64d60d0f8a69 100644
--- a/security/keys/Kconfig
+++ b/security/keys/Kconfig
@@ -5,7 +5,6 @@
 
 menuconfig KEYS
 	bool "Enable access key retention support"
-	select ASSOCIATIVE_ARRAY
 	help
 	  This option provides support for retaining authentication tokens and
 	  access keys in the kernel.
diff --git a/security/keys/internal.h b/security/keys/internal.h
index b7b622bc36a137..c452d71cce038d 100644
--- a/security/keys/internal.h
+++ b/security/keys/internal.h
@@ -21,6 +21,12 @@
 #include <linux/vmalloc.h>
 
 struct iovec;
+struct keyring_link;
+
+struct keyring_edit {
+	struct keyring_link *new;
+	struct keyring_link *old;
+};
 
 #ifdef __KDEBUG
 #define kenter(FMT, ...) \
@@ -98,13 +104,13 @@ extern int __key_move_lock(struct key *l_keyring, struct key *u_keyring,
 			   const struct keyring_index_key *index_key);
 extern int __key_link_begin(struct key *keyring,
 			    const struct keyring_index_key *index_key,
-			    struct assoc_array_edit **_edit);
+			    struct keyring_edit *edit);
 extern int __key_link_check_live_key(struct key *keyring, struct key *key);
 extern void __key_link(struct key *keyring, struct key *key,
-		       struct assoc_array_edit **_edit);
+		       struct keyring_edit *edit);
 extern void __key_link_end(struct key *keyring,
 			   const struct keyring_index_key *index_key,
-			   struct assoc_array_edit *edit);
+			   struct keyring_edit *edit);
 
 extern key_ref_t find_key_to_update(key_ref_t keyring_ref,
 				    const struct keyring_index_key *index_key);
@@ -122,7 +128,7 @@ struct keyring_search_context {
 #define KEYRING_SEARCH_SKIP_EXPIRED	0x0020	/* Ignore expired keys (intention to replace) */
 #define KEYRING_SEARCH_RECURSE		0x0040	/* Search child keyrings also */
 
-	int (*iterator)(const void *object, void *iterator_data);
+	int (*iterator)(const struct key *key, void *iterator_data);
 
 	/* Internal stuff */
 	int			skipped_ret;
diff --git a/security/keys/key.c b/security/keys/key.c
index 3f1f0fc137109a..20cf273cf4a3de 100644
--- a/security/keys/key.c
+++ b/security/keys/key.c
@@ -430,7 +430,7 @@ static int __key_instantiate_and_link(struct key *key,
 				      struct key_preparsed_payload *prep,
 				      struct key *keyring,
 				      struct key *authkey,
-				      struct assoc_array_edit **_edit)
+				      struct keyring_edit *edit)
 {
 	int ret, awaken;
 
@@ -461,7 +461,7 @@ static int __key_instantiate_and_link(struct key *key,
 				if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
 					set_bit(KEY_FLAG_KEEP, &key->flags);
 
-				__key_link(keyring, key, _edit);
+				__key_link(keyring, key, edit);
 			}
 
 			/* disable the authorisation key */
@@ -505,7 +505,7 @@ int key_instantiate_and_link(struct key *key,
 			     struct key *authkey)
 {
 	struct key_preparsed_payload prep;
-	struct assoc_array_edit *edit = NULL;
+	struct keyring_edit edit = {};
 	int ret;
 
 	memset(&prep, 0, sizeof(prep));
@@ -543,7 +543,7 @@ int key_instantiate_and_link(struct key *key,
 
 error_link_end:
 	if (keyring)
-		__key_link_end(keyring, &key->index_key, edit);
+		__key_link_end(keyring, &key->index_key, &edit);
 
 error:
 	if (key->type->preparse)
@@ -580,7 +580,7 @@ int key_reject_and_link(struct key *key,
 			struct key *keyring,
 			struct key *authkey)
 {
-	struct assoc_array_edit *edit = NULL;
+	struct keyring_edit edit = {};
 	int ret, awaken, link_ret = 0;
 
 	key_check(key);
@@ -599,12 +599,12 @@ int key_reject_and_link(struct key *key,
 			 * concurrent restriction install.
 			 */
 			if (keyring->restrict_link) {
-				__key_link_end(keyring, &key->index_key, edit);
+				__key_link_end(keyring, &key->index_key, &edit);
 				return -EPERM;
 			}
 			link_ret = __key_link_begin(keyring, &key->index_key, &edit);
 			if (link_ret < 0)
-				__key_link_end(keyring, &key->index_key, edit);
+				__key_link_end(keyring, &key->index_key, &edit);
 		}
 	}
 
@@ -635,7 +635,7 @@ int key_reject_and_link(struct key *key,
 	mutex_unlock(&key_construction_mutex);
 
 	if (keyring && link_ret == 0)
-		__key_link_end(keyring, &key->index_key, edit);
+		__key_link_end(keyring, &key->index_key, &edit);
 
 	/* wake up anyone waiting for a key to be constructed */
 	if (awaken)
@@ -825,7 +825,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
 		.description	= description,
 	};
 	struct key_preparsed_payload prep;
-	struct assoc_array_edit *edit = NULL;
+	struct keyring_edit edit = {};
 	const struct cred *cred = current_cred();
 	struct key *keyring, *key = NULL;
 	key_ref_t key_ref;
@@ -966,7 +966,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
 	key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
 
 error_link_end:
-	__key_link_end(keyring, &index_key, edit);
+	__key_link_end(keyring, &index_key, &edit);
 error_free_prep:
 	if (index_key.type->preparse)
 		index_key.type->free_preparse(&prep);
@@ -979,7 +979,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
 	/* we found a matching key, so we're going to try to update it
 	 * - we can drop the locks first as we have the key pinned
 	 */
-	__key_link_end(keyring, &index_key, edit);
+	__key_link_end(keyring, &index_key, &edit);
 
 	key = key_ref_to_ptr(key_ref);
 	if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) {
diff --git a/security/keys/keyring.c b/security/keys/keyring.c
index 5281da9d5bf750..04d9a98c0f3100 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,49 +383,51 @@ static void keyring_destroy(struct key *keyring)
 		kfree(keyres);
 	}
 
-	assoc_array_destroy(&keyring->keys, &keyring_assoc_array_ops);
+	index = rcu_dereference_protected(keyring->index, true);
+	if (index)
+		__keyring_index_free(index);
+}
+
+static unsigned long keyring_nr_links(const struct key *keyring)
+{
+	const struct keyring_index *index;
+
+	guard(rcu)();
+	index = rcu_dereference(keyring->index);
+	return index ? READ_ONCE(index->nr) : 0;
 }
 
+/**
+ * keyring_is_empty - Check whether a keyring is empty
+ * @keyring: The keyring to check.
+ */
+bool keyring_is_empty(const struct key *keyring)
+{
+	return keyring_nr_links(keyring) == 0;
+}
+EXPORT_SYMBOL(keyring_is_empty);
+
 /*
  * Describe a keyring for /proc.
  */
 static void keyring_describe(const struct key *keyring, struct seq_file *m)
 {
+	unsigned long nr;
+
 	if (keyring->description)
 		seq_puts(m, keyring->description);
 	else
 		seq_puts(m, "[anon]");
 
 	if (key_is_positive(keyring)) {
-		if (keyring->keys.nr_leaves_on_tree != 0)
-			seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree);
+		nr = keyring_nr_links(keyring);
+		if (nr != 0)
+			seq_printf(m, ": %lu", nr);
 		else
 			seq_puts(m, ": empty");
 	}
 }
 
-struct keyring_read_iterator_context {
-	size_t			buflen;
-	size_t			count;
-	key_serial_t		*buffer;
-};
-
-static int keyring_read_iterator(const void *object, void *data)
-{
-	struct keyring_read_iterator_context *ctx = data;
-	const struct key *key = keyring_ptr_to_key(object);
-
-	kenter("{%s,%d},,{%zu/%zu}",
-	       key->type->name, key->serial, ctx->count, ctx->buflen);
-
-	if (ctx->count >= ctx->buflen)
-		return 1;
-
-	*ctx->buffer++ = key->serial;
-	ctx->count += sizeof(key->serial);
-	return 0;
-}
-
 /*
  * Read a list of key IDs from the keyring's contents in binary form
  *
@@ -493,7 +438,10 @@ static int keyring_read_iterator(const void *object, void *data)
 static long keyring_read(const struct key *keyring,
 			 char *buffer, size_t buflen)
 {
-	struct keyring_read_iterator_context ctx;
+	struct keyring_index *links = keyring_index_locked(keyring);
+	key_serial_t *serials = (key_serial_t *)buffer;
+	struct keyring_link *link;
+	size_t count = 0;
 	long ret;
 
 	kenter("{%d},,%zu", key_serial(keyring), buflen);
@@ -501,25 +449,22 @@ static long keyring_read(const struct key *keyring,
 	if (buflen & (sizeof(key_serial_t) - 1))
 		return -EINVAL;
 
-	/* Copy as many key IDs as fit into the buffer */
-	if (buffer && buflen) {
-		ctx.buffer = (key_serial_t *)buffer;
-		ctx.buflen = buflen;
-		ctx.count = 0;
-		ret = assoc_array_iterate(&keyring->keys,
-					  keyring_read_iterator, &ctx);
-		if (ret < 0) {
-			kleave(" = %ld [iterate]", ret);
-			return ret;
+	if (buffer && buflen && links) {
+		list_for_each_entry(link, &links->list, list) {
+			if (count == buflen / sizeof(*serials))
+				break;
+
+			serials[count++] = keyring_link_key(link)->serial;
+			cond_resched();
 		}
 	}
 
-	/* Return the size of the buffer needed */
-	ret = keyring->keys.nr_leaves_on_tree * sizeof(key_serial_t);
+	ret = links ? links->nr * sizeof(key_serial_t) : 0;
 	if (ret <= buflen)
 		kleave("= %ld [ok]", ret);
 	else
 		kleave("= %ld [buffer too small]", ret);
+
 	return ret;
 }
 
@@ -583,10 +528,9 @@ bool key_default_cmp(const struct key *key,
 /*
  * Iteration function to consider each key found.
  */
-static int keyring_search_iterator(const void *object, void *iterator_data)
+static int keyring_search_iterator(const struct key *key, void *iterator_data)
 {
 	struct keyring_search_context *ctx = iterator_data;
-	const struct key *key = keyring_ptr_to_key(object);
 	unsigned long kflags = READ_ONCE(key->flags);
 	short state = key_read_state(key);
 
@@ -653,19 +597,78 @@ static int keyring_search_iterator(const void *object, void *iterator_data)
 /*
  * Search inside a keyring for a key.  We can search by walking to it
  * directly based on its index-key or we can iterate over the entire
- * tree looking for it, based on the match function.
+ * list looking for it, based on the match function.
  */
 static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)
 {
 	if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) {
-		const void *object;
+		struct keyring_link *link;
+		struct key *key;
+
+		link = keyring_find_link(rcu_dereference(keyring->index),
+					 &ctx->index_key);
+		if (!link)
+			return 0;
+		key = keyring_link_key(link);
+		return ctx->iterator(key, ctx);
+	}
+
+	return keyring_iterate(keyring, ctx->iterator, ctx);
+}
+
+/*
+ * 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;
 
-		object = assoc_array_find(&keyring->keys,
-					  &keyring_assoc_array_ops,
-					  &ctx->index_key);
-		return object ? ctx->iterator(object, ctx) : 0;
+	if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
+			      (1 << KEY_FLAG_REVOKED)))
+		return 0;
+
+	if (search_keyring(keyring, ctx))
+		goto found;
+
+	if (!(ctx->flags & KEYRING_SEARCH_RECURSE))
+		return 0;
+	links = rcu_dereference(keyring->index);
+	if (!links)
+		return 0;
+
+	list_for_each_entry_rcu(link, &links->list, list) {
+		struct key *key = keyring_link_key(link);
+
+		if (key->type != &key_type_keyring)
+			break;
+		if (depth >= KEYRING_SEARCH_MAX_DEPTH) {
+			if (!(ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP))
+				return 0;
+			ctx->result = ERR_PTR(-ELOOP);
+			return -ELOOP;
+		}
+
+		if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
+		    key_task_permission(make_key_ref(key, ctx->possessed),
+					ctx->cred, KEY_NEED_SEARCH) < 0)
+			continue;
+
+		ret = search_keyring_tree(key, ctx, depth + 1);
+		if (ret < 0)
+			return ret;
+		if (ret)
+			goto found;
 	}
-	return assoc_array_iterate(&keyring->keys, ctx->iterator, ctx);
+
+	return 0;
+
+found:
+	if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME))
+		keyring->last_used_at = ctx->now;
+	return 1;
 }
 
 /*
@@ -675,17 +678,7 @@ static int search_keyring(struct key *keyring, struct keyring_search_context *ct
 static bool search_nested_keyrings(struct key *keyring,
 				   struct keyring_search_context *ctx)
 {
-	struct {
-		struct key *keyring;
-		struct assoc_array_node *node;
-		int slot;
-	} stack[KEYRING_SEARCH_MAX_DEPTH];
-
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *ptr;
 	struct key *key;
-	int sp = 0, slot;
 
 	kenter("{%d},{%s,%s}",
 	       keyring->serial,
@@ -703,9 +696,9 @@ static bool search_nested_keyrings(struct key *keyring,
 	 * and whether it is valid or not.
 	 */
 	if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||
-	    keyring_compare_object(keyring, &ctx->index_key)) {
+	    keyring_index_key_equal(&keyring->index_key, &ctx->index_key)) {
 		ctx->skipped_ret = 2;
-		switch (ctx->iterator(keyring_key_to_ptr(keyring), ctx)) {
+		switch (ctx->iterator(keyring, ctx)) {
 		case 1:
 			goto found;
 		case 2:
@@ -717,152 +710,11 @@ static bool search_nested_keyrings(struct key *keyring,
 
 	ctx->skipped_ret = 0;
 
-	/* Start processing a new keyring */
-descend_to_keyring:
-	kdebug("descend to %d", keyring->serial);
-	if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
-			      (1 << KEY_FLAG_REVOKED)))
-		goto not_this_keyring;
-
-	/* Search through the keys in this keyring before its searching its
-	 * subtrees.
-	 */
-	if (search_keyring(keyring, ctx))
-		goto found;
-
-	/* Then manually iterate through the keyrings nested in this one.
-	 *
-	 * Start from the root node of the index tree.  Because of the way the
-	 * hash function has been set up, keyrings cluster on the leftmost
-	 * branch of the root node (root slot 0) or in the root node itself.
-	 * Non-keyrings avoid the leftmost branch of the root entirely (root
-	 * slots 1-15).
-	 */
-	if (!(ctx->flags & KEYRING_SEARCH_RECURSE))
-		goto not_this_keyring;
-
-	ptr = READ_ONCE(keyring->keys.root);
-	if (!ptr)
-		goto not_this_keyring;
-
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		/* If the root is a shortcut, either the keyring only contains
-		 * keyring pointers (everything clusters behind root slot 0) or
-		 * doesn't contain any keyring pointers.
-		 */
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		if ((shortcut->index_key[0] & ASSOC_ARRAY_FAN_MASK) != 0)
-			goto not_this_keyring;
-
-		ptr = READ_ONCE(shortcut->next_node);
-		node = assoc_array_ptr_to_node(ptr);
-		goto begin_node;
-	}
-
-	node = assoc_array_ptr_to_node(ptr);
-	ptr = node->slots[0];
-	if (!assoc_array_ptr_is_meta(ptr))
-		goto begin_node;
-
-descend_to_node:
-	/* Descend to a more distal node in this keyring's content tree and go
-	 * through that.
-	 */
-	kdebug("descend");
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		ptr = READ_ONCE(shortcut->next_node);
-		BUG_ON(!assoc_array_ptr_is_node(ptr));
-	}
-	node = assoc_array_ptr_to_node(ptr);
-
-begin_node:
-	kdebug("begin_node");
-	slot = 0;
-ascend_to_node:
-	/* Go through the slots in a node */
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]);
-
-		if (assoc_array_ptr_is_meta(ptr)) {
-			if (node->back_pointer ||
-			    assoc_array_ptr_is_shortcut(ptr))
-				goto descend_to_node;
-		}
-
-		if (!keyring_ptr_is_keyring(ptr))
-			continue;
-
-		key = keyring_ptr_to_key(ptr);
-
-		if (sp >= KEYRING_SEARCH_MAX_DEPTH) {
-			if (ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP) {
-				ctx->result = ERR_PTR(-ELOOP);
-				return false;
-			}
-			goto not_this_keyring;
-		}
-
-		/* Search a nested keyring */
-		if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
-		    key_task_permission(make_key_ref(key, ctx->possessed),
-					ctx->cred, KEY_NEED_SEARCH) < 0)
-			continue;
-
-		/* stack the current position */
-		stack[sp].keyring = keyring;
-		stack[sp].node = node;
-		stack[sp].slot = slot;
-		sp++;
-
-		/* begin again with the new keyring */
-		keyring = key;
-		goto descend_to_keyring;
-	}
-
-	/* We've dealt with all the slots in the current node, so now we need
-	 * to ascend to the parent and continue processing there.
-	 */
-	ptr = READ_ONCE(node->back_pointer);
-	slot = node->parent_slot;
-
-	if (ptr && assoc_array_ptr_is_shortcut(ptr)) {
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		ptr = READ_ONCE(shortcut->back_pointer);
-		slot = shortcut->parent_slot;
-	}
-	if (!ptr)
-		goto not_this_keyring;
-	node = assoc_array_ptr_to_node(ptr);
-	slot++;
-
-	/* If we've ascended to the root (zero backpointer), we must have just
-	 * finished processing the leftmost branch rather than the root slots -
-	 * so there can't be any more keyrings for us to find.
-	 */
-	if (node->back_pointer) {
-		kdebug("ascend %d", slot);
-		goto ascend_to_node;
-	}
-
-	/* The keyring we're looking at was disqualified or didn't contain a
-	 * matching key.
-	 */
-not_this_keyring:
-	kdebug("not_this_keyring %d", sp);
-	if (sp <= 0) {
+	if (search_keyring_tree(keyring, ctx, 0) <= 0) {
 		kleave(" = false");
 		return false;
 	}
 
-	/* Resume the processing of a keyring higher up in the tree */
-	sp--;
-	keyring = stack[sp].keyring;
-	node = stack[sp].node;
-	slot = stack[sp].slot + 1;
-	kdebug("ascend to %d [%d]", keyring->serial, slot);
-	goto ascend_to_node;
-
 	/* We found a viable match */
 found:
 	key = key_ref_to_ptr(ctx->result);
@@ -870,8 +722,6 @@ static bool search_nested_keyrings(struct key *keyring,
 	if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) {
 		key->last_used_at = ctx->now;
 		keyring->last_used_at = ctx->now;
-		while (sp > 0)
-			stack[--sp].keyring->last_used_at = ctx->now;
 	}
 	kleave(" = true");
 	return true;
@@ -1118,8 +968,8 @@ EXPORT_SYMBOL(keyring_restrict);
 key_ref_t find_key_to_update(key_ref_t keyring_ref,
 			     const struct keyring_index_key *index_key)
 {
+	struct keyring_link *link;
 	struct key *keyring, *key;
-	const void *object;
 
 	keyring = key_ref_to_ptr(keyring_ref);
 
@@ -1127,17 +977,16 @@ key_ref_t find_key_to_update(key_ref_t keyring_ref,
 	       keyring->serial, index_key->type->name, index_key->description);
 
 	guard(rcu)();
-	object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
-				  index_key);
+	link = keyring_find_link(rcu_dereference(keyring->index), index_key);
 
-	if (object)
+	if (link)
 		goto found;
 
 	kleave(" = NULL");
 	return NULL;
 
 found:
-	key = keyring_ptr_to_key(object);
+	key = keyring_link_key(link);
 	if (key->flags & ((1 << KEY_FLAG_INVALIDATED) |
 			  (1 << KEY_FLAG_REVOKED))) {
 		kleave(" = NULL [x]");
@@ -1207,11 +1056,10 @@ struct key *find_keyring_by_name(const char *name, bool uid_keyring)
 	return keyring;
 }
 
-static int keyring_detect_cycle_iterator(const void *object,
+static int keyring_detect_cycle_iterator(const struct key *key,
 					 void *iterator_data)
 {
 	struct keyring_search_context *ctx = iterator_data;
-	const struct key *key = keyring_ptr_to_key(object);
 
 	kenter("{%d}", key->serial);
 
@@ -1307,57 +1155,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 +1274,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 +1313,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 +1367,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 +1377,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 +1401,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 +1425,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 +1447,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 +1472,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 +1481,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 +1493,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 +1514,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 +1528,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 +1552,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 +1562,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 +1583,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 +1604,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 +1624,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 +1635,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 +1644,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/13 05:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 59903
							output: 25
							thoughts: 579
						

Thoughts:
**Analyzing the Keyring Subsystem Patch for Fuzzing Potential**

Okay, let's dive into this patch. My immediate thought is, this is significant. It's a fundamental change to the kernel's keyring data structures. The patch completely replaces the old `assoc_array` implementation with `rhashtable` combined with a linked list, impacting core files like `keyring.c`, `key.c`, and `request_key.c`. This isn't just a minor tweak; it's a major refactoring of the entire keys subsystem, which I know is a crucial security component.

The next question, of course, is, "Is this reachable?" Absolutely. The keyring functionality is exposed through syscalls like `add_key`, `keyctl`, and `request_key`, and that means it’s readily accessible from userspace. Furthermore, it's known to be heavily fuzzed by tools like syzkaller, running within standard virtualized environments. That already suggests this is prime fuzzing territory.

Considering the "WorthFuzzing" criteria, this patch hits every mark. We're talking about a core subsystem that's been fundamentally restructured, involving memory management, locking, and potentially complex RCU (Read-Copy-Update) logic. The introduction of `rhashtable` introduces new custom logic for managing the lifetime, locking, iteration, and likely recursion within a crucial security context.

Given the depth of this change, I'm already anticipating potential bugs: memory leaks, use-after-free conditions, races, and even deadlocks are all high on the list of likely vulnerabilities. The fact that the locking, RCU, and iteration is custom-built within the Rhashtable further raises my suspicions. I need to dig into the details to understand how they are being handled. This needs immediate and intensive fuzzing! I'll now be checking the Kconfig options within `security/keys/Kconfig` and `security/Kconfig` to identify the required configurations to reach the code.



4/2 2026/11/13 05:13 tool grepper
0m Args:
{
  "Expression": "config KEYS",
  "PathPrefixes": [
    "security/"
  ]
}

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/13 05:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 61055
							output: 22
							thoughts: 22
						

Thoughts:
Okay, here's my summary, tailored for an expert audience, as if it's coming directly from my own thought process:

**Diving into the Kernel's Key Management Configuration**

Right, let's get down to brass tacks. I need to understand the dependencies around the key management configuration within the kernel. Specifically, I need to trace where the `security/keys/Kconfig` file is included and, more broadly, what other kernel components are reliant on the `KEYS` symbol. This is fundamental for several reasons: perhaps I'm looking at potential security vulnerabilities, or possibly I'm working on a custom security module and need to see how my changes will ripple through the configuration system. Either way, pinpointing the inclusion hierarchy and dependencies is the first, and arguably most crucial, step in any such investigation. I'm going to start with a targeted search and analysis of the Kconfig files. This should give me the insights I need to proceed confidently.



6/2 2026/11/13 05:13 tool grepper
0m Args:
{
  "Expression": "source.*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"
}

7/2 2026/11/13 05:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 61360
							output: 32
							thoughts: 17
						

Thoughts:
Here's a summary of my thought process:

**Diving into the Kernel's Key Configuration**

Okay, time to get to the heart of the matter. I need to understand how the kernel's key management is configured. My initial instinct is to go directly to the source, the `security/keys/Kconfig` file. Specifically, I need to zero in on the lines related to `KEYS`. This configuration file is where all the build-time options related to the key management subsystem are defined. I'll be looking for dependencies, default values, help text, and anything that gives me a clear picture of what options are available and how they interact. This will be my starting point to understanding the options, settings, and implications.



8/2 2026/11/13 05:13 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"
}

9/2 2026/11/13 05:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 62135
							output: 31
							thoughts: 60
						

Thoughts:
Okay, let's see, my initial thought is, **Is `KEYS` standalone or does it rely on something else within the kernel?** The first clue is `security/keys/Kconfig` and line 6 specifically. It looks like `KEYS` is defined as a `menuconfig` option as a boolean. The crucial thing is that there's no `depends on` clause attached. That is certainly an indicator that it's a top-level feature. But, you know, just because Kconfig doesn't explicitly state a dependency doesn't mean it doesn't *implicitly* depend on something else, so I need to be sure. Time to move on to the `security/keys/Makefile` and figure out how the object files like `keyring.o` get built. I'm looking for clues about the build process and what other modules might be required. That should provide a definitive answer.



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

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

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

Args:
null

Results:
null

Tokens:
							input: 62860
							output: 25
							thoughts: 20
						

Thoughts:
Here's a summary of my thought process:

**Diving into the Security Build Process**

Okay, so I'm looking at `security/Makefile` because I need to understand how the security-related components are built, specifically the keys within the `security/keys/` directory. My immediate goal is to trace the build process for these keys and pinpoint any relevant configurations or dependencies. This kind of overview is crucial for me, as an expert, to understand the security posture of the software. I want to make sure the key generation, storage and usage aligns with security best practices. I will start by seeing how the Makefile orchestrates things and if I can get some context on any specific build rules. I'm hoping to understand if the build process properly handles sensitive information.



12/2 2026/11/13 05:13 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"
}

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

Args:
null

Results:
null

Tokens:
							input: 63110
							output: 31
							thoughts: 1091
						

Thoughts:
**Focusing Fuzzing on Keyring Operations**

Okay, so `CONFIG_KEYS` compiles the security keyrings code, that’s standard. Now, I want to zero in on specific kernel functions for fuzzing. I'm thinking focus symbols are the way to go here. Let's see what this patch specifically changed, so I can target the fuzzing to those areas.

I'm looking at the functions in `security/keys/keyring.c`, `security/keys/key.c`, and `security/keys/request_key.c`. There are a ton of them, and I'm compiling a quick mental list: `keyring_hashfn`, `keyring_obj_hashfn`, `keyring_index_key_equal`, the list goes on and on, with significant additions in the other files too, like `__key_instantiate_and_link`.

Now, the important part: which of these are actually *exposed* in vmlinux? I need to focus on the ones that are non-static, non-inlined, or specifically exported. From that initial list, I can narrow it down to: `keyring_clear`, `keyring_is_empty`, `key_link`, `key_unlink`, `key_move`, `keyring_gc`, `keyring_read`, `search_keyring_tree`, `search_nested_keyrings`, `keyring_find_link`, `keyring_get_index`, `__key_link_begin`, `__key_link`, `__key_link_end`, `keyring_destroy`, `key_instantiate_and_link`, `key_reject_and_link`, and `__key_create_or_update`.

Alright, let's make sure these aren't just super common functions. I don't want to waste time fuzzing `kmalloc` or some other ubiquitous routine. These *all* seem specific to the keyring system, which is good.

So, out of this narrowed-down list, I need to make some key selections. Which ones are the most prominent, and which are the ones that directly touch the recently modified code? I'm thinking I should really focus on `key_link`, `key_unlink`, `key_move`, `keyring_clear`, `keyring_read`, `keyring_gc`, `keyring_is_empty`, `keyring_find_link`, `search_keyring_tree`, `search_nested_keyrings`, `__key_link_begin`, `__key_link`, `__key_link_end`, and `keyring_get_index`. That should give me the most coverage for the code changed in the patch.

I'm checking `search_keyring_tree` to see if that's static, and what calls it. And yep, it appears that `search_nested_keyrings` calls `search_keyring_tree`, and `search_nested_keyrings` then gets called by the `keyring_search` functions. Sounds good, I've got a decent list of functions to focus on for fuzzing the code.



14/2 2026/11/13 05:14 tool grepper
0m Args:
{
  "Expression": "search_nested_keyrings",
  "PathPrefixes": [
    "security/keys/"
  ]
}

Results:
{
  "Output": "security/keys/keyring.c=622=static int search_keyring_tree(struct key *keyring,\n--\nsecurity/keys/keyring.c-677- */\nsecurity/keys/keyring.c:678:static bool search_nested_keyrings(struct key *keyring,\nsecurity/keys/keyring.c-679-\t\t\t\t   struct keyring_search_context *ctx)\n--\nsecurity/keys/keyring.c=764=key_ref_t keyring_search_rcu(key_ref_t keyring_ref,\n--\nsecurity/keys/keyring.c-786-\tctx-\u003enow = ktime_get_real_seconds();\nsecurity/keys/keyring.c:787:\tif (search_nested_keyrings(keyring, ctx))\nsecurity/keys/keyring.c-788-\t\t__key_get(key_ref_to_ptr(ctx-\u003eresult));\n--\nsecurity/keys/keyring.c=1082=static int keyring_detect_cycle(struct key *A, struct key *B)\n--\nsecurity/keys/keyring.c-1096-\trcu_read_lock();\nsecurity/keys/keyring.c:1097:\tsearch_nested_keyrings(B, \u0026ctx);\nsecurity/keys/keyring.c-1098-\trcu_read_unlock();\n"
}

15/2 2026/11/13 05:14 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 65264
							output: 32
							thoughts: 23
						

Thoughts:
Here's my understanding of the situation, presented from my perspective as an expert:

**Investigating `keyring_search` and `keyring_search_rcu`**

Alright, I need to get a clear picture of what's going on with `keyring_search` and `keyring_search_rcu`. Time to dive in and refresh my memory on their functionalities and, perhaps more importantly, how they interact within the larger keyring context. I'll need to remember the intricacies of how they handle concurrency and read-copy-update mechanisms (if that's where `keyring_search_rcu` is involved). I need to understand any potential performance differences or trade-offs between the two search functions. Are they used in distinct situations? Is one a more modern, optimized version of the other? Are they both used, and if so, how? I'll probably be able to infer some answers from the code, but I know better than to just skim. Gotta be thorough. Time to start digging and see where this leads.



16/2 2026/11/13 05:14 tool grepper
0m Args:
{
  "Expression": "keyring_search_rcu",
  "PathPrefixes": [
    "security/keys/"
  ]
}

Results:
{
  "Output": "security/keys/internal.h=140=extern bool key_default_cmp(const struct key *key,\nsecurity/keys/internal.h-141-\t\t\t    const struct key_match_data *match_data);\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);\n--\nsecurity/keys/keyring.c=678=static bool search_nested_keyrings(struct key *keyring,\n--\nsecurity/keys/keyring.c-730-/**\nsecurity/keys/keyring.c:731: * keyring_search_rcu - Search a keyring tree for a matching key under RCU\nsecurity/keys/keyring.c-732- * @keyring_ref: A pointer to the keyring with possession indicator.\n--\nsecurity/keys/keyring.c-763- */\nsecurity/keys/keyring.c:764:key_ref_t keyring_search_rcu(key_ref_t keyring_ref,\nsecurity/keys/keyring.c-765-\t\t\t     struct keyring_search_context *ctx)\n--\nsecurity/keys/keyring.c-798- *\nsecurity/keys/keyring.c:799: * As keyring_search_rcu() above, but using the current task's credentials and\nsecurity/keys/keyring.c-800- * type's default matching function and preferred search method.\n--\nsecurity/keys/keyring.c=802=key_ref_t keyring_search(key_ref_t keyring,\n--\nsecurity/keys/keyring.c-833-\trcu_read_lock();\nsecurity/keys/keyring.c:834:\tkey = keyring_search_rcu(keyring, \u0026ctx);\nsecurity/keys/keyring.c-835-\trcu_read_unlock();\n--\nsecurity/keys/process_keys.c=195=struct key *get_user_session_keyring_rcu(const struct cred *cred)\n--\nsecurity/keys/process_keys.c-217-\nsecurity/keys/process_keys.c:218:\tsession_keyring_r = keyring_search_rcu(make_key_ref(reg_keyring, true),\nsecurity/keys/process_keys.c-219-\t\t\t\t\t       \u0026ctx);\n--\nsecurity/keys/process_keys.c=432=key_ref_t search_cred_keyrings_rcu(struct keyring_search_context *ctx)\n--\nsecurity/keys/process_keys.c-450-\tif (cred-\u003ethread_keyring) {\nsecurity/keys/process_keys.c:451:\t\tkey_ref = keyring_search_rcu(\nsecurity/keys/process_keys.c-452-\t\t\tmake_key_ref(cred-\u003ethread_keyring, 1), ctx);\n--\nsecurity/keys/process_keys.c-468-\tif (cred-\u003eprocess_keyring) {\nsecurity/keys/process_keys.c:469:\t\tkey_ref = keyring_search_rcu(\nsecurity/keys/process_keys.c-470-\t\t\tmake_key_ref(cred-\u003eprocess_keyring, 1), ctx);\n--\nsecurity/keys/process_keys.c-489-\tif (cred-\u003esession_keyring) {\nsecurity/keys/process_keys.c:490:\t\tkey_ref = keyring_search_rcu(\nsecurity/keys/process_keys.c-491-\t\t\tmake_key_ref(cred-\u003esession_keyring, 1), ctx);\n--\nsecurity/keys/process_keys.c-510-\telse if ((user_session = get_user_session_keyring_rcu(cred))) {\nsecurity/keys/process_keys.c:511:\t\tkey_ref = keyring_search_rcu(make_key_ref(user_session, 1),\nsecurity/keys/process_keys.c-512-\t\t\t\t\t     ctx);\n"
}

17/2 2026/11/13 05:14 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 66563
							output: 26
							thoughts: 220
						

Thoughts:
**My Exploration of the Keyring Implementation**

Okay, so I'm diving into the keyring code, and the first obvious entry point for searching is `keyring_search_rcu`. That's the starting gun. Now, I should also look at the read operation, so I'll check out `keyring_read` – that's the `.read` callback for `key_type_keyring`, naturally.

Garbage collection is important to consider, so I'll be looking closely at `keyring_gc`, which is triggered by the garbage collector (`gc.c`). Beyond those, there's a lot to consider as there are a number of functions that seem important: `key_link`, `key_unlink`, `key_move`, and `keyring_clear`. I'll also check out `__key_link_begin`, `__key_link`, and `__key_link_end`.

Now, before I get too far down this rabbit hole, I need to check the configuration options. Is `CONFIG_KEYS` the only one relevant here, or are there others?

Ah, it seems `CONFIG_KEYS` is the only config that is directly related to the keyring functionality.

One last thing, let's take a quick look to see if `rhashtable` is guarded by any configs, as it's used in this context. It looks like `lib/rhashtable.c` is always built, as per `lib/Makefile`. Okay, so it's always available, that's good to know.



18/2 2026/11/13 05:14 tool grepper
0m Args:
{
  "Expression": "rhashtable",
  "PathPrefixes": [
    "lib/"
  ]
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 706 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (5 files in total):\nlib/Kconfig.debug:1\nlib/Makefile:3\nlib/objagg.c:20\nlib/rhashtable.c:114\nlib/test_rhashtable.c:53\n\nlib/Kconfig.debug=2581=config TEST_RHASHTABLE\n--\nlib/Kconfig.debug-2583-\thelp\nlib/Kconfig.debug:2584:\t  Enable this option to test the rhashtable functions at boot.\nlib/Kconfig.debug-2585-\n--\nlib/Makefile=51=obj-y\t+= lockref.o\nlib/Makefile-52-\nlib/Makefile:53:CONTEXT_ANALYSIS_rhashtable.o := y\nlib/Makefile-54-\nlib/Makefile=55=obj-y += bcd.o sort.o parser.o debug_locks.o random32.o \\\n--\nlib/Makefile-58-\t bsearch.o find_bit.o llist.o lwq.o memweight.o kfifo.o \\\nlib/Makefile:59:\t percpu-refcount.o rhashtable.o base64.o \\\nlib/Makefile-60-\t once.o refcount.o rcuref.o usercopy.o errseq.o bucket_locks.o \\\n--\nlib/Makefile=82=obj-$(CONFIG_TEST_WORKQUEUE) += test_workqueue.o\nlib/Makefile:83:obj-$(CONFIG_TEST_RHASHTABLE) += test_rhashtable.o\nlib/Makefile-84-obj-$(CONFIG_TEST_STATIC_KEYS) += test_static_keys.o\n--\nlib/objagg.c-5-#include \u003clinux/slab.h\u003e\nlib/objagg.c:6:#include \u003clinux/rhashtable.h\u003e\nlib/objagg.c-7-#include \u003clinux/idr.h\u003e\n--\nlib/objagg.c=15=struct objagg_hints {\nlib/objagg.c:16:\tstruct rhashtable node_ht;\nlib/objagg.c:17:\tstruct rhashtable_params ht_params;\nlib/objagg.c-18-\tstruct list_head node_list;\n--\nlib/objagg.c=35=objagg_hints_lookup(struct objagg_hints *objagg_hints, void *obj)\n--\nlib/objagg.c-38-\t\treturn NULL;\nlib/objagg.c:39:\treturn rhashtable_lookup_fast(\u0026objagg_hints-\u003enode_ht, obj,\nlib/objagg.c-40-\t\t\t\t      objagg_hints-\u003eht_params);\n--\nlib/objagg.c=43=struct objagg {\n--\nlib/objagg.c-45-\tvoid *priv;\nlib/objagg.c:46:\tstruct rhashtable obj_ht;\nlib/objagg.c:47:\tstruct rhashtable_params ht_params;\nlib/objagg.c-48-\tstruct list_head obj_list;\n--\nlib/objagg.c=158=static struct objagg_obj *objagg_obj_lookup(struct objagg *objagg, void *obj)\nlib/objagg.c-159-{\nlib/objagg.c:160:\treturn rhashtable_lookup_fast(\u0026objagg-\u003eobj_ht, obj, objagg-\u003eht_params);\nlib/objagg.c-161-}\n--\nlib/objagg.c=367=static struct objagg_obj *objagg_obj_create(struct objagg *objagg, void *obj)\n--\nlib/objagg.c-382-\nlib/objagg.c:383:\terr = rhashtable_insert_fast(\u0026objagg-\u003eobj_ht, \u0026objagg_obj-\u003eht_node,\nlib/objagg.c-384-\t\t\t\t     objagg-\u003eht_params);\n--\nlib/objagg.c=453=static void objagg_obj_destroy(struct objagg *objagg,\n--\nlib/objagg.c-458-\tlist_del(\u0026objagg_obj-\u003elist);\nlib/objagg.c:459:\trhashtable_remove_fast(\u0026objagg-\u003eobj_ht, \u0026objagg_obj-\u003eht_node,\nlib/objagg.c-460-\t\t\t       objagg-\u003eht_params);\n--\nlib/objagg.c=517=struct objagg *objagg_create(const struct objagg_ops *ops,\n--\nlib/objagg.c-542-\nlib/objagg.c:543:\terr = rhashtable_init(\u0026objagg-\u003eobj_ht, \u0026objagg-\u003eht_params);\nlib/objagg.c-544-\tif (err)\nlib/objagg.c:545:\t\tgoto err_rhashtable_init;\nlib/objagg.c-546-\n--\nlib/objagg.c-551-\nlib/objagg.c:552:err_rhashtable_init:\nlib/objagg.c-553-\tkfree(objagg);\n--\nlib/objagg.c=564=void objagg_destroy(struct objagg *objagg)\n--\nlib/objagg.c-568-\tWARN_ON(!list_empty(\u0026objagg-\u003eobj_list));\nlib/objagg.c:569:\trhashtable_destroy(\u0026objagg-\u003eobj_ht);\nlib/objagg.c-570-\tif (objagg-\u003ehints)\n--\nlib/objagg.c=652=objagg_hints_node_create(struct objagg_hints *objagg_hints,\n--\nlib/objagg.c-673-\nlib/objagg.c:674:\terr = rhashtable_insert_fast(\u0026objagg_hints-\u003enode_ht, \u0026hnode-\u003eht_node,\nlib/objagg.c-675-\t\t\t\t     objagg_hints-\u003eht_params);\n--\nlib/objagg.c=690=static void objagg_hints_flush(struct objagg_hints *objagg_hints)\n--\nlib/objagg.c-695-\t\tlist_del(\u0026hnode-\u003elist);\nlib/objagg.c:696:\t\trhashtable_remove_fast(\u0026objagg_hints-\u003enode_ht, \u0026hnode-\u003eht_node,\nlib/objagg.c-697-\t\t\t\t       objagg_hints-\u003eht_params);\n--\nlib/objagg.c=926=struct objagg_hints *objagg_hints_get(struct objagg *objagg,\n--\nlib/objagg.c-947-\nlib/objagg.c:948:\terr = rhashtable_init(\u0026objagg_hints-\u003enode_ht, \u0026objagg_hints-\u003eht_params);\nlib/objagg.c-949-\tif (err)\nlib/objagg.c:950:\t\tgoto err_rhashtable_init;\nlib/objagg.c-951-\n--\nlib/objagg.c-965-\tobjagg_hints_flush(objagg_hints);\nlib/objagg.c:966:\trhashtable_destroy(\u0026objagg_hints-\u003enode_ht);\nlib/objagg.c:967:err_rhashtable_init:\nlib/objagg.c-968-\tkfree(objagg_hints);\n--\nlib/objagg.c=979=void objagg_hints_put(struct objagg_hints *objagg_hints)\n--\nlib/objagg.c-983-\tobjagg_hints_flush(objagg_hints);\nlib/objagg.c:984:\trhashtable_destroy(\u0026objagg_hints-\u003enode_ht);\nlib/objagg.c-985-\tkfree(objagg_hints);\n--\nlib/rhashtable.c-25-#include \u003clinux/random.h\u003e\nlib/rhashtable.c:26:#include \u003clinux/rhashtable.h\u003e\nlib/rhashtable.c-27-#include \u003clinux/err.h\u003e\n--\nlib/rhashtable.c=34=union nested_table {\n--\nlib/rhashtable.c-38-\nlib/rhashtable.c:39:static u32 head_hashfn(struct rhashtable *ht,\nlib/rhashtable.c-40-\t\t       const struct bucket_table *tbl,\n--\nlib/rhashtable.c-48-\nlib/rhashtable.c:49:int lockdep_rht_mutex_is_held(struct rhashtable *ht)\nlib/rhashtable.c-50-{\n--\nlib/rhashtable.c=127=static void bucket_table_free_rcu(struct rcu_head *head)\n--\nlib/rhashtable.c-131-\nlib/rhashtable.c:132:static union nested_table *nested_table_alloc(struct rhashtable *ht,\nlib/rhashtable.c-133-\t\t\t\t\t      union nested_table __rcu **prev,\n--\nlib/rhashtable.c-157-\nlib/rhashtable.c:158:static struct bucket_table *nested_bucket_table_alloc(struct rhashtable *ht,\nlib/rhashtable.c-159-\t\t\t\t\t\t      size_t nbuckets,\n--\nlib/rhashtable.c-186-\nlib/rhashtable.c:187:static struct bucket_table *bucket_table_alloc(struct rhashtable *ht,\nlib/rhashtable.c-188-\t\t\t\t\t       size_t nbuckets,\n--\nlib/rhashtable.c-209-#ifdef CONFIG_LOCKDEP\nlib/rhashtable.c:210:\tlockdep_init_map(\u0026tbl-\u003edep_map, \"rhashtable_bucket\", ht-\u003elockdep_key, 0);\nlib/rhashtable.c-211-#endif\n--\nlib/rhashtable.c-225-\nlib/rhashtable.c:226:static struct bucket_table *rhashtable_last_table(struct rhashtable *ht,\nlib/rhashtable.c-227-\t\t\t\t\t\t  struct bucket_table *tbl)\n--\nlib/rhashtable.c-238-\nlib/rhashtable.c:239:static int rhashtable_rehash_one(struct rhashtable *ht,\nlib/rhashtable.c-240-\t\t\t\t struct rhash_lock_head __rcu **bkt,\n--\nlib/rhashtable.c-243-\tstruct bucket_table *old_tbl = rht_dereference(ht-\u003etbl, ht);\nlib/rhashtable.c:244:\tstruct bucket_table *new_tbl = rhashtable_last_table(ht, old_tbl);\nlib/rhashtable.c-245-\tint err = -EAGAIN;\n--\nlib/rhashtable.c-290-\nlib/rhashtable.c:291:static int rhashtable_rehash_chain(struct rhashtable *ht,\nlib/rhashtable.c-292-\t\t\t\t    unsigned int old_hash)\n--\nlib/rhashtable.c-302-\nlib/rhashtable.c:303:\twhile (!(err = rhashtable_rehash_one(ht, bkt, old_hash)))\nlib/rhashtable.c-304-\t\t;\n--\nlib/rhashtable.c-312-\nlib/rhashtable.c:313:static int rhashtable_rehash_attach(struct rhashtable *ht,\nlib/rhashtable.c-314-\t\t\t\t    struct bucket_table *old_tbl,\n--\nlib/rhashtable.c-329-\nlib/rhashtable.c:330:static int rhashtable_rehash_table(struct rhashtable *ht)\nlib/rhashtable.c-331-{\n--\nlib/rhashtable.c-333-\tstruct bucket_table *new_tbl;\nlib/rhashtable.c:334:\tstruct rhashtable_walker *walker;\nlib/rhashtable.c-335-\tunsigned int old_hash;\n--\nlib/rhashtable.c-342-\tfor (old_hash = 0; old_hash \u003c old_tbl-\u003esize; old_hash++) {\nlib/rhashtable.c:343:\t\terr = rhashtable_rehash_chain(ht, old_hash);\nlib/rhashtable.c-344-\t\tif (err)\n--\nlib/rhashtable.c-359-\t * We do this inside the locked region so that\nlib/rhashtable.c:360:\t * rhashtable_walk_stop() can use rcu_head_after_call_rcu()\nlib/rhashtable.c-361-\t * to check if it should not re-link the table.\n--\nlib/rhashtable.c-368-\nlib/rhashtable.c:369:static int rhashtable_rehash_alloc(struct rhashtable *ht,\nlib/rhashtable.c-370-\t\t\t\t   struct bucket_table *old_tbl,\n--\nlib/rhashtable.c-382-\nlib/rhashtable.c:383:\terr = rhashtable_rehash_attach(ht, old_tbl, new_tbl);\nlib/rhashtable.c-384-\tif (err)\n--\nlib/rhashtable.c-390-/**\nlib/rhashtable.c:391: * rhashtable_shrink - Shrink hash table while allowing concurrent lookups\nlib/rhashtable.c-392- * @ht:\t\tthe hash table to shrink\n--\nlib/rhashtable.c-405- */\nlib/rhashtable.c:406:static int rhashtable_shrink(struct rhashtable *ht)\nlib/rhashtable.c-407-\t__must_hold(\u0026ht-\u003emutex)\n--\nlib/rhashtable.c-423-\nlib/rhashtable.c:424:\treturn rhashtable_rehash_alloc(ht, old_tbl, size);\nlib/rhashtable.c-425-}\n--\n\n"
}

19/2 2026/11/13 05:14 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 70745
							output: 232
							thoughts: 1463
						

Thoughts:
**Analysis of Keyring Rework for Fuzzing**

Okay, so the `rhashtable` implementation is unconditionally built into the kernel, which is good.  The code changes I need to consider are enabled only with the `KEYS` config option, that's straightforward. I should double-check if any dependent subsystems, like dm-verity, fs-verity or bpf, had corresponding changes. Looks like some adaptions were necessary to the new `keyring_is_empty()` helper, but the core functionality lives in `security/keys/keyring.c`, and related files, where the data structure for keyrings is being swapped out.

Now, let's nail down those `FocusSymbols`.  I'm focusing on functions related to key linking, unlinking, searching, and management: `key_link`, `key_unlink`, `key_move`, `keyring_clear`, `keyring_read`, `keyring_gc`, `keyring_search_rcu`, `keyring_search`, `__key_link_begin`, `__key_link`, `__key_link_end`. I need to ensure these aren't ubiquitous and are specific to the key management code.

I need to confirm that those internal functions like `search_keyring_tree` are `static` and that their counterparts in vmlinux are visible. Seems some functions are `static`, but the ones I'm interested in aren't. Good. Also, there are function pointers being placed in `struct key_type key_type_keyring` so the compiler can't inline them away and those also have symbol entries in vmlinux. That's `keyring_read`, `keyring_destroy`, `keyring_instantiate`, `keyring_describe`, and `keyring_revoke`.  Excellent.

Alright, time to prep for `set-results`.  `WorthFuzzing` is definitively true. The patch fundamentally replaces the existing keyring storage, replacing the linked list with RCU-based `rhashtable`. The new code reimplements key linking, unlinking, searching with nested DFS traversal, garbage collection, reading, moving, and destruction, all using RCU and an rhashtable.  The code's reachable via userspace key management syscalls, so it's a prime target.

My reasoning for fuzzing is clear: it's a core subsystem, it introduces new locking and RCU memory lifecycles, and it's a completely new concurrent hash table implementation, meaning memory corruption bugs can easily happen if an edge case is missed in the implementation. `EnableConfigs` will be `["KEYS"]`. The `FocusSymbols` will be:  `keyring_clear`, `keyring_read`, `keyring_gc`, `keyring_search_rcu`, `keyring_search`, `keyring_destroy`, `key_link`, `key_unlink`, `key_move`, `__key_link_begin`, `__key_link`, `__key_link_end` and `find_key_to_update`.

Double-checking, `KEYS` is a boolean config, no dependencies. Perfect. It's fuzz-worthy: new data structure, new locking, critical subsystem. Let's get this set-results pushed.



20/2 2026/11/13 05:14 tool set-results
0m Args:
{
  "EnableConfigs": [
    "KEYS"
  ],
  "FocusSymbols": [
    "keyring_clear",
    "keyring_read",
    "keyring_gc",
    "keyring_search_rcu",
    "keyring_search",
    "keyring_destroy",
    "key_link",
    "key_unlink",
    "key_move",
    "__key_link_begin",
    "__key_link",
    "__key_link_end",
    "find_key_to_update"
  ],
  "Reasoning": "The patch removes the generic associative array (assoc_array) implementation from the kernel and completely replaces the internal keyring indexing mechanism with a resizable hash table (rhashtable) and RCU-protected linked list. This touches core key management and lookup logic, including linking, unlinking, nested keyring searching, reading, clearing, moving, and garbage collection under RCU. The code is directly reachable from userspace via the key management system calls (add_key, keyctl, request_key).",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "KEYS"
  ],
  "FocusSymbols": [
    "keyring_clear",
    "keyring_read",
    "keyring_gc",
    "keyring_search_rcu",
    "keyring_search",
    "keyring_destroy",
    "key_link",
    "key_unlink",
    "key_move",
    "__key_link_begin",
    "__key_link",
    "__key_link_end",
    "find_key_to_update"
  ],
  "Reasoning": "The patch removes the generic associative array (assoc_array) implementation from the kernel and completely replaces the internal keyring indexing mechanism with a resizable hash table (rhashtable) and RCU-protected linked list. This touches core key management and lookup logic, including linking, unlinking, nested keyring searching, reading, clearing, moving, and garbage collection under RCU. The code is directly reachable from userspace via the key management system calls (add_key, keyctl, request_key).",
  "WorthFuzzing": true
}

21/1 2026/11/13 05:14 action If
3m Args:
{
  "WorthFuzzing": true
}

Results:
null

22/2 2026/11/13 05:14 agent kmsan-evaluator
3m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series replaces the associative array (`assoc_array`) data structure in the keyring subsystem with a simpler `rhashtable` and `list_head` based index (`struct keyring_index` and `struct keyring_link`), while also removing the unused `assoc_array` library code and documentation.\n\nKMSAN vs KASAN Applicability Analysis:\n1. Kernel-to-User Copy / Info-Leaks: In `keyring_read()`, keys in the keyring are iterated over and their serial numbers (`key_serial_t`, 32-bit integers) are written sequentially into the destination buffer up to `links-\u003enr * sizeof(key_serial_t)`. `keyctl_read_key()` only copies the exact number of written bytes (`ret`) to user space via `copy_to_user()`. There are no padding gaps or uninitialized bytes in this data stream.\n2. Dynamic Allocations: All newly introduced structures (`struct keyring_index`, `struct keyring_link`) are allocated using `kzalloc_obj()`, guaranteeing zero-initialization of all fields and pointers.\n3. Stack Allocations: Instances of `struct keyring_edit` used to track transaction links are zero-initialized with `{}` across all callers (`key_instantiate_and_link`, `key_reject_and_link`, `key_link`, `key_move`, `construct_alloc_key`, etc.).\n4. Data Structures and Hashing: `struct keyring_index_key` layout changes (simplification from the union with machine-word packing to `u32 hash` and `unsigned int desc_len`) remove padding rather than introducing any uninitialized gaps. Hashing via SipHash operates strictly over initialized type/tag pointers and string descriptions.\n5. Other bug classes: Any risks in this patch series involve concurrency, RCU dereferencing/freeing (`call_rcu`), list/rhashtable operations, key reference counting, or locking (`keyring-\u003esem`), which are comprehensively detected by KASAN, PROVE_RCU, and LOCKDEP.\n\nTherefore, this patch series does not introduce or expose uninitialized memory risks, and 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 dce3c6a27421196608214dc306f23dcbc6e60b65
Author: syz-cluster <triage@syzkaller.com>
Date:   Fri Nov 13 05:13:11 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/core-api/assoc_array.rst b/Documentation/core-api/assoc_array.rst
deleted file mode 100644
index 19d89f92bf8da8..00000000000000
--- a/Documentation/core-api/assoc_array.rst
+++ /dev/null
@@ -1,564 +0,0 @@
-========================================
-Generic Associative Array Implementation
-========================================
-
-Overview
-========
-
-This associative array implementation is an object container with the following
-properties:
-
-1. Objects are opaque pointers.  The implementation does not care where they
-   point (if anywhere) or what they point to (if anything).
-
-   .. note::
-
-      Pointers to objects _must_ be zero in the least significant bit.
-
-2. Objects do not need to contain linkage blocks for use by the array.  This
-   permits an object to be located in multiple arrays simultaneously.
-   Rather, the array is made up of metadata blocks that point to objects.
-
-3. Objects require index keys to locate them within the array.
-
-4. Index keys must be unique.  Inserting an object with the same key as one
-   already in the array will replace the old object.
-
-5. Index keys can be of any length and can be of different lengths.
-
-6. Index keys should encode the length early on, before any variation due to
-   length is seen.
-
-7. Index keys can include a hash to scatter objects throughout the array.
-
-8. The array can iterated over.  The objects will not necessarily come out in
-   key order.
-
-9. The array can be iterated over while it is being modified, provided the
-   RCU readlock is being held by the iterator.  Note, however, under these
-   circumstances, some objects may be seen more than once.  If this is a
-   problem, the iterator should lock against modification.  Objects will not
-   be missed, however, unless deleted.
-
-10. Objects in the array can be looked up by means of their index key.
-
-11. Objects can be looked up while the array is being modified, provided the
-    RCU readlock is being held by the thread doing the look up.
-
-The implementation uses a tree of 16-pointer nodes internally that are indexed
-on each level by nibbles from the index key in the same manner as in a radix
-tree.  To improve memory efficiency, shortcuts can be emplaced to skip over
-what would otherwise be a series of single-occupancy nodes.  Further, nodes
-pack leaf object pointers into spare space in the node rather than making an
-extra branch until as such time an object needs to be added to a full node.
-
-
-The Public API
-==============
-
-The public API can be found in ``<linux/assoc_array.h>``.  The associative
-array is rooted on the following structure::
-
-    struct assoc_array {
-            ...
-    };
-
-The code is selected by enabling ``CONFIG_ASSOCIATIVE_ARRAY`` with::
-
-    ./script/config -e ASSOCIATIVE_ARRAY
-
-
-Edit Script
------------
-
-The insertion and deletion functions produce an 'edit script' that can later be
-applied to effect the changes without risking ``ENOMEM``. This retains the
-preallocated metadata blocks that will be installed in the internal tree and
-keeps track of the metadata blocks that will be removed from the tree when the
-script is applied.
-
-This is also used to keep track of dead blocks and dead objects after the
-script has been applied so that they can be freed later.  The freeing is done
-after an RCU grace period has passed - thus allowing access functions to
-proceed under the RCU read lock.
-
-The script appears as outside of the API as a pointer of the type::
-
-    struct assoc_array_edit;
-
-There are two functions for dealing with the script:
-
-1. Apply an edit script::
-
-    void assoc_array_apply_edit(struct assoc_array_edit *edit);
-
-   This will perform the edit functions, interpolating various write barriers
-   to permit accesses under the RCU read lock to continue.  The edit script
-   will then be passed to ``call_rcu()`` to free it and any dead stuff it
-   points to.
-
-2. Cancel an edit script::
-
-    void assoc_array_cancel_edit(struct assoc_array_edit *edit);
-
-   This frees the edit script and all preallocated memory immediately. If
-   this was for insertion, the new object is *not* released by this function,
-   but must rather be released by the caller.
-
-These functions are guaranteed not to fail.
-
-
-Operations Table
-----------------
-
-Various functions take a table of operations::
-
-    struct assoc_array_ops {
-            ...
-    };
-
-This points to a number of methods, all of which need to be provided:
-
-1. Get a chunk of index key from caller data::
-
-    unsigned long (*get_key_chunk)(const void *index_key, int level);
-
-   This should return a chunk of caller-supplied index key starting at the
-   *bit* position given by the level argument.  The level argument will be a
-   multiple of ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` and the function should return
-   ``ASSOC_ARRAY_KEY_CHUNK_SIZE bits``.  No error is possible.
-
-
-2. Get a chunk of an object's index key::
-
-    unsigned long (*get_object_key_chunk)(const void *object, int level);
-
-   As the previous function, but gets its data from an object in the array
-   rather than from a caller-supplied index key.
-
-
-3. See if this is the object we're looking for::
-
-    bool (*compare_object)(const void *object, const void *index_key);
-
-   Compare the object against an index key and return ``true`` if it matches
-   and ``false`` if it doesn't.
-
-
-4. Diff the index keys of two objects::
-
-    int (*diff_objects)(const void *object, const void *index_key);
-
-   Return the bit position at which the index key of the specified object
-   differs from the given index key or -1 if they are the same.
-
-
-5. Free an object::
-
-    void (*free_object)(void *object);
-
-   Free the specified object.  Note that this may be called an RCU grace period
-   after ``assoc_array_apply_edit()`` was called, so ``synchronize_rcu()`` may
-   be necessary on module unloading.
-
-
-Manipulation Functions
-----------------------
-
-There are a number of functions for manipulating an associative array:
-
-1. Initialise an associative array::
-
-    void assoc_array_init(struct assoc_array *array);
-
-   This initialises the base structure for an associative array.  It can't fail.
-
-
-2. Insert/replace an object in an associative array::
-
-    struct assoc_array_edit *
-    assoc_array_insert(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       const void *index_key,
-                       void *object);
-
-   This inserts the given object into the array.  Note that the least
-   significant bit of the pointer must be zero as it's used to type-mark
-   pointers internally.
-
-   If an object already exists for that key then it will be replaced with the
-   new object and the old one will be freed automatically.
-
-   The ``index_key`` argument should hold index key information and is
-   passed to the methods in the ops table when they are called.
-
-   This function makes no alteration to the array itself, but rather returns
-   an edit script that must be applied.  ``-ENOMEM`` is returned in the case of
-   an out-of-memory error.
-
-   The caller should lock exclusively against other modifiers of the array.
-
-
-3. Delete an object from an associative array::
-
-    struct assoc_array_edit *
-    assoc_array_delete(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       const void *index_key);
-
-   This deletes an object that matches the specified data from the array.
-
-   The ``index_key`` argument should hold index key information and is
-   passed to the methods in the ops table when they are called.
-
-   This function makes no alteration to the array itself, but rather returns
-   an edit script that must be applied.  ``-ENOMEM`` is returned in the case of
-   an out-of-memory error.  ``NULL`` will be returned if the specified object
-   is not found within the array.
-
-The caller should lock exclusively against other modifiers of the array.
-
-
-4. Delete all objects from an associative array::
-
-    struct assoc_array_edit *
-    assoc_array_clear(struct assoc_array *array,
-                      const struct assoc_array_ops *ops);
-
-   This deletes all the objects from an associative array and leaves it
-   completely empty.
-
-   This function makes no alteration to the array itself, but rather returns
-   an edit script that must be applied.  ``-ENOMEM`` is returned in the case of
-   an out-of-memory error.
-
-   The caller should lock exclusively against other modifiers of the array.
-
-
-5. Destroy an associative array, deleting all objects::
-
-    void assoc_array_destroy(struct assoc_array *array,
-                             const struct assoc_array_ops *ops);
-
-   This destroys the contents of the associative array and leaves it
-   completely empty.  It is not permitted for another thread to be traversing
-   the array under the RCU read lock at the same time as this function is
-   destroying it as no RCU deferral is performed on memory release -
-   something that would require memory to be allocated.
-
-   The caller should lock exclusively against other modifiers and accessors
-   of the array.
-
-
-6. Garbage collect an associative array::
-
-    int assoc_array_gc(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       bool (*iterator)(void *object, void *iterator_data),
-                       void *iterator_data);
-
-   This iterates over the objects in an associative array and passes each one
-   to ``iterator()``.  If ``iterator()`` returns ``true``, the object is kept.
-   If it returns ``false``, the object will be freed.  If the ``iterator()``
-   function returns ``true``, it must perform any appropriate refcount
-   incrementing on the object before returning.
-
-   The internal tree will be packed down if possible as part of the iteration
-   to reduce the number of nodes in it.
-
-   The ``iterator_data`` is passed directly to ``iterator()`` and is otherwise
-   ignored by the function.
-
-   The function will return ``0`` if successful and ``-ENOMEM`` if there wasn't
-   enough memory.
-
-   It is possible for other threads to iterate over or search the array under
-   the RCU read lock while this function is in progress.  The caller should
-   lock exclusively against other modifiers of the array.
-
-
-Access Functions
-----------------
-
-There are two functions for accessing an associative array:
-
-1. Iterate over all the objects in an associative array::
-
-    int assoc_array_iterate(const struct assoc_array *array,
-                            int (*iterator)(const void *object,
-                                            void *iterator_data),
-                            void *iterator_data);
-
-   This passes each object in the array to the iterator callback function.
-   ``iterator_data`` is private data for that function.
-
-   This may be used on an array at the same time as the array is being
-   modified, provided the RCU read lock is held.  Under such circumstances,
-   it is possible for the iteration function to see some objects twice.  If
-   this is a problem, then modification should be locked against.  The
-   iteration algorithm should not, however, miss any objects.
-
-   The function will return ``0`` if no objects were in the array or else it
-   will return the result of the last iterator function called.  Iteration
-   stops immediately if any call to the iteration function results in a
-   non-zero return.
-
-
-2. Find an object in an associative array::
-
-    void *assoc_array_find(const struct assoc_array *array,
-                           const struct assoc_array_ops *ops,
-                           const void *index_key);
-
-   This walks through the array's internal tree directly to the object
-   specified by the index key.
-
-   This may be used on an array at the same time as the array is being
-   modified, provided the RCU read lock is held.
-
-   The function will return the object if found (and set ``*_type`` to the
-   object type) or will return ``NULL`` if the object was not found.
-
-
-Index Key Form
---------------
-
-The index key can be of any form, but since the algorithms aren't told how long
-the key is, it is strongly recommended that the index key includes its length
-very early on before any variation due to the length would have an effect on
-comparisons.
-
-This will cause leaves with different length keys to scatter away from each
-other - and those with the same length keys to cluster together.
-
-It is also recommended that the index key begin with a hash of the rest of the
-key to maximise scattering throughout keyspace.
-
-The better the scattering, the wider and lower the internal tree will be.
-
-Poor scattering isn't too much of a problem as there are shortcuts and nodes
-can contain mixtures of leaves and metadata pointers.
-
-The index key is read in chunks of machine word.  Each chunk is subdivided into
-one nibble (4 bits) per level, so on a 32-bit CPU this is good for 8 levels and
-on a 64-bit CPU, 16 levels.  Unless the scattering is really poor, it is
-unlikely that more than one word of any particular index key will have to be
-used.
-
-
-Internal Workings
-=================
-
-The associative array data structure has an internal tree.  This tree is
-constructed of two types of metadata blocks: nodes and shortcuts.
-
-A node is an array of slots.  Each slot can contain one of four things:
-
-* A NULL pointer, indicating that the slot is empty.
-* A pointer to an object (a leaf).
-* A pointer to a node at the next level.
-* A pointer to a shortcut.
-
-
-Basic Internal Tree Layout
---------------------------
-
-Ignoring shortcuts for the moment, the nodes form a multilevel tree.  The index
-key space is strictly subdivided by the nodes in the tree and nodes occur on
-fixed levels.  For example::
-
- Level: 0               1               2               3
-        =============== =============== =============== ===============
-                                                        NODE D
-                        NODE B          NODE C  +------>+---+
-                +------>+---+   +------>+---+   |       | 0 |
-        NODE A  |       | 0 |   |       | 0 |   |       +---+
-        +---+   |       +---+   |       +---+   |       :   :
-        | 0 |   |       :   :   |       :   :   |       +---+
-        +---+   |       +---+   |       +---+   |       | f |
-        | 1 |---+       | 3 |---+       | 7 |---+       +---+
-        +---+           +---+           +---+
-        :   :           :   :           | 8 |---+
-        +---+           +---+           +---+   |       NODE E
-        | e |---+       | f |           :   :   +------>+---+
-        +---+   |       +---+           +---+           | 0 |
-        | f |   |                       | f |           +---+
-        +---+   |                       +---+           :   :
-                |       NODE F                          +---+
-                +------>+---+                           | f |
-                        | 0 |           NODE G          +---+
-                        +---+   +------>+---+
-                        :   :   |       | 0 |
-                        +---+   |       +---+
-                        | 6 |---+       :   :
-                        +---+           +---+
-                        :   :           | f |
-                        +---+           +---+
-                        | f |
-                        +---+
-
-In the above example, there are 7 nodes (A-G), each with 16 slots (0-f).
-Assuming no other meta data nodes in the tree, the key space is divided
-thusly:
-
-    ===========     ====
-    KEY PREFIX      NODE
-    ===========     ====
-    137*            D
-    138*            E
-    13[0-69-f]*     C
-    1[0-24-f]*      B
-    e6*             G
-    e[0-57-f]*      F
-    [02-df]*        A
-    ===========     ====
-
-So, for instance, keys with the following example index keys will be found in
-the appropriate nodes:
-
-    =============== ======= ====
-    INDEX KEY       PREFIX  NODE
-    =============== ======= ====
-    13694892892489  13      C
-    13795289025897  137     D
-    13889dde88793   138     E
-    138bbb89003093  138     E
-    1394879524789   12      C
-    1458952489      1       B
-    9431809de993ba  \-      A
-    b4542910809cd   \-      A
-    e5284310def98   e       F
-    e68428974237    e6      G
-    e7fffcbd443     e       F
-    f3842239082     \-      A
-    =============== ======= ====
-
-To save memory, if a node can hold all the leaves in its portion of keyspace,
-then the node will have all those leaves in it and will not have any metadata
-pointers - even if some of those leaves would like to be in the same slot.
-
-A node can contain a heterogeneous mix of leaves and metadata pointers.
-Metadata pointers must be in the slots that match their subdivisions of key
-space.  The leaves can be in any slot not occupied by a metadata pointer.  It
-is guaranteed that none of the leaves in a node will match a slot occupied by a
-metadata pointer.  If the metadata pointer is there, any leaf whose key matches
-the metadata key prefix must be in the subtree that the metadata pointer points
-to.
-
-In the above example list of index keys, node A will contain:
-
-    ====    =============== ==================
-    SLOT    CONTENT         INDEX KEY (PREFIX)
-    ====    =============== ==================
-    1       PTR TO NODE B   1*
-    any     LEAF            9431809de993ba
-    any     LEAF            b4542910809cd
-    e       PTR TO NODE F   e*
-    any     LEAF            f3842239082
-    ====    =============== ==================
-
-and node B:
-
-    ====    =============== ==================
-    SLOT    CONTENT         INDEX KEY (PREFIX)
-    ====    =============== ==================
-    3       PTR TO NODE C   13*
-    any     LEAF            1458952489
-    ====    =============== ==================
-
-
-Shortcuts
----------
-
-Shortcuts are metadata records that jump over a piece of keyspace.  A shortcut
-is a replacement for a series of single-occupancy nodes ascending through the
-levels.  Shortcuts exist to save memory and to speed up traversal.
-
-It is possible for the root of the tree to be a shortcut - say, for example,
-the tree contains at least 17 nodes all with key prefix ``1111``.  The
-insertion algorithm will insert a shortcut to skip over the ``1111`` keyspace
-in a single bound and get to the fourth level where these actually become
-different.
-
-
-Splitting And Collapsing Nodes
-------------------------------
-
-Each node has a maximum capacity of 16 leaves and metadata pointers.  If the
-insertion algorithm finds that it is trying to insert a 17th object into a
-node, that node will be split such that at least two leaves that have a common
-key segment at that level end up in a separate node rooted on that slot for
-that common key segment.
-
-If the leaves in a full node and the leaf that is being inserted are
-sufficiently similar, then a shortcut will be inserted into the tree.
-
-When the number of objects in the subtree rooted at a node falls to 16 or
-fewer, then the subtree will be collapsed down to a single node - and this will
-ripple towards the root if possible.
-
-
-Non-Recursive Iteration
------------------------
-
-Each node and shortcut contains a back pointer to its parent and the number of
-slot in that parent that points to it.  None-recursive iteration uses these to
-proceed rootwards through the tree, going to the parent node, slot N + 1 to
-make sure progress is made without the need for a stack.
-
-The backpointers, however, make simultaneous alteration and iteration tricky.
-
-
-Simultaneous Alteration And Iteration
--------------------------------------
-
-There are a number of cases to consider:
-
-1. Simple insert/replace.  This involves simply replacing a NULL or old
-   matching leaf pointer with the pointer to the new leaf after a barrier.
-   The metadata blocks don't change otherwise.  An old leaf won't be freed
-   until after the RCU grace period.
-
-2. Simple delete.  This involves just clearing an old matching leaf.  The
-   metadata blocks don't change otherwise.  The old leaf won't be freed until
-   after the RCU grace period.
-
-3. Insertion replacing part of a subtree that we haven't yet entered.  This
-   may involve replacement of part of that subtree - but that won't affect
-   the iteration as we won't have reached the pointer to it yet and the
-   ancestry blocks are not replaced (the layout of those does not change).
-
-4. Insertion replacing nodes that we're actively processing.  This isn't a
-   problem as we've passed the anchoring pointer and won't switch onto the
-   new layout until we follow the back pointers - at which point we've
-   already examined the leaves in the replaced node (we iterate over all the
-   leaves in a node before following any of its metadata pointers).
-
-   We might, however, re-see some leaves that have been split out into a new
-   branch that's in a slot further along than we were at.
-
-5. Insertion replacing nodes that we're processing a dependent branch of.
-   This won't affect us until we follow the back pointers.  Similar to (4).
-
-6. Deletion collapsing a branch under us.  This doesn't affect us because the
-   back pointers will get us back to the parent of the new node before we
-   could see the new node.  The entire collapsed subtree is thrown away
-   unchanged - and will still be rooted on the same slot, so we shouldn't
-   process it a second time as we'll go back to slot + 1.
-
-.. note::
-
-   Under some circumstances, we need to simultaneously change the parent
-   pointer and the parent slot pointer on a node (say, for example, we
-   inserted another node before it and moved it up a level).  We cannot do
-   this without locking against a read - so we have to replace that node too.
-
-   However, when we're changing a shortcut into a node this isn't a problem
-   as shortcuts only have one slot and so the parent slot number isn't used
-   when traversing backwards over one.  This means that it's okay to change
-   the slot number first - provided suitable barriers are used to make sure
-   the parent slot number is read after the back pointer.
-
-Obsolete blocks and leaves are freed up after an RCU grace period has passed,
-so as long as anyone doing walking or iteration holds the RCU read lock, the
-old superstructure should not go away on them.
diff --git a/Documentation/core-api/index.rst b/Documentation/core-api/index.rst
index 92f91c6a0d79d6..d56c60663b0c40 100644
--- a/Documentation/core-api/index.rst
+++ b/Documentation/core-api/index.rst
@@ -38,7 +38,6 @@ Library functionality that is used throughout the kernel.
    kobject
    kref
    cleanup
-   assoc_array
    folio_queue
    xarray
    maple_tree
diff --git a/Documentation/translations/zh_CN/core-api/assoc_array.rst b/Documentation/translations/zh_CN/core-api/assoc_array.rst
deleted file mode 100644
index 3649bf0d148807..00000000000000
--- a/Documentation/translations/zh_CN/core-api/assoc_array.rst
+++ /dev/null
@@ -1,473 +0,0 @@
-.. include:: ../disclaimer-zh_CN.rst
-
-:Original: Documentation/core-api/assoc_array.rst
-
-:翻译:
-
- 司延腾 Yanteng Si <siyanteng@loongson.cn>
-
-:校译:
-
-
-
-.. _cn_core-api_assoc_array:
-
-==================
-通用关联数组的实现
-==================
-
-简介
-====
-
-这个关联数组的实现是一个具有以下属性的对象容器:
-
-1. 对象是不透明的指针。该实现不关心它们指向哪里(如果有的话)或它们指向什么(如果有的
-   话)。
-
-   .. note::
-
-      指向对象的指针 *必须* 在最小有效位为零。
-
-2. 对象不需要包含供数组使用的链接块。这允许一个对象同时位于多个数组中。相反,数组是
-   由指向对象的元数据块组成的。
-
-3. 对象需要索引键来定位它们在阵列中的位置。
-
-4. 索引键必须是唯一的。插入一个与已经在数组中的且具有相同键值的对象将取代旧的对象。
-
-5. 索引键可以是任何长度,也可以是不同的长度。
-
-6. 索引键应该在早期就对长度进行编码,即在任何由于长度引起的变化出现之前。
-
-7. 索引键可以包括一个哈希值,以便将对象分散到整个数组中。
-
-8. 该数组可以迭代。对象不一定会按索引键的顺序出现。
-
-9.  数组可以在被修改的时候进行迭代,只要RCU的读锁被迭代器持有。然而,请注意,在这种情
-    况下,一些对象可能会被看到不止一次。如果这是个问题,迭代器应该锁定以防止修改。然
-    而,除非删除,否则对象不会被错过。
-
-10. 数组中的对象可以通过其索引键进行查询。
-
-11. 当数组被修改时,对象可以被查询,前提是进行查询的线程持有RCU的读锁。
-
-该实现在内部使用了一棵由16个指针节点组成的树,这些节点在每一层都由索引键的小数点进行索
-引,其方式与基数树相同。为了提高内存效率,可以放置快捷键,以跳过本来是一系列单占节点的地
-方。此外,节点将叶子对象指针打包到节点的空闲空间中,而不是做一个额外的分支,直到有对象
-需要被添加到一个完整的节点中。
-
-公用API
-=======
-
-公用API可以在 ``<linux/assoc_array.h>`` 中找到。关联数组的根是以下结构::
-
-    struct assoc_array {
-            ...
-    };
-
-该代码是通过启用 ``CONFIG_ASSOCIATIVE_ARRAY`` 来选择的,以::
-
-    ./script/config -e ASSOCIATIVE_ARRAY
-
-
-编辑脚本
---------
-
-插入和删除功能会产生一个“编辑脚本”,以后可以应用这个脚本来实现更改,而不会造成 ``ENOMEM``
-风险。这保留了将被安装在内部树中的预分配的元数据块,并跟踪应用脚本时将从树中删除的元数
-据块。
-
-在脚本应用后,这也被用来跟踪死块和死对象,以便以后可以释放它们。释放是在RCU宽限期过后
-进行的--因此允许访问功能在RCU读锁下进行。
-
-脚本在API之外显示为一个类型为::
-
-    struct assoc_array_edit;
-
-有两个处理脚本的功能:
-
-1. 应用一个编辑脚本::
-
-    void assoc_array_apply_edit(struct assoc_array_edit *edit);
-
-这将执行编辑功能,插值各种写屏障,以允许在RCU读锁下的访问继续进行。然后,编辑脚本将被
-传递给 ``call_rcu()`` ,以释放它和它所指向的任何死的东西。
-
-2. Cancel an edit script::
-
-    void assoc_array_cancel_edit(struct assoc_array_edit *edit);
-
-这将立即释放编辑脚本和所有预分配的内存。如果这是为了插入,新的对象不会被这个函数释放,
-而是必须由调用者释放。
-
-这些函数保证不会失败。
-
-
-操作表
-------
-
-各种功能采用了一个操作表::
-
-    struct assoc_array_ops {
-            ...
-    };
-
-这指出了一些方法,所有这些方法都需要提供:
-
-1. 从调用者数据中获取索引键的一个块::
-
-    unsigned long (*get_key_chunk)(const void *index_key, int level);
-
-这应该返回一个由调用者提供的索引键的块,从level参数给出的 *比特* 位置开始。level参数将
-是 ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` 的倍数,该函数应返回 ``ASSOC_ARRAY_KEY_CHUNK_SIZE``
-位。不可能出现错误。
-
-
-2. 获取一个对象的索引键的一个块::
-
-    unsigned long (*get_object_key_chunk)(const void *object, int level);
-
-和前面的函数一样,但是从数组中的一个对象而不是从调用者提供的索引键中获取数据。
-
-
-3. 看看这是否是我们要找的对象::
-
-    bool (*compare_object)(const void *object, const void *index_key);
-
-将对象与一个索引键进行比较,如果匹配则返回 ``true`` ,不匹配则返回 ``false`` 。
-
-
-4. 对两个对象的索引键进行比较::
-
-    int (*diff_objects)(const void *object, const void *index_key);
-
-返回指定对象的索引键与给定索引键不同的比特位置,如果它们相同,则返回-1。
-
-
-5. 释放一个对象::
-
-    void (*free_object)(void *object);
-
-释放指定的对象。注意,这可能是在调用 ``assoc_array_apply_edit()`` 后的一个RCU宽限期内
-调用的,所以在模块卸载时可能需要 ``synchronize_rcu()`` 。
-
-
-操控函数
---------
-
-有一些函数用于操控关联数组:
-
-1. 初始化一个关联数组::
-
-    void assoc_array_init(struct assoc_array *array);
-
-这将初始化一个关联数组的基础结构。它不会失败。
-
-
-2. 在一个关联数组中插入/替换一个对象::
-
-    struct assoc_array_edit *
-    assoc_array_insert(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       const void *index_key,
-                       void *object);
-
-这将把给定的对象插入数组中。注意,指针的最小有效位必须是0,因为它被用来在内部标记指针的类
-型。
-
-如果该键已经存在一个对象,那么它将被新的对象所取代,旧的对象将被自动释放。
-
-``index_key`` 参数应持有索引键信息,并在调用OPP表中的方法时传递给它们。
-
-这个函数不对数组本身做任何改动,而是返回一个必须应用的编辑脚本。如果出现内存不足的错误,会
-返回 ``-ENOMEM`` 。
-
-调用者应专门锁定数组的其他修改器。
-
-
-3. 从一个关联数组中删除一个对象::
-
-    struct assoc_array_edit *
-    assoc_array_delete(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       const void *index_key);
-
-这将从数组中删除一个符合指定数据的对象。
-
-``index_key`` 参数应持有索引键信息,并在调用OPP表中的方法时传递给它们。
-
-这个函数不对数组本身做任何改动,而是返回一个必须应用的编辑脚本。 ``-ENOMEM`` 在出现内存不足
-的错误时返回。如果在数组中没有找到指定的对象,将返回 ``NULL`` 。
-
-调用者应该对数组的其他修改者进行专门锁定。
-
-
-4. 从一个关联数组中删除所有对象::
-
-    struct assoc_array_edit *
-    assoc_array_clear(struct assoc_array *array,
-                      const struct assoc_array_ops *ops);
-
-这个函数删除了一个关联数组中的所有对象,使其完全为空。
-
-这个函数没有对数组本身做任何改动,而是返回一个必须应用的编辑脚本。如果出现内存不足
-的错误,则返回 ``-ENOMEM`` 。
-
-调用者应专门锁定数组的其他修改者。
-
-
-5. 销毁一个关联数组,删除所有对象::
-
-    void assoc_array_destroy(struct assoc_array *array,
-                             const struct assoc_array_ops *ops);
-
-这将破坏关联数组的内容,使其完全为空。在这个函数销毁数组的同时,不允许另一个线程在RCU读锁
-下遍历数组,因为在内存释放时不执行RCU延迟,这需要分配内存。
-
-调用者应该专门针对数组的其他修改者和访问者进行锁定。
-
-
-6. 垃圾回收一个关联数组::
-
-    int assoc_array_gc(struct assoc_array *array,
-                       const struct assoc_array_ops *ops,
-                       bool (*iterator)(void *object, void *iterator_data),
-                       void *iterator_data);
-
-这是对一个关联数组中的对象进行迭代,并将每个对象传递给 ``iterator()`` 。如果 ``iterator()`` 返回
-true,该对象被保留。如果它返回 ``false`` ,该对象将被释放。如果 ``iterator()`` 函数返回 ``true`` ,它必须
-在返回之前对该对象进行适当的 ``refcount`` 递增。
-
-如果可能的话,内部树将被打包下来,作为迭代的一部分,以减少其中的节点数量。
-
-``iterator_data`` 被直接传递给 ``iterator()`` ,否则会被函数忽略。
-
-如果成功,该函数将返回 ``0`` ,如果没有足够的内存,则返回 ``-ENOMEM`` 。
-
-在这个函数执行过程中,其他线程有可能在RCU读锁下迭代或搜索阵列。调用者应该专门针对数组的其他
-修改者进行锁定。
-
-
-访问函数
---------
-
-有两个函数用于访问一个关联数组:
-
-1. 遍历一个关联数组中的所有对象::
-
-    int assoc_array_iterate(const struct assoc_array *array,
-                            int (*iterator)(const void *object,
-                                            void *iterator_data),
-                            void *iterator_data);
-
-这将数组中的每个对象传递给迭代器回调函数。 ``iterator_data`` 是该函数的私有数据。
-
-在数组被修改的同时,可以在数组上使用这个方法,前提是RCU读锁被持有。在这种情况下,迭代函数有
-可能两次看到某些对象。如果这是个问题,那么修改应该被锁定。然而,迭代算法不应该错过任何对象。
-
-如果数组中没有对象,该函数将返回 ``0`` ,否则将返回最后一次调用的迭代器函数的结果。如果对迭代函数
-的任何调用导致非零返回,迭代立即停止。
-
-
-2. 在一个关联数组中寻找一个对象::
-
-    void *assoc_array_find(const struct assoc_array *array,
-                           const struct assoc_array_ops *ops,
-                           const void *index_key);
-
-这将直接穿过数组的内部树,到达索引键所指定的对象。
-
-这个函数可以在修改数组的同时用在数组上,前提是RCU读锁被持有。
-
-如果找到对象,该函数将返回对象(并将 ``*_type`` 设置为对象的类型),如果没有找到对象,将返回 ``NULL`` 。
-
-
-索引键形式
-----------
-
-索引键可以是任何形式的,但是由于算法没有被告知键有多长,所以强烈建议在任何由于长度而产生的变化
-对比较产生影响之前,索引键应该很早就包括其长度。
-
-这将导致具有不同长度键的叶子相互分散,而具有相同长度键的叶子则聚集在一起。
-
-我们还建议索引键以键的其余部分的哈希值开始,以最大限度地提高整个键空间的散布情况。
-
-分散性越好,内部树就越宽,越低。
-
-分散性差并不是一个太大的问题,因为有快捷键,节点可以包含叶子和元数据指针的混合物。
-
-索引键是以机器字的块状来读取的。每个块被细分为每层一个nibble(4比特),所以在32位CPU上这适合8层,
-在64位CPU上适合16层。除非散布情况真的很差,否则不太可能有超过一个字的任何特定索引键需要被使用。
-
-
-内部工作机制
-============
-
-关联数组数据结构有一个内部树。这个树由两种类型的元数据块构成:节点和快捷键。
-
-一个节点是一个槽的数组。每个槽可以包含以下四种东西之一:
-
-* 一个NULL的指针,表示槽是空的。
-* 一个指向对象(叶子)的指针。
-* 一个指向下一级节点的指针。
-* 一个指向快捷键的指针。
-
-
-基本的内部树形布局
-------------------
-
-暂时不考虑快捷键,节点形成一个多级树。索引键空间被树上的节点严格细分,节点出现在固定的层次上。例如::
-
- Level: 0               1               2               3
-        =============== =============== =============== ===============
-                                                        NODE D
-                        NODE B          NODE C  +------>+---+
-                +------>+---+   +------>+---+   |       | 0 |
-        NODE A  |       | 0 |   |       | 0 |   |       +---+
-        +---+   |       +---+   |       +---+   |       :   :
-        | 0 |   |       :   :   |       :   :   |       +---+
-        +---+   |       +---+   |       +---+   |       | f |
-        | 1 |---+       | 3 |---+       | 7 |---+       +---+
-        +---+           +---+           +---+
-        :   :           :   :           | 8 |---+
-        +---+           +---+           +---+   |       NODE E
-        | e |---+       | f |           :   :   +------>+---+
-        +---+   |       +---+           +---+           | 0 |
-        | f |   |                       | f |           +---+
-        +---+   |                       +---+           :   :
-                |       NODE F                          +---+
-                +------>+---+                           | f |
-                        | 0 |           NODE G          +---+
-                        +---+   +------>+---+
-                        :   :   |       | 0 |
-                        +---+   |       +---+
-                        | 6 |---+       :   :
-                        +---+           +---+
-                        :   :           | f |
-                        +---+           +---+
-                        | f |
-                        +---+
-
-在上述例子中,有7个节点(A-G),每个节点有16个槽(0-f)。假设树上没有其他元数据节点,那么密钥空间
-是这样划分的::
-
-    KEY PREFIX      NODE
-    ==========      ====
-    137*            D
-    138*            E
-    13[0-69-f]*     C
-    1[0-24-f]*      B
-    e6*             G
-    e[0-57-f]*      F
-    [02-df]*        A
-
-因此,例如,具有以下示例索引键的键将在适当的节点中被找到::
-
-    INDEX KEY       PREFIX  NODE
-    =============== ======= ====
-    13694892892489  13      C
-    13795289025897  137     D
-    13889dde88793   138     E
-    138bbb89003093  138     E
-    1394879524789   12      C
-    1458952489      1       B
-    9431809de993ba  -       A
-    b4542910809cd   -       A
-    e5284310def98   e       F
-    e68428974237    e6      G
-    e7fffcbd443     e       F
-    f3842239082     -       A
-
-为了节省内存,如果一个节点可以容纳它的那部分键空间中的所有叶子,那么这个节点将有所有这些叶子,而不
-会有任何元数据指针——即使其中一些叶子想在同一个槽中。
-
-一个节点可以包含叶子和元数据指针的异质性混合。元数据指针必须在与它们的关键空间的细分相匹配的槽中。
-叶子可以在任何没有被元数据指针占据的槽中。保证一个节点中没有一个叶子会与元数据指针占据的槽相匹配。
-如果元数据指针在那里,任何键与元数据键前缀相匹配的叶必须在元数据指针指向的子树中。
-
-在上面的索引键的例子列表中,节点A将包含::
-
-    SLOT    CONTENT         INDEX KEY (PREFIX)
-    ====    =============== ==================
-    1       PTR TO NODE B   1*
-    any     LEAF            9431809de993ba
-    any     LEAF            b4542910809cd
-    e       PTR TO NODE F   e*
-    any     LEAF            f3842239082
-
-和节点B::
-
-    3	PTR TO NODE C	13*
-    any	LEAF		1458952489
-
-
-快捷键
----------
-
-快捷键是跳过一块键空间的元数据记录。快捷键是一系列通过层次上升的单占节点的替代物。快捷键的存在是
-为了节省内存和加快遍历速度。
-
-树的根部有可能是一个快捷键——比如说,树至少包含17个节点,都有键前缀 ``1111`` 。插入算法将插入一个快捷键,
-以单次跳过 ``1111`` 的键位,并到达第四层,在这里,这些键位实际上变得不同。
-
-
-拆分和合并节点
-------------------------------
-
-每个节点的最大容量为16个叶子和元数据指针。如果插入算法发现它正试图将一个第17个对象插入到一个节点中,
-该节点将被拆分,使得至少两个在该层有一个共同的关键段的叶子最终在一个单独的节点中,该共同的关键段的根
-在该槽上。
-
-如果一个完整的节点中的叶子和被插入的叶子足够相似,那么就会在树中插入一个快捷键。
-
-当根植于某个节点的子树中的对象数量下降到16个或更少时,那么该子树将被合并成一个单独的节点——如果可能的
-话,这将向根部扩散。
-
-
-非递归式迭代
-------------
-
-每个节点和快捷键都包含一个指向其父节点的后置指针,以及该父节点中指向它的槽数。非递归迭代使用这些来
-通过树的根部进行,前往父节点,槽N+1,以确保在没有堆栈的情况下取得进展。
-
-然而,反向指针使得同时改变和迭代变得很棘手。
-
-
-同时改变和迭代
---------------
-
-有一些情况需要考虑:
-
-1. 简单的插入/替换。这涉及到简单地将一个NULL或旧的匹配叶子的指针替换为屏障后的新叶子的指针。否则元数
-   据块不会改变。一个旧的叶子直到RCU宽限期过后才会被释放。
-
-2. 简单删除。这只是涉及到清除一个旧的匹配叶子。元数据块不会有其他变化。旧的叶子直到RCU宽限期之后才会
-   被释放。
-
-3. 插入,替换我们还没有进入的子树的一部分。这可能涉及到替换该子树的一部分——但这不会影响迭代,因为我们
-   还没有到达它的指针,而且祖先块也不会被替换(这些块的布局不会改变)。
-
-4. 插入替换了我们正在处理的节点。这不是一个问题,因为我们已经通过了锚定指针,直到我们跟随后面的指针才
-   会切换到新的布局上——这时我们已经检查了被替换节点的叶子(在跟随任何元数据指针之前,我们会迭代一个节
-   点的所有叶子)。
-
-   然而,我们可能会重新看到一些叶子,这些叶子已经被分割成一个新的分支,而这个分支的位置比我们之前的位
-   置更远。
-
-5. 插入替换了我们正在处理的依赖分支的节点。这不会影响到我们,直到我们跟随后面的指针。与(4)类似。
-
-6. 删掉我们下面的一个分支。这不会影响我们,因为在我们看到新节点之前,回溯指针会让我们回到新节点的父节
-   点。整个崩溃的子树被扔掉了,没有任何变化——而且仍然会在同一个槽上生根,所以我们不应该第二次处理它,
-   因为我们会回到槽+1。
-
-.. note::
-
-    在某些情况下,我们需要同时改变一个节点的父指针和父槽指针(比如说,我们在它之前插入了另一个节点,
-    并把它往上移了一层)。我们不能在不锁定读取的情况下这样做——所以我们必须同时替换该节点。
-
-    然而,当我们把一个快捷键改成一个节点时,这不是一个问题,因为快捷键只有一个槽,所以当向后遍
-    历一个槽时,不会使用父槽号。这意味着先改变槽位号是可以的——只要使用适当的屏障来确保父槽位号在后
-    退指针之后被读取。
-
-过时的块和叶子在RCU宽限期过后会被释放,所以只要任何进行遍历或迭代的人持有RCU读锁,旧的上层建筑就不
-应该在他们身上消失。
diff --git a/Documentation/translations/zh_CN/core-api/index.rst b/Documentation/translations/zh_CN/core-api/index.rst
index 453a02cd1f4486..ec4b03b2a0a60e 100644
--- a/Documentation/translations/zh_CN/core-api/index.rst
+++ b/Documentation/translations/zh_CN/core-api/index.rst
@@ -41,7 +41,6 @@
 
    kobject
    kref
-   assoc_array
    xarray
    rbtree
    idr
diff --git a/drivers/md/dm-verity-verify-sig.c b/drivers/md/dm-verity-verify-sig.c
index 0c65c7a31da8bd..bd5143aae4fa96 100644
--- a/drivers/md/dm-verity-verify-sig.c
+++ b/drivers/md/dm-verity-verify-sig.c
@@ -153,7 +153,7 @@ int verity_verify_root_hash(const void *root_hash, size_t root_hash_len,
 	if (ret != -ENOKEY && ret != -EKEYREJECTED)
 		return ret;
 
-	if (dm_verity_keyring->keys.nr_leaves_on_tree &&
+	if (!keyring_is_empty(dm_verity_keyring) &&
 	    dm_verity_keyring->restrict_link)
 		ret = verify_pkcs7_signature(root_hash, root_hash_len,
 					     sig_data, sig_len,
diff --git a/fs/verity/signature.c b/fs/verity/signature.c
index 2f49c5d9d98705..b45b39b829b298 100644
--- a/fs/verity/signature.c
+++ b/fs/verity/signature.c
@@ -70,7 +70,7 @@ int fsverity_verify_signature(const struct fsverity_info *vi,
 		return 0;
 	}
 
-	if (fsverity_keyring->keys.nr_leaves_on_tree == 0) {
+	if (keyring_is_empty(fsverity_keyring)) {
 		/*
 		 * The ".fs-verity" keyring is empty, due to builtin signatures
 		 * being supported by the kernel but not actually being used.
diff --git a/include/keys/keyring-type.h b/include/keys/keyring-type.h
index 1dc83862f519ad..314832f5dc4a99 100644
--- a/include/keys/keyring-type.h
+++ b/include/keys/keyring-type.h
@@ -9,6 +9,5 @@
 #define _KEYS_KEYRING_TYPE_H
 
 #include <linux/key.h>
-#include <linux/assoc_array.h>
 
 #endif /* _KEYS_KEYRING_TYPE_H */
diff --git a/include/linux/assoc_array.h b/include/linux/assoc_array.h
deleted file mode 100644
index 8b3f230ce89440..00000000000000
--- a/include/linux/assoc_array.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0-or-later */
-/* Generic associative array implementation.
- *
- * See Documentation/core-api/assoc_array.rst for information.
- *
- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.
- * Written by David Howells (dhowells@redhat.com)
- */
-
-#ifndef _LINUX_ASSOC_ARRAY_H
-#define _LINUX_ASSOC_ARRAY_H
-
-#ifdef CONFIG_ASSOCIATIVE_ARRAY
-
-#include <linux/types.h>
-
-#define ASSOC_ARRAY_KEY_CHUNK_SIZE BITS_PER_LONG /* Key data retrieved in chunks of this size */
-
-/*
- * Generic associative array.
- */
-struct assoc_array {
-	struct assoc_array_ptr	*root;		/* The node at the root of the tree */
-	unsigned long		nr_leaves_on_tree;
-};
-
-/*
- * Operations on objects and index keys for use by array manipulation routines.
- */
-struct assoc_array_ops {
-	/* Method to get a chunk of an index key from caller-supplied data */
-	unsigned long (*get_key_chunk)(const void *index_key, int level);
-
-	/* Method to get a piece of an object's index key */
-	unsigned long (*get_object_key_chunk)(const void *object, int level);
-
-	/* Is this the object we're looking for? */
-	bool (*compare_object)(const void *object, const void *index_key);
-
-	/* How different is an object from an index key, to a bit position in
-	 * their keys? (or -1 if they're the same)
-	 */
-	int (*diff_objects)(const void *object, const void *index_key);
-
-	/* Method to free an object. */
-	void (*free_object)(void *object);
-};
-
-/*
- * Access and manipulation functions.
- */
-struct assoc_array_edit;
-
-static inline void assoc_array_init(struct assoc_array *array)
-{
-	array->root = NULL;
-	array->nr_leaves_on_tree = 0;
-}
-
-extern int assoc_array_iterate(const struct assoc_array *array,
-			       int (*iterator)(const void *object,
-					       void *iterator_data),
-			       void *iterator_data);
-extern void *assoc_array_find(const struct assoc_array *array,
-			      const struct assoc_array_ops *ops,
-			      const void *index_key);
-extern void assoc_array_destroy(struct assoc_array *array,
-				const struct assoc_array_ops *ops);
-extern struct assoc_array_edit *assoc_array_insert(struct assoc_array *array,
-						   const struct assoc_array_ops *ops,
-						   const void *index_key,
-						   void *object);
-extern void assoc_array_insert_set_object(struct assoc_array_edit *edit,
-					  void *object);
-extern struct assoc_array_edit *assoc_array_delete(struct assoc_array *array,
-						   const struct assoc_array_ops *ops,
-						   const void *index_key);
-extern struct assoc_array_edit *assoc_array_clear(struct assoc_array *array,
-						  const struct assoc_array_ops *ops);
-extern void assoc_array_apply_edit(struct assoc_array_edit *edit);
-extern void assoc_array_cancel_edit(struct assoc_array_edit *edit);
-extern int assoc_array_gc(struct assoc_array *array,
-			  const struct assoc_array_ops *ops,
-			  bool (*iterator)(void *object, void *iterator_data),
-			  void *iterator_data);
-
-#endif /* CONFIG_ASSOCIATIVE_ARRAY */
-#endif /* _LINUX_ASSOC_ARRAY_H */
diff --git a/include/linux/assoc_array_priv.h b/include/linux/assoc_array_priv.h
deleted file mode 100644
index dca733ef675038..00000000000000
--- a/include/linux/assoc_array_priv.h
+++ /dev/null
@@ -1,178 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0-or-later */
-/* Private definitions for the generic associative array implementation.
- *
- * See Documentation/core-api/assoc_array.rst for information.
- *
- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.
- * Written by David Howells (dhowells@redhat.com)
- */
-
-#ifndef _LINUX_ASSOC_ARRAY_PRIV_H
-#define _LINUX_ASSOC_ARRAY_PRIV_H
-
-#ifdef CONFIG_ASSOCIATIVE_ARRAY
-
-#include <linux/assoc_array.h>
-
-#define ASSOC_ARRAY_FAN_OUT		16	/* Number of slots per node */
-#define ASSOC_ARRAY_FAN_MASK		(ASSOC_ARRAY_FAN_OUT - 1)
-#define ASSOC_ARRAY_LEVEL_STEP		(ilog2(ASSOC_ARRAY_FAN_OUT))
-#define ASSOC_ARRAY_LEVEL_STEP_MASK	(ASSOC_ARRAY_LEVEL_STEP - 1)
-#define ASSOC_ARRAY_KEY_CHUNK_MASK	(ASSOC_ARRAY_KEY_CHUNK_SIZE - 1)
-#define ASSOC_ARRAY_KEY_CHUNK_SHIFT	(ilog2(BITS_PER_LONG))
-
-/*
- * Undefined type representing a pointer with type information in the bottom
- * two bits.
- */
-struct assoc_array_ptr;
-
-/*
- * An N-way node in the tree.
- *
- * Each slot contains one of four things:
- *
- *	(1) Nothing (NULL).
- *
- *	(2) A leaf object (pointer types 0).
- *
- *	(3) A next-level node (pointer type 1, subtype 0).
- *
- *	(4) A shortcut (pointer type 1, subtype 1).
- *
- * The tree is optimised for search-by-ID, but permits reasonable iteration
- * also.
- *
- * The tree is navigated by constructing an index key consisting of an array of
- * segments, where each segment is ilog2(ASSOC_ARRAY_FAN_OUT) bits in size.
- *
- * The segments correspond to levels of the tree (the first segment is used at
- * level 0, the second at level 1, etc.).
- */
-struct assoc_array_node {
-	struct assoc_array_ptr	*back_pointer;
-	u8			parent_slot;
-	struct assoc_array_ptr	*slots[ASSOC_ARRAY_FAN_OUT];
-	unsigned long		nr_leaves_on_branch;
-};
-
-/*
- * A shortcut through the index space out to where a collection of nodes/leaves
- * with the same IDs live.
- */
-struct assoc_array_shortcut {
-	struct assoc_array_ptr	*back_pointer;
-	int			parent_slot;
-	int			skip_to_level;
-	struct assoc_array_ptr	*next_node;
-	unsigned long		index_key[];
-};
-
-/*
- * Preallocation cache.
- */
-struct assoc_array_edit {
-	struct rcu_head			rcu;
-	struct assoc_array		*array;
-	const struct assoc_array_ops	*ops;
-	const struct assoc_array_ops	*ops_for_excised_subtree;
-	struct assoc_array_ptr		*leaf;
-	struct assoc_array_ptr		**leaf_p;
-	struct assoc_array_ptr		*dead_leaf;
-	struct assoc_array_ptr		*new_meta[3];
-	struct assoc_array_ptr		*excised_meta[1];
-	struct assoc_array_ptr		*excised_subtree;
-	struct assoc_array_ptr		**set_backpointers[ASSOC_ARRAY_FAN_OUT];
-	struct assoc_array_ptr		*set_backpointers_to;
-	struct assoc_array_node		*adjust_count_on;
-	long				adjust_count_by;
-	struct {
-		struct assoc_array_ptr	**ptr;
-		struct assoc_array_ptr	*to;
-	} set[2];
-	struct {
-		u8			*p;
-		u8			to;
-	} set_parent_slot[1];
-	u8				segment_cache[ASSOC_ARRAY_FAN_OUT + 1];
-};
-
-/*
- * Internal tree member pointers are marked in the bottom one or two bits to
- * indicate what type they are so that we don't have to look behind every
- * pointer to see what it points to.
- *
- * We provide functions to test type annotations and to create and translate
- * the annotated pointers.
- */
-#define ASSOC_ARRAY_PTR_TYPE_MASK 0x1UL
-#define ASSOC_ARRAY_PTR_LEAF_TYPE 0x0UL	/* Points to leaf (or nowhere) */
-#define ASSOC_ARRAY_PTR_META_TYPE 0x1UL	/* Points to node or shortcut */
-#define ASSOC_ARRAY_PTR_SUBTYPE_MASK	0x2UL
-#define ASSOC_ARRAY_PTR_NODE_SUBTYPE	0x0UL
-#define ASSOC_ARRAY_PTR_SHORTCUT_SUBTYPE 0x2UL
-
-static inline bool assoc_array_ptr_is_meta(const struct assoc_array_ptr *x)
-{
-	return (unsigned long)x & ASSOC_ARRAY_PTR_TYPE_MASK;
-}
-static inline bool assoc_array_ptr_is_leaf(const struct assoc_array_ptr *x)
-{
-	return !assoc_array_ptr_is_meta(x);
-}
-static inline bool assoc_array_ptr_is_shortcut(const struct assoc_array_ptr *x)
-{
-	return (unsigned long)x & ASSOC_ARRAY_PTR_SUBTYPE_MASK;
-}
-static inline bool assoc_array_ptr_is_node(const struct assoc_array_ptr *x)
-{
-	return !assoc_array_ptr_is_shortcut(x);
-}
-
-static inline void *assoc_array_ptr_to_leaf(const struct assoc_array_ptr *x)
-{
-	return (void *)((unsigned long)x & ~ASSOC_ARRAY_PTR_TYPE_MASK);
-}
-
-static inline
-unsigned long __assoc_array_ptr_to_meta(const struct assoc_array_ptr *x)
-{
-	return (unsigned long)x &
-		~(ASSOC_ARRAY_PTR_SUBTYPE_MASK | ASSOC_ARRAY_PTR_TYPE_MASK);
-}
-static inline
-struct assoc_array_node *assoc_array_ptr_to_node(const struct assoc_array_ptr *x)
-{
-	return (struct assoc_array_node *)__assoc_array_ptr_to_meta(x);
-}
-static inline
-struct assoc_array_shortcut *assoc_array_ptr_to_shortcut(const struct assoc_array_ptr *x)
-{
-	return (struct assoc_array_shortcut *)__assoc_array_ptr_to_meta(x);
-}
-
-static inline
-struct assoc_array_ptr *__assoc_array_x_to_ptr(const void *p, unsigned long t)
-{
-	return (struct assoc_array_ptr *)((unsigned long)p | t);
-}
-static inline
-struct assoc_array_ptr *assoc_array_leaf_to_ptr(const void *p)
-{
-	return __assoc_array_x_to_ptr(p, ASSOC_ARRAY_PTR_LEAF_TYPE);
-}
-static inline
-struct assoc_array_ptr *assoc_array_node_to_ptr(const struct assoc_array_node *p)
-{
-	return __assoc_array_x_to_ptr(
-		p, ASSOC_ARRAY_PTR_META_TYPE | ASSOC_ARRAY_PTR_NODE_SUBTYPE);
-}
-static inline
-struct assoc_array_ptr *assoc_array_shortcut_to_ptr(const struct assoc_array_shortcut *p)
-{
-	return __assoc_array_x_to_ptr(
-		p, ASSOC_ARRAY_PTR_META_TYPE | ASSOC_ARRAY_PTR_SHORTCUT_SUBTYPE);
-}
-
-#endif /* CONFIG_ASSOCIATIVE_ARRAY */
-#endif /* _LINUX_ASSOC_ARRAY_PRIV_H */
diff --git a/include/linux/key-type.h b/include/linux/key-type.h
index c4f329b6ae3fed..bb97bd3e5af4fa 100644
--- a/include/linux/key-type.h
+++ b/include/linux/key-type.h
@@ -161,7 +161,6 @@ struct key_type {
 				     const void *in, const void *in2);
 
 	/* internal fields */
-	atomic64_t		index_id;	/* Opaque keyring index ID */
 	struct list_head	link;		/* link in types list */
 	struct lock_class_key	lock_class;	/* key->sem lock class */
 } __randomize_layout;
diff --git a/include/linux/key.h b/include/linux/key.h
index 420412aab9263a..0d2d64e10f7baf 100644
--- a/include/linux/key.h
+++ b/include/linux/key.h
@@ -17,7 +17,6 @@
 #include <linux/sysctl.h>
 #include <linux/rwsem.h>
 #include <linux/atomic.h>
-#include <linux/assoc_array.h>
 #include <linux/refcount.h>
 #include <linux/time64.h>
 
@@ -107,34 +106,21 @@ struct key_owner;
 struct key_tag;
 struct keyring_list;
 struct keyring_name;
+struct keyring_index;
 
 struct key_tag {
 	struct rcu_head		rcu;
-	atomic64_t		index_id;	/* Opaque keyring index ID */
 	refcount_t		usage;
 	bool			removed;	/* T when subject removed */
 };
 
 struct keyring_index_key {
 	/* [!] If this structure is altered, the union in struct key must change too! */
-	unsigned long		hash;			/* Hash value */
-	union {
-		struct {
-#ifdef __LITTLE_ENDIAN /* Put desc_len at the LSB of x */
-			u16	desc_len;
-			char	desc[sizeof(long) - 2];	/* First few chars of description */
-#else
-			char	desc[sizeof(long) - 2];	/* First few chars of description */
-			u16	desc_len;
-#endif
-		};
-		unsigned long x;
-	};
+	u32			hash;			/* Hash value */
+	unsigned int		desc_len;
 	struct key_type		*type;
 	struct key_tag		*domain_tag;	/* Domain of operation */
 	const char		*description;
-	u64			type_id;	/* Cached index IDs */
-	u64			domain_id;
 };
 
 union key_payload {
@@ -252,13 +238,11 @@ struct key {
 	union {
 		struct keyring_index_key index_key;
 		struct {
-			unsigned long	hash;
-			unsigned long	len_desc;
+			u32		hash;
+			unsigned int	desc_len;
 			struct key_type	*type;		/* type of key */
 			struct key_tag	*domain_tag;	/* Domain of operation */
 			char		*description;
-			u64		type_id;
-			u64		domain_id;
 		};
 	};
 
@@ -271,7 +255,7 @@ struct key {
 		struct {
 			/* Keyring bits */
 			struct list_head name_link;
-			struct assoc_array keys;
+			struct keyring_index __rcu *index;
 		};
 	};
 
@@ -439,6 +423,7 @@ extern int restrict_link_reject(struct key *keyring,
 				struct key *restriction_key);
 
 extern int keyring_clear(struct key *keyring);
+bool keyring_is_empty(const struct key *keyring);
 
 extern key_ref_t keyring_search(key_ref_t keyring,
 				struct key_type *type,
diff --git a/kernel/bpf/keys.c b/kernel/bpf/keys.c
index bffc356839ac56..24e0416abc99dd 100644
--- a/kernel/bpf/keys.c
+++ b/kernel/bpf/keys.c
@@ -29,7 +29,7 @@ struct bpf_key *bpf_lookup_keyring(void)
 
 	if (!bpf_keyring)
 		return NULL;
-	if (!READ_ONCE(bpf_keyring->keys.nr_leaves_on_tree) ||
+	if (keyring_is_empty(bpf_keyring) ||
 	    !READ_ONCE(bpf_keyring->restrict_link))
 		return NULL;
 
diff --git a/lib/Kconfig b/lib/Kconfig
index 1e42f5167c68bc..f70382dbb15954 100644
--- a/lib/Kconfig
+++ b/lib/Kconfig
@@ -349,20 +349,6 @@ config XARRAY_MULTI
 	  Support entries which occupy multiple consecutive indices in the
 	  XArray.
 
-config ASSOCIATIVE_ARRAY
-	bool
-	help
-	  Generic associative array.  Can be searched and iterated over whilst
-	  it is being modified.  It is also reasonably quick to search and
-	  modify.  The algorithms are non-recursive, and the trees are highly
-	  capacious.
-
-	  See:
-
-		Documentation/core-api/assoc_array.rst
-
-	  for more information.
-
 config CLOSURES
 	bool
 
diff --git a/lib/Makefile b/lib/Makefile
index a2afe954805cb8..4777dfcc824405 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -141,7 +141,6 @@ obj-$(CONFIG_GENERIC_HWEIGHT) += hweight.o
 
 obj-$(CONFIG_BTREE) += btree.o
 obj-$(CONFIG_INTERVAL_TREE) += interval_tree.o
-obj-$(CONFIG_ASSOCIATIVE_ARRAY) += assoc_array.o
 obj-$(CONFIG_DEBUG_PREEMPT) += smp_processor_id.o
 obj-$(CONFIG_LIST_HARDENED) += list_debug.o
 obj-$(CONFIG_DEBUG_OBJECTS) += debugobjects.o
diff --git a/lib/assoc_array.c b/lib/assoc_array.c
deleted file mode 100644
index b6c9723e12ced5..00000000000000
--- a/lib/assoc_array.c
+++ /dev/null
@@ -1,1724 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0-or-later
-/* Generic associative array implementation.
- *
- * See Documentation/core-api/assoc_array.rst for information.
- *
- * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.
- * Written by David Howells (dhowells@redhat.com)
- */
-//#define DEBUG
-#include <linux/rcupdate.h>
-#include <linux/slab.h>
-#include <linux/err.h>
-#include <linux/assoc_array_priv.h>
-
-/*
- * Iterate over an associative array.  The caller must hold the RCU read lock
- * or better.
- */
-static int assoc_array_subtree_iterate(const struct assoc_array_ptr *root,
-				       const struct assoc_array_ptr *stop,
-				       int (*iterator)(const void *leaf,
-						       void *iterator_data),
-				       void *iterator_data)
-{
-	const struct assoc_array_shortcut *shortcut;
-	const struct assoc_array_node *node;
-	const struct assoc_array_ptr *cursor, *ptr, *parent;
-	unsigned long has_meta;
-	int slot, ret;
-
-	cursor = root;
-
-begin_node:
-	if (assoc_array_ptr_is_shortcut(cursor)) {
-		/* Descend through a shortcut */
-		shortcut = assoc_array_ptr_to_shortcut(cursor);
-		cursor = READ_ONCE(shortcut->next_node); /* Address dependency. */
-	}
-
-	node = assoc_array_ptr_to_node(cursor);
-	slot = 0;
-
-	/* We perform two passes of each node.
-	 *
-	 * The first pass does all the leaves in this node.  This means we
-	 * don't miss any leaves if the node is split up by insertion whilst
-	 * we're iterating over the branches rooted here (we may, however, see
-	 * some leaves twice).
-	 */
-	has_meta = 0;
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-		has_meta |= (unsigned long)ptr;
-		if (ptr && assoc_array_ptr_is_leaf(ptr)) {
-			/* We need a barrier between the read of the pointer,
-			 * which is supplied by the above READ_ONCE().
-			 */
-			/* Invoke the callback */
-			ret = iterator(assoc_array_ptr_to_leaf(ptr),
-				       iterator_data);
-			if (ret)
-				return ret;
-		}
-	}
-
-	/* The second pass attends to all the metadata pointers.  If we follow
-	 * one of these we may find that we don't come back here, but rather go
-	 * back to a replacement node with the leaves in a different layout.
-	 *
-	 * We are guaranteed to make progress, however, as the slot number for
-	 * a particular portion of the key space cannot change - and we
-	 * continue at the back pointer + 1.
-	 */
-	if (!(has_meta & ASSOC_ARRAY_PTR_META_TYPE))
-		goto finished_node;
-	slot = 0;
-
-continue_node:
-	node = assoc_array_ptr_to_node(cursor);
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-		if (assoc_array_ptr_is_meta(ptr)) {
-			cursor = ptr;
-			goto begin_node;
-		}
-	}
-
-finished_node:
-	/* Move up to the parent (may need to skip back over a shortcut) */
-	parent = READ_ONCE(node->back_pointer); /* Address dependency. */
-	slot = node->parent_slot;
-	if (parent == stop)
-		return 0;
-
-	if (assoc_array_ptr_is_shortcut(parent)) {
-		shortcut = assoc_array_ptr_to_shortcut(parent);
-		cursor = parent;
-		parent = READ_ONCE(shortcut->back_pointer); /* Address dependency. */
-		slot = shortcut->parent_slot;
-		if (parent == stop)
-			return 0;
-	}
-
-	/* Ascend to next slot in parent node */
-	cursor = parent;
-	slot++;
-	goto continue_node;
-}
-
-/**
- * assoc_array_iterate - Pass all objects in the array to a callback
- * @array: The array to iterate over.
- * @iterator: The callback function.
- * @iterator_data: Private data for the callback function.
- *
- * Iterate over all the objects in an associative array.  Each one will be
- * presented to the iterator function.
- *
- * If the array is being modified concurrently with the iteration then it is
- * possible that some objects in the array will be passed to the iterator
- * callback more than once - though every object should be passed at least
- * once.  If this is undesirable then the caller must lock against modification
- * for the duration of this function.
- *
- * The function will return 0 if no objects were in the array or else it will
- * return the result of the last iterator function called.  Iteration stops
- * immediately if any call to the iteration function results in a non-zero
- * return.
- *
- * The caller should hold the RCU read lock or better if concurrent
- * modification is possible.
- */
-int assoc_array_iterate(const struct assoc_array *array,
-			int (*iterator)(const void *object,
-					void *iterator_data),
-			void *iterator_data)
-{
-	struct assoc_array_ptr *root = READ_ONCE(array->root); /* Address dependency. */
-
-	if (!root)
-		return 0;
-	return assoc_array_subtree_iterate(root, NULL, iterator, iterator_data);
-}
-
-enum assoc_array_walk_status {
-	assoc_array_walk_tree_empty,
-	assoc_array_walk_found_terminal_node,
-	assoc_array_walk_found_wrong_shortcut,
-};
-
-struct assoc_array_walk_result {
-	struct {
-		struct assoc_array_node	*node;	/* Node in which leaf might be found */
-		int		level;
-		int		slot;
-	} terminal_node;
-	struct {
-		struct assoc_array_shortcut *shortcut;
-		int		level;
-		int		sc_level;
-		unsigned long	sc_segments;
-		unsigned long	dissimilarity;
-	} wrong_shortcut;
-};
-
-/*
- * Navigate through the internal tree looking for the closest node to the key.
- */
-static enum assoc_array_walk_status
-assoc_array_walk(const struct assoc_array *array,
-		 const struct assoc_array_ops *ops,
-		 const void *index_key,
-		 struct assoc_array_walk_result *result)
-{
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *cursor, *ptr;
-	unsigned long sc_segments, dissimilarity;
-	unsigned long segments;
-	int level, sc_level, next_sc_level;
-	int slot;
-
-	pr_devel("-->%s()\n", __func__);
-
-	cursor = READ_ONCE(array->root);  /* Address dependency. */
-	if (!cursor)
-		return assoc_array_walk_tree_empty;
-
-	level = 0;
-
-	/* Use segments from the key for the new leaf to navigate through the
-	 * internal tree, skipping through nodes and shortcuts that are on
-	 * route to the destination.  Eventually we'll come to a slot that is
-	 * either empty or contains a leaf at which point we've found a node in
-	 * which the leaf we're looking for might be found or into which it
-	 * should be inserted.
-	 */
-jumped:
-	segments = ops->get_key_chunk(index_key, level);
-	pr_devel("segments[%d]: %lx\n", level, segments);
-
-	if (assoc_array_ptr_is_shortcut(cursor))
-		goto follow_shortcut;
-
-consider_node:
-	node = assoc_array_ptr_to_node(cursor);
-	slot = segments >> (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
-	slot &= ASSOC_ARRAY_FAN_MASK;
-	ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-
-	pr_devel("consider slot %x [ix=%d type=%lu]\n",
-		 slot, level, (unsigned long)ptr & 3);
-
-	if (!assoc_array_ptr_is_meta(ptr)) {
-		/* The node doesn't have a node/shortcut pointer in the slot
-		 * corresponding to the index key that we have to follow.
-		 */
-		result->terminal_node.node = node;
-		result->terminal_node.level = level;
-		result->terminal_node.slot = slot;
-		pr_devel("<--%s() = terminal_node\n", __func__);
-		return assoc_array_walk_found_terminal_node;
-	}
-
-	if (assoc_array_ptr_is_node(ptr)) {
-		/* There is a pointer to a node in the slot corresponding to
-		 * this index key segment, so we need to follow it.
-		 */
-		cursor = ptr;
-		level += ASSOC_ARRAY_LEVEL_STEP;
-		if ((level & ASSOC_ARRAY_KEY_CHUNK_MASK) != 0)
-			goto consider_node;
-		goto jumped;
-	}
-
-	/* There is a shortcut in the slot corresponding to the index key
-	 * segment.  We follow the shortcut if its partial index key matches
-	 * this leaf's.  Otherwise we need to split the shortcut.
-	 */
-	cursor = ptr;
-follow_shortcut:
-	shortcut = assoc_array_ptr_to_shortcut(cursor);
-	pr_devel("shortcut to %d\n", shortcut->skip_to_level);
-	sc_level = level + ASSOC_ARRAY_LEVEL_STEP;
-	BUG_ON(sc_level > shortcut->skip_to_level);
-
-	do {
-		/* Check the leaf against the shortcut's index key a word at a
-		 * time, trimming the final word (the shortcut stores the index
-		 * key completely from the root to the shortcut's target).
-		 */
-		if ((sc_level & ASSOC_ARRAY_KEY_CHUNK_MASK) == 0)
-			segments = ops->get_key_chunk(index_key, sc_level);
-
-		sc_segments = shortcut->index_key[sc_level >> ASSOC_ARRAY_KEY_CHUNK_SHIFT];
-		dissimilarity = segments ^ sc_segments;
-
-		if (shortcut->skip_to_level < round_down(sc_level,
-				ASSOC_ARRAY_KEY_CHUNK_SIZE) + ASSOC_ARRAY_KEY_CHUNK_SIZE) {
-			/* Trim segments that are beyond the shortcut */
-			int shift = shortcut->skip_to_level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-			dissimilarity &= ~(ULONG_MAX << shift);
-			next_sc_level = shortcut->skip_to_level;
-		} else {
-			next_sc_level = sc_level + ASSOC_ARRAY_KEY_CHUNK_SIZE;
-			next_sc_level = round_down(next_sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		}
-
-		if (dissimilarity != 0) {
-			/* This shortcut points elsewhere */
-			result->wrong_shortcut.shortcut = shortcut;
-			result->wrong_shortcut.level = level;
-			result->wrong_shortcut.sc_level = sc_level;
-			result->wrong_shortcut.sc_segments = sc_segments;
-			result->wrong_shortcut.dissimilarity = dissimilarity;
-			return assoc_array_walk_found_wrong_shortcut;
-		}
-
-		sc_level = next_sc_level;
-	} while (sc_level < shortcut->skip_to_level);
-
-	/* The shortcut matches the leaf's index to this point. */
-	cursor = READ_ONCE(shortcut->next_node); /* Address dependency. */
-	if (((level ^ sc_level) & ~ASSOC_ARRAY_KEY_CHUNK_MASK) != 0) {
-		level = sc_level;
-		goto jumped;
-	} else {
-		level = sc_level;
-		goto consider_node;
-	}
-}
-
-/**
- * assoc_array_find - Find an object by index key
- * @array: The associative array to search.
- * @ops: The operations to use.
- * @index_key: The key to the object.
- *
- * Find an object in an associative array by walking through the internal tree
- * to the node that should contain the object and then searching the leaves
- * there.  NULL is returned if the requested object was not found in the array.
- *
- * The caller must hold the RCU read lock or better.
- */
-void *assoc_array_find(const struct assoc_array *array,
-		       const struct assoc_array_ops *ops,
-		       const void *index_key)
-{
-	struct assoc_array_walk_result result;
-	const struct assoc_array_node *node;
-	const struct assoc_array_ptr *ptr;
-	const void *leaf;
-	int slot;
-
-	if (assoc_array_walk(array, ops, index_key, &result) !=
-	    assoc_array_walk_found_terminal_node)
-		return NULL;
-
-	node = result.terminal_node.node;
-
-	/* If the target key is available to us, it's has to be pointed to by
-	 * the terminal node.
-	 */
-	for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
-		if (ptr && assoc_array_ptr_is_leaf(ptr)) {
-			/* We need a barrier between the read of the pointer
-			 * and dereferencing the pointer - but only if we are
-			 * actually going to dereference it.
-			 */
-			leaf = assoc_array_ptr_to_leaf(ptr);
-			if (ops->compare_object(leaf, index_key))
-				return (void *)leaf;
-		}
-	}
-
-	return NULL;
-}
-
-/*
- * Destructively iterate over an associative array.  The caller must prevent
- * other simultaneous accesses.
- */
-static void assoc_array_destroy_subtree(struct assoc_array_ptr *root,
-					const struct assoc_array_ops *ops)
-{
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *cursor, *parent = NULL;
-	int slot = -1;
-
-	pr_devel("-->%s()\n", __func__);
-
-	cursor = root;
-	if (!cursor) {
-		pr_devel("empty\n");
-		return;
-	}
-
-move_to_meta:
-	if (assoc_array_ptr_is_shortcut(cursor)) {
-		/* Descend through a shortcut */
-		pr_devel("[%d] shortcut\n", slot);
-		BUG_ON(!assoc_array_ptr_is_shortcut(cursor));
-		shortcut = assoc_array_ptr_to_shortcut(cursor);
-		BUG_ON(shortcut->back_pointer != parent);
-		BUG_ON(slot != -1 && shortcut->parent_slot != slot);
-		parent = cursor;
-		cursor = shortcut->next_node;
-		slot = -1;
-		BUG_ON(!assoc_array_ptr_is_node(cursor));
-	}
-
-	pr_devel("[%d] node\n", slot);
-	node = assoc_array_ptr_to_node(cursor);
-	BUG_ON(node->back_pointer != parent);
-	BUG_ON(slot != -1 && node->parent_slot != slot);
-	slot = 0;
-
-continue_node:
-	pr_devel("Node %p [back=%p]\n", node, node->back_pointer);
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		struct assoc_array_ptr *ptr = node->slots[slot];
-		if (!ptr)
-			continue;
-		if (assoc_array_ptr_is_meta(ptr)) {
-			parent = cursor;
-			cursor = ptr;
-			goto move_to_meta;
-		}
-
-		if (ops) {
-			pr_devel("[%d] free leaf\n", slot);
-			ops->free_object(assoc_array_ptr_to_leaf(ptr));
-		}
-	}
-
-	parent = node->back_pointer;
-	slot = node->parent_slot;
-	pr_devel("free node\n");
-	kfree(node);
-	if (!parent)
-		return; /* Done */
-
-	/* Move back up to the parent (may need to free a shortcut on
-	 * the way up) */
-	if (assoc_array_ptr_is_shortcut(parent)) {
-		shortcut = assoc_array_ptr_to_shortcut(parent);
-		BUG_ON(shortcut->next_node != cursor);
-		cursor = parent;
-		parent = shortcut->back_pointer;
-		slot = shortcut->parent_slot;
-		pr_devel("free shortcut\n");
-		kfree(shortcut);
-		if (!parent)
-			return;
-
-		BUG_ON(!assoc_array_ptr_is_node(parent));
-	}
-
-	/* Ascend to next slot in parent node */
-	pr_devel("ascend to %p[%d]\n", parent, slot);
-	cursor = parent;
-	node = assoc_array_ptr_to_node(cursor);
-	slot++;
-	goto continue_node;
-}
-
-/**
- * assoc_array_destroy - Destroy an associative array
- * @array: The array to destroy.
- * @ops: The operations to use.
- *
- * Discard all metadata and free all objects in an associative array.  The
- * array will be empty and ready to use again upon completion.  This function
- * cannot fail.
- *
- * The caller must prevent all other accesses whilst this takes place as no
- * attempt is made to adjust pointers gracefully to permit RCU readlock-holding
- * accesses to continue.  On the other hand, no memory allocation is required.
- */
-void assoc_array_destroy(struct assoc_array *array,
-			 const struct assoc_array_ops *ops)
-{
-	assoc_array_destroy_subtree(array->root, ops);
-	array->root = NULL;
-}
-
-/*
- * Handle insertion into an empty tree.
- */
-static bool assoc_array_insert_in_empty_tree(struct assoc_array_edit *edit)
-{
-	struct assoc_array_node *new_n0;
-
-	pr_devel("-->%s()\n", __func__);
-
-	new_n0 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n0)
-		return false;
-
-	edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-	edit->leaf_p = &new_n0->slots[0];
-	edit->adjust_count_on = new_n0;
-	edit->set[0].ptr = &edit->array->root;
-	edit->set[0].to = assoc_array_node_to_ptr(new_n0);
-
-	pr_devel("<--%s() = ok [no root]\n", __func__);
-	return true;
-}
-
-/*
- * Handle insertion into a terminal node.
- */
-static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit,
-						  const struct assoc_array_ops *ops,
-						  const void *index_key,
-						  struct assoc_array_walk_result *result)
-{
-	struct assoc_array_shortcut *shortcut, *new_s0;
-	struct assoc_array_node *node, *new_n0, *new_n1, *side;
-	struct assoc_array_ptr *ptr;
-	unsigned long dissimilarity, base_seg, blank;
-	size_t keylen;
-	bool have_meta;
-	int level, diff;
-	int slot, next_slot, free_slot, i, j;
-
-	node	= result->terminal_node.node;
-	level	= result->terminal_node.level;
-	edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot;
-
-	pr_devel("-->%s()\n", __func__);
-
-	/* We arrived at a node which doesn't have an onward node or shortcut
-	 * pointer that we have to follow.  This means that (a) the leaf we
-	 * want must go here (either by insertion or replacement) or (b) we
-	 * need to split this node and insert in one of the fragments.
-	 */
-	free_slot = -1;
-
-	/* Firstly, we have to check the leaves in this node to see if there's
-	 * a matching one we should replace in place.
-	 */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		ptr = node->slots[i];
-		if (!ptr) {
-			free_slot = i;
-			continue;
-		}
-		if (assoc_array_ptr_is_leaf(ptr) &&
-		    ops->compare_object(assoc_array_ptr_to_leaf(ptr),
-					index_key)) {
-			pr_devel("replace in slot %d\n", i);
-			edit->leaf_p = &node->slots[i];
-			edit->dead_leaf = node->slots[i];
-			pr_devel("<--%s() = ok [replace]\n", __func__);
-			return true;
-		}
-	}
-
-	/* If there is a free slot in this node then we can just insert the
-	 * leaf here.
-	 */
-	if (free_slot >= 0) {
-		pr_devel("insert in free slot %d\n", free_slot);
-		edit->leaf_p = &node->slots[free_slot];
-		edit->adjust_count_on = node;
-		pr_devel("<--%s() = ok [insert]\n", __func__);
-		return true;
-	}
-
-	/* The node has no spare slots - so we're either going to have to split
-	 * it or insert another node before it.
-	 *
-	 * Whatever, we're going to need at least two new nodes - so allocate
-	 * those now.  We may also need a new shortcut, but we deal with that
-	 * when we need it.
-	 */
-	new_n0 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n0)
-		return false;
-	edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-	new_n1 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n1)
-		return false;
-	edit->new_meta[1] = assoc_array_node_to_ptr(new_n1);
-
-	/* We need to find out how similar the leaves are. */
-	pr_devel("no spare slots\n");
-	have_meta = false;
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		ptr = node->slots[i];
-		if (assoc_array_ptr_is_meta(ptr)) {
-			edit->segment_cache[i] = 0xff;
-			have_meta = true;
-			continue;
-		}
-		base_seg = ops->get_object_key_chunk(
-			assoc_array_ptr_to_leaf(ptr), level);
-		base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-		edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
-	}
-
-	if (have_meta) {
-		pr_devel("have meta\n");
-		goto split_node;
-	}
-
-	/* The node contains only leaves */
-	dissimilarity = 0;
-	base_seg = edit->segment_cache[0];
-	for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++)
-		dissimilarity |= edit->segment_cache[i] ^ base_seg;
-
-	pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity);
-
-	if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) {
-		/* The old leaves all cluster in the same slot.  We will need
-		 * to insert a shortcut if the new node wants to cluster with them.
-		 */
-		if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0)
-			goto all_leaves_cluster_together;
-
-		/* Otherwise all the old leaves cluster in the same slot, but
-		 * the new leaf wants to go into a different slot - so we
-		 * create a new node (n0) to hold the new leaf and a pointer to
-		 * a new node (n1) holding all the old leaves.
-		 *
-		 * This can be done by falling through to the node splitting
-		 * path.
-		 */
-		pr_devel("present leaves cluster but not new leaf\n");
-	}
-
-split_node:
-	pr_devel("split node\n");
-
-	/* We need to split the current node.  The node must contain anything
-	 * from a single leaf (in the one leaf case, this leaf will cluster
-	 * with the new leaf) and the rest meta-pointers, to all leaves, some
-	 * of which may cluster.
-	 *
-	 * It won't contain the case in which all the current leaves plus the
-	 * new leaves want to cluster in the same slot.
-	 *
-	 * We need to expel at least two leaves out of a set consisting of the
-	 * leaves in the node and the new leaf.  The current meta pointers can
-	 * just be copied as they shouldn't cluster with any of the leaves.
-	 *
-	 * We need a new node (n0) to replace the current one and a new node to
-	 * take the expelled nodes (n1).
-	 */
-	edit->set[0].to = assoc_array_node_to_ptr(new_n0);
-	new_n0->back_pointer = node->back_pointer;
-	new_n0->parent_slot = node->parent_slot;
-	new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
-	new_n1->parent_slot = -1; /* Need to calculate this */
-
-do_split_node:
-	pr_devel("do_split_node\n");
-
-	new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
-	new_n1->nr_leaves_on_branch = 0;
-
-	/* Begin by finding two matching leaves.  There have to be at least two
-	 * that match - even if there are meta pointers - because any leaf that
-	 * would match a slot with a meta pointer in it must be somewhere
-	 * behind that meta pointer and cannot be here.  Further, given N
-	 * remaining leaf slots, we now have N+1 leaves to go in them.
-	 */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		slot = edit->segment_cache[i];
-		if (slot != 0xff)
-			for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++)
-				if (edit->segment_cache[j] == slot)
-					goto found_slot_for_multiple_occupancy;
-	}
-found_slot_for_multiple_occupancy:
-	pr_devel("same slot: %x %x [%02x]\n", i, j, slot);
-	BUG_ON(i >= ASSOC_ARRAY_FAN_OUT);
-	BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1);
-	BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT);
-
-	new_n1->parent_slot = slot;
-
-	/* Metadata pointers cannot change slot */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
-		if (assoc_array_ptr_is_meta(node->slots[i]))
-			new_n0->slots[i] = node->slots[i];
-		else
-			new_n0->slots[i] = NULL;
-	BUG_ON(new_n0->slots[slot] != NULL);
-	new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1);
-
-	/* Filter the leaf pointers between the new nodes */
-	free_slot = -1;
-	next_slot = 0;
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		if (assoc_array_ptr_is_meta(node->slots[i]))
-			continue;
-		if (edit->segment_cache[i] == slot) {
-			new_n1->slots[next_slot++] = node->slots[i];
-			new_n1->nr_leaves_on_branch++;
-		} else {
-			do {
-				free_slot++;
-			} while (new_n0->slots[free_slot] != NULL);
-			new_n0->slots[free_slot] = node->slots[i];
-		}
-	}
-
-	pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot);
-
-	if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) {
-		do {
-			free_slot++;
-		} while (new_n0->slots[free_slot] != NULL);
-		edit->leaf_p = &new_n0->slots[free_slot];
-		edit->adjust_count_on = new_n0;
-	} else {
-		edit->leaf_p = &new_n1->slots[next_slot++];
-		edit->adjust_count_on = new_n1;
-	}
-
-	BUG_ON(next_slot <= 1);
-
-	edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0);
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		if (edit->segment_cache[i] == 0xff) {
-			ptr = node->slots[i];
-			BUG_ON(assoc_array_ptr_is_leaf(ptr));
-			if (assoc_array_ptr_is_node(ptr)) {
-				side = assoc_array_ptr_to_node(ptr);
-				edit->set_backpointers[i] = &side->back_pointer;
-			} else {
-				shortcut = assoc_array_ptr_to_shortcut(ptr);
-				edit->set_backpointers[i] = &shortcut->back_pointer;
-			}
-		}
-	}
-
-	ptr = node->back_pointer;
-	if (!ptr)
-		edit->set[0].ptr = &edit->array->root;
-	else if (assoc_array_ptr_is_node(ptr))
-		edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot];
-	else
-		edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node;
-	edit->excised_meta[0] = assoc_array_node_to_ptr(node);
-	pr_devel("<--%s() = ok [split node]\n", __func__);
-	return true;
-
-all_leaves_cluster_together:
-	/* All the leaves, new and old, want to cluster together in this node
-	 * in the same slot, so we have to replace this node with a shortcut to
-	 * skip over the identical parts of the key and then place a pair of
-	 * nodes, one inside the other, at the end of the shortcut and
-	 * distribute the keys between them.
-	 *
-	 * Firstly we need to work out where the leaves start diverging as a
-	 * bit position into their keys so that we know how big the shortcut
-	 * needs to be.
-	 *
-	 * We only need to make a single pass of N of the N+1 leaves because if
-	 * any keys differ between themselves at bit X then at least one of
-	 * them must also differ with the base key at bit X or before.
-	 */
-	pr_devel("all leaves cluster together\n");
-	diff = INT_MAX;
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]),
-					  index_key);
-		if (x < diff) {
-			BUG_ON(x < 0);
-			diff = x;
-		}
-	}
-	BUG_ON(diff == INT_MAX);
-	BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP);
-
-	keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-	keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-
-	new_s0 = kzalloc_flex(*new_s0, index_key, keylen);
-	if (!new_s0)
-		return false;
-	edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0);
-
-	edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
-	new_s0->back_pointer = node->back_pointer;
-	new_s0->parent_slot = node->parent_slot;
-	new_s0->next_node = assoc_array_node_to_ptr(new_n0);
-	new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
-	new_n0->parent_slot = 0;
-	new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
-	new_n1->parent_slot = -1; /* Need to calculate this */
-
-	new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK;
-	pr_devel("skip_to_level = %d [diff %d]\n", level, diff);
-	BUG_ON(level <= 0);
-
-	for (i = 0; i < keylen; i++)
-		new_s0->index_key[i] =
-			ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE);
-
-	if (level & ASSOC_ARRAY_KEY_CHUNK_MASK) {
-		blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
-		pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank);
-		new_s0->index_key[keylen - 1] &= ~blank;
-	}
-
-	/* This now reduces to a node splitting exercise for which we'll need
-	 * to regenerate the disparity table.
-	 */
-	for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-		ptr = node->slots[i];
-		base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr),
-						     level);
-		base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-		edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
-	}
-
-	base_seg = ops->get_key_chunk(index_key, level);
-	base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
-	edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK;
-	goto do_split_node;
-}
-
-/*
- * Handle insertion into the middle of a shortcut.
- */
-static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit,
-					    const struct assoc_array_ops *ops,
-					    struct assoc_array_walk_result *result)
-{
-	struct assoc_array_shortcut *shortcut, *new_s0, *new_s1;
-	struct assoc_array_node *node, *new_n0, *side;
-	unsigned long sc_segments, dissimilarity, blank;
-	size_t keylen;
-	int level, sc_level, diff;
-	int sc_slot;
-
-	shortcut	= result->wrong_shortcut.shortcut;
-	level		= result->wrong_shortcut.level;
-	sc_level	= result->wrong_shortcut.sc_level;
-	sc_segments	= result->wrong_shortcut.sc_segments;
-	dissimilarity	= result->wrong_shortcut.dissimilarity;
-
-	pr_devel("-->%s(ix=%d dis=%lx scix=%d)\n",
-		 __func__, level, dissimilarity, sc_level);
-
-	/* We need to split a shortcut and insert a node between the two
-	 * pieces.  Zero-length pieces will be dispensed with entirely.
-	 *
-	 * First of all, we need to find out in which level the first
-	 * difference was.
-	 */
-	diff = __ffs(dissimilarity);
-	diff &= ~ASSOC_ARRAY_LEVEL_STEP_MASK;
-	diff += sc_level & ~ASSOC_ARRAY_KEY_CHUNK_MASK;
-	pr_devel("diff=%d\n", diff);
-
-	if (!shortcut->back_pointer) {
-		edit->set[0].ptr = &edit->array->root;
-	} else if (assoc_array_ptr_is_node(shortcut->back_pointer)) {
-		node = assoc_array_ptr_to_node(shortcut->back_pointer);
-		edit->set[0].ptr = &node->slots[shortcut->parent_slot];
-	} else {
-		BUG();
-	}
-
-	edit->excised_meta[0] = assoc_array_shortcut_to_ptr(shortcut);
-
-	/* Create a new node now since we're going to need it anyway */
-	new_n0 = kzalloc_obj(struct assoc_array_node);
-	if (!new_n0)
-		return false;
-	edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-	edit->adjust_count_on = new_n0;
-
-	/* Insert a new shortcut before the new node if this segment isn't of
-	 * zero length - otherwise we just connect the new node directly to the
-	 * parent.
-	 */
-	level += ASSOC_ARRAY_LEVEL_STEP;
-	if (diff > level) {
-		pr_devel("pre-shortcut %d...%d\n", level, diff);
-		keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-
-		new_s0 = kzalloc_flex(*new_s0, index_key, keylen);
-		if (!new_s0)
-			return false;
-		edit->new_meta[1] = assoc_array_shortcut_to_ptr(new_s0);
-		edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
-		new_s0->back_pointer = shortcut->back_pointer;
-		new_s0->parent_slot = shortcut->parent_slot;
-		new_s0->next_node = assoc_array_node_to_ptr(new_n0);
-		new_s0->skip_to_level = diff;
-
-		new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
-		new_n0->parent_slot = 0;
-
-		memcpy(new_s0->index_key, shortcut->index_key,
-		       flex_array_size(new_s0, index_key, keylen));
-
-		blank = ULONG_MAX << (diff & ASSOC_ARRAY_KEY_CHUNK_MASK);
-		pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, diff, blank);
-		new_s0->index_key[keylen - 1] &= ~blank;
-	} else {
-		pr_devel("no pre-shortcut\n");
-		edit->set[0].to = assoc_array_node_to_ptr(new_n0);
-		new_n0->back_pointer = shortcut->back_pointer;
-		new_n0->parent_slot = shortcut->parent_slot;
-	}
-
-	side = assoc_array_ptr_to_node(shortcut->next_node);
-	new_n0->nr_leaves_on_branch = side->nr_leaves_on_branch;
-
-	/* We need to know which slot in the new node is going to take a
-	 * metadata pointer.
-	 */
-	sc_slot = sc_segments >> (diff & ASSOC_ARRAY_KEY_CHUNK_MASK);
-	sc_slot &= ASSOC_ARRAY_FAN_MASK;
-
-	pr_devel("new slot %lx >> %d -> %d\n",
-		 sc_segments, diff & ASSOC_ARRAY_KEY_CHUNK_MASK, sc_slot);
-
-	/* Determine whether we need to follow the new node with a replacement
-	 * for the current shortcut.  We could in theory reuse the current
-	 * shortcut if its parent slot number doesn't change - but that's a
-	 * 1-in-16 chance so not worth expending the code upon.
-	 */
-	level = diff + ASSOC_ARRAY_LEVEL_STEP;
-	if (level < shortcut->skip_to_level) {
-		pr_devel("post-shortcut %d...%d\n", level, shortcut->skip_to_level);
-		keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-
-		new_s1 = kzalloc_flex(*new_s1, index_key, keylen);
-		if (!new_s1)
-			return false;
-		edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s1);
-
-		new_s1->back_pointer = assoc_array_node_to_ptr(new_n0);
-		new_s1->parent_slot = sc_slot;
-		new_s1->next_node = shortcut->next_node;
-		new_s1->skip_to_level = shortcut->skip_to_level;
-
-		new_n0->slots[sc_slot] = assoc_array_shortcut_to_ptr(new_s1);
-
-		memcpy(new_s1->index_key, shortcut->index_key,
-		       flex_array_size(new_s1, index_key, keylen));
-
-		edit->set[1].ptr = &side->back_pointer;
-		edit->set[1].to = assoc_array_shortcut_to_ptr(new_s1);
-	} else {
-		pr_devel("no post-shortcut\n");
-
-		/* We don't have to replace the pointed-to node as long as we
-		 * use memory barriers to make sure the parent slot number is
-		 * changed before the back pointer (the parent slot number is
-		 * irrelevant to the old parent shortcut).
-		 */
-		new_n0->slots[sc_slot] = shortcut->next_node;
-		edit->set_parent_slot[0].p = &side->parent_slot;
-		edit->set_parent_slot[0].to = sc_slot;
-		edit->set[1].ptr = &side->back_pointer;
-		edit->set[1].to = assoc_array_node_to_ptr(new_n0);
-	}
-
-	/* Install the new leaf in a spare slot in the new node. */
-	if (sc_slot == 0)
-		edit->leaf_p = &new_n0->slots[1];
-	else
-		edit->leaf_p = &new_n0->slots[0];
-
-	pr_devel("<--%s() = ok [split shortcut]\n", __func__);
-	return true;
-}
-
-/**
- * assoc_array_insert - Script insertion of an object into an associative array
- * @array: The array to insert into.
- * @ops: The operations to use.
- * @index_key: The key to insert at.
- * @object: The object to insert.
- *
- * Precalculate and preallocate a script for the insertion or replacement of an
- * object in an associative array.  This results in an edit script that can
- * either be applied or cancelled.
- *
- * The function returns a pointer to an edit script or -ENOMEM.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-struct assoc_array_edit *assoc_array_insert(struct assoc_array *array,
-					    const struct assoc_array_ops *ops,
-					    const void *index_key,
-					    void *object)
-{
-	struct assoc_array_walk_result result;
-	struct assoc_array_edit *edit;
-
-	pr_devel("-->%s()\n", __func__);
-
-	/* The leaf pointer we're given must not have the bottom bit set as we
-	 * use those for type-marking the pointer.  NULL pointers are also not
-	 * allowed as they indicate an empty slot but we have to allow them
-	 * here as they can be updated later.
-	 */
-	BUG_ON(assoc_array_ptr_is_meta(object));
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return ERR_PTR(-ENOMEM);
-	edit->array = array;
-	edit->ops = ops;
-	edit->leaf = assoc_array_leaf_to_ptr(object);
-	edit->adjust_count_by = 1;
-
-	switch (assoc_array_walk(array, ops, index_key, &result)) {
-	case assoc_array_walk_tree_empty:
-		/* Allocate a root node if there isn't one yet */
-		if (!assoc_array_insert_in_empty_tree(edit))
-			goto enomem;
-		return edit;
-
-	case assoc_array_walk_found_terminal_node:
-		/* We found a node that doesn't have a node/shortcut pointer in
-		 * the slot corresponding to the index key that we have to
-		 * follow.
-		 */
-		if (!assoc_array_insert_into_terminal_node(edit, ops, index_key,
-							   &result))
-			goto enomem;
-		return edit;
-
-	case assoc_array_walk_found_wrong_shortcut:
-		/* We found a shortcut that didn't match our key in a slot we
-		 * needed to follow.
-		 */
-		if (!assoc_array_insert_mid_shortcut(edit, ops, &result))
-			goto enomem;
-		return edit;
-	}
-
-enomem:
-	/* Clean up after an out of memory error */
-	pr_devel("enomem\n");
-	assoc_array_cancel_edit(edit);
-	return ERR_PTR(-ENOMEM);
-}
-
-/**
- * assoc_array_insert_set_object - Set the new object pointer in an edit script
- * @edit: The edit script to modify.
- * @object: The object pointer to set.
- *
- * Change the object to be inserted in an edit script.  The object pointed to
- * by the old object is not freed.  This must be done prior to applying the
- * script.
- */
-void assoc_array_insert_set_object(struct assoc_array_edit *edit, void *object)
-{
-	BUG_ON(!object);
-	edit->leaf = assoc_array_leaf_to_ptr(object);
-}
-
-struct assoc_array_delete_collapse_context {
-	struct assoc_array_node	*node;
-	const void		*skip_leaf;
-	int			slot;
-};
-
-/*
- * Subtree collapse to node iterator.
- */
-static int assoc_array_delete_collapse_iterator(const void *leaf,
-						void *iterator_data)
-{
-	struct assoc_array_delete_collapse_context *collapse = iterator_data;
-
-	if (leaf == collapse->skip_leaf)
-		return 0;
-
-	BUG_ON(collapse->slot >= ASSOC_ARRAY_FAN_OUT);
-
-	collapse->node->slots[collapse->slot++] = assoc_array_leaf_to_ptr(leaf);
-	return 0;
-}
-
-/**
- * assoc_array_delete - Script deletion of an object from an associative array
- * @array: The array to search.
- * @ops: The operations to use.
- * @index_key: The key to the object.
- *
- * Precalculate and preallocate a script for the deletion of an object from an
- * associative array.  This results in an edit script that can either be
- * applied or cancelled.
- *
- * The function returns a pointer to an edit script if the object was found,
- * NULL if the object was not found or -ENOMEM.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-struct assoc_array_edit *assoc_array_delete(struct assoc_array *array,
-					    const struct assoc_array_ops *ops,
-					    const void *index_key)
-{
-	struct assoc_array_delete_collapse_context collapse;
-	struct assoc_array_walk_result result;
-	struct assoc_array_node *node, *new_n0;
-	struct assoc_array_edit *edit;
-	struct assoc_array_ptr *ptr;
-	bool has_meta;
-	int slot, i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return ERR_PTR(-ENOMEM);
-	edit->array = array;
-	edit->ops = ops;
-	edit->adjust_count_by = -1;
-
-	switch (assoc_array_walk(array, ops, index_key, &result)) {
-	case assoc_array_walk_found_terminal_node:
-		/* We found a node that should contain the leaf we've been
-		 * asked to remove - *if* it's in the tree.
-		 */
-		pr_devel("terminal_node\n");
-		node = result.terminal_node.node;
-
-		for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-			ptr = node->slots[slot];
-			if (ptr &&
-			    assoc_array_ptr_is_leaf(ptr) &&
-			    ops->compare_object(assoc_array_ptr_to_leaf(ptr),
-						index_key))
-				goto found_leaf;
-		}
-		fallthrough;
-	case assoc_array_walk_tree_empty:
-	case assoc_array_walk_found_wrong_shortcut:
-	default:
-		assoc_array_cancel_edit(edit);
-		pr_devel("not found\n");
-		return NULL;
-	}
-
-found_leaf:
-	BUG_ON(array->nr_leaves_on_tree <= 0);
-
-	/* In the simplest form of deletion we just clear the slot and release
-	 * the leaf after a suitable interval.
-	 */
-	edit->dead_leaf = node->slots[slot];
-	edit->set[0].ptr = &node->slots[slot];
-	edit->set[0].to = NULL;
-	edit->adjust_count_on = node;
-
-	/* If that concludes erasure of the last leaf, then delete the entire
-	 * internal array.
-	 */
-	if (array->nr_leaves_on_tree == 1) {
-		edit->set[1].ptr = &array->root;
-		edit->set[1].to = NULL;
-		edit->adjust_count_on = NULL;
-		edit->excised_subtree = array->root;
-		pr_devel("all gone\n");
-		return edit;
-	}
-
-	/* However, we'd also like to clear up some metadata blocks if we
-	 * possibly can.
-	 *
-	 * We go for a simple algorithm of: if this node has FAN_OUT or fewer
-	 * leaves in it, then attempt to collapse it - and attempt to
-	 * recursively collapse up the tree.
-	 *
-	 * We could also try and collapse in partially filled subtrees to take
-	 * up space in this node.
-	 */
-	if (node->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) {
-		struct assoc_array_node *parent, *grandparent;
-		struct assoc_array_ptr *ptr;
-
-		/* First of all, we need to know if this node has metadata so
-		 * that we don't try collapsing if all the leaves are already
-		 * here.
-		 */
-		has_meta = false;
-		for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-			ptr = node->slots[i];
-			if (assoc_array_ptr_is_meta(ptr)) {
-				has_meta = true;
-				break;
-			}
-		}
-
-		pr_devel("leaves: %ld [m=%d]\n",
-			 node->nr_leaves_on_branch - 1, has_meta);
-
-		/* Look further up the tree to see if we can collapse this node
-		 * into a more proximal node too.
-		 */
-		parent = node;
-	collapse_up:
-		pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch);
-
-		ptr = parent->back_pointer;
-		if (!ptr)
-			goto do_collapse;
-		if (assoc_array_ptr_is_shortcut(ptr)) {
-			struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(ptr);
-			ptr = s->back_pointer;
-			if (!ptr)
-				goto do_collapse;
-		}
-
-		grandparent = assoc_array_ptr_to_node(ptr);
-		if (grandparent->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) {
-			parent = grandparent;
-			goto collapse_up;
-		}
-
-	do_collapse:
-		/* There's no point collapsing if the original node has no meta
-		 * pointers to discard and if we didn't merge into one of that
-		 * node's ancestry.
-		 */
-		if (has_meta || parent != node) {
-			node = parent;
-
-			/* Create a new node to collapse into */
-			new_n0 = kzalloc_obj(struct assoc_array_node);
-			if (!new_n0)
-				goto enomem;
-			edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
-
-			new_n0->back_pointer = node->back_pointer;
-			new_n0->parent_slot = node->parent_slot;
-			new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
-			edit->adjust_count_on = new_n0;
-
-			collapse.node = new_n0;
-			collapse.skip_leaf = assoc_array_ptr_to_leaf(edit->dead_leaf);
-			collapse.slot = 0;
-			assoc_array_subtree_iterate(assoc_array_node_to_ptr(node),
-						    node->back_pointer,
-						    assoc_array_delete_collapse_iterator,
-						    &collapse);
-			pr_devel("collapsed %d,%lu\n", collapse.slot, new_n0->nr_leaves_on_branch);
-			BUG_ON(collapse.slot != new_n0->nr_leaves_on_branch - 1);
-
-			if (!node->back_pointer) {
-				edit->set[1].ptr = &array->root;
-			} else if (assoc_array_ptr_is_leaf(node->back_pointer)) {
-				BUG();
-			} else if (assoc_array_ptr_is_node(node->back_pointer)) {
-				struct assoc_array_node *p =
-					assoc_array_ptr_to_node(node->back_pointer);
-				edit->set[1].ptr = &p->slots[node->parent_slot];
-			} else if (assoc_array_ptr_is_shortcut(node->back_pointer)) {
-				struct assoc_array_shortcut *s =
-					assoc_array_ptr_to_shortcut(node->back_pointer);
-				edit->set[1].ptr = &s->next_node;
-			}
-			edit->set[1].to = assoc_array_node_to_ptr(new_n0);
-			edit->excised_subtree = assoc_array_node_to_ptr(node);
-		}
-	}
-
-	return edit;
-
-enomem:
-	/* Clean up after an out of memory error */
-	pr_devel("enomem\n");
-	assoc_array_cancel_edit(edit);
-	return ERR_PTR(-ENOMEM);
-}
-
-/**
- * assoc_array_clear - Script deletion of all objects from an associative array
- * @array: The array to clear.
- * @ops: The operations to use.
- *
- * Precalculate and preallocate a script for the deletion of all the objects
- * from an associative array.  This results in an edit script that can either
- * be applied or cancelled.
- *
- * The function returns a pointer to an edit script if there are objects to be
- * deleted, NULL if there are no objects in the array or -ENOMEM.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-struct assoc_array_edit *assoc_array_clear(struct assoc_array *array,
-					   const struct assoc_array_ops *ops)
-{
-	struct assoc_array_edit *edit;
-
-	pr_devel("-->%s()\n", __func__);
-
-	if (!array->root)
-		return NULL;
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return ERR_PTR(-ENOMEM);
-	edit->array = array;
-	edit->ops = ops;
-	edit->set[1].ptr = &array->root;
-	edit->set[1].to = NULL;
-	edit->excised_subtree = array->root;
-	edit->ops_for_excised_subtree = ops;
-	pr_devel("all gone\n");
-	return edit;
-}
-
-/*
- * Handle the deferred destruction after an applied edit.
- */
-static void assoc_array_rcu_cleanup(struct rcu_head *head)
-{
-	struct assoc_array_edit *edit =
-		container_of(head, struct assoc_array_edit, rcu);
-	int i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	if (edit->dead_leaf)
-		edit->ops->free_object(assoc_array_ptr_to_leaf(edit->dead_leaf));
-	for (i = 0; i < ARRAY_SIZE(edit->excised_meta); i++)
-		if (edit->excised_meta[i])
-			kfree(assoc_array_ptr_to_node(edit->excised_meta[i]));
-
-	if (edit->excised_subtree) {
-		BUG_ON(assoc_array_ptr_is_leaf(edit->excised_subtree));
-		if (assoc_array_ptr_is_node(edit->excised_subtree)) {
-			struct assoc_array_node *n =
-				assoc_array_ptr_to_node(edit->excised_subtree);
-			n->back_pointer = NULL;
-		} else {
-			struct assoc_array_shortcut *s =
-				assoc_array_ptr_to_shortcut(edit->excised_subtree);
-			s->back_pointer = NULL;
-		}
-		assoc_array_destroy_subtree(edit->excised_subtree,
-					    edit->ops_for_excised_subtree);
-	}
-
-	kfree(edit);
-}
-
-/**
- * assoc_array_apply_edit - Apply an edit script to an associative array
- * @edit: The script to apply.
- *
- * Apply an edit script to an associative array to effect an insertion,
- * deletion or clearance.  As the edit script includes preallocated memory,
- * this is guaranteed not to fail.
- *
- * The edit script, dead objects and dead metadata will be scheduled for
- * destruction after an RCU grace period to permit those doing read-only
- * accesses on the array to continue to do so under the RCU read lock whilst
- * the edit is taking place.
- */
-void assoc_array_apply_edit(struct assoc_array_edit *edit)
-{
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *ptr;
-	int i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	smp_wmb();
-	if (edit->leaf_p)
-		*edit->leaf_p = edit->leaf;
-
-	smp_wmb();
-	for (i = 0; i < ARRAY_SIZE(edit->set_parent_slot); i++)
-		if (edit->set_parent_slot[i].p)
-			*edit->set_parent_slot[i].p = edit->set_parent_slot[i].to;
-
-	smp_wmb();
-	for (i = 0; i < ARRAY_SIZE(edit->set_backpointers); i++)
-		if (edit->set_backpointers[i])
-			*edit->set_backpointers[i] = edit->set_backpointers_to;
-
-	smp_wmb();
-	for (i = 0; i < ARRAY_SIZE(edit->set); i++)
-		if (edit->set[i].ptr)
-			*edit->set[i].ptr = edit->set[i].to;
-
-	if (edit->array->root == NULL) {
-		edit->array->nr_leaves_on_tree = 0;
-	} else if (edit->adjust_count_on) {
-		node = edit->adjust_count_on;
-		for (;;) {
-			node->nr_leaves_on_branch += edit->adjust_count_by;
-
-			ptr = node->back_pointer;
-			if (!ptr)
-				break;
-			if (assoc_array_ptr_is_shortcut(ptr)) {
-				shortcut = assoc_array_ptr_to_shortcut(ptr);
-				ptr = shortcut->back_pointer;
-				if (!ptr)
-					break;
-			}
-			BUG_ON(!assoc_array_ptr_is_node(ptr));
-			node = assoc_array_ptr_to_node(ptr);
-		}
-
-		edit->array->nr_leaves_on_tree += edit->adjust_count_by;
-	}
-
-	call_rcu(&edit->rcu, assoc_array_rcu_cleanup);
-}
-
-/**
- * assoc_array_cancel_edit - Discard an edit script.
- * @edit: The script to discard.
- *
- * Free an edit script and all the preallocated data it holds without making
- * any changes to the associative array it was intended for.
- *
- * NOTE!  In the case of an insertion script, this does _not_ release the leaf
- * that was to be inserted.  That is left to the caller.
- */
-void assoc_array_cancel_edit(struct assoc_array_edit *edit)
-{
-	struct assoc_array_ptr *ptr;
-	int i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	/* Clean up after an out of memory error */
-	for (i = 0; i < ARRAY_SIZE(edit->new_meta); i++) {
-		ptr = edit->new_meta[i];
-		if (ptr) {
-			if (assoc_array_ptr_is_node(ptr))
-				kfree(assoc_array_ptr_to_node(ptr));
-			else
-				kfree(assoc_array_ptr_to_shortcut(ptr));
-		}
-	}
-	kfree(edit);
-}
-
-/**
- * assoc_array_gc - Garbage collect an associative array.
- * @array: The array to clean.
- * @ops: The operations to use.
- * @iterator: A callback function to pass judgement on each object.
- * @iterator_data: Private data for the callback function.
- *
- * Collect garbage from an associative array and pack down the internal tree to
- * save memory.
- *
- * The iterator function is asked to pass judgement upon each object in the
- * array.  If it returns false, the object is discard and if it returns true,
- * the object is kept.  If it returns true, it must increment the object's
- * usage count (or whatever it needs to do to retain it) before returning.
- *
- * This function returns 0 if successful or -ENOMEM if out of memory.  In the
- * latter case, the array is not changed.
- *
- * The caller should lock against other modifications and must continue to hold
- * the lock until assoc_array_apply_edit() has been called.
- *
- * Accesses to the tree may take place concurrently with this function,
- * provided they hold the RCU read lock.
- */
-int assoc_array_gc(struct assoc_array *array,
-		   const struct assoc_array_ops *ops,
-		   bool (*iterator)(void *object, void *iterator_data),
-		   void *iterator_data)
-{
-	struct assoc_array_shortcut *shortcut, *new_s;
-	struct assoc_array_node *node, *new_n;
-	struct assoc_array_edit *edit;
-	struct assoc_array_ptr *cursor, *ptr;
-	struct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp;
-	unsigned long nr_leaves_on_tree;
-	bool retained;
-	int keylen, slot, nr_free, next_slot, i;
-
-	pr_devel("-->%s()\n", __func__);
-
-	if (!array->root)
-		return 0;
-
-	edit = kzalloc_obj(struct assoc_array_edit);
-	if (!edit)
-		return -ENOMEM;
-	edit->array = array;
-	edit->ops = ops;
-	edit->ops_for_excised_subtree = ops;
-	edit->set[0].ptr = &array->root;
-	edit->excised_subtree = array->root;
-
-	new_root = new_parent = NULL;
-	new_ptr_pp = &new_root;
-	cursor = array->root;
-
-descend:
-	/* If this point is a shortcut, then we need to duplicate it and
-	 * advance the target cursor.
-	 */
-	if (assoc_array_ptr_is_shortcut(cursor)) {
-		shortcut = assoc_array_ptr_to_shortcut(cursor);
-		keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
-		keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
-		new_s = kmalloc_flex(*new_s, index_key, keylen);
-		if (!new_s)
-			goto enomem;
-		pr_devel("dup shortcut %p -> %p\n", shortcut, new_s);
-		memcpy(new_s, shortcut, struct_size(new_s, index_key, keylen));
-		new_s->back_pointer = new_parent;
-		new_s->parent_slot = shortcut->parent_slot;
-		*new_ptr_pp = new_parent = assoc_array_shortcut_to_ptr(new_s);
-		new_ptr_pp = &new_s->next_node;
-		cursor = shortcut->next_node;
-	}
-
-	/* Duplicate the node at this position */
-	node = assoc_array_ptr_to_node(cursor);
-	new_n = kzalloc_obj(struct assoc_array_node);
-	if (!new_n)
-		goto enomem;
-	pr_devel("dup node %p -> %p\n", node, new_n);
-	new_n->back_pointer = new_parent;
-	new_n->parent_slot = node->parent_slot;
-	*new_ptr_pp = new_parent = assoc_array_node_to_ptr(new_n);
-	new_ptr_pp = NULL;
-	slot = 0;
-
-continue_node:
-	/* Filter across any leaves and gc any subtrees */
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = node->slots[slot];
-		if (!ptr)
-			continue;
-
-		if (assoc_array_ptr_is_leaf(ptr)) {
-			if (iterator(assoc_array_ptr_to_leaf(ptr),
-				     iterator_data))
-				/* The iterator will have done any reference
-				 * counting on the object for us.
-				 */
-				new_n->slots[slot] = ptr;
-			continue;
-		}
-
-		new_ptr_pp = &new_n->slots[slot];
-		cursor = ptr;
-		goto descend;
-	}
-
-retry_compress:
-	pr_devel("-- compress node %p --\n", new_n);
-
-	/* Count up the number of empty slots in this node and work out the
-	 * subtree leaf count.
-	 */
-	new_n->nr_leaves_on_branch = 0;
-	nr_free = 0;
-	for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = new_n->slots[slot];
-		if (!ptr)
-			nr_free++;
-		else if (assoc_array_ptr_is_leaf(ptr))
-			new_n->nr_leaves_on_branch++;
-	}
-	pr_devel("free=%d, leaves=%lu\n", nr_free, new_n->nr_leaves_on_branch);
-
-	/* See what we can fold in */
-	retained = false;
-	next_slot = 0;
-	for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		struct assoc_array_shortcut *s;
-		struct assoc_array_node *child;
-
-		ptr = new_n->slots[slot];
-		if (!ptr || assoc_array_ptr_is_leaf(ptr))
-			continue;
-
-		s = NULL;
-		if (assoc_array_ptr_is_shortcut(ptr)) {
-			s = assoc_array_ptr_to_shortcut(ptr);
-			ptr = s->next_node;
-		}
-
-		child = assoc_array_ptr_to_node(ptr);
-		new_n->nr_leaves_on_branch += child->nr_leaves_on_branch;
-
-		if (child->nr_leaves_on_branch <= nr_free + 1) {
-			/* Fold the child node into this one */
-			pr_devel("[%d] fold node %lu/%d [nx %d]\n",
-				 slot, child->nr_leaves_on_branch, nr_free + 1,
-				 next_slot);
-
-			/* We would already have reaped an intervening shortcut
-			 * on the way back up the tree.
-			 */
-			BUG_ON(s);
-
-			new_n->slots[slot] = NULL;
-			nr_free++;
-			if (slot < next_slot)
-				next_slot = slot;
-			for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
-				struct assoc_array_ptr *p = child->slots[i];
-				if (!p)
-					continue;
-				BUG_ON(assoc_array_ptr_is_meta(p));
-				while (new_n->slots[next_slot])
-					next_slot++;
-				BUG_ON(next_slot >= ASSOC_ARRAY_FAN_OUT);
-				new_n->slots[next_slot++] = p;
-				nr_free--;
-			}
-			kfree(child);
-		} else {
-			pr_devel("[%d] retain node %lu/%d [nx %d]\n",
-				 slot, child->nr_leaves_on_branch, nr_free + 1,
-				 next_slot);
-			retained = true;
-		}
-	}
-
-	if (retained && new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) {
-		pr_devel("internal nodes remain despite enough space, retrying\n");
-		goto retry_compress;
-	}
-	pr_devel("after: %lu\n", new_n->nr_leaves_on_branch);
-
-	nr_leaves_on_tree = new_n->nr_leaves_on_branch;
-
-	/* Excise this node if it is singly occupied by a shortcut */
-	if (nr_free == ASSOC_ARRAY_FAN_OUT - 1) {
-		for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++)
-			if ((ptr = new_n->slots[slot]))
-				break;
-
-		if (assoc_array_ptr_is_meta(ptr) &&
-		    assoc_array_ptr_is_shortcut(ptr)) {
-			pr_devel("excise node %p with 1 shortcut\n", new_n);
-			new_s = assoc_array_ptr_to_shortcut(ptr);
-			new_parent = new_n->back_pointer;
-			slot = new_n->parent_slot;
-			kfree(new_n);
-			if (!new_parent) {
-				new_s->back_pointer = NULL;
-				new_s->parent_slot = 0;
-				new_root = ptr;
-				goto gc_complete;
-			}
-
-			if (assoc_array_ptr_is_shortcut(new_parent)) {
-				/* We can discard any preceding shortcut also */
-				struct assoc_array_shortcut *s =
-					assoc_array_ptr_to_shortcut(new_parent);
-
-				pr_devel("excise preceding shortcut\n");
-
-				new_parent = new_s->back_pointer = s->back_pointer;
-				slot = new_s->parent_slot = s->parent_slot;
-				kfree(s);
-				if (!new_parent) {
-					new_s->back_pointer = NULL;
-					new_s->parent_slot = 0;
-					new_root = ptr;
-					goto gc_complete;
-				}
-			}
-
-			new_s->back_pointer = new_parent;
-			new_s->parent_slot = slot;
-			new_n = assoc_array_ptr_to_node(new_parent);
-			new_n->slots[slot] = ptr;
-			goto ascend_old_tree;
-		}
-	}
-
-	/* Excise any shortcuts we might encounter that point to nodes that
-	 * only contain leaves.
-	 */
-	ptr = new_n->back_pointer;
-	if (!ptr)
-		goto gc_complete;
-
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		new_s = assoc_array_ptr_to_shortcut(ptr);
-		new_parent = new_s->back_pointer;
-		slot = new_s->parent_slot;
-
-		if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) {
-			struct assoc_array_node *n;
-
-			pr_devel("excise shortcut\n");
-			new_n->back_pointer = new_parent;
-			new_n->parent_slot = slot;
-			kfree(new_s);
-			if (!new_parent) {
-				new_root = assoc_array_node_to_ptr(new_n);
-				goto gc_complete;
-			}
-
-			n = assoc_array_ptr_to_node(new_parent);
-			n->slots[slot] = assoc_array_node_to_ptr(new_n);
-		}
-	} else {
-		new_parent = ptr;
-	}
-	new_n = assoc_array_ptr_to_node(new_parent);
-
-ascend_old_tree:
-	ptr = node->back_pointer;
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		slot = shortcut->parent_slot;
-		cursor = shortcut->back_pointer;
-		if (!cursor)
-			goto gc_complete;
-	} else {
-		slot = node->parent_slot;
-		cursor = ptr;
-	}
-	BUG_ON(!cursor);
-	node = assoc_array_ptr_to_node(cursor);
-	slot++;
-	goto continue_node;
-
-gc_complete:
-	edit->set[0].to = new_root;
-	assoc_array_apply_edit(edit);
-	array->nr_leaves_on_tree = nr_leaves_on_tree;
-	return 0;
-
-enomem:
-	pr_devel("enomem\n");
-	assoc_array_destroy_subtree(new_root, edit->ops);
-	kfree(edit);
-	return -ENOMEM;
-}
diff --git a/security/keys/Kconfig b/security/keys/Kconfig
index f4510d8cb485f4..3f64d60d0f8a69 100644
--- a/security/keys/Kconfig
+++ b/security/keys/Kconfig
@@ -5,7 +5,6 @@
 
 menuconfig KEYS
 	bool "Enable access key retention support"
-	select ASSOCIATIVE_ARRAY
 	help
 	  This option provides support for retaining authentication tokens and
 	  access keys in the kernel.
diff --git a/security/keys/internal.h b/security/keys/internal.h
index b7b622bc36a137..c452d71cce038d 100644
--- a/security/keys/internal.h
+++ b/security/keys/internal.h
@@ -21,6 +21,12 @@
 #include <linux/vmalloc.h>
 
 struct iovec;
+struct keyring_link;
+
+struct keyring_edit {
+	struct keyring_link *new;
+	struct keyring_link *old;
+};
 
 #ifdef __KDEBUG
 #define kenter(FMT, ...) \
@@ -98,13 +104,13 @@ extern int __key_move_lock(struct key *l_keyring, struct key *u_keyring,
 			   const struct keyring_index_key *index_key);
 extern int __key_link_begin(struct key *keyring,
 			    const struct keyring_index_key *index_key,
-			    struct assoc_array_edit **_edit);
+			    struct keyring_edit *edit);
 extern int __key_link_check_live_key(struct key *keyring, struct key *key);
 extern void __key_link(struct key *keyring, struct key *key,
-		       struct assoc_array_edit **_edit);
+		       struct keyring_edit *edit);
 extern void __key_link_end(struct key *keyring,
 			   const struct keyring_index_key *index_key,
-			   struct assoc_array_edit *edit);
+			   struct keyring_edit *edit);
 
 extern key_ref_t find_key_to_update(key_ref_t keyring_ref,
 				    const struct keyring_index_key *index_key);
@@ -122,7 +128,7 @@ struct keyring_search_context {
 #define KEYRING_SEARCH_SKIP_EXPIRED	0x0020	/* Ignore expired keys (intention to replace) */
 #define KEYRING_SEARCH_RECURSE		0x0040	/* Search child keyrings also */
 
-	int (*iterator)(const void *object, void *iterator_data);
+	int (*iterator)(const struct key *key, void *iterator_data);
 
 	/* Internal stuff */
 	int			skipped_ret;
diff --git a/security/keys/key.c b/security/keys/key.c
index 3f1f0fc137109a..20cf273cf4a3de 100644
--- a/security/keys/key.c
+++ b/security/keys/key.c
@@ -430,7 +430,7 @@ static int __key_instantiate_and_link(struct key *key,
 				      struct key_preparsed_payload *prep,
 				      struct key *keyring,
 				      struct key *authkey,
-				      struct assoc_array_edit **_edit)
+				      struct keyring_edit *edit)
 {
 	int ret, awaken;
 
@@ -461,7 +461,7 @@ static int __key_instantiate_and_link(struct key *key,
 				if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
 					set_bit(KEY_FLAG_KEEP, &key->flags);
 
-				__key_link(keyring, key, _edit);
+				__key_link(keyring, key, edit);
 			}
 
 			/* disable the authorisation key */
@@ -505,7 +505,7 @@ int key_instantiate_and_link(struct key *key,
 			     struct key *authkey)
 {
 	struct key_preparsed_payload prep;
-	struct assoc_array_edit *edit = NULL;
+	struct keyring_edit edit = {};
 	int ret;
 
 	memset(&prep, 0, sizeof(prep));
@@ -543,7 +543,7 @@ int key_instantiate_and_link(struct key *key,
 
 error_link_end:
 	if (keyring)
-		__key_link_end(keyring, &key->index_key, edit);
+		__key_link_end(keyring, &key->index_key, &edit);
 
 error:
 	if (key->type->preparse)
@@ -580,7 +580,7 @@ int key_reject_and_link(struct key *key,
 			struct key *keyring,
 			struct key *authkey)
 {
-	struct assoc_array_edit *edit = NULL;
+	struct keyring_edit edit = {};
 	int ret, awaken, link_ret = 0;
 
 	key_check(key);
@@ -599,12 +599,12 @@ int key_reject_and_link(struct key *key,
 			 * concurrent restriction install.
 			 */
 			if (keyring->restrict_link) {
-				__key_link_end(keyring, &key->index_key, edit);
+				__key_link_end(keyring, &key->index_key, &edit);
 				return -EPERM;
 			}
 			link_ret = __key_link_begin(keyring, &key->index_key, &edit);
 			if (link_ret < 0)
-				__key_link_end(keyring, &key->index_key, edit);
+				__key_link_end(keyring, &key->index_key, &edit);
 		}
 	}
 
@@ -635,7 +635,7 @@ int key_reject_and_link(struct key *key,
 	mutex_unlock(&key_construction_mutex);
 
 	if (keyring && link_ret == 0)
-		__key_link_end(keyring, &key->index_key, edit);
+		__key_link_end(keyring, &key->index_key, &edit);
 
 	/* wake up anyone waiting for a key to be constructed */
 	if (awaken)
@@ -825,7 +825,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
 		.description	= description,
 	};
 	struct key_preparsed_payload prep;
-	struct assoc_array_edit *edit = NULL;
+	struct keyring_edit edit = {};
 	const struct cred *cred = current_cred();
 	struct key *keyring, *key = NULL;
 	key_ref_t key_ref;
@@ -966,7 +966,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
 	key_ref = make_key_ref(key, is_key_possessed(keyring_ref));
 
 error_link_end:
-	__key_link_end(keyring, &index_key, edit);
+	__key_link_end(keyring, &index_key, &edit);
 error_free_prep:
 	if (index_key.type->preparse)
 		index_key.type->free_preparse(&prep);
@@ -979,7 +979,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
 	/* we found a matching key, so we're going to try to update it
 	 * - we can drop the locks first as we have the key pinned
 	 */
-	__key_link_end(keyring, &index_key, edit);
+	__key_link_end(keyring, &index_key, &edit);
 
 	key = key_ref_to_ptr(key_ref);
 	if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags)) {
diff --git a/security/keys/keyring.c b/security/keys/keyring.c
index 5281da9d5bf750..04d9a98c0f3100 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,49 +383,51 @@ static void keyring_destroy(struct key *keyring)
 		kfree(keyres);
 	}
 
-	assoc_array_destroy(&keyring->keys, &keyring_assoc_array_ops);
+	index = rcu_dereference_protected(keyring->index, true);
+	if (index)
+		__keyring_index_free(index);
+}
+
+static unsigned long keyring_nr_links(const struct key *keyring)
+{
+	const struct keyring_index *index;
+
+	guard(rcu)();
+	index = rcu_dereference(keyring->index);
+	return index ? READ_ONCE(index->nr) : 0;
 }
 
+/**
+ * keyring_is_empty - Check whether a keyring is empty
+ * @keyring: The keyring to check.
+ */
+bool keyring_is_empty(const struct key *keyring)
+{
+	return keyring_nr_links(keyring) == 0;
+}
+EXPORT_SYMBOL(keyring_is_empty);
+
 /*
  * Describe a keyring for /proc.
  */
 static void keyring_describe(const struct key *keyring, struct seq_file *m)
 {
+	unsigned long nr;
+
 	if (keyring->description)
 		seq_puts(m, keyring->description);
 	else
 		seq_puts(m, "[anon]");
 
 	if (key_is_positive(keyring)) {
-		if (keyring->keys.nr_leaves_on_tree != 0)
-			seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree);
+		nr = keyring_nr_links(keyring);
+		if (nr != 0)
+			seq_printf(m, ": %lu", nr);
 		else
 			seq_puts(m, ": empty");
 	}
 }
 
-struct keyring_read_iterator_context {
-	size_t			buflen;
-	size_t			count;
-	key_serial_t		*buffer;
-};
-
-static int keyring_read_iterator(const void *object, void *data)
-{
-	struct keyring_read_iterator_context *ctx = data;
-	const struct key *key = keyring_ptr_to_key(object);
-
-	kenter("{%s,%d},,{%zu/%zu}",
-	       key->type->name, key->serial, ctx->count, ctx->buflen);
-
-	if (ctx->count >= ctx->buflen)
-		return 1;
-
-	*ctx->buffer++ = key->serial;
-	ctx->count += sizeof(key->serial);
-	return 0;
-}
-
 /*
  * Read a list of key IDs from the keyring's contents in binary form
  *
@@ -493,7 +438,10 @@ static int keyring_read_iterator(const void *object, void *data)
 static long keyring_read(const struct key *keyring,
 			 char *buffer, size_t buflen)
 {
-	struct keyring_read_iterator_context ctx;
+	struct keyring_index *links = keyring_index_locked(keyring);
+	key_serial_t *serials = (key_serial_t *)buffer;
+	struct keyring_link *link;
+	size_t count = 0;
 	long ret;
 
 	kenter("{%d},,%zu", key_serial(keyring), buflen);
@@ -501,25 +449,22 @@ static long keyring_read(const struct key *keyring,
 	if (buflen & (sizeof(key_serial_t) - 1))
 		return -EINVAL;
 
-	/* Copy as many key IDs as fit into the buffer */
-	if (buffer && buflen) {
-		ctx.buffer = (key_serial_t *)buffer;
-		ctx.buflen = buflen;
-		ctx.count = 0;
-		ret = assoc_array_iterate(&keyring->keys,
-					  keyring_read_iterator, &ctx);
-		if (ret < 0) {
-			kleave(" = %ld [iterate]", ret);
-			return ret;
+	if (buffer && buflen && links) {
+		list_for_each_entry(link, &links->list, list) {
+			if (count == buflen / sizeof(*serials))
+				break;
+
+			serials[count++] = keyring_link_key(link)->serial;
+			cond_resched();
 		}
 	}
 
-	/* Return the size of the buffer needed */
-	ret = keyring->keys.nr_leaves_on_tree * sizeof(key_serial_t);
+	ret = links ? links->nr * sizeof(key_serial_t) : 0;
 	if (ret <= buflen)
 		kleave("= %ld [ok]", ret);
 	else
 		kleave("= %ld [buffer too small]", ret);
+
 	return ret;
 }
 
@@ -583,10 +528,9 @@ bool key_default_cmp(const struct key *key,
 /*
  * Iteration function to consider each key found.
  */
-static int keyring_search_iterator(const void *object, void *iterator_data)
+static int keyring_search_iterator(const struct key *key, void *iterator_data)
 {
 	struct keyring_search_context *ctx = iterator_data;
-	const struct key *key = keyring_ptr_to_key(object);
 	unsigned long kflags = READ_ONCE(key->flags);
 	short state = key_read_state(key);
 
@@ -653,19 +597,78 @@ static int keyring_search_iterator(const void *object, void *iterator_data)
 /*
  * Search inside a keyring for a key.  We can search by walking to it
  * directly based on its index-key or we can iterate over the entire
- * tree looking for it, based on the match function.
+ * list looking for it, based on the match function.
  */
 static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)
 {
 	if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_DIRECT) {
-		const void *object;
+		struct keyring_link *link;
+		struct key *key;
+
+		link = keyring_find_link(rcu_dereference(keyring->index),
+					 &ctx->index_key);
+		if (!link)
+			return 0;
+		key = keyring_link_key(link);
+		return ctx->iterator(key, ctx);
+	}
+
+	return keyring_iterate(keyring, ctx->iterator, ctx);
+}
+
+/*
+ * 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;
 
-		object = assoc_array_find(&keyring->keys,
-					  &keyring_assoc_array_ops,
-					  &ctx->index_key);
-		return object ? ctx->iterator(object, ctx) : 0;
+	if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
+			      (1 << KEY_FLAG_REVOKED)))
+		return 0;
+
+	if (search_keyring(keyring, ctx))
+		goto found;
+
+	if (!(ctx->flags & KEYRING_SEARCH_RECURSE))
+		return 0;
+	links = rcu_dereference(keyring->index);
+	if (!links)
+		return 0;
+
+	list_for_each_entry_rcu(link, &links->list, list) {
+		struct key *key = keyring_link_key(link);
+
+		if (key->type != &key_type_keyring)
+			break;
+		if (depth >= KEYRING_SEARCH_MAX_DEPTH) {
+			if (!(ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP))
+				return 0;
+			ctx->result = ERR_PTR(-ELOOP);
+			return -ELOOP;
+		}
+
+		if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
+		    key_task_permission(make_key_ref(key, ctx->possessed),
+					ctx->cred, KEY_NEED_SEARCH) < 0)
+			continue;
+
+		ret = search_keyring_tree(key, ctx, depth + 1);
+		if (ret < 0)
+			return ret;
+		if (ret)
+			goto found;
 	}
-	return assoc_array_iterate(&keyring->keys, ctx->iterator, ctx);
+
+	return 0;
+
+found:
+	if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME))
+		keyring->last_used_at = ctx->now;
+	return 1;
 }
 
 /*
@@ -675,17 +678,7 @@ static int search_keyring(struct key *keyring, struct keyring_search_context *ct
 static bool search_nested_keyrings(struct key *keyring,
 				   struct keyring_search_context *ctx)
 {
-	struct {
-		struct key *keyring;
-		struct assoc_array_node *node;
-		int slot;
-	} stack[KEYRING_SEARCH_MAX_DEPTH];
-
-	struct assoc_array_shortcut *shortcut;
-	struct assoc_array_node *node;
-	struct assoc_array_ptr *ptr;
 	struct key *key;
-	int sp = 0, slot;
 
 	kenter("{%d},{%s,%s}",
 	       keyring->serial,
@@ -703,9 +696,9 @@ static bool search_nested_keyrings(struct key *keyring,
 	 * and whether it is valid or not.
 	 */
 	if (ctx->match_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||
-	    keyring_compare_object(keyring, &ctx->index_key)) {
+	    keyring_index_key_equal(&keyring->index_key, &ctx->index_key)) {
 		ctx->skipped_ret = 2;
-		switch (ctx->iterator(keyring_key_to_ptr(keyring), ctx)) {
+		switch (ctx->iterator(keyring, ctx)) {
 		case 1:
 			goto found;
 		case 2:
@@ -717,152 +710,11 @@ static bool search_nested_keyrings(struct key *keyring,
 
 	ctx->skipped_ret = 0;
 
-	/* Start processing a new keyring */
-descend_to_keyring:
-	kdebug("descend to %d", keyring->serial);
-	if (keyring->flags & ((1 << KEY_FLAG_INVALIDATED) |
-			      (1 << KEY_FLAG_REVOKED)))
-		goto not_this_keyring;
-
-	/* Search through the keys in this keyring before its searching its
-	 * subtrees.
-	 */
-	if (search_keyring(keyring, ctx))
-		goto found;
-
-	/* Then manually iterate through the keyrings nested in this one.
-	 *
-	 * Start from the root node of the index tree.  Because of the way the
-	 * hash function has been set up, keyrings cluster on the leftmost
-	 * branch of the root node (root slot 0) or in the root node itself.
-	 * Non-keyrings avoid the leftmost branch of the root entirely (root
-	 * slots 1-15).
-	 */
-	if (!(ctx->flags & KEYRING_SEARCH_RECURSE))
-		goto not_this_keyring;
-
-	ptr = READ_ONCE(keyring->keys.root);
-	if (!ptr)
-		goto not_this_keyring;
-
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		/* If the root is a shortcut, either the keyring only contains
-		 * keyring pointers (everything clusters behind root slot 0) or
-		 * doesn't contain any keyring pointers.
-		 */
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		if ((shortcut->index_key[0] & ASSOC_ARRAY_FAN_MASK) != 0)
-			goto not_this_keyring;
-
-		ptr = READ_ONCE(shortcut->next_node);
-		node = assoc_array_ptr_to_node(ptr);
-		goto begin_node;
-	}
-
-	node = assoc_array_ptr_to_node(ptr);
-	ptr = node->slots[0];
-	if (!assoc_array_ptr_is_meta(ptr))
-		goto begin_node;
-
-descend_to_node:
-	/* Descend to a more distal node in this keyring's content tree and go
-	 * through that.
-	 */
-	kdebug("descend");
-	if (assoc_array_ptr_is_shortcut(ptr)) {
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		ptr = READ_ONCE(shortcut->next_node);
-		BUG_ON(!assoc_array_ptr_is_node(ptr));
-	}
-	node = assoc_array_ptr_to_node(ptr);
-
-begin_node:
-	kdebug("begin_node");
-	slot = 0;
-ascend_to_node:
-	/* Go through the slots in a node */
-	for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
-		ptr = READ_ONCE(node->slots[slot]);
-
-		if (assoc_array_ptr_is_meta(ptr)) {
-			if (node->back_pointer ||
-			    assoc_array_ptr_is_shortcut(ptr))
-				goto descend_to_node;
-		}
-
-		if (!keyring_ptr_is_keyring(ptr))
-			continue;
-
-		key = keyring_ptr_to_key(ptr);
-
-		if (sp >= KEYRING_SEARCH_MAX_DEPTH) {
-			if (ctx->flags & KEYRING_SEARCH_DETECT_TOO_DEEP) {
-				ctx->result = ERR_PTR(-ELOOP);
-				return false;
-			}
-			goto not_this_keyring;
-		}
-
-		/* Search a nested keyring */
-		if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) &&
-		    key_task_permission(make_key_ref(key, ctx->possessed),
-					ctx->cred, KEY_NEED_SEARCH) < 0)
-			continue;
-
-		/* stack the current position */
-		stack[sp].keyring = keyring;
-		stack[sp].node = node;
-		stack[sp].slot = slot;
-		sp++;
-
-		/* begin again with the new keyring */
-		keyring = key;
-		goto descend_to_keyring;
-	}
-
-	/* We've dealt with all the slots in the current node, so now we need
-	 * to ascend to the parent and continue processing there.
-	 */
-	ptr = READ_ONCE(node->back_pointer);
-	slot = node->parent_slot;
-
-	if (ptr && assoc_array_ptr_is_shortcut(ptr)) {
-		shortcut = assoc_array_ptr_to_shortcut(ptr);
-		ptr = READ_ONCE(shortcut->back_pointer);
-		slot = shortcut->parent_slot;
-	}
-	if (!ptr)
-		goto not_this_keyring;
-	node = assoc_array_ptr_to_node(ptr);
-	slot++;
-
-	/* If we've ascended to the root (zero backpointer), we must have just
-	 * finished processing the leftmost branch rather than the root slots -
-	 * so there can't be any more keyrings for us to find.
-	 */
-	if (node->back_pointer) {
-		kdebug("ascend %d", slot);
-		goto ascend_to_node;
-	}
-
-	/* The keyring we're looking at was disqualified or didn't contain a
-	 * matching key.
-	 */
-not_this_keyring:
-	kdebug("not_this_keyring %d", sp);
-	if (sp <= 0) {
+	if (search_keyring_tree(keyring, ctx, 0) <= 0) {
 		kleave(" = false");
 		return false;
 	}
 
-	/* Resume the processing of a keyring higher up in the tree */
-	sp--;
-	keyring = stack[sp].keyring;
-	node = stack[sp].node;
-	slot = stack[sp].slot + 1;
-	kdebug("ascend to %d [%d]", keyring->serial, slot);
-	goto ascend_to_node;
-
 	/* We found a viable match */
 found:
 	key = key_ref_to_ptr(ctx->result);
@@ -870,8 +722,6 @@ static bool search_nested_keyrings(struct key *keyring,
 	if (!(ctx->flags & KEYRING_SEARCH_NO_UPDATE_TIME)) {
 		key->last_used_at = ctx->now;
 		keyring->last_used_at = ctx->now;
-		while (sp > 0)
-			stack[--sp].keyring->last_used_at = ctx->now;
 	}
 	kleave(" = true");
 	return true;
@@ -1118,8 +968,8 @@ EXPORT_SYMBOL(keyring_restrict);
 key_ref_t find_key_to_update(key_ref_t keyring_ref,
 			     const struct keyring_index_key *index_key)
 {
+	struct keyring_link *link;
 	struct key *keyring, *key;
-	const void *object;
 
 	keyring = key_ref_to_ptr(keyring_ref);
 
@@ -1127,17 +977,16 @@ key_ref_t find_key_to_update(key_ref_t keyring_ref,
 	       keyring->serial, index_key->type->name, index_key->description);
 
 	guard(rcu)();
-	object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
-				  index_key);
+	link = keyring_find_link(rcu_dereference(keyring->index), index_key);
 
-	if (object)
+	if (link)
 		goto found;
 
 	kleave(" = NULL");
 	return NULL;
 
 found:
-	key = keyring_ptr_to_key(object);
+	key = keyring_link_key(link);
 	if (key->flags & ((1 << KEY_FLAG_INVALIDATED) |
 			  (1 << KEY_FLAG_REVOKED))) {
 		kleave(" = NULL [x]");
@@ -1207,11 +1056,10 @@ struct key *find_keyring_by_name(const char *name, bool uid_keyring)
 	return keyring;
 }
 
-static int keyring_detect_cycle_iterator(const void *object,
+static int keyring_detect_cycle_iterator(const struct key *key,
 					 void *iterator_data)
 {
 	struct keyring_search_context *ctx = iterator_data;
-	const struct key *key = keyring_ptr_to_key(object);
 
 	kenter("{%d}", key->serial);
 
@@ -1307,57 +1155,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 +1274,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 +1313,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 +1367,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 +1377,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 +1401,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 +1425,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 +1447,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 +1472,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 +1481,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 +1493,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 +1514,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 +1528,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 +1552,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 +1562,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 +1583,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 +1604,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 +1624,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 +1635,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 +1644,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

23/3 2026/11/13 05:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 59115
							output: 20
							thoughts: 1307
						

Thoughts:
**Analyzing the Patch for KMSAN Fuzzing Necessity**

Okay, let's break this down. My goal is to determine if this patch necessitates a dedicated KMSAN fuzzing session. The rule is clear: KMSAN is expensive, and it's only warranted if the changes introduce or expose uninitialized memory risks that *only* KMSAN can detect. If KASAN, LOCKDEP, or other standard detectors can catch it, we skip the KMSAN session.

First, I see the patch removes `lib/assoc_array.c`, `include/linux/assoc_array.h`, and related files. Effectively, the `assoc_array` data structure is being replaced. This indicates a significant internal change. It looks like they're shifting the keyring's internal representation from an `assoc_array` to a hash table plus linked list structure, using `struct rhashtable` and `struct list_head`, within a `struct keyring_index`.

Looking closely, the patch also modifies `struct keyring_index_key` and `struct key` in `include/linux/key.h`. It appears the `keyring_index_key` is being simplified, and the key itself has a union. The bit-fields are being reorganized, changing `unsigned long` hash and length/description fields to `u32` hash and `unsigned int` desc_len. The `desc` array's position and sizes appear to be affected, though this depends on architecture due to bitfield sizing. The use of `type_id` and `domain_id` are removed.

Now, let's focus on the critical `keyring_read` function. It seems to have undergone a significant overhaul. Previously, `keyring_read` iterated using `assoc_array_iterate`. Now, it uses a linked list with `list_for_each_entry`. It now accesses the internal structures, and copies the `key_serial_t` values, checking the `buffer` size. This is how the key serials are copied into user space.

I need to investigate how this new implementation of `keyring_read` interacts with userspace. I need to know where it's being called to understand the context and potential for uninitialized memory exposure. I'll search the kernel code for calls to `keyring_read` to trace its usage. Specifically, I'm watching for how the `keyring_index` is being accessed, and whether the modification to `desc_len` and the reordering of the structure leads to possible initialization issues.

I'm keeping a sharp eye out for places where uninitialized memory could be read, written, or leaked to userspace. That's the KMSAN trigger. The structure changes and the move to a new indexing scheme are the prime suspects, because those internal data structures are now *different*.



24/3 2026/11/13 05:15 tool grepper
0m Args:
{
  "Expression": "keyring_read\\b"
}

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

25/3 2026/11/13 05:15 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 61339
							output: 35
							thoughts: 53
						

Thoughts:
Here's my thought process, as if I were analyzing this code:

**Analyzing Keyring Read Functionality**

Okay, so I see that `keyring_read` is essentially an alias for `key_type_keyring.read`. This immediately tells me we're dealing with a specific read operation associated with keyring objects. Now, the crucial question is: where is this `key_type->read` function actually *used*? I need to understand the call flow to see how this read operation fits into the larger picture of the key management system.

I’m going to use search to determine where `key_type->read` is called. It may be called directly as `.read` or it might be called indirectly through functions like `key_read` or even `keyctl_read_key`. I'll want to cover all bases to get a good understanding of what calls it. This will give me all of the relevant call sites.



26/3 2026/11/13 05:15 tool grepper
0m Args:
{
  "Expression": "keyctl_read_key|key_validate",
  "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/dh.c=18=static ssize_t dh_data_from_key(key_serial_t keyid, const void **data)\n--\nsecurity/keys/dh.c-35-\t\tdown_read(\u0026key-\u003esem);\nsecurity/keys/dh.c:36:\t\tstatus = key_validate(key);\nsecurity/keys/dh.c-37-\t\tif (status == 0) {\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-807-\tdown_read(\u0026key-\u003esem);\nsecurity/keys/keyctl.c:808:\tret = key_validate(key);\nsecurity/keys/keyctl.c-809-\tif (ret == 0) {\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--\nsecurity/keys/permission.c=92=EXPORT_SYMBOL(key_task_permission);\n--\nsecurity/keys/permission.c-94-/**\nsecurity/keys/permission.c:95: * key_validate - Validate a key.\nsecurity/keys/permission.c-96- * @key: The key to be validated.\n--\nsecurity/keys/permission.c-101- */\nsecurity/keys/permission.c:102:int key_validate(const struct key *key)\nsecurity/keys/permission.c-103-{\n--\nsecurity/keys/permission.c-122-}\nsecurity/keys/permission.c:123:EXPORT_SYMBOL(key_validate);\n--\nsecurity/keys/process_keys.c=549=key_ref_t search_process_keyrings_rcu(struct keyring_search_context *ctx)\n--\nsecurity/keys/process_keys.c-569-\t\trka = dereference_key_rcu(cred-\u003erequest_key_auth);\nsecurity/keys/process_keys.c:570:\t\tif (rka \u0026\u0026 key_validate(cred-\u003erequest_key_auth) == 0) {\nsecurity/keys/process_keys.c-571-\t\t\t//// was search_process_keyrings() [ie. recursive]\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-872-\t\t} else if (need_perm != KEY_DEFER_PERM_CHECK) {\nsecurity/keys/process_keys.c:873:\t\t\tret = key_validate(key);\nsecurity/keys/process_keys.c-874-\t\t\tif (ret \u003c 0)\n--\nsecurity/keys/request_key.c=118=static int call_sbin_request_key(struct key *authkey, void *aux)\n--\nsecurity/keys/request_key.c-201-\t\tif (test_bit(KEY_FLAG_USER_CONSTRUCT, \u0026key-\u003eflags) ||\nsecurity/keys/request_key.c:202:\t\t    key_validate(key) \u003c 0)\nsecurity/keys/request_key.c-203-\t\t\tret = -ENOKEY;\n--\nsecurity/keys/request_key.c=681=int wait_for_key_construction(struct key *key, bool intr)\n--\nsecurity/keys/request_key.c-691-\t\treturn ret;\nsecurity/keys/request_key.c:692:\treturn key_validate(key);\nsecurity/keys/request_key.c-693-}\n"
}

27/3 2026/11/13 05:15 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 63248
							output: 36
							thoughts: 40
						

Thoughts:
Here's my analysis of the provided text, as though I'm thinking through the code myself:

**Diving into `keyctl_read_key` and Memory Management**

Alright, let's get down to brass tacks. I need to understand the memory handling within `keyctl_read_key` from `security/keys/keyctl.c`. Specifically, I want to trace how that `buffer` is allocated, populated with key data, and ultimately copied back to user space. Understanding this is crucial for spotting potential vulnerabilities like buffer overflows or information leaks. I'll need to pay close attention to the size calculations, the allocation strategy (is it static, dynamic, or from a pool?), and the mechanisms used to copy the data. Any subtle errors here could have serious security implications, especially given the sensitive nature of cryptographic keys. I will be looking closely at how the kernel validates the buffer size and content.



28/3 2026/11/13 05:15 tool read-file
0m Args:
{
  "File": "security/keys/keyctl.c",
  "FirstLine": 828,
  "LineCount": 95
}

Results:
{
  "Contents": " 828:\t */\n 829:\tlong keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)\n 830:\t{\n 831:\t\tstruct key *key;\n 832:\t\tkey_ref_t key_ref;\n 833:\t\tlong ret;\n 834:\t\tchar *key_data = NULL;\n 835:\t\tsize_t key_data_len;\n 836:\t\n 837:\t\t/* find the key first */\n 838:\t\tkey_ref = lookup_user_key(keyid, 0, KEY_DEFER_PERM_CHECK);\n 839:\t\tif (IS_ERR(key_ref)) {\n 840:\t\t\tret = -ENOKEY;\n 841:\t\t\tgoto out;\n 842:\t\t}\n 843:\t\n 844:\t\tkey = key_ref_to_ptr(key_ref);\n 845:\t\n 846:\t\tret = key_read_state(key);\n 847:\t\tif (ret \u003c 0)\n 848:\t\t\tgoto key_put_out; /* Negatively instantiated */\n 849:\t\n 850:\t\t/* see if we can read it directly */\n 851:\t\tret = key_permission(key_ref, KEY_NEED_READ);\n 852:\t\tif (ret == 0)\n 853:\t\t\tgoto can_read_key;\n 854:\t\tif (ret != -EACCES)\n 855:\t\t\tgoto key_put_out;\n 856:\t\n 857:\t\t/* we can't; see if it's searchable from this process's keyrings\n 858:\t\t * - we automatically take account of the fact that it may be\n 859:\t\t *   dangling off an instantiation key\n 860:\t\t */\n 861:\t\tif (!is_key_possessed(key_ref)) {\n 862:\t\t\tret = -EACCES;\n 863:\t\t\tgoto key_put_out;\n 864:\t\t}\n 865:\t\n 866:\t\t/* the key is probably readable - now try to read it */\n 867:\tcan_read_key:\n 868:\t\tif (!buffer || !buflen) {\n 869:\t\t\t/* Get the key length from the read method */\n 870:\t\t\tret = __keyctl_read_key(key, NULL, 0);\n 871:\t\t\tgoto key_put_out;\n 872:\t\t}\n 873:\t\n 874:\t\t/*\n 875:\t\t * Read the data with the semaphore held (since we might sleep)\n 876:\t\t * to protect against the key being updated or revoked.\n 877:\t\t *\n 878:\t\t * Allocating a temporary buffer to hold the keys before\n 879:\t\t * transferring them to user buffer to avoid potential\n 880:\t\t * deadlock involving page fault and mmap_lock.\n 881:\t\t *\n 882:\t\t * key_data_len = (buflen \u003c= PAGE_SIZE)\n 883:\t\t *\t\t? buflen : actual length of key data\n 884:\t\t *\n 885:\t\t * This prevents allocating arbitrary large buffer which can\n 886:\t\t * be much larger than the actual key length. In the latter case,\n 887:\t\t * at least 2 passes of this loop is required.\n 888:\t\t */\n 889:\t\tkey_data_len = (buflen \u003c= PAGE_SIZE) ? buflen : 0;\n 890:\t\tfor (;;) {\n 891:\t\t\tif (key_data_len) {\n 892:\t\t\t\tkey_data = kvmalloc(key_data_len, GFP_KERNEL);\n 893:\t\t\t\tif (!key_data) {\n 894:\t\t\t\t\tret = -ENOMEM;\n 895:\t\t\t\t\tgoto key_put_out;\n 896:\t\t\t\t}\n 897:\t\t\t}\n 898:\t\n 899:\t\t\tret = __keyctl_read_key(key, key_data, key_data_len);\n 900:\t\n 901:\t\t\t/*\n 902:\t\t\t * Read methods will just return the required length without\n 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"
}

29/3 2026/11/13 05:15 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 64938
							output: 36
							thoughts: 247
						

Thoughts:
**Analyzing `keyctl_read_key` in `security/keys/keyctl.c`**

Okay, let's dive into lines 889-922 of `security/keys/keyctl.c`. Hold on, I need to focus on `keyctl_read_key`. Let's assume `buflen` is, say, 1024, which is less than or equal to `PAGE_SIZE`.

Looking at line 889, `key_data_len` becomes 1024. Then, line 892 calls `kvmalloc(key_data_len, GFP_KERNEL)`. Ah, a critical point! `kvmalloc` *doesn't* zero the allocated memory. It's not `kvzalloc`. This is something to remember!

Now, on line 899, we call `__keyctl_read_key(key, key_data, key_data_len)`. The function then calls `key->type->read(key, buffer, buflen)`! Time to investigate `__keyctl_read_key` further.



30/3 2026/11/13 05:15 tool read-file
0m Args:
{
  "File": "security/keys/keyctl.c",
  "FirstLine": 803,
  "LineCount": 25
}

Results:
{
  "Contents": " 803:\tstatic long __keyctl_read_key(struct key *key, char *buffer, size_t buflen)\n 804:\t{\n 805:\t\tlong ret;\n 806:\t\n 807:\t\tdown_read(\u0026key-\u003esem);\n 808:\t\tret = key_validate(key);\n 809:\t\tif (ret == 0) {\n 810:\t\t\tif (key-\u003etype-\u003eread)\n 811:\t\t\t\tret = key-\u003etype-\u003eread(key, buffer, buflen);\n 812:\t\t\telse\n 813:\t\t\t\tret = -EOPNOTSUPP;\n 814:\t\t}\n 815:\t\tup_read(\u0026key-\u003esem);\n 816:\t\treturn ret;\n 817:\t}\n 818:\t\n 819:\t/*\n 820:\t * Read a key's payload.\n 821:\t *\n 822:\t * The key must either grant the caller Read permission, or it must grant the\n 823:\t * caller Search permission when searched for from the process keyrings.\n 824:\t *\n 825:\t * If successful, we place up to buflen bytes of data into the buffer, if one\n 826:\t * is provided, and return the amount of data that is available in the key,\n 827:\t * irrespective of how much we copied into the buffer.\n"
}

31/3 2026/11/13 05:15 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 65845
							output: 20
							thoughts: 5215
						

Thoughts:
**Deep Dive into `keyring_read` and Related Structures**

Alright, let's break this down systematically. My initial observation is focused on `keyring_read` and how it interacts with the keyring index. The core concern is the potential for discrepancies between the intended data written to a buffer and the actual state of the keyring. I'm seeing a possible race condition, or a subtle vulnerability arising from how the number of entries in a keyring (`links->nr`) is updated relative to its actual content (`links->list`).

The function `keyring_read` intends to read key serials from a keyring and place them into a buffer provided by user space. The size of the buffer is checked, and then a loop iterates over entries in `links->list`. The critical bit is that `ret` in `keyring_read` calculates the *expected* number of bytes (based on `links->nr`), while `count` reflects the number of serials *actually* written into `serials`. If `count` ever differs from `links->nr`, this is where my attention will focus. The code copies to user space based on `ret`, so if `count` < `links->nr` the user space will be given a small slice of data. If `links->nr` is greater than the number of items in `links->list` this can lead to returning a buffer of data that is incomplete.

This is a key area of concern. Specifically, the relationship between `links->nr` (the expected number of keys) and the actual entries in `links->list`. Looking at the functions called to modify `links->nr`, I've identified several: `__key_link`, `__key_unlink`, and `keyring_gc`. `__key_link` adds an item to the list, incrementing `links->nr`. `__key_unlink` removes an item and decrements the counter. `keyring_gc` deletes keys from the list, decrementing `links->nr`, and is safe. The key question is whether there are circumstances where these operations are not atomic, or where failures lead to inconsistencies.

I'm digging deeper into how these elements are managed. Looking at `__key_link_begin`, I see that `link` is allocated and inserted into the `rhashtable` but is *not* initially added to `links->list`. The link and its `key` are then later added during `__key_link`. This looks like a window of vulnerability! What if the process is interrupted *after* `rhashtable_insert_fast` but *before* the list is updated? This could leave the list incomplete, while `links->nr` is incremented. `__key_link_end` would clean up if there was an error in the previous insert or replace in `__key_link`.

`keyring_gc` also caught my eye. The `list_for_each_entry_safe` loop is correct and safe to use, and `rhashtable_remove_fast` can return an error which is handled safely.

Now, focusing on how this all ties into user space, especially the `keyctl_read_key` and its interaction with buffer sizes. If `buflen` is small enough (<= PAGE_SIZE), the kernel allocates a local buffer (`key_data`). This buffer contains uninitialized data, and a read will be performed. If there is a bug with the `count` or `ret` in `keyring_read`, this is where it will be seen. If `links->nr` is 2, the `ret` will be calculated to be 8 bytes, which is copied into user space. However, if the list does not have 2 items, there can be unexpected results.

I'm now investigating locking in this scenario. `keyring_index_locked(keyring)` uses `rcu_dereference_protected`, meaning the structure is accessed with an RCU read lock. `keyctl_read_key` calls `__keyctl_read_key`, which does `down_read(&key->sem)`. This read lock is needed for the read, and it means writers can't run. `keyring_gc` also grabs a write lock with `down_write(&keyring->sem)` so the write lock prevents concurrent modification.

Finally, I'm examining memory layout to ensure there are no alignment issues, which might lead to unexpected behavior. The `keyring_index_key` struct appears correct now.



32/3 2026/11/13 05:16 tool grepper
0m Args:
{
  "Expression": "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=86=static int keyring_obj_cmpfn(struct rhashtable_compare_arg *arg,\n--\nsecurity/keys/keyring.c-91-\nsecurity/keys/keyring.c:92:\treturn !key || !keyring_index_key_equal(\u0026key-\u003eindex_key, arg-\u003ekey);\nsecurity/keys/keyring.c-93-}\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=678=static bool search_nested_keyrings(struct key *keyring,\n--\nsecurity/keys/keyring.c-698-\tif (ctx-\u003ematch_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||\nsecurity/keys/keyring.c:699:\t    keyring_index_key_equal(\u0026keyring-\u003eindex_key, \u0026ctx-\u003eindex_key)) {\nsecurity/keys/keyring.c-700-\t\tctx-\u003eskipped_ret = 2;\n--\nsecurity/keys/keyring.c=968=key_ref_t find_key_to_update(key_ref_t keyring_ref,\nsecurity/keys/keyring.c:969:\t\t\t     const struct keyring_index_key *index_key)\nsecurity/keys/keyring.c-970-{\n--\nsecurity/keys/keyring.c=1105=int __key_link_lock(struct key *keyring,\nsecurity/keys/keyring.c:1106:\t\t    const struct keyring_index_key *index_key)\nsecurity/keys/keyring.c-1107-\t__acquires(\u0026keyring-\u003esem)\n--\nsecurity/keys/keyring.c=1127=int __key_move_lock(struct key *l_keyring, struct key *u_keyring,\nsecurity/keys/keyring.c:1128:\t\t    const struct keyring_index_key *index_key)\nsecurity/keys/keyring.c-1129-\t__acquires(\u0026l_keyring-\u003esem)\n--\nsecurity/keys/keyring.c=1184=int __key_link_begin(struct key *keyring,\nsecurity/keys/keyring.c:1185:\t\t     const struct keyring_index_key *index_key,\nsecurity/keys/keyring.c-1186-\t\t     struct keyring_edit *edit)\n--\nsecurity/keys/keyring.c=1314=void __key_link_end(struct key *keyring,\nsecurity/keys/keyring.c:1315:\t\t    const struct keyring_index_key *index_key,\nsecurity/keys/keyring.c-1316-\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"
}

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

Args:
null

Results:
null

Tokens:
							input: 74138
							output: 34
							thoughts: 28
						

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

**Diving into `index_key` Initialization**

Okay, so I'm trying to trace the initialization of `index_key`. I need to figure out how it's being set up initially. My first instinct is to dive directly into the code. Let's start with `security/keys/persistent.c` and specifically line 80. Hopefully, that line will give me the answer, or at least point me in the right direction. It's the most logical place to begin my investigation. I'm expecting to find either a direct assignment or a function call that ultimately handles the allocation and population of this critical value. This is a common pattern, and I will be looking for this.



34/3 2026/11/13 05:16 tool read-file
0m Args:
{
  "File": "security/keys/persistent.c",
  "FirstLine": 80,
  "LineCount": 40
}

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 115:\t\t\treturn ret;\n 116:\t\tcreated = ret == 0;\n 117:\t\n 118:\tfound:\n 119:\t\tpersistent = key_ref_to_ptr(persistent_ref);\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 74990
							output: 30
							thoughts: 23
						

Thoughts:
Here's my take on the thought process, from an expert's perspective:

**Diving into Key Initialization**

Alright, let's get down to brass tacks. I'm going to take a peek at the `key_alloc` function. The real question I want answered is *precisely* how that `key->index_key` member gets initialized. It's crucial, and the way it's done likely has implications for performance and, critically, how the data structures interact downstream. Understanding the initialization here is the foundation for analyzing any issues with the allocation or usage of the key index.



36/3 2026/11/13 05:16 tool grepper
0m Args:
{
  "Expression": "key_alloc\\b",
  "PathPrefixes": [
    "security/keys/"
  ]
}

Results:
{
  "Output": "security/keys/encrypted-keys/encrypted.c=528=static int derived_key_decrypt(struct encrypted_key_payload *epayload,\n--\nsecurity/keys/encrypted-keys/encrypted.c-574-/* Allocate memory for decrypted key and datablob. */\nsecurity/keys/encrypted-keys/encrypted.c:575:static struct encrypted_key_payload *encrypted_key_alloc(struct key *key,\nsecurity/keys/encrypted-keys/encrypted.c-576-\t\t\t\t\t\t\t const char *format,\n--\nsecurity/keys/encrypted-keys/encrypted.c=793=static int encrypted_instantiate(struct key *key,\n--\nsecurity/keys/encrypted-keys/encrypted.c-818-\nsecurity/keys/encrypted-keys/encrypted.c:819:\tepayload = encrypted_key_alloc(key, format, master_desc,\nsecurity/keys/encrypted-keys/encrypted.c-820-\t\t\t\t       decrypted_datalen, decrypted_data);\n--\nsecurity/keys/encrypted-keys/encrypted.c=855=static int encrypted_update(struct key *key, struct key_preparsed_payload *prep)\n--\nsecurity/keys/encrypted-keys/encrypted.c-883-\nsecurity/keys/encrypted-keys/encrypted.c:884:\tnew_epayload = encrypted_key_alloc(key, epayload-\u003eformat,\nsecurity/keys/encrypted-keys/encrypted.c-885-\t\t\t\t\t   new_master_desc, epayload-\u003edatalen, NULL);\n--\nsecurity/keys/key.c=133=static inline void key_alloc_serial(struct key *key)\n--\nsecurity/keys/key.c-191-/**\nsecurity/keys/key.c:192: * key_alloc - Allocate a key of the specified type.\nsecurity/keys/key.c-193- * @type: The type of key to allocate.\n--\nsecurity/keys/key.c-221- * be done by either never unregistering the key type, or making sure\nsecurity/keys/key.c:222: * key_alloc() calls don't race with module unloading.\nsecurity/keys/key.c-223- */\nsecurity/keys/key.c:224:struct key *key_alloc(struct key_type *type, const char *desc,\nsecurity/keys/key.c-225-\t\t      kuid_t uid, kgid_t gid, const struct cred *cred,\n--\nsecurity/keys/key.c-317-\t/* let the security module know about the key */\nsecurity/keys/key.c:318:\tret = security_key_alloc(key, cred, flags);\nsecurity/keys/key.c-319-\tif (ret \u003c 0)\n--\nsecurity/keys/key.c-362-}\nsecurity/keys/key.c:363:EXPORT_SYMBOL(key_alloc);\nsecurity/keys/key.c-364-\n--\nsecurity/keys/key.c=815=static key_ref_t __key_create_or_update(key_ref_t keyring_ref,\n--\nsecurity/keys/key.c-947-\t/* allocate a new key */\nsecurity/keys/key.c:948:\tkey = key_alloc(index_key.type, index_key.description,\nsecurity/keys/key.c-949-\t\t\tcred-\u003efsuid, cred-\u003efsgid, cred, perm, flags, NULL);\n--\nsecurity/keys/keyring.c=474=struct key *keyring_alloc(const char *description, kuid_t uid, kgid_t gid,\n--\nsecurity/keys/keyring.c-482-\nsecurity/keys/keyring.c:483:\tkeyring = key_alloc(\u0026key_type_keyring, description,\nsecurity/keys/keyring.c-484-\t\t\t    uid, gid, cred, perm, flags, restrict_link);\n--\nsecurity/keys/request_key.c=369=static int construct_alloc_key(struct keyring_search_context *ctx,\n--\nsecurity/keys/request_key.c-394-\nsecurity/keys/request_key.c:395:\tkey = key_alloc(ctx-\u003eindex_key.type, ctx-\u003eindex_key.description,\nsecurity/keys/request_key.c-396-\t\t\tctx-\u003ecred-\u003efsuid, ctx-\u003ecred-\u003efsgid, ctx-\u003ecred,\n--\nsecurity/keys/request_key.c=489=static struct key *construct_key_and_link(struct keyring_search_context *ctx,\n--\nsecurity/keys/request_key.c-553- * @dest_keyring: Where to cache the key.\nsecurity/keys/request_key.c:554: * @flags: Flags to key_alloc().\nsecurity/keys/request_key.c-555- *\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-250-\nsecurity/keys/request_key_auth.c:251:\tauthkey = key_alloc(\u0026key_type_request_key_auth, desc,\nsecurity/keys/request_key_auth.c-252-\t\t\t    cred-\u003efsuid, cred-\u003efsgid, cred,\n"
}

37/3 2026/11/13 05:16 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 76519
							output: 35
							thoughts: 26
						

Thoughts:
Okay, let's dive into this. I'm going to pull up `security/keys/key.c` and zero in on `key_alloc()` around line 224. I know this function like the back of my hand, but a refresher never hurts, and it's always good to revisit the code in context. I'm expecting this function to be the core of creating new keys, so I'll be looking for things like memory allocation, initialization of the `key` structure, and any crucial checks that might affect security or performance. I'm especially interested in how it handles error conditions and what resources it protects. Let's see what we've got.



38/3 2026/11/13 05:16 tool read-file
0m Args:
{
  "File": "security/keys/key.c",
  "FirstLine": 265,
  "LineCount": 55
}

Results:
{
  "Contents": " 265:\t\t\tspin_lock_irqsave(\u0026user-\u003elock, irqflags);\n 266:\t\t\tif (!(flags \u0026 KEY_ALLOC_QUOTA_OVERRUN)) {\n 267:\t\t\t\tif (user-\u003eqnkeys + 1 \u003e maxkeys ||\n 268:\t\t\t\t    user-\u003eqnbytes + quotalen \u003e maxbytes ||\n 269:\t\t\t\t    user-\u003eqnbytes + quotalen \u003c user-\u003eqnbytes)\n 270:\t\t\t\t\tgoto no_quota;\n 271:\t\t\t}\n 272:\t\n 273:\t\t\tuser-\u003eqnkeys++;\n 274:\t\t\tuser-\u003eqnbytes += quotalen;\n 275:\t\t\tspin_unlock_irqrestore(\u0026user-\u003elock, irqflags);\n 276:\t\t}\n 277:\t\n 278:\t\t/* allocate and initialise the key and its description */\n 279:\t\tkey = kmem_cache_zalloc(key_jar, GFP_KERNEL);\n 280:\t\tif (!key)\n 281:\t\t\tgoto no_memory_2;\n 282:\t\n 283:\t\tkey-\u003eindex_key.desc_len = desclen;\n 284:\t\tkey-\u003eindex_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL);\n 285:\t\tif (!key-\u003eindex_key.description)\n 286:\t\t\tgoto no_memory_3;\n 287:\t\tkey-\u003eindex_key.type = type;\n 288:\t\tkey_set_index_key(\u0026key-\u003eindex_key);\n 289:\t\n 290:\t\trefcount_set(\u0026key-\u003eusage, 1);\n 291:\t\tinit_rwsem(\u0026key-\u003esem);\n 292:\t\tlockdep_set_class(\u0026key-\u003esem, \u0026type-\u003elock_class);\n 293:\t\tkey-\u003euser = user;\n 294:\t\tkey-\u003equotalen = quotalen;\n 295:\t\tkey-\u003edatalen = type-\u003edef_datalen;\n 296:\t\tkey-\u003euid = uid;\n 297:\t\tkey-\u003egid = gid;\n 298:\t\tkey-\u003eperm = perm;\n 299:\t\tkey-\u003eexpiry = TIME64_MAX;\n 300:\t\tkey-\u003erestrict_link = restrict_link;\n 301:\t\tkey-\u003elast_used_at = ktime_get_real_seconds();\n 302:\t\n 303:\t\tkey-\u003eflags |= 1 \u003c\u003c KEY_FLAG_USER_ALIVE;\n 304:\t\tif (!(flags \u0026 KEY_ALLOC_NOT_IN_QUOTA))\n 305:\t\t\tkey-\u003eflags |= 1 \u003c\u003c KEY_FLAG_IN_QUOTA;\n 306:\t\tif (flags \u0026 KEY_ALLOC_BUILT_IN)\n 307:\t\t\tkey-\u003eflags |= 1 \u003c\u003c KEY_FLAG_BUILTIN;\n 308:\t\tif (flags \u0026 KEY_ALLOC_UID_KEYRING)\n 309:\t\t\tkey-\u003eflags |= 1 \u003c\u003c KEY_FLAG_UID_KEYRING;\n 310:\t\tif (flags \u0026 KEY_ALLOC_SET_KEEP)\n 311:\t\t\tkey-\u003eflags |= 1 \u003c\u003c KEY_FLAG_KEEP;\n 312:\t\n 313:\t#ifdef KEY_DEBUGGING\n 314:\t\tkey-\u003emagic = KEY_DEBUG_MAGIC;\n 315:\t#endif\n 316:\t\n 317:\t\t/* let the security module know about the key */\n 318:\t\tret = security_key_alloc(key, cred, flags);\n 319:\t\tif (ret \u003c 0)\n"
}

39/3 2026/11/13 05:16 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 77649
							output: 31
							thoughts: 600
						

Thoughts:
**Analyzing Keyring Index Key Hashing**

Okay, let's break this down. First, the code allocates memory for `key` using `kmem_cache_zalloc` and zero-initializes the allocated memory. That's good practice. Now, I'm diving into `key_set_index_key`. This function seems to handle populating the `index_key` structure. The important part I'm seeing is how the `domain_tag` is handled. If it's not already set, it either grabs the `key_domain` from the current network namespace, or defaults to a `default_domain_tag`.  Makes sense; that sets up the proper context for the key.

Now, let's look at `hash_key_type_and_desc`. This is where the interesting bit happens. It uses a SipHash to generate a hash value for the `index_key`. Critically, it uses a per-boot random key with `get_random_once`, which is security best practice.  Before this change, the code was dealing with opaque IDs, such as `type_id` and `domain_id`. The change appears to be in how it inputs to the hash. Now it's hashing the *pointers* to the `type` and `domain_tag` structures. The comment confirms that this is safe because SipHash is cryptographically secure. Since it uses SipHash, it is safe to use the pointers as part of the hash, because that won't leak information. The final hash value, `index_key->hash`, is a truncated 32-bit value.

I'm thinking now, I should check how `struct keyring_search_context ctx` is created. I'll need to go to the `security/keys/` directory to figure that out.



40/3 2026/11/13 05:16 tool grepper
0m Args:
{
  "Expression": "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=531=static int keyring_search_iterator(const struct key *key, void *iterator_data)\nsecurity/keys/keyring.c-532-{\nsecurity/keys/keyring.c:533:\tstruct keyring_search_context *ctx = iterator_data;\nsecurity/keys/keyring.c-534-\tunsigned long kflags = READ_ONCE(key-\u003eflags);\n--\nsecurity/keys/keyring.c-601- */\nsecurity/keys/keyring.c:602:static int search_keyring(struct key *keyring, struct keyring_search_context *ctx)\nsecurity/keys/keyring.c-603-{\n--\nsecurity/keys/keyring.c=622=static int search_keyring_tree(struct key *keyring,\nsecurity/keys/keyring.c:623:\t\t\t       struct keyring_search_context *ctx, int depth)\nsecurity/keys/keyring.c-624-{\n--\nsecurity/keys/keyring.c=678=static bool search_nested_keyrings(struct key *keyring,\nsecurity/keys/keyring.c:679:\t\t\t\t   struct keyring_search_context *ctx)\nsecurity/keys/keyring.c-680-{\n--\nsecurity/keys/keyring.c=764=key_ref_t keyring_search_rcu(key_ref_t keyring_ref,\nsecurity/keys/keyring.c:765:\t\t\t     struct keyring_search_context *ctx)\nsecurity/keys/keyring.c-766-{\n--\nsecurity/keys/keyring.c=802=key_ref_t keyring_search(key_ref_t keyring,\n--\nsecurity/keys/keyring.c-806-{\nsecurity/keys/keyring.c:807:\tstruct keyring_search_context ctx = {\nsecurity/keys/keyring.c-808-\t\t.index_key.type\t\t= type,\n--\nsecurity/keys/keyring.c=1059=static int keyring_detect_cycle_iterator(const struct key *key,\n--\nsecurity/keys/keyring.c-1061-{\nsecurity/keys/keyring.c:1062:\tstruct keyring_search_context *ctx = iterator_data;\nsecurity/keys/keyring.c-1063-\n--\nsecurity/keys/keyring.c=1082=static int keyring_detect_cycle(struct key *A, struct key *B)\nsecurity/keys/keyring.c-1083-{\nsecurity/keys/keyring.c:1084:\tstruct keyring_search_context ctx = {\nsecurity/keys/keyring.c-1085-\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"
}

41/3 2026/11/13 05:16 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 80717
							output: 36
							thoughts: 7398
						

Thoughts:
**Deep Dive into Keyring Code and Potential Vulnerabilities**

Alright, let's break this down systematically. My initial observation is the widespread use of `struct keyring_search_context ctx` with designated initializers. Then, the hash table operations, and comparison functions are the next focus. The hash functions `keyring_hashfn` and `keyring_obj_hashfn` use the `index_key`'s hash. This is where I start really focusing: the `index_key->hash` is calculated by `key_set_index_key`, which looks safe so far.

Now I am getting into the details.  The `rhashtable` implementation comes into view, and this is where potential race conditions or uninitialized memory reads are most likely.  Specifically, the `keyring_obj_cmpfn` function and `link->key` is a concern. The critical point seems to be the potential for `key` to be NULL during the initial insertion. The design specifically allows this to support resizing. So a link is inserted with a NULL key, and later this is set by `rcu_assign_pointer`. This is fine. But how are these structures freed? The `__key_link_end` function removes the link. If there is an abort, `rhashtable_remove_fast` is called, and `link->key` will be NULL, but `key_put` is called with NULL, and `kfree` is called, so also not a problem.

The `search_keyring_tree` function is then examined. The linked list `&links->list` is traversed in the correct order, and the logic is as I'd expect.

Next is a detailed audit of every allocated structure: `keyring_index`, `keyring_link`, `keyring_edit`, and `keyring_index_key`. All appear correctly initialized, zero or set. However, a deep dive into `key_set_index_key` revealed a critical point. The use of a static `default_domain_tag` in `key_set_index_key` is fine. The `hash_key_type_and_desc` function is where the memory safety might be an issue. In `hash_key_type_and_desc`, the `siphash` function is called with `index_key->description` which could point to an uninitialized buffer, potentially causing issues!

Next the code verifies the removal of `assoc_array`. The patch removes code and makes changes to files that refer to assoc_array and removes these files as no longer required.

Next, I check the modifications to the check for emptiness with `keyring_is_empty`. This checks the `nr_links` value.

Then I get to the crux of the matter: `keyring_read`. This one could be a big problem. I need to trace exactly where the buffer comes from. The `keyctl_read_key` function allocates a `key_data` buffer. If the buffer size (`buflen`) is greater than `PAGE_SIZE`, a buffer is allocated. The `keyring_read` function could be reading and writing uninitialized `key_data` to a user-space buffer.

I need to trace the call paths to be sure. I see that the `keyctl_read_key` function can result in a key read to a buffer. However, the data length of this key is known, so it's not possible to copy uninitialized data.

Let's carefully think about `keyring_read()` and the potential leak. The `keyctl_read_key` function allocates a buffer, either using `kvmalloc` or the stack. If the initial buffer size is greater than `PAGE_SIZE`, it allocates and if it's not large enough it's reallocated. Inside the loop, it calls `__keyctl_read_key` which in turn calls `keyring_read`. I check that the `buffer` passed to `keyring_read` is properly initialized. I see that for the "small" case of `buflen <= PAGE_SIZE` then `key_data` is allocated and it is uninitialized. The loop writes data to `serials`. If there are fewer than `links->nr` entries in the list, then uninitialized memory could be leaked. So I carefully check the loop in `keyring_read` and it's relationship to the data's length and if there are writes to a buffer with insufficient memory to hold them. Also I need to check how the number of links in the list matches `links->nr`.

I now know that the write function of `keyring_read` does the correct thing: the number of bytes that are read are controlled, so I'm very confident there's no leak.


42/3 2026/11/13 05:17 tool read-file
0m Args:
{
  "File": "security/keys/keyring.c",
  "FirstLine": 750,
  "LineCount": 70
}

Results:
{
  "Contents": " 750:\t * determine the match.  Normally the match function from the key type would be\n 751:\t * used.\n 752:\t *\n 753:\t * RCU can be used to prevent the keyring key lists from disappearing without\n 754:\t * the need to take lots of locks.\n 755:\t *\n 756:\t * Returns a pointer to the found key and increments the key usage count if\n 757:\t * successful; -EAGAIN if no matching keys were found, or if expired or revoked\n 758:\t * keys were found; -ENOKEY if only negative keys were found; -ENOTDIR if the\n 759:\t * specified keyring wasn't a keyring.\n 760:\t *\n 761:\t * In the case of a successful return, the possession attribute from\n 762:\t * @keyring_ref is propagated to the returned key reference.\n 763:\t */\n 764:\tkey_ref_t keyring_search_rcu(key_ref_t keyring_ref,\n 765:\t\t\t\t     struct keyring_search_context *ctx)\n 766:\t{\n 767:\t\tstruct key *keyring;\n 768:\t\tlong err;\n 769:\t\n 770:\t\tctx-\u003eiterator = keyring_search_iterator;\n 771:\t\tctx-\u003epossessed = is_key_possessed(keyring_ref);\n 772:\t\tctx-\u003eresult = ERR_PTR(-EAGAIN);\n 773:\t\n 774:\t\tkeyring = key_ref_to_ptr(keyring_ref);\n 775:\t\tkey_check(keyring);\n 776:\t\n 777:\t\tif (keyring-\u003etype != \u0026key_type_keyring)\n 778:\t\t\treturn ERR_PTR(-ENOTDIR);\n 779:\t\n 780:\t\tif (!(ctx-\u003eflags \u0026 KEYRING_SEARCH_NO_CHECK_PERM)) {\n 781:\t\t\terr = key_task_permission(keyring_ref, ctx-\u003ecred, KEY_NEED_SEARCH);\n 782:\t\t\tif (err \u003c 0)\n 783:\t\t\t\treturn ERR_PTR(err);\n 784:\t\t}\n 785:\t\n 786:\t\tctx-\u003enow = ktime_get_real_seconds();\n 787:\t\tif (search_nested_keyrings(keyring, ctx))\n 788:\t\t\t__key_get(key_ref_to_ptr(ctx-\u003eresult));\n 789:\t\treturn ctx-\u003eresult;\n 790:\t}\n 791:\t\n 792:\t/**\n 793:\t * keyring_search - Search the supplied keyring tree for a matching key\n 794:\t * @keyring: The root of the keyring tree to be searched.\n 795:\t * @type: The type of keyring we want to find.\n 796:\t * @description: The name of the keyring we want to find.\n 797:\t * @recurse: True to search the children of @keyring also\n 798:\t *\n 799:\t * As keyring_search_rcu() above, but using the current task's credentials and\n 800:\t * type's default matching function and preferred search method.\n 801:\t */\n 802:\tkey_ref_t keyring_search(key_ref_t keyring,\n 803:\t\t\t\t struct key_type *type,\n 804:\t\t\t\t const char *description,\n 805:\t\t\t\t bool recurse)\n 806:\t{\n 807:\t\tstruct keyring_search_context ctx = {\n 808:\t\t\t.index_key.type\t\t= type,\n 809:\t\t\t.index_key.description\t= description,\n 810:\t\t\t.cred\t\t\t= current_cred(),\n 811:\t\t\t.match_data.cmp\t\t= key_default_cmp,\n 812:\t\t\t.match_data.raw_data\t= description,\n 813:\t\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\n 814:\t\t\t.flags\t\t\t= KEYRING_SEARCH_DO_STATE_CHECK,\n 815:\t\t};\n 816:\t\tkey_ref_t key;\n 817:\t\tsize_t desclen;\n 818:\t\tint ret;\n 819:\t\n"
}

43/3 2026/11/13 05:17 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 90304
							output: 36
							thoughts: 24
						

Thoughts:
Okay, here's my interpretation of what's going on in those lines of `security/keys/keyring.c`, from an expert's perspective:

**Diving into `security/keys/keyring.c` - Lines 820-845**

Right, let's zero in on lines 820-845. I know this code well, but a quick refresh never hurts. I suspect these lines are dealing with... ah, yes, I recognize the pattern now. We're likely in the weeds of the keyring management functions. Specifically, it seems we're dealing with the core logic surrounding *something*. Given the context, it could be a key lookup, a permissions check during a key operation, or potentially the removal of a key. The range itself is a decent size, suggesting a self-contained routine or section of a larger function. I'm mentally parsing the control flow… Is it handling an error condition, or a successful path? Are there calls to other keyring functions, potentially to a helper that does the heavy lifting or to a standard library function? I’m looking for any conditional statements – `if`, `else`, `switch` – these will guide me through the decision-making process within this specific function. I’m already anticipating potential race conditions or security vulnerabilities; my brain immediately jumps to thinking about how locking mechanisms are used here and if there are any obvious timing issues, or potential buffer overflows that might be exploitable. Given the depth of the file, this could be where the system enforces the core rules surrounding key access and permissions, and if that's the case, then security is paramount here, and so it's critical to avoid any logical loopholes that could undermine the integrity of the key management system.



44/3 2026/11/13 05:17 tool read-file
0m Args:
{
  "File": "security/keys/keyring.c",
  "FirstLine": 820,
  "LineCount": 25
}

Results:
{
  "Contents": " 820:\t\tdesclen = strlen(description);\n 821:\t\tif (desclen \u003e= KEY_MAX_DESC_SIZE)\n 822:\t\t\treturn ERR_PTR(-EINVAL);\n 823:\t\tctx.index_key.desc_len = desclen;\n 824:\t\n 825:\t\tif (recurse)\n 826:\t\t\tctx.flags |= KEYRING_SEARCH_RECURSE;\n 827:\t\tif (type-\u003ematch_preparse) {\n 828:\t\t\tret = type-\u003ematch_preparse(\u0026ctx.match_data);\n 829:\t\t\tif (ret \u003c 0)\n 830:\t\t\t\treturn ERR_PTR(ret);\n 831:\t\t}\n 832:\t\n 833:\t\trcu_read_lock();\n 834:\t\tkey = keyring_search_rcu(keyring, \u0026ctx);\n 835:\t\trcu_read_unlock();\n 836:\t\n 837:\t\tif (type-\u003ematch_free)\n 838:\t\t\ttype-\u003ematch_free(\u0026ctx.match_data);\n 839:\t\treturn key;\n 840:\t}\n 841:\tEXPORT_SYMBOL(keyring_search);\n 842:\t\n 843:\tstatic struct key_restriction *keyring_restriction_alloc(\n 844:\t\tkey_restrict_link_func_t check)\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 91107
							output: 21
							thoughts: 537
						

Thoughts:
**Investigating the `keyring_search` Function**

Okay, hold on a second. I need to take a closer look at `keyring_search`. Specifically, I'm examining this `struct keyring_search_context ctx = { ... };` declaration.  I'm seeing that `ctx.index_key.desc_len = desclen;` is set. Now, the key question is, is `key_set_index_key(&ctx.index_key)` explicitly called *within* this function?  I need to verify the index key setup, so let me quickly jump to lines 807-835...right...

Wait a minute, WHERE is `key_set_index_key(&ctx.index_key)` called? Let me search!

Okay, I've got it, lines 807-835 show the structure.

`keyring_search` does indeed initialize the context:

Hold up. It looks like it *doesn't* explicitly call `key_set_index_key` directly in this code block. So, was `key_set_index_key` called in the *old* code before this patch? Or is it called elsewhere in the code base that interacts with this? Perhaps `match_preparse` is responsible for setting it up, or maybe something else entirely? I need to search the entire codebase for any calls to `key_set_index_key` to understand the full picture.


46/3 2026/11/13 05:17 tool grepper
0m Args:
{
  "Expression": "key_set_index_key"
}

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

47/3 2026/11/13 05:17 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 92618
							output: 36
							thoughts: 111
						

Thoughts:
Okay, here's my assessment of that code snippet, presented as my thought process:

**Diving into the Keyring Code**

Aha! My attention is immediately drawn to `security/keys/keyring.c`, specifically lines 692-693. This `search_nested_keyrings` function… I remember that function. Now I see that right at the start of that function, there's a crucial conditional:

`if (ctx->index_key.description)`
`key_set_index_key(&ctx->index_key);`

Interesting. It's calling `key_set_index_key` when there's an index key description present. Right at the beginning of the search. I need to understand that call now in context. Let me zoom out and scan the surrounding lines, specifically lines 685-697.



48/3 2026/11/13 05:17 tool read-file
0m Args:
{
  "File": "security/keys/keyring.c",
  "FirstLine": 685,
  "LineCount": 20
}

Results:
{
  "Contents": " 685:\t\t       ctx-\u003eindex_key.type-\u003ename,\n 686:\t\t       ctx-\u003eindex_key.description);\n 687:\t\n 688:\t#define STATE_CHECKS (KEYRING_SEARCH_NO_STATE_CHECK | KEYRING_SEARCH_DO_STATE_CHECK)\n 689:\t\tBUG_ON((ctx-\u003eflags \u0026 STATE_CHECKS) == 0 ||\n 690:\t\t       (ctx-\u003eflags \u0026 STATE_CHECKS) == STATE_CHECKS);\n 691:\t\n 692:\t\tif (ctx-\u003eindex_key.description)\n 693:\t\t\tkey_set_index_key(\u0026ctx-\u003eindex_key);\n 694:\t\n 695:\t\t/* Check to see if this top-level keyring is what we are looking for\n 696:\t\t * and whether it is valid or not.\n 697:\t\t */\n 698:\t\tif (ctx-\u003ematch_data.lookup_type == KEYRING_SEARCH_LOOKUP_ITERATE ||\n 699:\t\t    keyring_index_key_equal(\u0026keyring-\u003eindex_key, \u0026ctx-\u003eindex_key)) {\n 700:\t\t\tctx-\u003eskipped_ret = 2;\n 701:\t\t\tswitch (ctx-\u003eiterator(keyring, ctx)) {\n 702:\t\t\tcase 1:\n 703:\t\t\t\tgoto found;\n 704:\t\t\tcase 2:\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 93316
							output: 37
							thoughts: 180
						

Thoughts:
Okay, let's see.

**Analyzing the Key Search Logic**

Alright, so I'm looking at this `search_nested_keyrings` function and it's calling `key_set_index_key(&ctx->index_key)` when `ctx->index_key.description` isn't null. My immediate thought is, what happens if that `description` *is* NULL? Does this path even handle a NULL `description` gracefully? That's a potential vulnerability or at least a point of unexpected behavior I need to investigate. I need to figure out under what conditions `ctx->index_key.description` can actually be NULL. Specifically, when is `lookup_type` used with a NULL description.

Let's trace it back to where the `index_key` is set. Okay, I see in `proc.c` that `ctx.index_key = key->index_key;` assignment where the description *is* set, but I need to understand when it *might* be NULL. The `lookup_user_key` in `process_keys.c` looks like a key place to look. I need to examine lines 666-700 in `security/keys/process_keys.c` very closely to see how the `index_key` is populated and if a NULL description is a possible scenario during searches. I will pay special attention to the logic around key lookups and creation. I need to understand this NULL condition and its impact on the search mechanism.



50/3 2026/11/13 05:17 tool read-file
0m Args:
{
  "File": "security/keys/process_keys.c",
  "FirstLine": 666,
  "LineCount": 40
}

Results:
{
  "Contents": " 666:\tkey_ref_t lookup_user_key(key_serial_t id, unsigned long lflags,\n 667:\t\t\t\t  enum key_need_perm need_perm)\n 668:\t{\n 669:\t\tstruct keyring_search_context ctx = {\n 670:\t\t\t.match_data.cmp\t\t= lookup_user_key_possessed,\n 671:\t\t\t.match_data.lookup_type\t= KEYRING_SEARCH_LOOKUP_DIRECT,\n 672:\t\t\t.flags\t\t\t= (KEYRING_SEARCH_NO_STATE_CHECK |\n 673:\t\t\t\t\t\t   KEYRING_SEARCH_RECURSE),\n 674:\t\t};\n 675:\t\tstruct request_key_auth *rka;\n 676:\t\tstruct key *key, *user_session;\n 677:\t\tkey_ref_t key_ref, skey_ref;\n 678:\t\tint ret;\n 679:\t\n 680:\ttry_again:\n 681:\t\tctx.cred = get_current_cred();\n 682:\t\tkey_ref = ERR_PTR(-ENOKEY);\n 683:\t\n 684:\t\tswitch (id) {\n 685:\t\tcase KEY_SPEC_THREAD_KEYRING:\n 686:\t\t\tif (!ctx.cred-\u003ethread_keyring) {\n 687:\t\t\t\tif (!(lflags \u0026 KEY_LOOKUP_CREATE))\n 688:\t\t\t\t\tgoto error;\n 689:\t\n 690:\t\t\t\tret = install_thread_keyring();\n 691:\t\t\t\tif (ret \u003c 0) {\n 692:\t\t\t\t\tkey_ref = ERR_PTR(ret);\n 693:\t\t\t\t\tgoto error;\n 694:\t\t\t\t}\n 695:\t\t\t\tgoto reget_creds;\n 696:\t\t\t}\n 697:\t\n 698:\t\t\tkey = ctx.cred-\u003ethread_keyring;\n 699:\t\t\t__key_get(key);\n 700:\t\t\tkey_ref = make_key_ref(key, 1);\n 701:\t\t\tbreak;\n 702:\t\n 703:\t\tcase KEY_SPEC_PROCESS_KEYRING:\n 704:\t\t\tif (!ctx.cred-\u003eprocess_keyring) {\n 705:\t\t\t\tif (!(lflags \u0026 KEY_LOOKUP_CREATE))\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 94470
							output: 37
							thoughts: 15
						

Thoughts:
Okay, here's my interpretation of that thought process, tailored for an expert audience, and presented as if it were my own internal monologue:

**Diving into `lookup_user_key`**

Alright, time to dig deeper into `lookup_user_key`. I'm curious what the subsequent operations are within that function. I already have a mental model of how it's *supposed* to work based on the broader system design, but the devil's always in the details, especially with key lookup routines. I'm thinking specifically about potential edge cases, performance bottlenecks related to data structures or caching, and, of course, any potential security vulnerabilities, like timing attacks or improper sanitization. I'm going to look for any logic that might skip error handling, or that uses a lookup key in a way that’s outside of the expected bounds of operation. Let's see if there's any cleverness (or lack thereof) hidden in there that needs my immediate attention.



52/3 2026/11/13 05:17 tool read-file
0m Args:
{
  "File": "security/keys/process_keys.c",
  "FirstLine": 750,
  "LineCount": 40
}

Results:
{
  "Contents": " 750:\t\n 751:\t\tcase KEY_SPEC_USER_KEYRING:\n 752:\t\t\tret = look_up_user_keyrings(\u0026key, NULL);\n 753:\t\t\tif (ret \u003c 0)\n 754:\t\t\t\tgoto error;\n 755:\t\t\tkey_ref = make_key_ref(key, 1);\n 756:\t\t\tbreak;\n 757:\t\n 758:\t\tcase KEY_SPEC_USER_SESSION_KEYRING:\n 759:\t\t\tret = look_up_user_keyrings(NULL, \u0026key);\n 760:\t\t\tif (ret \u003c 0)\n 761:\t\t\t\tgoto error;\n 762:\t\t\tkey_ref = make_key_ref(key, 1);\n 763:\t\t\tbreak;\n 764:\t\n 765:\t\tcase KEY_SPEC_GROUP_KEYRING:\n 766:\t\t\t/* group keyrings are not yet supported */\n 767:\t\t\tkey_ref = ERR_PTR(-EINVAL);\n 768:\t\t\tgoto error;\n 769:\t\n 770:\t\tcase KEY_SPEC_REQKEY_AUTH_KEY:\n 771:\t\t\tkey = ctx.cred-\u003erequest_key_auth;\n 772:\t\t\tif (!key)\n 773:\t\t\t\tgoto error;\n 774:\t\n 775:\t\t\t__key_get(key);\n 776:\t\t\tkey_ref = make_key_ref(key, 1);\n 777:\t\t\tbreak;\n 778:\t\n 779:\t\tcase KEY_SPEC_REQUESTOR_KEYRING:\n 780:\t\t\tif (!ctx.cred-\u003erequest_key_auth)\n 781:\t\t\t\tgoto error;\n 782:\t\n 783:\t\t\tdown_read(\u0026ctx.cred-\u003erequest_key_auth-\u003esem);\n 784:\t\t\tif (test_bit(KEY_FLAG_REVOKED,\n 785:\t\t\t\t     \u0026ctx.cred-\u003erequest_key_auth-\u003eflags)) {\n 786:\t\t\t\tkey_ref = ERR_PTR(-EKEYREVOKED);\n 787:\t\t\t\tkey = NULL;\n 788:\t\t\t} else {\n 789:\t\t\t\trka = ctx.cred-\u003erequest_key_auth-\u003epayload.data[0];\n"
}

53/3 2026/11/13 05:17 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 95329
							output: 37
							thoughts: 21
						

Thoughts:
Okay, let's break this down. Here's how I'd approach this, thinking as the code itself:

**Investigating the `lookup_user_key` Function with `id > 0`**

Alright, I'm thinking about the `lookup_user_key` function. Specifically, I'm focusing on the condition where `id > 0`. This is a crucial area because it almost certainly dictates the core behavior. What does this if statement trigger? What's the *intention* of this `id > 0` check within the `lookup_user_key` function? I suspect the design wants to limit its behavior based on the id value to reduce overhead, security concerns, or simplify logic. Does this lead to a direct database query? Perhaps it triggers an optimized retrieval method for known user keys? Or, does it filter or exclude certain users from the lookup process?

The ramifications here are important. If the `id` were somehow accidentally negative or zero, what would happen? Does it return a "not found" state? Does it throw an exception? Does it silently bypass the logic, potentially leading to unexpected results or even a vulnerability if the function is not defensively programmed? I need to understand what this `id > 0` condition *means* in the context of the user key lookup. It could be an optimization, it could be a crucial security check, or it could be masking a subtle, but critical bug. I'll need to follow the code execution path to find out.



54/3 2026/11/13 05:18 tool read-file
0m Args:
{
  "File": "security/keys/process_keys.c",
  "FirstLine": 815,
  "LineCount": 45
}

Results:
{
  "Contents": " 815:\t\t\tkey_ref = make_key_ref(key, 0);\n 816:\t\t\tbreak;\n 817:\t\n 818:\t\tcase KEY_SPEC_FS_VERITY_KEYRING:\n 819:\t\t\tkey = fs_verity_keyring;\n 820:\t\t\tif (!key)\n 821:\t\t\t\tgoto error;\n 822:\t\t\t__key_get(key);\n 823:\t\t\tkey_ref = make_key_ref(key, 0);\n 824:\t\t\tbreak;\n 825:\t\n 826:\t\tdefault:\n 827:\t\t\tkey_ref = ERR_PTR(-EINVAL);\n 828:\t\t\tif (id \u003c 1)\n 829:\t\t\t\tgoto error;\n 830:\t\n 831:\t\t\tkey = key_lookup(id);\n 832:\t\t\tif (IS_ERR(key)) {\n 833:\t\t\t\tkey_ref = ERR_CAST(key);\n 834:\t\t\t\tgoto error;\n 835:\t\t\t}\n 836:\t\n 837:\t\t\tkey_ref = make_key_ref(key, 0);\n 838:\t\n 839:\t\t\t/* check to see if we possess the key */\n 840:\t\t\tctx.index_key\t\t\t= key-\u003eindex_key;\n 841:\t\t\tctx.match_data.raw_data\t\t= key;\n 842:\t\t\tkdebug(\"check possessed\");\n 843:\t\t\trcu_read_lock();\n 844:\t\t\tskey_ref = search_process_keyrings_rcu(\u0026ctx);\n 845:\t\t\trcu_read_unlock();\n 846:\t\t\tkdebug(\"possessed=%p\", skey_ref);\n 847:\t\n 848:\t\t\tif (!IS_ERR(skey_ref)) {\n 849:\t\t\t\tkey_put(key);\n 850:\t\t\t\tkey_ref = skey_ref;\n 851:\t\t\t}\n 852:\t\n 853:\t\t\tbreak;\n 854:\t\t}\n 855:\t\n 856:\t\t/* unlink does not use the nominated key in any way, so can skip all\n 857:\t\t * the permission checks as it is only concerned with the keyring */\n 858:\t\tif (need_perm != KEY_NEED_UNLINK) {\n 859:\t\t\tif (!(lflags \u0026 KEY_LOOKUP_PARTIAL)) {\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 96345
							output: 495
							thoughts: 2728
						

Thoughts:
**Analysis of Keyring Indexing Implementation and KMSAN Applicability**

Okay, let's break this down. The code snippet involves a deep dive into keyring search implementation within the Linux kernel, specifically the new `rhashtable`-based indexing (`struct keyring_index`) replacing the old `assoc_array` approach. My primary concern here, as always, is correctness and security. The critical question is whether this change introduces any subtle memory safety issues, especially those only detectable by KMSAN.

My initial observations focus on the direct comparisons. The old `assoc_array` method had some serious complexity, especially in how it navigated nested keyrings. This new code simplifies the structure with a depth-first search strategy, making it much more readable. This alone is a big win for maintainability and reduces the risk of logic errors. The `search_keyring_tree` function, now recursively traversing keyrings, is a good example.

The main areas of concern revolve around uninitialized memory reads, especially those that could lead to information leaks or crashes. I carefully examine the flow, looking for instances where data structures are allocated but not fully initialized, or where uninitialized variables are used in conditional branches or copies to user space.

Specifically, I'm analyzing the `keyring_search_context`, `keyring_index`, `keyring_link`, and associated structures. The crucial parts are `search_keyring` and `search_keyring_tree`. I go through the logic and confirm that:

1.  **User-space copies:** `keyring_read` is the *only* place data is copied out. It copies key serials into a buffer, but I verified there's no struct padding, no risk of uninitialized bytes, and that only initialized entries are copied.
2.  **Dynamic allocations:** The `keyring_index` and `keyring_link` structures are allocated with `kzalloc_obj`, which *guarantees* zero-initialization. This includes the rhashtable, list heads, and all embedded fields. There's no risk here.
3.  **Stack variables:** Stack variables such as `struct keyring_edit edit = {}` are explicitly initialized with `{}` before usage in relevant files (e.g. `key.c`).
4.  **Field initialization**: `keyring_index_key` fields are initialized during `key_alloc()` (which uses `kmem_cache_zalloc`).
5.  **Conditional logic**: The control flow looks sound. No conditional branches depend on potentially uninitialized variables.

Given all this, I'm confident there are no KMSAN-specific risks. The code *does* have potential concurrency and locking-related bugs (e.g., RCU, locking order, use-after-free, missing locks), but those are well within the scope of KASAN, LOCKDEP, and PROVE\_RCU. I can see no path where the code could read uninitialized memory and exhibit that behavior without being detected by the standard debugging tools, so `NeedsKMSAN=false`.



56/3 2026/11/13 05:18 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series replaces the associative array (`assoc_array`) data structure in the keyring subsystem with a simpler `rhashtable` and `list_head` based index (`struct keyring_index` and `struct keyring_link`), while also removing the unused `assoc_array` library code and documentation.\n\nKMSAN vs KASAN Applicability Analysis:\n1. Kernel-to-User Copy / Info-Leaks: In `keyring_read()`, keys in the keyring are iterated over and their serial numbers (`key_serial_t`, 32-bit integers) are written sequentially into the destination buffer up to `links-\u003enr * sizeof(key_serial_t)`. `keyctl_read_key()` only copies the exact number of written bytes (`ret`) to user space via `copy_to_user()`. There are no padding gaps or uninitialized bytes in this data stream.\n2. Dynamic Allocations: All newly introduced structures (`struct keyring_index`, `struct keyring_link`) are allocated using `kzalloc_obj()`, guaranteeing zero-initialization of all fields and pointers.\n3. Stack Allocations: Instances of `struct keyring_edit` used to track transaction links are zero-initialized with `{}` across all callers (`key_instantiate_and_link`, `key_reject_and_link`, `key_link`, `key_move`, `construct_alloc_key`, etc.).\n4. Data Structures and Hashing: `struct keyring_index_key` layout changes (simplification from the union with machine-word packing to `u32 hash` and `unsigned int desc_len`) remove padding rather than introducing any uninitialized gaps. Hashing via SipHash operates strictly over initialized type/tag pointers and string descriptions.\n5. Other bug classes: Any risks in this patch series involve concurrency, RCU dereferencing/freeing (`call_rcu`), list/rhashtable operations, key reference counting, or locking (`keyring-\u003esem`), which are comprehensively detected by KASAN, PROVE_RCU, and LOCKDEP.\n\nTherefore, this patch series does not introduce or expose uninitialized memory risks, and a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series replaces the associative array (`assoc_array`) data structure in the keyring subsystem with a simpler `rhashtable` and `list_head` based index (`struct keyring_index` and `struct keyring_link`), while also removing the unused `assoc_array` library code and documentation.\n\nKMSAN vs KASAN Applicability Analysis:\n1. Kernel-to-User Copy / Info-Leaks: In `keyring_read()`, keys in the keyring are iterated over and their serial numbers (`key_serial_t`, 32-bit integers) are written sequentially into the destination buffer up to `links-\u003enr * sizeof(key_serial_t)`. `keyctl_read_key()` only copies the exact number of written bytes (`ret`) to user space via `copy_to_user()`. There are no padding gaps or uninitialized bytes in this data stream.\n2. Dynamic Allocations: All newly introduced structures (`struct keyring_index`, `struct keyring_link`) are allocated using `kzalloc_obj()`, guaranteeing zero-initialization of all fields and pointers.\n3. Stack Allocations: Instances of `struct keyring_edit` used to track transaction links are zero-initialized with `{}` across all callers (`key_instantiate_and_link`, `key_reject_and_link`, `key_link`, `key_move`, `construct_alloc_key`, etc.).\n4. Data Structures and Hashing: `struct keyring_index_key` layout changes (simplification from the union with machine-word packing to `u32 hash` and `unsigned int desc_len`) remove padding rather than introducing any uninitialized gaps. Hashing via SipHash operates strictly over initialized type/tag pointers and string descriptions.\n5. Other bug classes: Any risks in this patch series involve concurrency, RCU dereferencing/freeing (`call_rcu`), list/rhashtable operations, key reference counting, or locking (`keyring-\u003esem`), which are comprehensively detected by KASAN, PROVE_RCU, and LOCKDEP.\n\nTherefore, this patch series does not introduce or expose uninitialized memory risks, and 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)