Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-or-later
0002 /* Generic associative array implementation.
0003  *
0004  * See Documentation/core-api/assoc_array.rst for information.
0005  *
0006  * Copyright (C) 2013 Red Hat, Inc. All Rights Reserved.
0007  * Written by David Howells (dhowells@redhat.com)
0008  */
0009 //#define DEBUG
0010 #include <linux/rcupdate.h>
0011 #include <linux/slab.h>
0012 #include <linux/err.h>
0013 #include <linux/assoc_array_priv.h>
0014 
0015 /*
0016  * Iterate over an associative array.  The caller must hold the RCU read lock
0017  * or better.
0018  */
0019 static int assoc_array_subtree_iterate(const struct assoc_array_ptr *root,
0020                        const struct assoc_array_ptr *stop,
0021                        int (*iterator)(const void *leaf,
0022                                void *iterator_data),
0023                        void *iterator_data)
0024 {
0025     const struct assoc_array_shortcut *shortcut;
0026     const struct assoc_array_node *node;
0027     const struct assoc_array_ptr *cursor, *ptr, *parent;
0028     unsigned long has_meta;
0029     int slot, ret;
0030 
0031     cursor = root;
0032 
0033 begin_node:
0034     if (assoc_array_ptr_is_shortcut(cursor)) {
0035         /* Descend through a shortcut */
0036         shortcut = assoc_array_ptr_to_shortcut(cursor);
0037         cursor = READ_ONCE(shortcut->next_node); /* Address dependency. */
0038     }
0039 
0040     node = assoc_array_ptr_to_node(cursor);
0041     slot = 0;
0042 
0043     /* We perform two passes of each node.
0044      *
0045      * The first pass does all the leaves in this node.  This means we
0046      * don't miss any leaves if the node is split up by insertion whilst
0047      * we're iterating over the branches rooted here (we may, however, see
0048      * some leaves twice).
0049      */
0050     has_meta = 0;
0051     for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
0052         ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
0053         has_meta |= (unsigned long)ptr;
0054         if (ptr && assoc_array_ptr_is_leaf(ptr)) {
0055             /* We need a barrier between the read of the pointer,
0056              * which is supplied by the above READ_ONCE().
0057              */
0058             /* Invoke the callback */
0059             ret = iterator(assoc_array_ptr_to_leaf(ptr),
0060                        iterator_data);
0061             if (ret)
0062                 return ret;
0063         }
0064     }
0065 
0066     /* The second pass attends to all the metadata pointers.  If we follow
0067      * one of these we may find that we don't come back here, but rather go
0068      * back to a replacement node with the leaves in a different layout.
0069      *
0070      * We are guaranteed to make progress, however, as the slot number for
0071      * a particular portion of the key space cannot change - and we
0072      * continue at the back pointer + 1.
0073      */
0074     if (!(has_meta & ASSOC_ARRAY_PTR_META_TYPE))
0075         goto finished_node;
0076     slot = 0;
0077 
0078 continue_node:
0079     node = assoc_array_ptr_to_node(cursor);
0080     for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
0081         ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
0082         if (assoc_array_ptr_is_meta(ptr)) {
0083             cursor = ptr;
0084             goto begin_node;
0085         }
0086     }
0087 
0088 finished_node:
0089     /* Move up to the parent (may need to skip back over a shortcut) */
0090     parent = READ_ONCE(node->back_pointer); /* Address dependency. */
0091     slot = node->parent_slot;
0092     if (parent == stop)
0093         return 0;
0094 
0095     if (assoc_array_ptr_is_shortcut(parent)) {
0096         shortcut = assoc_array_ptr_to_shortcut(parent);
0097         cursor = parent;
0098         parent = READ_ONCE(shortcut->back_pointer); /* Address dependency. */
0099         slot = shortcut->parent_slot;
0100         if (parent == stop)
0101             return 0;
0102     }
0103 
0104     /* Ascend to next slot in parent node */
0105     cursor = parent;
0106     slot++;
0107     goto continue_node;
0108 }
0109 
0110 /**
0111  * assoc_array_iterate - Pass all objects in the array to a callback
0112  * @array: The array to iterate over.
0113  * @iterator: The callback function.
0114  * @iterator_data: Private data for the callback function.
0115  *
0116  * Iterate over all the objects in an associative array.  Each one will be
0117  * presented to the iterator function.
0118  *
0119  * If the array is being modified concurrently with the iteration then it is
0120  * possible that some objects in the array will be passed to the iterator
0121  * callback more than once - though every object should be passed at least
0122  * once.  If this is undesirable then the caller must lock against modification
0123  * for the duration of this function.
0124  *
0125  * The function will return 0 if no objects were in the array or else it will
0126  * return the result of the last iterator function called.  Iteration stops
0127  * immediately if any call to the iteration function results in a non-zero
0128  * return.
0129  *
0130  * The caller should hold the RCU read lock or better if concurrent
0131  * modification is possible.
0132  */
0133 int assoc_array_iterate(const struct assoc_array *array,
0134             int (*iterator)(const void *object,
0135                     void *iterator_data),
0136             void *iterator_data)
0137 {
0138     struct assoc_array_ptr *root = READ_ONCE(array->root); /* Address dependency. */
0139 
0140     if (!root)
0141         return 0;
0142     return assoc_array_subtree_iterate(root, NULL, iterator, iterator_data);
0143 }
0144 
0145 enum assoc_array_walk_status {
0146     assoc_array_walk_tree_empty,
0147     assoc_array_walk_found_terminal_node,
0148     assoc_array_walk_found_wrong_shortcut,
0149 };
0150 
0151 struct assoc_array_walk_result {
0152     struct {
0153         struct assoc_array_node *node;  /* Node in which leaf might be found */
0154         int     level;
0155         int     slot;
0156     } terminal_node;
0157     struct {
0158         struct assoc_array_shortcut *shortcut;
0159         int     level;
0160         int     sc_level;
0161         unsigned long   sc_segments;
0162         unsigned long   dissimilarity;
0163     } wrong_shortcut;
0164 };
0165 
0166 /*
0167  * Navigate through the internal tree looking for the closest node to the key.
0168  */
0169 static enum assoc_array_walk_status
0170 assoc_array_walk(const struct assoc_array *array,
0171          const struct assoc_array_ops *ops,
0172          const void *index_key,
0173          struct assoc_array_walk_result *result)
0174 {
0175     struct assoc_array_shortcut *shortcut;
0176     struct assoc_array_node *node;
0177     struct assoc_array_ptr *cursor, *ptr;
0178     unsigned long sc_segments, dissimilarity;
0179     unsigned long segments;
0180     int level, sc_level, next_sc_level;
0181     int slot;
0182 
0183     pr_devel("-->%s()\n", __func__);
0184 
0185     cursor = READ_ONCE(array->root);  /* Address dependency. */
0186     if (!cursor)
0187         return assoc_array_walk_tree_empty;
0188 
0189     level = 0;
0190 
0191     /* Use segments from the key for the new leaf to navigate through the
0192      * internal tree, skipping through nodes and shortcuts that are on
0193      * route to the destination.  Eventually we'll come to a slot that is
0194      * either empty or contains a leaf at which point we've found a node in
0195      * which the leaf we're looking for might be found or into which it
0196      * should be inserted.
0197      */
0198 jumped:
0199     segments = ops->get_key_chunk(index_key, level);
0200     pr_devel("segments[%d]: %lx\n", level, segments);
0201 
0202     if (assoc_array_ptr_is_shortcut(cursor))
0203         goto follow_shortcut;
0204 
0205 consider_node:
0206     node = assoc_array_ptr_to_node(cursor);
0207     slot = segments >> (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
0208     slot &= ASSOC_ARRAY_FAN_MASK;
0209     ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
0210 
0211     pr_devel("consider slot %x [ix=%d type=%lu]\n",
0212          slot, level, (unsigned long)ptr & 3);
0213 
0214     if (!assoc_array_ptr_is_meta(ptr)) {
0215         /* The node doesn't have a node/shortcut pointer in the slot
0216          * corresponding to the index key that we have to follow.
0217          */
0218         result->terminal_node.node = node;
0219         result->terminal_node.level = level;
0220         result->terminal_node.slot = slot;
0221         pr_devel("<--%s() = terminal_node\n", __func__);
0222         return assoc_array_walk_found_terminal_node;
0223     }
0224 
0225     if (assoc_array_ptr_is_node(ptr)) {
0226         /* There is a pointer to a node in the slot corresponding to
0227          * this index key segment, so we need to follow it.
0228          */
0229         cursor = ptr;
0230         level += ASSOC_ARRAY_LEVEL_STEP;
0231         if ((level & ASSOC_ARRAY_KEY_CHUNK_MASK) != 0)
0232             goto consider_node;
0233         goto jumped;
0234     }
0235 
0236     /* There is a shortcut in the slot corresponding to the index key
0237      * segment.  We follow the shortcut if its partial index key matches
0238      * this leaf's.  Otherwise we need to split the shortcut.
0239      */
0240     cursor = ptr;
0241 follow_shortcut:
0242     shortcut = assoc_array_ptr_to_shortcut(cursor);
0243     pr_devel("shortcut to %d\n", shortcut->skip_to_level);
0244     sc_level = level + ASSOC_ARRAY_LEVEL_STEP;
0245     BUG_ON(sc_level > shortcut->skip_to_level);
0246 
0247     do {
0248         /* Check the leaf against the shortcut's index key a word at a
0249          * time, trimming the final word (the shortcut stores the index
0250          * key completely from the root to the shortcut's target).
0251          */
0252         if ((sc_level & ASSOC_ARRAY_KEY_CHUNK_MASK) == 0)
0253             segments = ops->get_key_chunk(index_key, sc_level);
0254 
0255         sc_segments = shortcut->index_key[sc_level >> ASSOC_ARRAY_KEY_CHUNK_SHIFT];
0256         dissimilarity = segments ^ sc_segments;
0257 
0258         if (round_up(sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE) > shortcut->skip_to_level) {
0259             /* Trim segments that are beyond the shortcut */
0260             int shift = shortcut->skip_to_level & ASSOC_ARRAY_KEY_CHUNK_MASK;
0261             dissimilarity &= ~(ULONG_MAX << shift);
0262             next_sc_level = shortcut->skip_to_level;
0263         } else {
0264             next_sc_level = sc_level + ASSOC_ARRAY_KEY_CHUNK_SIZE;
0265             next_sc_level = round_down(next_sc_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
0266         }
0267 
0268         if (dissimilarity != 0) {
0269             /* This shortcut points elsewhere */
0270             result->wrong_shortcut.shortcut = shortcut;
0271             result->wrong_shortcut.level = level;
0272             result->wrong_shortcut.sc_level = sc_level;
0273             result->wrong_shortcut.sc_segments = sc_segments;
0274             result->wrong_shortcut.dissimilarity = dissimilarity;
0275             return assoc_array_walk_found_wrong_shortcut;
0276         }
0277 
0278         sc_level = next_sc_level;
0279     } while (sc_level < shortcut->skip_to_level);
0280 
0281     /* The shortcut matches the leaf's index to this point. */
0282     cursor = READ_ONCE(shortcut->next_node); /* Address dependency. */
0283     if (((level ^ sc_level) & ~ASSOC_ARRAY_KEY_CHUNK_MASK) != 0) {
0284         level = sc_level;
0285         goto jumped;
0286     } else {
0287         level = sc_level;
0288         goto consider_node;
0289     }
0290 }
0291 
0292 /**
0293  * assoc_array_find - Find an object by index key
0294  * @array: The associative array to search.
0295  * @ops: The operations to use.
0296  * @index_key: The key to the object.
0297  *
0298  * Find an object in an associative array by walking through the internal tree
0299  * to the node that should contain the object and then searching the leaves
0300  * there.  NULL is returned if the requested object was not found in the array.
0301  *
0302  * The caller must hold the RCU read lock or better.
0303  */
0304 void *assoc_array_find(const struct assoc_array *array,
0305                const struct assoc_array_ops *ops,
0306                const void *index_key)
0307 {
0308     struct assoc_array_walk_result result;
0309     const struct assoc_array_node *node;
0310     const struct assoc_array_ptr *ptr;
0311     const void *leaf;
0312     int slot;
0313 
0314     if (assoc_array_walk(array, ops, index_key, &result) !=
0315         assoc_array_walk_found_terminal_node)
0316         return NULL;
0317 
0318     node = result.terminal_node.node;
0319 
0320     /* If the target key is available to us, it's has to be pointed to by
0321      * the terminal node.
0322      */
0323     for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
0324         ptr = READ_ONCE(node->slots[slot]); /* Address dependency. */
0325         if (ptr && assoc_array_ptr_is_leaf(ptr)) {
0326             /* We need a barrier between the read of the pointer
0327              * and dereferencing the pointer - but only if we are
0328              * actually going to dereference it.
0329              */
0330             leaf = assoc_array_ptr_to_leaf(ptr);
0331             if (ops->compare_object(leaf, index_key))
0332                 return (void *)leaf;
0333         }
0334     }
0335 
0336     return NULL;
0337 }
0338 
0339 /*
0340  * Destructively iterate over an associative array.  The caller must prevent
0341  * other simultaneous accesses.
0342  */
0343 static void assoc_array_destroy_subtree(struct assoc_array_ptr *root,
0344                     const struct assoc_array_ops *ops)
0345 {
0346     struct assoc_array_shortcut *shortcut;
0347     struct assoc_array_node *node;
0348     struct assoc_array_ptr *cursor, *parent = NULL;
0349     int slot = -1;
0350 
0351     pr_devel("-->%s()\n", __func__);
0352 
0353     cursor = root;
0354     if (!cursor) {
0355         pr_devel("empty\n");
0356         return;
0357     }
0358 
0359 move_to_meta:
0360     if (assoc_array_ptr_is_shortcut(cursor)) {
0361         /* Descend through a shortcut */
0362         pr_devel("[%d] shortcut\n", slot);
0363         BUG_ON(!assoc_array_ptr_is_shortcut(cursor));
0364         shortcut = assoc_array_ptr_to_shortcut(cursor);
0365         BUG_ON(shortcut->back_pointer != parent);
0366         BUG_ON(slot != -1 && shortcut->parent_slot != slot);
0367         parent = cursor;
0368         cursor = shortcut->next_node;
0369         slot = -1;
0370         BUG_ON(!assoc_array_ptr_is_node(cursor));
0371     }
0372 
0373     pr_devel("[%d] node\n", slot);
0374     node = assoc_array_ptr_to_node(cursor);
0375     BUG_ON(node->back_pointer != parent);
0376     BUG_ON(slot != -1 && node->parent_slot != slot);
0377     slot = 0;
0378 
0379 continue_node:
0380     pr_devel("Node %p [back=%p]\n", node, node->back_pointer);
0381     for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
0382         struct assoc_array_ptr *ptr = node->slots[slot];
0383         if (!ptr)
0384             continue;
0385         if (assoc_array_ptr_is_meta(ptr)) {
0386             parent = cursor;
0387             cursor = ptr;
0388             goto move_to_meta;
0389         }
0390 
0391         if (ops) {
0392             pr_devel("[%d] free leaf\n", slot);
0393             ops->free_object(assoc_array_ptr_to_leaf(ptr));
0394         }
0395     }
0396 
0397     parent = node->back_pointer;
0398     slot = node->parent_slot;
0399     pr_devel("free node\n");
0400     kfree(node);
0401     if (!parent)
0402         return; /* Done */
0403 
0404     /* Move back up to the parent (may need to free a shortcut on
0405      * the way up) */
0406     if (assoc_array_ptr_is_shortcut(parent)) {
0407         shortcut = assoc_array_ptr_to_shortcut(parent);
0408         BUG_ON(shortcut->next_node != cursor);
0409         cursor = parent;
0410         parent = shortcut->back_pointer;
0411         slot = shortcut->parent_slot;
0412         pr_devel("free shortcut\n");
0413         kfree(shortcut);
0414         if (!parent)
0415             return;
0416 
0417         BUG_ON(!assoc_array_ptr_is_node(parent));
0418     }
0419 
0420     /* Ascend to next slot in parent node */
0421     pr_devel("ascend to %p[%d]\n", parent, slot);
0422     cursor = parent;
0423     node = assoc_array_ptr_to_node(cursor);
0424     slot++;
0425     goto continue_node;
0426 }
0427 
0428 /**
0429  * assoc_array_destroy - Destroy an associative array
0430  * @array: The array to destroy.
0431  * @ops: The operations to use.
0432  *
0433  * Discard all metadata and free all objects in an associative array.  The
0434  * array will be empty and ready to use again upon completion.  This function
0435  * cannot fail.
0436  *
0437  * The caller must prevent all other accesses whilst this takes place as no
0438  * attempt is made to adjust pointers gracefully to permit RCU readlock-holding
0439  * accesses to continue.  On the other hand, no memory allocation is required.
0440  */
0441 void assoc_array_destroy(struct assoc_array *array,
0442              const struct assoc_array_ops *ops)
0443 {
0444     assoc_array_destroy_subtree(array->root, ops);
0445     array->root = NULL;
0446 }
0447 
0448 /*
0449  * Handle insertion into an empty tree.
0450  */
0451 static bool assoc_array_insert_in_empty_tree(struct assoc_array_edit *edit)
0452 {
0453     struct assoc_array_node *new_n0;
0454 
0455     pr_devel("-->%s()\n", __func__);
0456 
0457     new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
0458     if (!new_n0)
0459         return false;
0460 
0461     edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
0462     edit->leaf_p = &new_n0->slots[0];
0463     edit->adjust_count_on = new_n0;
0464     edit->set[0].ptr = &edit->array->root;
0465     edit->set[0].to = assoc_array_node_to_ptr(new_n0);
0466 
0467     pr_devel("<--%s() = ok [no root]\n", __func__);
0468     return true;
0469 }
0470 
0471 /*
0472  * Handle insertion into a terminal node.
0473  */
0474 static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit,
0475                           const struct assoc_array_ops *ops,
0476                           const void *index_key,
0477                           struct assoc_array_walk_result *result)
0478 {
0479     struct assoc_array_shortcut *shortcut, *new_s0;
0480     struct assoc_array_node *node, *new_n0, *new_n1, *side;
0481     struct assoc_array_ptr *ptr;
0482     unsigned long dissimilarity, base_seg, blank;
0483     size_t keylen;
0484     bool have_meta;
0485     int level, diff;
0486     int slot, next_slot, free_slot, i, j;
0487 
0488     node    = result->terminal_node.node;
0489     level   = result->terminal_node.level;
0490     edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot;
0491 
0492     pr_devel("-->%s()\n", __func__);
0493 
0494     /* We arrived at a node which doesn't have an onward node or shortcut
0495      * pointer that we have to follow.  This means that (a) the leaf we
0496      * want must go here (either by insertion or replacement) or (b) we
0497      * need to split this node and insert in one of the fragments.
0498      */
0499     free_slot = -1;
0500 
0501     /* Firstly, we have to check the leaves in this node to see if there's
0502      * a matching one we should replace in place.
0503      */
0504     for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
0505         ptr = node->slots[i];
0506         if (!ptr) {
0507             free_slot = i;
0508             continue;
0509         }
0510         if (assoc_array_ptr_is_leaf(ptr) &&
0511             ops->compare_object(assoc_array_ptr_to_leaf(ptr),
0512                     index_key)) {
0513             pr_devel("replace in slot %d\n", i);
0514             edit->leaf_p = &node->slots[i];
0515             edit->dead_leaf = node->slots[i];
0516             pr_devel("<--%s() = ok [replace]\n", __func__);
0517             return true;
0518         }
0519     }
0520 
0521     /* If there is a free slot in this node then we can just insert the
0522      * leaf here.
0523      */
0524     if (free_slot >= 0) {
0525         pr_devel("insert in free slot %d\n", free_slot);
0526         edit->leaf_p = &node->slots[free_slot];
0527         edit->adjust_count_on = node;
0528         pr_devel("<--%s() = ok [insert]\n", __func__);
0529         return true;
0530     }
0531 
0532     /* The node has no spare slots - so we're either going to have to split
0533      * it or insert another node before it.
0534      *
0535      * Whatever, we're going to need at least two new nodes - so allocate
0536      * those now.  We may also need a new shortcut, but we deal with that
0537      * when we need it.
0538      */
0539     new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
0540     if (!new_n0)
0541         return false;
0542     edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
0543     new_n1 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
0544     if (!new_n1)
0545         return false;
0546     edit->new_meta[1] = assoc_array_node_to_ptr(new_n1);
0547 
0548     /* We need to find out how similar the leaves are. */
0549     pr_devel("no spare slots\n");
0550     have_meta = false;
0551     for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
0552         ptr = node->slots[i];
0553         if (assoc_array_ptr_is_meta(ptr)) {
0554             edit->segment_cache[i] = 0xff;
0555             have_meta = true;
0556             continue;
0557         }
0558         base_seg = ops->get_object_key_chunk(
0559             assoc_array_ptr_to_leaf(ptr), level);
0560         base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
0561         edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
0562     }
0563 
0564     if (have_meta) {
0565         pr_devel("have meta\n");
0566         goto split_node;
0567     }
0568 
0569     /* The node contains only leaves */
0570     dissimilarity = 0;
0571     base_seg = edit->segment_cache[0];
0572     for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++)
0573         dissimilarity |= edit->segment_cache[i] ^ base_seg;
0574 
0575     pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity);
0576 
0577     if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) {
0578         /* The old leaves all cluster in the same slot.  We will need
0579          * to insert a shortcut if the new node wants to cluster with them.
0580          */
0581         if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0)
0582             goto all_leaves_cluster_together;
0583 
0584         /* Otherwise all the old leaves cluster in the same slot, but
0585          * the new leaf wants to go into a different slot - so we
0586          * create a new node (n0) to hold the new leaf and a pointer to
0587          * a new node (n1) holding all the old leaves.
0588          *
0589          * This can be done by falling through to the node splitting
0590          * path.
0591          */
0592         pr_devel("present leaves cluster but not new leaf\n");
0593     }
0594 
0595 split_node:
0596     pr_devel("split node\n");
0597 
0598     /* We need to split the current node.  The node must contain anything
0599      * from a single leaf (in the one leaf case, this leaf will cluster
0600      * with the new leaf) and the rest meta-pointers, to all leaves, some
0601      * of which may cluster.
0602      *
0603      * It won't contain the case in which all the current leaves plus the
0604      * new leaves want to cluster in the same slot.
0605      *
0606      * We need to expel at least two leaves out of a set consisting of the
0607      * leaves in the node and the new leaf.  The current meta pointers can
0608      * just be copied as they shouldn't cluster with any of the leaves.
0609      *
0610      * We need a new node (n0) to replace the current one and a new node to
0611      * take the expelled nodes (n1).
0612      */
0613     edit->set[0].to = assoc_array_node_to_ptr(new_n0);
0614     new_n0->back_pointer = node->back_pointer;
0615     new_n0->parent_slot = node->parent_slot;
0616     new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
0617     new_n1->parent_slot = -1; /* Need to calculate this */
0618 
0619 do_split_node:
0620     pr_devel("do_split_node\n");
0621 
0622     new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
0623     new_n1->nr_leaves_on_branch = 0;
0624 
0625     /* Begin by finding two matching leaves.  There have to be at least two
0626      * that match - even if there are meta pointers - because any leaf that
0627      * would match a slot with a meta pointer in it must be somewhere
0628      * behind that meta pointer and cannot be here.  Further, given N
0629      * remaining leaf slots, we now have N+1 leaves to go in them.
0630      */
0631     for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
0632         slot = edit->segment_cache[i];
0633         if (slot != 0xff)
0634             for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++)
0635                 if (edit->segment_cache[j] == slot)
0636                     goto found_slot_for_multiple_occupancy;
0637     }
0638 found_slot_for_multiple_occupancy:
0639     pr_devel("same slot: %x %x [%02x]\n", i, j, slot);
0640     BUG_ON(i >= ASSOC_ARRAY_FAN_OUT);
0641     BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1);
0642     BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT);
0643 
0644     new_n1->parent_slot = slot;
0645 
0646     /* Metadata pointers cannot change slot */
0647     for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
0648         if (assoc_array_ptr_is_meta(node->slots[i]))
0649             new_n0->slots[i] = node->slots[i];
0650         else
0651             new_n0->slots[i] = NULL;
0652     BUG_ON(new_n0->slots[slot] != NULL);
0653     new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1);
0654 
0655     /* Filter the leaf pointers between the new nodes */
0656     free_slot = -1;
0657     next_slot = 0;
0658     for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
0659         if (assoc_array_ptr_is_meta(node->slots[i]))
0660             continue;
0661         if (edit->segment_cache[i] == slot) {
0662             new_n1->slots[next_slot++] = node->slots[i];
0663             new_n1->nr_leaves_on_branch++;
0664         } else {
0665             do {
0666                 free_slot++;
0667             } while (new_n0->slots[free_slot] != NULL);
0668             new_n0->slots[free_slot] = node->slots[i];
0669         }
0670     }
0671 
0672     pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot);
0673 
0674     if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) {
0675         do {
0676             free_slot++;
0677         } while (new_n0->slots[free_slot] != NULL);
0678         edit->leaf_p = &new_n0->slots[free_slot];
0679         edit->adjust_count_on = new_n0;
0680     } else {
0681         edit->leaf_p = &new_n1->slots[next_slot++];
0682         edit->adjust_count_on = new_n1;
0683     }
0684 
0685     BUG_ON(next_slot <= 1);
0686 
0687     edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0);
0688     for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
0689         if (edit->segment_cache[i] == 0xff) {
0690             ptr = node->slots[i];
0691             BUG_ON(assoc_array_ptr_is_leaf(ptr));
0692             if (assoc_array_ptr_is_node(ptr)) {
0693                 side = assoc_array_ptr_to_node(ptr);
0694                 edit->set_backpointers[i] = &side->back_pointer;
0695             } else {
0696                 shortcut = assoc_array_ptr_to_shortcut(ptr);
0697                 edit->set_backpointers[i] = &shortcut->back_pointer;
0698             }
0699         }
0700     }
0701 
0702     ptr = node->back_pointer;
0703     if (!ptr)
0704         edit->set[0].ptr = &edit->array->root;
0705     else if (assoc_array_ptr_is_node(ptr))
0706         edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot];
0707     else
0708         edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node;
0709     edit->excised_meta[0] = assoc_array_node_to_ptr(node);
0710     pr_devel("<--%s() = ok [split node]\n", __func__);
0711     return true;
0712 
0713 all_leaves_cluster_together:
0714     /* All the leaves, new and old, want to cluster together in this node
0715      * in the same slot, so we have to replace this node with a shortcut to
0716      * skip over the identical parts of the key and then place a pair of
0717      * nodes, one inside the other, at the end of the shortcut and
0718      * distribute the keys between them.
0719      *
0720      * Firstly we need to work out where the leaves start diverging as a
0721      * bit position into their keys so that we know how big the shortcut
0722      * needs to be.
0723      *
0724      * We only need to make a single pass of N of the N+1 leaves because if
0725      * any keys differ between themselves at bit X then at least one of
0726      * them must also differ with the base key at bit X or before.
0727      */
0728     pr_devel("all leaves cluster together\n");
0729     diff = INT_MAX;
0730     for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
0731         int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]),
0732                       index_key);
0733         if (x < diff) {
0734             BUG_ON(x < 0);
0735             diff = x;
0736         }
0737     }
0738     BUG_ON(diff == INT_MAX);
0739     BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP);
0740 
0741     keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
0742     keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
0743 
0744     new_s0 = kzalloc(struct_size(new_s0, index_key, keylen), GFP_KERNEL);
0745     if (!new_s0)
0746         return false;
0747     edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0);
0748 
0749     edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
0750     new_s0->back_pointer = node->back_pointer;
0751     new_s0->parent_slot = node->parent_slot;
0752     new_s0->next_node = assoc_array_node_to_ptr(new_n0);
0753     new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
0754     new_n0->parent_slot = 0;
0755     new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
0756     new_n1->parent_slot = -1; /* Need to calculate this */
0757 
0758     new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK;
0759     pr_devel("skip_to_level = %d [diff %d]\n", level, diff);
0760     BUG_ON(level <= 0);
0761 
0762     for (i = 0; i < keylen; i++)
0763         new_s0->index_key[i] =
0764             ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE);
0765 
0766     if (level & ASSOC_ARRAY_KEY_CHUNK_MASK) {
0767         blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
0768         pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank);
0769         new_s0->index_key[keylen - 1] &= ~blank;
0770     }
0771 
0772     /* This now reduces to a node splitting exercise for which we'll need
0773      * to regenerate the disparity table.
0774      */
0775     for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
0776         ptr = node->slots[i];
0777         base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr),
0778                              level);
0779         base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
0780         edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
0781     }
0782 
0783     base_seg = ops->get_key_chunk(index_key, level);
0784     base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
0785     edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK;
0786     goto do_split_node;
0787 }
0788 
0789 /*
0790  * Handle insertion into the middle of a shortcut.
0791  */
0792 static bool assoc_array_insert_mid_shortcut(struct assoc_array_edit *edit,
0793                         const struct assoc_array_ops *ops,
0794                         struct assoc_array_walk_result *result)
0795 {
0796     struct assoc_array_shortcut *shortcut, *new_s0, *new_s1;
0797     struct assoc_array_node *node, *new_n0, *side;
0798     unsigned long sc_segments, dissimilarity, blank;
0799     size_t keylen;
0800     int level, sc_level, diff;
0801     int sc_slot;
0802 
0803     shortcut    = result->wrong_shortcut.shortcut;
0804     level       = result->wrong_shortcut.level;
0805     sc_level    = result->wrong_shortcut.sc_level;
0806     sc_segments = result->wrong_shortcut.sc_segments;
0807     dissimilarity   = result->wrong_shortcut.dissimilarity;
0808 
0809     pr_devel("-->%s(ix=%d dis=%lx scix=%d)\n",
0810          __func__, level, dissimilarity, sc_level);
0811 
0812     /* We need to split a shortcut and insert a node between the two
0813      * pieces.  Zero-length pieces will be dispensed with entirely.
0814      *
0815      * First of all, we need to find out in which level the first
0816      * difference was.
0817      */
0818     diff = __ffs(dissimilarity);
0819     diff &= ~ASSOC_ARRAY_LEVEL_STEP_MASK;
0820     diff += sc_level & ~ASSOC_ARRAY_KEY_CHUNK_MASK;
0821     pr_devel("diff=%d\n", diff);
0822 
0823     if (!shortcut->back_pointer) {
0824         edit->set[0].ptr = &edit->array->root;
0825     } else if (assoc_array_ptr_is_node(shortcut->back_pointer)) {
0826         node = assoc_array_ptr_to_node(shortcut->back_pointer);
0827         edit->set[0].ptr = &node->slots[shortcut->parent_slot];
0828     } else {
0829         BUG();
0830     }
0831 
0832     edit->excised_meta[0] = assoc_array_shortcut_to_ptr(shortcut);
0833 
0834     /* Create a new node now since we're going to need it anyway */
0835     new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
0836     if (!new_n0)
0837         return false;
0838     edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
0839     edit->adjust_count_on = new_n0;
0840 
0841     /* Insert a new shortcut before the new node if this segment isn't of
0842      * zero length - otherwise we just connect the new node directly to the
0843      * parent.
0844      */
0845     level += ASSOC_ARRAY_LEVEL_STEP;
0846     if (diff > level) {
0847         pr_devel("pre-shortcut %d...%d\n", level, diff);
0848         keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
0849         keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
0850 
0851         new_s0 = kzalloc(struct_size(new_s0, index_key, keylen),
0852                  GFP_KERNEL);
0853         if (!new_s0)
0854             return false;
0855         edit->new_meta[1] = assoc_array_shortcut_to_ptr(new_s0);
0856         edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
0857         new_s0->back_pointer = shortcut->back_pointer;
0858         new_s0->parent_slot = shortcut->parent_slot;
0859         new_s0->next_node = assoc_array_node_to_ptr(new_n0);
0860         new_s0->skip_to_level = diff;
0861 
0862         new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
0863         new_n0->parent_slot = 0;
0864 
0865         memcpy(new_s0->index_key, shortcut->index_key,
0866                flex_array_size(new_s0, index_key, keylen));
0867 
0868         blank = ULONG_MAX << (diff & ASSOC_ARRAY_KEY_CHUNK_MASK);
0869         pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, diff, blank);
0870         new_s0->index_key[keylen - 1] &= ~blank;
0871     } else {
0872         pr_devel("no pre-shortcut\n");
0873         edit->set[0].to = assoc_array_node_to_ptr(new_n0);
0874         new_n0->back_pointer = shortcut->back_pointer;
0875         new_n0->parent_slot = shortcut->parent_slot;
0876     }
0877 
0878     side = assoc_array_ptr_to_node(shortcut->next_node);
0879     new_n0->nr_leaves_on_branch = side->nr_leaves_on_branch;
0880 
0881     /* We need to know which slot in the new node is going to take a
0882      * metadata pointer.
0883      */
0884     sc_slot = sc_segments >> (diff & ASSOC_ARRAY_KEY_CHUNK_MASK);
0885     sc_slot &= ASSOC_ARRAY_FAN_MASK;
0886 
0887     pr_devel("new slot %lx >> %d -> %d\n",
0888          sc_segments, diff & ASSOC_ARRAY_KEY_CHUNK_MASK, sc_slot);
0889 
0890     /* Determine whether we need to follow the new node with a replacement
0891      * for the current shortcut.  We could in theory reuse the current
0892      * shortcut if its parent slot number doesn't change - but that's a
0893      * 1-in-16 chance so not worth expending the code upon.
0894      */
0895     level = diff + ASSOC_ARRAY_LEVEL_STEP;
0896     if (level < shortcut->skip_to_level) {
0897         pr_devel("post-shortcut %d...%d\n", level, shortcut->skip_to_level);
0898         keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
0899         keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
0900 
0901         new_s1 = kzalloc(struct_size(new_s1, index_key, keylen),
0902                  GFP_KERNEL);
0903         if (!new_s1)
0904             return false;
0905         edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s1);
0906 
0907         new_s1->back_pointer = assoc_array_node_to_ptr(new_n0);
0908         new_s1->parent_slot = sc_slot;
0909         new_s1->next_node = shortcut->next_node;
0910         new_s1->skip_to_level = shortcut->skip_to_level;
0911 
0912         new_n0->slots[sc_slot] = assoc_array_shortcut_to_ptr(new_s1);
0913 
0914         memcpy(new_s1->index_key, shortcut->index_key,
0915                flex_array_size(new_s1, index_key, keylen));
0916 
0917         edit->set[1].ptr = &side->back_pointer;
0918         edit->set[1].to = assoc_array_shortcut_to_ptr(new_s1);
0919     } else {
0920         pr_devel("no post-shortcut\n");
0921 
0922         /* We don't have to replace the pointed-to node as long as we
0923          * use memory barriers to make sure the parent slot number is
0924          * changed before the back pointer (the parent slot number is
0925          * irrelevant to the old parent shortcut).
0926          */
0927         new_n0->slots[sc_slot] = shortcut->next_node;
0928         edit->set_parent_slot[0].p = &side->parent_slot;
0929         edit->set_parent_slot[0].to = sc_slot;
0930         edit->set[1].ptr = &side->back_pointer;
0931         edit->set[1].to = assoc_array_node_to_ptr(new_n0);
0932     }
0933 
0934     /* Install the new leaf in a spare slot in the new node. */
0935     if (sc_slot == 0)
0936         edit->leaf_p = &new_n0->slots[1];
0937     else
0938         edit->leaf_p = &new_n0->slots[0];
0939 
0940     pr_devel("<--%s() = ok [split shortcut]\n", __func__);
0941     return edit;
0942 }
0943 
0944 /**
0945  * assoc_array_insert - Script insertion of an object into an associative array
0946  * @array: The array to insert into.
0947  * @ops: The operations to use.
0948  * @index_key: The key to insert at.
0949  * @object: The object to insert.
0950  *
0951  * Precalculate and preallocate a script for the insertion or replacement of an
0952  * object in an associative array.  This results in an edit script that can
0953  * either be applied or cancelled.
0954  *
0955  * The function returns a pointer to an edit script or -ENOMEM.
0956  *
0957  * The caller should lock against other modifications and must continue to hold
0958  * the lock until assoc_array_apply_edit() has been called.
0959  *
0960  * Accesses to the tree may take place concurrently with this function,
0961  * provided they hold the RCU read lock.
0962  */
0963 struct assoc_array_edit *assoc_array_insert(struct assoc_array *array,
0964                         const struct assoc_array_ops *ops,
0965                         const void *index_key,
0966                         void *object)
0967 {
0968     struct assoc_array_walk_result result;
0969     struct assoc_array_edit *edit;
0970 
0971     pr_devel("-->%s()\n", __func__);
0972 
0973     /* The leaf pointer we're given must not have the bottom bit set as we
0974      * use those for type-marking the pointer.  NULL pointers are also not
0975      * allowed as they indicate an empty slot but we have to allow them
0976      * here as they can be updated later.
0977      */
0978     BUG_ON(assoc_array_ptr_is_meta(object));
0979 
0980     edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL);
0981     if (!edit)
0982         return ERR_PTR(-ENOMEM);
0983     edit->array = array;
0984     edit->ops = ops;
0985     edit->leaf = assoc_array_leaf_to_ptr(object);
0986     edit->adjust_count_by = 1;
0987 
0988     switch (assoc_array_walk(array, ops, index_key, &result)) {
0989     case assoc_array_walk_tree_empty:
0990         /* Allocate a root node if there isn't one yet */
0991         if (!assoc_array_insert_in_empty_tree(edit))
0992             goto enomem;
0993         return edit;
0994 
0995     case assoc_array_walk_found_terminal_node:
0996         /* We found a node that doesn't have a node/shortcut pointer in
0997          * the slot corresponding to the index key that we have to
0998          * follow.
0999          */
1000         if (!assoc_array_insert_into_terminal_node(edit, ops, index_key,
1001                                &result))
1002             goto enomem;
1003         return edit;
1004 
1005     case assoc_array_walk_found_wrong_shortcut:
1006         /* We found a shortcut that didn't match our key in a slot we
1007          * needed to follow.
1008          */
1009         if (!assoc_array_insert_mid_shortcut(edit, ops, &result))
1010             goto enomem;
1011         return edit;
1012     }
1013 
1014 enomem:
1015     /* Clean up after an out of memory error */
1016     pr_devel("enomem\n");
1017     assoc_array_cancel_edit(edit);
1018     return ERR_PTR(-ENOMEM);
1019 }
1020 
1021 /**
1022  * assoc_array_insert_set_object - Set the new object pointer in an edit script
1023  * @edit: The edit script to modify.
1024  * @object: The object pointer to set.
1025  *
1026  * Change the object to be inserted in an edit script.  The object pointed to
1027  * by the old object is not freed.  This must be done prior to applying the
1028  * script.
1029  */
1030 void assoc_array_insert_set_object(struct assoc_array_edit *edit, void *object)
1031 {
1032     BUG_ON(!object);
1033     edit->leaf = assoc_array_leaf_to_ptr(object);
1034 }
1035 
1036 struct assoc_array_delete_collapse_context {
1037     struct assoc_array_node *node;
1038     const void      *skip_leaf;
1039     int         slot;
1040 };
1041 
1042 /*
1043  * Subtree collapse to node iterator.
1044  */
1045 static int assoc_array_delete_collapse_iterator(const void *leaf,
1046                         void *iterator_data)
1047 {
1048     struct assoc_array_delete_collapse_context *collapse = iterator_data;
1049 
1050     if (leaf == collapse->skip_leaf)
1051         return 0;
1052 
1053     BUG_ON(collapse->slot >= ASSOC_ARRAY_FAN_OUT);
1054 
1055     collapse->node->slots[collapse->slot++] = assoc_array_leaf_to_ptr(leaf);
1056     return 0;
1057 }
1058 
1059 /**
1060  * assoc_array_delete - Script deletion of an object from an associative array
1061  * @array: The array to search.
1062  * @ops: The operations to use.
1063  * @index_key: The key to the object.
1064  *
1065  * Precalculate and preallocate a script for the deletion of an object from an
1066  * associative array.  This results in an edit script that can either be
1067  * applied or cancelled.
1068  *
1069  * The function returns a pointer to an edit script if the object was found,
1070  * NULL if the object was not found or -ENOMEM.
1071  *
1072  * The caller should lock against other modifications and must continue to hold
1073  * the lock until assoc_array_apply_edit() has been called.
1074  *
1075  * Accesses to the tree may take place concurrently with this function,
1076  * provided they hold the RCU read lock.
1077  */
1078 struct assoc_array_edit *assoc_array_delete(struct assoc_array *array,
1079                         const struct assoc_array_ops *ops,
1080                         const void *index_key)
1081 {
1082     struct assoc_array_delete_collapse_context collapse;
1083     struct assoc_array_walk_result result;
1084     struct assoc_array_node *node, *new_n0;
1085     struct assoc_array_edit *edit;
1086     struct assoc_array_ptr *ptr;
1087     bool has_meta;
1088     int slot, i;
1089 
1090     pr_devel("-->%s()\n", __func__);
1091 
1092     edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL);
1093     if (!edit)
1094         return ERR_PTR(-ENOMEM);
1095     edit->array = array;
1096     edit->ops = ops;
1097     edit->adjust_count_by = -1;
1098 
1099     switch (assoc_array_walk(array, ops, index_key, &result)) {
1100     case assoc_array_walk_found_terminal_node:
1101         /* We found a node that should contain the leaf we've been
1102          * asked to remove - *if* it's in the tree.
1103          */
1104         pr_devel("terminal_node\n");
1105         node = result.terminal_node.node;
1106 
1107         for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
1108             ptr = node->slots[slot];
1109             if (ptr &&
1110                 assoc_array_ptr_is_leaf(ptr) &&
1111                 ops->compare_object(assoc_array_ptr_to_leaf(ptr),
1112                         index_key))
1113                 goto found_leaf;
1114         }
1115         fallthrough;
1116     case assoc_array_walk_tree_empty:
1117     case assoc_array_walk_found_wrong_shortcut:
1118     default:
1119         assoc_array_cancel_edit(edit);
1120         pr_devel("not found\n");
1121         return NULL;
1122     }
1123 
1124 found_leaf:
1125     BUG_ON(array->nr_leaves_on_tree <= 0);
1126 
1127     /* In the simplest form of deletion we just clear the slot and release
1128      * the leaf after a suitable interval.
1129      */
1130     edit->dead_leaf = node->slots[slot];
1131     edit->set[0].ptr = &node->slots[slot];
1132     edit->set[0].to = NULL;
1133     edit->adjust_count_on = node;
1134 
1135     /* If that concludes erasure of the last leaf, then delete the entire
1136      * internal array.
1137      */
1138     if (array->nr_leaves_on_tree == 1) {
1139         edit->set[1].ptr = &array->root;
1140         edit->set[1].to = NULL;
1141         edit->adjust_count_on = NULL;
1142         edit->excised_subtree = array->root;
1143         pr_devel("all gone\n");
1144         return edit;
1145     }
1146 
1147     /* However, we'd also like to clear up some metadata blocks if we
1148      * possibly can.
1149      *
1150      * We go for a simple algorithm of: if this node has FAN_OUT or fewer
1151      * leaves in it, then attempt to collapse it - and attempt to
1152      * recursively collapse up the tree.
1153      *
1154      * We could also try and collapse in partially filled subtrees to take
1155      * up space in this node.
1156      */
1157     if (node->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) {
1158         struct assoc_array_node *parent, *grandparent;
1159         struct assoc_array_ptr *ptr;
1160 
1161         /* First of all, we need to know if this node has metadata so
1162          * that we don't try collapsing if all the leaves are already
1163          * here.
1164          */
1165         has_meta = false;
1166         for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
1167             ptr = node->slots[i];
1168             if (assoc_array_ptr_is_meta(ptr)) {
1169                 has_meta = true;
1170                 break;
1171             }
1172         }
1173 
1174         pr_devel("leaves: %ld [m=%d]\n",
1175              node->nr_leaves_on_branch - 1, has_meta);
1176 
1177         /* Look further up the tree to see if we can collapse this node
1178          * into a more proximal node too.
1179          */
1180         parent = node;
1181     collapse_up:
1182         pr_devel("collapse subtree: %ld\n", parent->nr_leaves_on_branch);
1183 
1184         ptr = parent->back_pointer;
1185         if (!ptr)
1186             goto do_collapse;
1187         if (assoc_array_ptr_is_shortcut(ptr)) {
1188             struct assoc_array_shortcut *s = assoc_array_ptr_to_shortcut(ptr);
1189             ptr = s->back_pointer;
1190             if (!ptr)
1191                 goto do_collapse;
1192         }
1193 
1194         grandparent = assoc_array_ptr_to_node(ptr);
1195         if (grandparent->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT + 1) {
1196             parent = grandparent;
1197             goto collapse_up;
1198         }
1199 
1200     do_collapse:
1201         /* There's no point collapsing if the original node has no meta
1202          * pointers to discard and if we didn't merge into one of that
1203          * node's ancestry.
1204          */
1205         if (has_meta || parent != node) {
1206             node = parent;
1207 
1208             /* Create a new node to collapse into */
1209             new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
1210             if (!new_n0)
1211                 goto enomem;
1212             edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
1213 
1214             new_n0->back_pointer = node->back_pointer;
1215             new_n0->parent_slot = node->parent_slot;
1216             new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
1217             edit->adjust_count_on = new_n0;
1218 
1219             collapse.node = new_n0;
1220             collapse.skip_leaf = assoc_array_ptr_to_leaf(edit->dead_leaf);
1221             collapse.slot = 0;
1222             assoc_array_subtree_iterate(assoc_array_node_to_ptr(node),
1223                             node->back_pointer,
1224                             assoc_array_delete_collapse_iterator,
1225                             &collapse);
1226             pr_devel("collapsed %d,%lu\n", collapse.slot, new_n0->nr_leaves_on_branch);
1227             BUG_ON(collapse.slot != new_n0->nr_leaves_on_branch - 1);
1228 
1229             if (!node->back_pointer) {
1230                 edit->set[1].ptr = &array->root;
1231             } else if (assoc_array_ptr_is_leaf(node->back_pointer)) {
1232                 BUG();
1233             } else if (assoc_array_ptr_is_node(node->back_pointer)) {
1234                 struct assoc_array_node *p =
1235                     assoc_array_ptr_to_node(node->back_pointer);
1236                 edit->set[1].ptr = &p->slots[node->parent_slot];
1237             } else if (assoc_array_ptr_is_shortcut(node->back_pointer)) {
1238                 struct assoc_array_shortcut *s =
1239                     assoc_array_ptr_to_shortcut(node->back_pointer);
1240                 edit->set[1].ptr = &s->next_node;
1241             }
1242             edit->set[1].to = assoc_array_node_to_ptr(new_n0);
1243             edit->excised_subtree = assoc_array_node_to_ptr(node);
1244         }
1245     }
1246 
1247     return edit;
1248 
1249 enomem:
1250     /* Clean up after an out of memory error */
1251     pr_devel("enomem\n");
1252     assoc_array_cancel_edit(edit);
1253     return ERR_PTR(-ENOMEM);
1254 }
1255 
1256 /**
1257  * assoc_array_clear - Script deletion of all objects from an associative array
1258  * @array: The array to clear.
1259  * @ops: The operations to use.
1260  *
1261  * Precalculate and preallocate a script for the deletion of all the objects
1262  * from an associative array.  This results in an edit script that can either
1263  * be applied or cancelled.
1264  *
1265  * The function returns a pointer to an edit script if there are objects to be
1266  * deleted, NULL if there are no objects in the array or -ENOMEM.
1267  *
1268  * The caller should lock against other modifications and must continue to hold
1269  * the lock until assoc_array_apply_edit() has been called.
1270  *
1271  * Accesses to the tree may take place concurrently with this function,
1272  * provided they hold the RCU read lock.
1273  */
1274 struct assoc_array_edit *assoc_array_clear(struct assoc_array *array,
1275                        const struct assoc_array_ops *ops)
1276 {
1277     struct assoc_array_edit *edit;
1278 
1279     pr_devel("-->%s()\n", __func__);
1280 
1281     if (!array->root)
1282         return NULL;
1283 
1284     edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL);
1285     if (!edit)
1286         return ERR_PTR(-ENOMEM);
1287     edit->array = array;
1288     edit->ops = ops;
1289     edit->set[1].ptr = &array->root;
1290     edit->set[1].to = NULL;
1291     edit->excised_subtree = array->root;
1292     edit->ops_for_excised_subtree = ops;
1293     pr_devel("all gone\n");
1294     return edit;
1295 }
1296 
1297 /*
1298  * Handle the deferred destruction after an applied edit.
1299  */
1300 static void assoc_array_rcu_cleanup(struct rcu_head *head)
1301 {
1302     struct assoc_array_edit *edit =
1303         container_of(head, struct assoc_array_edit, rcu);
1304     int i;
1305 
1306     pr_devel("-->%s()\n", __func__);
1307 
1308     if (edit->dead_leaf)
1309         edit->ops->free_object(assoc_array_ptr_to_leaf(edit->dead_leaf));
1310     for (i = 0; i < ARRAY_SIZE(edit->excised_meta); i++)
1311         if (edit->excised_meta[i])
1312             kfree(assoc_array_ptr_to_node(edit->excised_meta[i]));
1313 
1314     if (edit->excised_subtree) {
1315         BUG_ON(assoc_array_ptr_is_leaf(edit->excised_subtree));
1316         if (assoc_array_ptr_is_node(edit->excised_subtree)) {
1317             struct assoc_array_node *n =
1318                 assoc_array_ptr_to_node(edit->excised_subtree);
1319             n->back_pointer = NULL;
1320         } else {
1321             struct assoc_array_shortcut *s =
1322                 assoc_array_ptr_to_shortcut(edit->excised_subtree);
1323             s->back_pointer = NULL;
1324         }
1325         assoc_array_destroy_subtree(edit->excised_subtree,
1326                         edit->ops_for_excised_subtree);
1327     }
1328 
1329     kfree(edit);
1330 }
1331 
1332 /**
1333  * assoc_array_apply_edit - Apply an edit script to an associative array
1334  * @edit: The script to apply.
1335  *
1336  * Apply an edit script to an associative array to effect an insertion,
1337  * deletion or clearance.  As the edit script includes preallocated memory,
1338  * this is guaranteed not to fail.
1339  *
1340  * The edit script, dead objects and dead metadata will be scheduled for
1341  * destruction after an RCU grace period to permit those doing read-only
1342  * accesses on the array to continue to do so under the RCU read lock whilst
1343  * the edit is taking place.
1344  */
1345 void assoc_array_apply_edit(struct assoc_array_edit *edit)
1346 {
1347     struct assoc_array_shortcut *shortcut;
1348     struct assoc_array_node *node;
1349     struct assoc_array_ptr *ptr;
1350     int i;
1351 
1352     pr_devel("-->%s()\n", __func__);
1353 
1354     smp_wmb();
1355     if (edit->leaf_p)
1356         *edit->leaf_p = edit->leaf;
1357 
1358     smp_wmb();
1359     for (i = 0; i < ARRAY_SIZE(edit->set_parent_slot); i++)
1360         if (edit->set_parent_slot[i].p)
1361             *edit->set_parent_slot[i].p = edit->set_parent_slot[i].to;
1362 
1363     smp_wmb();
1364     for (i = 0; i < ARRAY_SIZE(edit->set_backpointers); i++)
1365         if (edit->set_backpointers[i])
1366             *edit->set_backpointers[i] = edit->set_backpointers_to;
1367 
1368     smp_wmb();
1369     for (i = 0; i < ARRAY_SIZE(edit->set); i++)
1370         if (edit->set[i].ptr)
1371             *edit->set[i].ptr = edit->set[i].to;
1372 
1373     if (edit->array->root == NULL) {
1374         edit->array->nr_leaves_on_tree = 0;
1375     } else if (edit->adjust_count_on) {
1376         node = edit->adjust_count_on;
1377         for (;;) {
1378             node->nr_leaves_on_branch += edit->adjust_count_by;
1379 
1380             ptr = node->back_pointer;
1381             if (!ptr)
1382                 break;
1383             if (assoc_array_ptr_is_shortcut(ptr)) {
1384                 shortcut = assoc_array_ptr_to_shortcut(ptr);
1385                 ptr = shortcut->back_pointer;
1386                 if (!ptr)
1387                     break;
1388             }
1389             BUG_ON(!assoc_array_ptr_is_node(ptr));
1390             node = assoc_array_ptr_to_node(ptr);
1391         }
1392 
1393         edit->array->nr_leaves_on_tree += edit->adjust_count_by;
1394     }
1395 
1396     call_rcu(&edit->rcu, assoc_array_rcu_cleanup);
1397 }
1398 
1399 /**
1400  * assoc_array_cancel_edit - Discard an edit script.
1401  * @edit: The script to discard.
1402  *
1403  * Free an edit script and all the preallocated data it holds without making
1404  * any changes to the associative array it was intended for.
1405  *
1406  * NOTE!  In the case of an insertion script, this does _not_ release the leaf
1407  * that was to be inserted.  That is left to the caller.
1408  */
1409 void assoc_array_cancel_edit(struct assoc_array_edit *edit)
1410 {
1411     struct assoc_array_ptr *ptr;
1412     int i;
1413 
1414     pr_devel("-->%s()\n", __func__);
1415 
1416     /* Clean up after an out of memory error */
1417     for (i = 0; i < ARRAY_SIZE(edit->new_meta); i++) {
1418         ptr = edit->new_meta[i];
1419         if (ptr) {
1420             if (assoc_array_ptr_is_node(ptr))
1421                 kfree(assoc_array_ptr_to_node(ptr));
1422             else
1423                 kfree(assoc_array_ptr_to_shortcut(ptr));
1424         }
1425     }
1426     kfree(edit);
1427 }
1428 
1429 /**
1430  * assoc_array_gc - Garbage collect an associative array.
1431  * @array: The array to clean.
1432  * @ops: The operations to use.
1433  * @iterator: A callback function to pass judgement on each object.
1434  * @iterator_data: Private data for the callback function.
1435  *
1436  * Collect garbage from an associative array and pack down the internal tree to
1437  * save memory.
1438  *
1439  * The iterator function is asked to pass judgement upon each object in the
1440  * array.  If it returns false, the object is discard and if it returns true,
1441  * the object is kept.  If it returns true, it must increment the object's
1442  * usage count (or whatever it needs to do to retain it) before returning.
1443  *
1444  * This function returns 0 if successful or -ENOMEM if out of memory.  In the
1445  * latter case, the array is not changed.
1446  *
1447  * The caller should lock against other modifications and must continue to hold
1448  * the lock until assoc_array_apply_edit() has been called.
1449  *
1450  * Accesses to the tree may take place concurrently with this function,
1451  * provided they hold the RCU read lock.
1452  */
1453 int assoc_array_gc(struct assoc_array *array,
1454            const struct assoc_array_ops *ops,
1455            bool (*iterator)(void *object, void *iterator_data),
1456            void *iterator_data)
1457 {
1458     struct assoc_array_shortcut *shortcut, *new_s;
1459     struct assoc_array_node *node, *new_n;
1460     struct assoc_array_edit *edit;
1461     struct assoc_array_ptr *cursor, *ptr;
1462     struct assoc_array_ptr *new_root, *new_parent, **new_ptr_pp;
1463     unsigned long nr_leaves_on_tree;
1464     bool retained;
1465     int keylen, slot, nr_free, next_slot, i;
1466 
1467     pr_devel("-->%s()\n", __func__);
1468 
1469     if (!array->root)
1470         return 0;
1471 
1472     edit = kzalloc(sizeof(struct assoc_array_edit), GFP_KERNEL);
1473     if (!edit)
1474         return -ENOMEM;
1475     edit->array = array;
1476     edit->ops = ops;
1477     edit->ops_for_excised_subtree = ops;
1478     edit->set[0].ptr = &array->root;
1479     edit->excised_subtree = array->root;
1480 
1481     new_root = new_parent = NULL;
1482     new_ptr_pp = &new_root;
1483     cursor = array->root;
1484 
1485 descend:
1486     /* If this point is a shortcut, then we need to duplicate it and
1487      * advance the target cursor.
1488      */
1489     if (assoc_array_ptr_is_shortcut(cursor)) {
1490         shortcut = assoc_array_ptr_to_shortcut(cursor);
1491         keylen = round_up(shortcut->skip_to_level, ASSOC_ARRAY_KEY_CHUNK_SIZE);
1492         keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
1493         new_s = kmalloc(struct_size(new_s, index_key, keylen),
1494                 GFP_KERNEL);
1495         if (!new_s)
1496             goto enomem;
1497         pr_devel("dup shortcut %p -> %p\n", shortcut, new_s);
1498         memcpy(new_s, shortcut, struct_size(new_s, index_key, keylen));
1499         new_s->back_pointer = new_parent;
1500         new_s->parent_slot = shortcut->parent_slot;
1501         *new_ptr_pp = new_parent = assoc_array_shortcut_to_ptr(new_s);
1502         new_ptr_pp = &new_s->next_node;
1503         cursor = shortcut->next_node;
1504     }
1505 
1506     /* Duplicate the node at this position */
1507     node = assoc_array_ptr_to_node(cursor);
1508     new_n = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
1509     if (!new_n)
1510         goto enomem;
1511     pr_devel("dup node %p -> %p\n", node, new_n);
1512     new_n->back_pointer = new_parent;
1513     new_n->parent_slot = node->parent_slot;
1514     *new_ptr_pp = new_parent = assoc_array_node_to_ptr(new_n);
1515     new_ptr_pp = NULL;
1516     slot = 0;
1517 
1518 continue_node:
1519     /* Filter across any leaves and gc any subtrees */
1520     for (; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
1521         ptr = node->slots[slot];
1522         if (!ptr)
1523             continue;
1524 
1525         if (assoc_array_ptr_is_leaf(ptr)) {
1526             if (iterator(assoc_array_ptr_to_leaf(ptr),
1527                      iterator_data))
1528                 /* The iterator will have done any reference
1529                  * counting on the object for us.
1530                  */
1531                 new_n->slots[slot] = ptr;
1532             continue;
1533         }
1534 
1535         new_ptr_pp = &new_n->slots[slot];
1536         cursor = ptr;
1537         goto descend;
1538     }
1539 
1540 retry_compress:
1541     pr_devel("-- compress node %p --\n", new_n);
1542 
1543     /* Count up the number of empty slots in this node and work out the
1544      * subtree leaf count.
1545      */
1546     new_n->nr_leaves_on_branch = 0;
1547     nr_free = 0;
1548     for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
1549         ptr = new_n->slots[slot];
1550         if (!ptr)
1551             nr_free++;
1552         else if (assoc_array_ptr_is_leaf(ptr))
1553             new_n->nr_leaves_on_branch++;
1554     }
1555     pr_devel("free=%d, leaves=%lu\n", nr_free, new_n->nr_leaves_on_branch);
1556 
1557     /* See what we can fold in */
1558     retained = false;
1559     next_slot = 0;
1560     for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++) {
1561         struct assoc_array_shortcut *s;
1562         struct assoc_array_node *child;
1563 
1564         ptr = new_n->slots[slot];
1565         if (!ptr || assoc_array_ptr_is_leaf(ptr))
1566             continue;
1567 
1568         s = NULL;
1569         if (assoc_array_ptr_is_shortcut(ptr)) {
1570             s = assoc_array_ptr_to_shortcut(ptr);
1571             ptr = s->next_node;
1572         }
1573 
1574         child = assoc_array_ptr_to_node(ptr);
1575         new_n->nr_leaves_on_branch += child->nr_leaves_on_branch;
1576 
1577         if (child->nr_leaves_on_branch <= nr_free + 1) {
1578             /* Fold the child node into this one */
1579             pr_devel("[%d] fold node %lu/%d [nx %d]\n",
1580                  slot, child->nr_leaves_on_branch, nr_free + 1,
1581                  next_slot);
1582 
1583             /* We would already have reaped an intervening shortcut
1584              * on the way back up the tree.
1585              */
1586             BUG_ON(s);
1587 
1588             new_n->slots[slot] = NULL;
1589             nr_free++;
1590             if (slot < next_slot)
1591                 next_slot = slot;
1592             for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
1593                 struct assoc_array_ptr *p = child->slots[i];
1594                 if (!p)
1595                     continue;
1596                 BUG_ON(assoc_array_ptr_is_meta(p));
1597                 while (new_n->slots[next_slot])
1598                     next_slot++;
1599                 BUG_ON(next_slot >= ASSOC_ARRAY_FAN_OUT);
1600                 new_n->slots[next_slot++] = p;
1601                 nr_free--;
1602             }
1603             kfree(child);
1604         } else {
1605             pr_devel("[%d] retain node %lu/%d [nx %d]\n",
1606                  slot, child->nr_leaves_on_branch, nr_free + 1,
1607                  next_slot);
1608             retained = true;
1609         }
1610     }
1611 
1612     if (retained && new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) {
1613         pr_devel("internal nodes remain despite enough space, retrying\n");
1614         goto retry_compress;
1615     }
1616     pr_devel("after: %lu\n", new_n->nr_leaves_on_branch);
1617 
1618     nr_leaves_on_tree = new_n->nr_leaves_on_branch;
1619 
1620     /* Excise this node if it is singly occupied by a shortcut */
1621     if (nr_free == ASSOC_ARRAY_FAN_OUT - 1) {
1622         for (slot = 0; slot < ASSOC_ARRAY_FAN_OUT; slot++)
1623             if ((ptr = new_n->slots[slot]))
1624                 break;
1625 
1626         if (assoc_array_ptr_is_meta(ptr) &&
1627             assoc_array_ptr_is_shortcut(ptr)) {
1628             pr_devel("excise node %p with 1 shortcut\n", new_n);
1629             new_s = assoc_array_ptr_to_shortcut(ptr);
1630             new_parent = new_n->back_pointer;
1631             slot = new_n->parent_slot;
1632             kfree(new_n);
1633             if (!new_parent) {
1634                 new_s->back_pointer = NULL;
1635                 new_s->parent_slot = 0;
1636                 new_root = ptr;
1637                 goto gc_complete;
1638             }
1639 
1640             if (assoc_array_ptr_is_shortcut(new_parent)) {
1641                 /* We can discard any preceding shortcut also */
1642                 struct assoc_array_shortcut *s =
1643                     assoc_array_ptr_to_shortcut(new_parent);
1644 
1645                 pr_devel("excise preceding shortcut\n");
1646 
1647                 new_parent = new_s->back_pointer = s->back_pointer;
1648                 slot = new_s->parent_slot = s->parent_slot;
1649                 kfree(s);
1650                 if (!new_parent) {
1651                     new_s->back_pointer = NULL;
1652                     new_s->parent_slot = 0;
1653                     new_root = ptr;
1654                     goto gc_complete;
1655                 }
1656             }
1657 
1658             new_s->back_pointer = new_parent;
1659             new_s->parent_slot = slot;
1660             new_n = assoc_array_ptr_to_node(new_parent);
1661             new_n->slots[slot] = ptr;
1662             goto ascend_old_tree;
1663         }
1664     }
1665 
1666     /* Excise any shortcuts we might encounter that point to nodes that
1667      * only contain leaves.
1668      */
1669     ptr = new_n->back_pointer;
1670     if (!ptr)
1671         goto gc_complete;
1672 
1673     if (assoc_array_ptr_is_shortcut(ptr)) {
1674         new_s = assoc_array_ptr_to_shortcut(ptr);
1675         new_parent = new_s->back_pointer;
1676         slot = new_s->parent_slot;
1677 
1678         if (new_n->nr_leaves_on_branch <= ASSOC_ARRAY_FAN_OUT) {
1679             struct assoc_array_node *n;
1680 
1681             pr_devel("excise shortcut\n");
1682             new_n->back_pointer = new_parent;
1683             new_n->parent_slot = slot;
1684             kfree(new_s);
1685             if (!new_parent) {
1686                 new_root = assoc_array_node_to_ptr(new_n);
1687                 goto gc_complete;
1688             }
1689 
1690             n = assoc_array_ptr_to_node(new_parent);
1691             n->slots[slot] = assoc_array_node_to_ptr(new_n);
1692         }
1693     } else {
1694         new_parent = ptr;
1695     }
1696     new_n = assoc_array_ptr_to_node(new_parent);
1697 
1698 ascend_old_tree:
1699     ptr = node->back_pointer;
1700     if (assoc_array_ptr_is_shortcut(ptr)) {
1701         shortcut = assoc_array_ptr_to_shortcut(ptr);
1702         slot = shortcut->parent_slot;
1703         cursor = shortcut->back_pointer;
1704         if (!cursor)
1705             goto gc_complete;
1706     } else {
1707         slot = node->parent_slot;
1708         cursor = ptr;
1709     }
1710     BUG_ON(!cursor);
1711     node = assoc_array_ptr_to_node(cursor);
1712     slot++;
1713     goto continue_node;
1714 
1715 gc_complete:
1716     edit->set[0].to = new_root;
1717     assoc_array_apply_edit(edit);
1718     array->nr_leaves_on_tree = nr_leaves_on_tree;
1719     return 0;
1720 
1721 enomem:
1722     pr_devel("enomem\n");
1723     assoc_array_destroy_subtree(new_root, edit->ops);
1724     kfree(edit);
1725     return -ENOMEM;
1726 }