0001 ========================================
0002 Generic Associative Array Implementation
0003 ========================================
0004
0005 Overview
0006 ========
0007
0008 This associative array implementation is an object container with the following
0009 properties:
0010
0011 1. Objects are opaque pointers. The implementation does not care where they
0012 point (if anywhere) or what they point to (if anything).
0013
0014 .. note::
0015
0016 Pointers to objects _must_ be zero in the least significant bit.
0017
0018 2. Objects do not need to contain linkage blocks for use by the array. This
0019 permits an object to be located in multiple arrays simultaneously.
0020 Rather, the array is made up of metadata blocks that point to objects.
0021
0022 3. Objects require index keys to locate them within the array.
0023
0024 4. Index keys must be unique. Inserting an object with the same key as one
0025 already in the array will replace the old object.
0026
0027 5. Index keys can be of any length and can be of different lengths.
0028
0029 6. Index keys should encode the length early on, before any variation due to
0030 length is seen.
0031
0032 7. Index keys can include a hash to scatter objects throughout the array.
0033
0034 8. The array can iterated over. The objects will not necessarily come out in
0035 key order.
0036
0037 9. The array can be iterated over while it is being modified, provided the
0038 RCU readlock is being held by the iterator. Note, however, under these
0039 circumstances, some objects may be seen more than once. If this is a
0040 problem, the iterator should lock against modification. Objects will not
0041 be missed, however, unless deleted.
0042
0043 10. Objects in the array can be looked up by means of their index key.
0044
0045 11. Objects can be looked up while the array is being modified, provided the
0046 RCU readlock is being held by the thread doing the look up.
0047
0048 The implementation uses a tree of 16-pointer nodes internally that are indexed
0049 on each level by nibbles from the index key in the same manner as in a radix
0050 tree. To improve memory efficiency, shortcuts can be emplaced to skip over
0051 what would otherwise be a series of single-occupancy nodes. Further, nodes
0052 pack leaf object pointers into spare space in the node rather than making an
0053 extra branch until as such time an object needs to be added to a full node.
0054
0055
0056 The Public API
0057 ==============
0058
0059 The public API can be found in ``<linux/assoc_array.h>``. The associative
0060 array is rooted on the following structure::
0061
0062 struct assoc_array {
0063 ...
0064 };
0065
0066 The code is selected by enabling ``CONFIG_ASSOCIATIVE_ARRAY`` with::
0067
0068 ./script/config -e ASSOCIATIVE_ARRAY
0069
0070
0071 Edit Script
0072 -----------
0073
0074 The insertion and deletion functions produce an 'edit script' that can later be
0075 applied to effect the changes without risking ``ENOMEM``. This retains the
0076 preallocated metadata blocks that will be installed in the internal tree and
0077 keeps track of the metadata blocks that will be removed from the tree when the
0078 script is applied.
0079
0080 This is also used to keep track of dead blocks and dead objects after the
0081 script has been applied so that they can be freed later. The freeing is done
0082 after an RCU grace period has passed - thus allowing access functions to
0083 proceed under the RCU read lock.
0084
0085 The script appears as outside of the API as a pointer of the type::
0086
0087 struct assoc_array_edit;
0088
0089 There are two functions for dealing with the script:
0090
0091 1. Apply an edit script::
0092
0093 void assoc_array_apply_edit(struct assoc_array_edit *edit);
0094
0095 This will perform the edit functions, interpolating various write barriers
0096 to permit accesses under the RCU read lock to continue. The edit script
0097 will then be passed to ``call_rcu()`` to free it and any dead stuff it points
0098 to.
0099
0100 2. Cancel an edit script::
0101
0102 void assoc_array_cancel_edit(struct assoc_array_edit *edit);
0103
0104 This frees the edit script and all preallocated memory immediately. If
0105 this was for insertion, the new object is _not_ released by this function,
0106 but must rather be released by the caller.
0107
0108 These functions are guaranteed not to fail.
0109
0110
0111 Operations Table
0112 ----------------
0113
0114 Various functions take a table of operations::
0115
0116 struct assoc_array_ops {
0117 ...
0118 };
0119
0120 This points to a number of methods, all of which need to be provided:
0121
0122 1. Get a chunk of index key from caller data::
0123
0124 unsigned long (*get_key_chunk)(const void *index_key, int level);
0125
0126 This should return a chunk of caller-supplied index key starting at the
0127 *bit* position given by the level argument. The level argument will be a
0128 multiple of ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` and the function should return
0129 ``ASSOC_ARRAY_KEY_CHUNK_SIZE bits``. No error is possible.
0130
0131
0132 2. Get a chunk of an object's index key::
0133
0134 unsigned long (*get_object_key_chunk)(const void *object, int level);
0135
0136 As the previous function, but gets its data from an object in the array
0137 rather than from a caller-supplied index key.
0138
0139
0140 3. See if this is the object we're looking for::
0141
0142 bool (*compare_object)(const void *object, const void *index_key);
0143
0144 Compare the object against an index key and return ``true`` if it matches and
0145 ``false`` if it doesn't.
0146
0147
0148 4. Diff the index keys of two objects::
0149
0150 int (*diff_objects)(const void *object, const void *index_key);
0151
0152 Return the bit position at which the index key of the specified object
0153 differs from the given index key or -1 if they are the same.
0154
0155
0156 5. Free an object::
0157
0158 void (*free_object)(void *object);
0159
0160 Free the specified object. Note that this may be called an RCU grace period
0161 after ``assoc_array_apply_edit()`` was called, so ``synchronize_rcu()`` may be
0162 necessary on module unloading.
0163
0164
0165 Manipulation Functions
0166 ----------------------
0167
0168 There are a number of functions for manipulating an associative array:
0169
0170 1. Initialise an associative array::
0171
0172 void assoc_array_init(struct assoc_array *array);
0173
0174 This initialises the base structure for an associative array. It can't fail.
0175
0176
0177 2. Insert/replace an object in an associative array::
0178
0179 struct assoc_array_edit *
0180 assoc_array_insert(struct assoc_array *array,
0181 const struct assoc_array_ops *ops,
0182 const void *index_key,
0183 void *object);
0184
0185 This inserts the given object into the array. Note that the least
0186 significant bit of the pointer must be zero as it's used to type-mark
0187 pointers internally.
0188
0189 If an object already exists for that key then it will be replaced with the
0190 new object and the old one will be freed automatically.
0191
0192 The ``index_key`` argument should hold index key information and is
0193 passed to the methods in the ops table when they are called.
0194
0195 This function makes no alteration to the array itself, but rather returns
0196 an edit script that must be applied. ``-ENOMEM`` is returned in the case of
0197 an out-of-memory error.
0198
0199 The caller should lock exclusively against other modifiers of the array.
0200
0201
0202 3. Delete an object from an associative array::
0203
0204 struct assoc_array_edit *
0205 assoc_array_delete(struct assoc_array *array,
0206 const struct assoc_array_ops *ops,
0207 const void *index_key);
0208
0209 This deletes an object that matches the specified data from the array.
0210
0211 The ``index_key`` argument should hold index key information and is
0212 passed to the methods in the ops table when they are called.
0213
0214 This function makes no alteration to the array itself, but rather returns
0215 an edit script that must be applied. ``-ENOMEM`` is returned in the case of
0216 an out-of-memory error. ``NULL`` will be returned if the specified object is
0217 not found within the array.
0218
0219 The caller should lock exclusively against other modifiers of the array.
0220
0221
0222 4. Delete all objects from an associative array::
0223
0224 struct assoc_array_edit *
0225 assoc_array_clear(struct assoc_array *array,
0226 const struct assoc_array_ops *ops);
0227
0228 This deletes all the objects from an associative array and leaves it
0229 completely empty.
0230
0231 This function makes no alteration to the array itself, but rather returns
0232 an edit script that must be applied. ``-ENOMEM`` is returned in the case of
0233 an out-of-memory error.
0234
0235 The caller should lock exclusively against other modifiers of the array.
0236
0237
0238 5. Destroy an associative array, deleting all objects::
0239
0240 void assoc_array_destroy(struct assoc_array *array,
0241 const struct assoc_array_ops *ops);
0242
0243 This destroys the contents of the associative array and leaves it
0244 completely empty. It is not permitted for another thread to be traversing
0245 the array under the RCU read lock at the same time as this function is
0246 destroying it as no RCU deferral is performed on memory release -
0247 something that would require memory to be allocated.
0248
0249 The caller should lock exclusively against other modifiers and accessors
0250 of the array.
0251
0252
0253 6. Garbage collect an associative array::
0254
0255 int assoc_array_gc(struct assoc_array *array,
0256 const struct assoc_array_ops *ops,
0257 bool (*iterator)(void *object, void *iterator_data),
0258 void *iterator_data);
0259
0260 This iterates over the objects in an associative array and passes each one to
0261 ``iterator()``. If ``iterator()`` returns ``true``, the object is kept. If it
0262 returns ``false``, the object will be freed. If the ``iterator()`` function
0263 returns ``true``, it must perform any appropriate refcount incrementing on the
0264 object before returning.
0265
0266 The internal tree will be packed down if possible as part of the iteration
0267 to reduce the number of nodes in it.
0268
0269 The ``iterator_data`` is passed directly to ``iterator()`` and is otherwise
0270 ignored by the function.
0271
0272 The function will return ``0`` if successful and ``-ENOMEM`` if there wasn't
0273 enough memory.
0274
0275 It is possible for other threads to iterate over or search the array under
0276 the RCU read lock while this function is in progress. The caller should
0277 lock exclusively against other modifiers of the array.
0278
0279
0280 Access Functions
0281 ----------------
0282
0283 There are two functions for accessing an associative array:
0284
0285 1. Iterate over all the objects in an associative array::
0286
0287 int assoc_array_iterate(const struct assoc_array *array,
0288 int (*iterator)(const void *object,
0289 void *iterator_data),
0290 void *iterator_data);
0291
0292 This passes each object in the array to the iterator callback function.
0293 ``iterator_data`` is private data for that function.
0294
0295 This may be used on an array at the same time as the array is being
0296 modified, provided the RCU read lock is held. Under such circumstances,
0297 it is possible for the iteration function to see some objects twice. If
0298 this is a problem, then modification should be locked against. The
0299 iteration algorithm should not, however, miss any objects.
0300
0301 The function will return ``0`` if no objects were in the array or else it will
0302 return the result of the last iterator function called. Iteration stops
0303 immediately if any call to the iteration function results in a non-zero
0304 return.
0305
0306
0307 2. Find an object in an associative array::
0308
0309 void *assoc_array_find(const struct assoc_array *array,
0310 const struct assoc_array_ops *ops,
0311 const void *index_key);
0312
0313 This walks through the array's internal tree directly to the object
0314 specified by the index key..
0315
0316 This may be used on an array at the same time as the array is being
0317 modified, provided the RCU read lock is held.
0318
0319 The function will return the object if found (and set ``*_type`` to the object
0320 type) or will return ``NULL`` if the object was not found.
0321
0322
0323 Index Key Form
0324 --------------
0325
0326 The index key can be of any form, but since the algorithms aren't told how long
0327 the key is, it is strongly recommended that the index key includes its length
0328 very early on before any variation due to the length would have an effect on
0329 comparisons.
0330
0331 This will cause leaves with different length keys to scatter away from each
0332 other - and those with the same length keys to cluster together.
0333
0334 It is also recommended that the index key begin with a hash of the rest of the
0335 key to maximise scattering throughout keyspace.
0336
0337 The better the scattering, the wider and lower the internal tree will be.
0338
0339 Poor scattering isn't too much of a problem as there are shortcuts and nodes
0340 can contain mixtures of leaves and metadata pointers.
0341
0342 The index key is read in chunks of machine word. Each chunk is subdivided into
0343 one nibble (4 bits) per level, so on a 32-bit CPU this is good for 8 levels and
0344 on a 64-bit CPU, 16 levels. Unless the scattering is really poor, it is
0345 unlikely that more than one word of any particular index key will have to be
0346 used.
0347
0348
0349 Internal Workings
0350 =================
0351
0352 The associative array data structure has an internal tree. This tree is
0353 constructed of two types of metadata blocks: nodes and shortcuts.
0354
0355 A node is an array of slots. Each slot can contain one of four things:
0356
0357 * A NULL pointer, indicating that the slot is empty.
0358 * A pointer to an object (a leaf).
0359 * A pointer to a node at the next level.
0360 * A pointer to a shortcut.
0361
0362
0363 Basic Internal Tree Layout
0364 --------------------------
0365
0366 Ignoring shortcuts for the moment, the nodes form a multilevel tree. The index
0367 key space is strictly subdivided by the nodes in the tree and nodes occur on
0368 fixed levels. For example::
0369
0370 Level: 0 1 2 3
0371 =============== =============== =============== ===============
0372 NODE D
0373 NODE B NODE C +------>+---+
0374 +------>+---+ +------>+---+ | | 0 |
0375 NODE A | | 0 | | | 0 | | +---+
0376 +---+ | +---+ | +---+ | : :
0377 | 0 | | : : | : : | +---+
0378 +---+ | +---+ | +---+ | | f |
0379 | 1 |---+ | 3 |---+ | 7 |---+ +---+
0380 +---+ +---+ +---+
0381 : : : : | 8 |---+
0382 +---+ +---+ +---+ | NODE E
0383 | e |---+ | f | : : +------>+---+
0384 +---+ | +---+ +---+ | 0 |
0385 | f | | | f | +---+
0386 +---+ | +---+ : :
0387 | NODE F +---+
0388 +------>+---+ | f |
0389 | 0 | NODE G +---+
0390 +---+ +------>+---+
0391 : : | | 0 |
0392 +---+ | +---+
0393 | 6 |---+ : :
0394 +---+ +---+
0395 : : | f |
0396 +---+ +---+
0397 | f |
0398 +---+
0399
0400 In the above example, there are 7 nodes (A-G), each with 16 slots (0-f).
0401 Assuming no other meta data nodes in the tree, the key space is divided
0402 thusly::
0403
0404 KEY PREFIX NODE
0405 ========== ====
0406 137* D
0407 138* E
0408 13[0-69-f]* C
0409 1[0-24-f]* B
0410 e6* G
0411 e[0-57-f]* F
0412 [02-df]* A
0413
0414 So, for instance, keys with the following example index keys will be found in
0415 the appropriate nodes::
0416
0417 INDEX KEY PREFIX NODE
0418 =============== ======= ====
0419 13694892892489 13 C
0420 13795289025897 137 D
0421 13889dde88793 138 E
0422 138bbb89003093 138 E
0423 1394879524789 12 C
0424 1458952489 1 B
0425 9431809de993ba - A
0426 b4542910809cd - A
0427 e5284310def98 e F
0428 e68428974237 e6 G
0429 e7fffcbd443 e F
0430 f3842239082 - A
0431
0432 To save memory, if a node can hold all the leaves in its portion of keyspace,
0433 then the node will have all those leaves in it and will not have any metadata
0434 pointers - even if some of those leaves would like to be in the same slot.
0435
0436 A node can contain a heterogeneous mix of leaves and metadata pointers.
0437 Metadata pointers must be in the slots that match their subdivisions of key
0438 space. The leaves can be in any slot not occupied by a metadata pointer. It
0439 is guaranteed that none of the leaves in a node will match a slot occupied by a
0440 metadata pointer. If the metadata pointer is there, any leaf whose key matches
0441 the metadata key prefix must be in the subtree that the metadata pointer points
0442 to.
0443
0444 In the above example list of index keys, node A will contain::
0445
0446 SLOT CONTENT INDEX KEY (PREFIX)
0447 ==== =============== ==================
0448 1 PTR TO NODE B 1*
0449 any LEAF 9431809de993ba
0450 any LEAF b4542910809cd
0451 e PTR TO NODE F e*
0452 any LEAF f3842239082
0453
0454 and node B::
0455
0456 3 PTR TO NODE C 13*
0457 any LEAF 1458952489
0458
0459
0460 Shortcuts
0461 ---------
0462
0463 Shortcuts are metadata records that jump over a piece of keyspace. A shortcut
0464 is a replacement for a series of single-occupancy nodes ascending through the
0465 levels. Shortcuts exist to save memory and to speed up traversal.
0466
0467 It is possible for the root of the tree to be a shortcut - say, for example,
0468 the tree contains at least 17 nodes all with key prefix ``1111``. The
0469 insertion algorithm will insert a shortcut to skip over the ``1111`` keyspace
0470 in a single bound and get to the fourth level where these actually become
0471 different.
0472
0473
0474 Splitting And Collapsing Nodes
0475 ------------------------------
0476
0477 Each node has a maximum capacity of 16 leaves and metadata pointers. If the
0478 insertion algorithm finds that it is trying to insert a 17th object into a
0479 node, that node will be split such that at least two leaves that have a common
0480 key segment at that level end up in a separate node rooted on that slot for
0481 that common key segment.
0482
0483 If the leaves in a full node and the leaf that is being inserted are
0484 sufficiently similar, then a shortcut will be inserted into the tree.
0485
0486 When the number of objects in the subtree rooted at a node falls to 16 or
0487 fewer, then the subtree will be collapsed down to a single node - and this will
0488 ripple towards the root if possible.
0489
0490
0491 Non-Recursive Iteration
0492 -----------------------
0493
0494 Each node and shortcut contains a back pointer to its parent and the number of
0495 slot in that parent that points to it. None-recursive iteration uses these to
0496 proceed rootwards through the tree, going to the parent node, slot N + 1 to
0497 make sure progress is made without the need for a stack.
0498
0499 The backpointers, however, make simultaneous alteration and iteration tricky.
0500
0501
0502 Simultaneous Alteration And Iteration
0503 -------------------------------------
0504
0505 There are a number of cases to consider:
0506
0507 1. Simple insert/replace. This involves simply replacing a NULL or old
0508 matching leaf pointer with the pointer to the new leaf after a barrier.
0509 The metadata blocks don't change otherwise. An old leaf won't be freed
0510 until after the RCU grace period.
0511
0512 2. Simple delete. This involves just clearing an old matching leaf. The
0513 metadata blocks don't change otherwise. The old leaf won't be freed until
0514 after the RCU grace period.
0515
0516 3. Insertion replacing part of a subtree that we haven't yet entered. This
0517 may involve replacement of part of that subtree - but that won't affect
0518 the iteration as we won't have reached the pointer to it yet and the
0519 ancestry blocks are not replaced (the layout of those does not change).
0520
0521 4. Insertion replacing nodes that we're actively processing. This isn't a
0522 problem as we've passed the anchoring pointer and won't switch onto the
0523 new layout until we follow the back pointers - at which point we've
0524 already examined the leaves in the replaced node (we iterate over all the
0525 leaves in a node before following any of its metadata pointers).
0526
0527 We might, however, re-see some leaves that have been split out into a new
0528 branch that's in a slot further along than we were at.
0529
0530 5. Insertion replacing nodes that we're processing a dependent branch of.
0531 This won't affect us until we follow the back pointers. Similar to (4).
0532
0533 6. Deletion collapsing a branch under us. This doesn't affect us because the
0534 back pointers will get us back to the parent of the new node before we
0535 could see the new node. The entire collapsed subtree is thrown away
0536 unchanged - and will still be rooted on the same slot, so we shouldn't
0537 process it a second time as we'll go back to slot + 1.
0538
0539 .. note::
0540
0541 Under some circumstances, we need to simultaneously change the parent
0542 pointer and the parent slot pointer on a node (say, for example, we
0543 inserted another node before it and moved it up a level). We cannot do
0544 this without locking against a read - so we have to replace that node too.
0545
0546 However, when we're changing a shortcut into a node this isn't a problem
0547 as shortcuts only have one slot and so the parent slot number isn't used
0548 when traversing backwards over one. This means that it's okay to change
0549 the slot number first - provided suitable barriers are used to make sure
0550 the parent slot number is read after the back pointer.
0551
0552 Obsolete blocks and leaves are freed up after an RCU grace period has passed,
0553 so as long as anyone doing walking or iteration holds the RCU read lock, the
0554 old superstructure should not go away on them.