brintos

brintos / linux-shallow public Read only

0
0
Text · 20.8 KiB · 792bbf9 Raw
555 lines · plain
1========================================2Generic Associative Array Implementation3========================================4 5Overview6========7 8This associative array implementation is an object container with the following9properties:10 111. Objects are opaque pointers.  The implementation does not care where they12   point (if anywhere) or what they point to (if anything).13 14   .. note::15 16      Pointers to objects _must_ be zero in the least significant bit.17 182. Objects do not need to contain linkage blocks for use by the array.  This19   permits an object to be located in multiple arrays simultaneously.20   Rather, the array is made up of metadata blocks that point to objects.21 223. Objects require index keys to locate them within the array.23 244. Index keys must be unique.  Inserting an object with the same key as one25   already in the array will replace the old object.26 275. Index keys can be of any length and can be of different lengths.28 296. Index keys should encode the length early on, before any variation due to30   length is seen.31 327. Index keys can include a hash to scatter objects throughout the array.33 348. The array can iterated over.  The objects will not necessarily come out in35   key order.36 379. The array can be iterated over while it is being modified, provided the38   RCU readlock is being held by the iterator.  Note, however, under these39   circumstances, some objects may be seen more than once.  If this is a40   problem, the iterator should lock against modification.  Objects will not41   be missed, however, unless deleted.42 4310. Objects in the array can be looked up by means of their index key.44 4511. Objects can be looked up while the array is being modified, provided the46    RCU readlock is being held by the thread doing the look up.47 48The implementation uses a tree of 16-pointer nodes internally that are indexed49on each level by nibbles from the index key in the same manner as in a radix50tree.  To improve memory efficiency, shortcuts can be emplaced to skip over51what would otherwise be a series of single-occupancy nodes.  Further, nodes52pack leaf object pointers into spare space in the node rather than making an53extra branch until as such time an object needs to be added to a full node.54 55 56The Public API57==============58 59The public API can be found in ``<linux/assoc_array.h>``.  The associative60array is rooted on the following structure::61 62    struct assoc_array {63            ...64    };65 66The code is selected by enabling ``CONFIG_ASSOCIATIVE_ARRAY`` with::67 68    ./script/config -e ASSOCIATIVE_ARRAY69 70 71Edit Script72-----------73 74The insertion and deletion functions produce an 'edit script' that can later be75applied to effect the changes without risking ``ENOMEM``. This retains the76preallocated metadata blocks that will be installed in the internal tree and77keeps track of the metadata blocks that will be removed from the tree when the78script is applied.79 80This is also used to keep track of dead blocks and dead objects after the81script has been applied so that they can be freed later.  The freeing is done82after an RCU grace period has passed - thus allowing access functions to83proceed under the RCU read lock.84 85The script appears as outside of the API as a pointer of the type::86 87    struct assoc_array_edit;88 89There are two functions for dealing with the script:90 911. Apply an edit script::92 93    void assoc_array_apply_edit(struct assoc_array_edit *edit);94 95This will perform the edit functions, interpolating various write barriers96to permit accesses under the RCU read lock to continue.  The edit script97will then be passed to ``call_rcu()`` to free it and any dead stuff it points98to.99 1002. Cancel an edit script::101 102    void assoc_array_cancel_edit(struct assoc_array_edit *edit);103 104This frees the edit script and all preallocated memory immediately. If105this was for insertion, the new object is _not_ released by this function,106but must rather be released by the caller.107 108These functions are guaranteed not to fail.109 110 111Operations Table112----------------113 114Various functions take a table of operations::115 116    struct assoc_array_ops {117            ...118    };119 120This points to a number of methods, all of which need to be provided:121 1221. Get a chunk of index key from caller data::123 124    unsigned long (*get_key_chunk)(const void *index_key, int level);125 126This should return a chunk of caller-supplied index key starting at the127*bit* position given by the level argument.  The level argument will be a128multiple of ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` and the function should return129``ASSOC_ARRAY_KEY_CHUNK_SIZE bits``.  No error is possible.130 131 1322. Get a chunk of an object's index key::133 134    unsigned long (*get_object_key_chunk)(const void *object, int level);135 136As the previous function, but gets its data from an object in the array137rather than from a caller-supplied index key.138 139 1403. See if this is the object we're looking for::141 142    bool (*compare_object)(const void *object, const void *index_key);143 144Compare the object against an index key and return ``true`` if it matches and145``false`` if it doesn't.146 147 1484. Diff the index keys of two objects::149 150    int (*diff_objects)(const void *object, const void *index_key);151 152Return the bit position at which the index key of the specified object153differs from the given index key or -1 if they are the same.154 155 1565. Free an object::157 158    void (*free_object)(void *object);159 160Free the specified object.  Note that this may be called an RCU grace period161after ``assoc_array_apply_edit()`` was called, so ``synchronize_rcu()`` may be162necessary on module unloading.163 164 165Manipulation Functions166----------------------167 168There are a number of functions for manipulating an associative array:169 1701. Initialise an associative array::171 172    void assoc_array_init(struct assoc_array *array);173 174This initialises the base structure for an associative array.  It can't fail.175 176 1772. Insert/replace an object in an associative array::178 179    struct assoc_array_edit *180    assoc_array_insert(struct assoc_array *array,181                       const struct assoc_array_ops *ops,182                       const void *index_key,183                       void *object);184 185This inserts the given object into the array.  Note that the least186significant bit of the pointer must be zero as it's used to type-mark187pointers internally.188 189If an object already exists for that key then it will be replaced with the190new object and the old one will be freed automatically.191 192The ``index_key`` argument should hold index key information and is193passed to the methods in the ops table when they are called.194 195This function makes no alteration to the array itself, but rather returns196an edit script that must be applied.  ``-ENOMEM`` is returned in the case of197an out-of-memory error.198 199The caller should lock exclusively against other modifiers of the array.200 201 2023. Delete an object from an associative array::203 204    struct assoc_array_edit *205    assoc_array_delete(struct assoc_array *array,206                       const struct assoc_array_ops *ops,207                       const void *index_key);208 209This deletes an object that matches the specified data from the array.210 211The ``index_key`` argument should hold index key information and is212passed to the methods in the ops table when they are called.213 214This function makes no alteration to the array itself, but rather returns215an edit script that must be applied.  ``-ENOMEM`` is returned in the case of216an out-of-memory error.  ``NULL`` will be returned if the specified object is217not found within the array.218 219The caller should lock exclusively against other modifiers of the array.220 221 2224. Delete all objects from an associative array::223 224    struct assoc_array_edit *225    assoc_array_clear(struct assoc_array *array,226                      const struct assoc_array_ops *ops);227 228This deletes all the objects from an associative array and leaves it229completely empty.230 231This function makes no alteration to the array itself, but rather returns232an edit script that must be applied.  ``-ENOMEM`` is returned in the case of233an out-of-memory error.234 235The caller should lock exclusively against other modifiers of the array.236 237 2385. Destroy an associative array, deleting all objects::239 240    void assoc_array_destroy(struct assoc_array *array,241                             const struct assoc_array_ops *ops);242 243This destroys the contents of the associative array and leaves it244completely empty.  It is not permitted for another thread to be traversing245the array under the RCU read lock at the same time as this function is246destroying it as no RCU deferral is performed on memory release -247something that would require memory to be allocated.248 249The caller should lock exclusively against other modifiers and accessors250of the array.251 252 2536. Garbage collect an associative array::254 255    int assoc_array_gc(struct assoc_array *array,256                       const struct assoc_array_ops *ops,257                       bool (*iterator)(void *object, void *iterator_data),258                       void *iterator_data);259 260This iterates over the objects in an associative array and passes each one to261``iterator()``.  If ``iterator()`` returns ``true``, the object is kept.  If it262returns ``false``, the object will be freed.  If the ``iterator()`` function263returns ``true``, it must perform any appropriate refcount incrementing on the264object before returning.265 266The internal tree will be packed down if possible as part of the iteration267to reduce the number of nodes in it.268 269The ``iterator_data`` is passed directly to ``iterator()`` and is otherwise270ignored by the function.271 272The function will return ``0`` if successful and ``-ENOMEM`` if there wasn't273enough memory.274 275It is possible for other threads to iterate over or search the array under276the RCU read lock while this function is in progress.  The caller should277lock exclusively against other modifiers of the array.278 279 280Access Functions281----------------282 283There are two functions for accessing an associative array:284 2851. Iterate over all the objects in an associative array::286 287    int assoc_array_iterate(const struct assoc_array *array,288                            int (*iterator)(const void *object,289                                            void *iterator_data),290                            void *iterator_data);291 292This passes each object in the array to the iterator callback function.293``iterator_data`` is private data for that function.294 295This may be used on an array at the same time as the array is being296modified, provided the RCU read lock is held.  Under such circumstances,297it is possible for the iteration function to see some objects twice.  If298this is a problem, then modification should be locked against.  The299iteration algorithm should not, however, miss any objects.300 301The function will return ``0`` if no objects were in the array or else it will302return the result of the last iterator function called.  Iteration stops303immediately if any call to the iteration function results in a non-zero304return.305 306 3072. Find an object in an associative array::308 309    void *assoc_array_find(const struct assoc_array *array,310                           const struct assoc_array_ops *ops,311                           const void *index_key);312 313This walks through the array's internal tree directly to the object314specified by the index key..315 316This may be used on an array at the same time as the array is being317modified, provided the RCU read lock is held.318 319The function will return the object if found (and set ``*_type`` to the object320type) or will return ``NULL`` if the object was not found.321 322 323Index Key Form324--------------325 326The index key can be of any form, but since the algorithms aren't told how long327the key is, it is strongly recommended that the index key includes its length328very early on before any variation due to the length would have an effect on329comparisons.330 331This will cause leaves with different length keys to scatter away from each332other - and those with the same length keys to cluster together.333 334It is also recommended that the index key begin with a hash of the rest of the335key to maximise scattering throughout keyspace.336 337The better the scattering, the wider and lower the internal tree will be.338 339Poor scattering isn't too much of a problem as there are shortcuts and nodes340can contain mixtures of leaves and metadata pointers.341 342The index key is read in chunks of machine word.  Each chunk is subdivided into343one nibble (4 bits) per level, so on a 32-bit CPU this is good for 8 levels and344on a 64-bit CPU, 16 levels.  Unless the scattering is really poor, it is345unlikely that more than one word of any particular index key will have to be346used.347 348 349Internal Workings350=================351 352The associative array data structure has an internal tree.  This tree is353constructed of two types of metadata blocks: nodes and shortcuts.354 355A node is an array of slots.  Each slot can contain one of four things:356 357* A NULL pointer, indicating that the slot is empty.358* A pointer to an object (a leaf).359* A pointer to a node at the next level.360* A pointer to a shortcut.361 362 363Basic Internal Tree Layout364--------------------------365 366Ignoring shortcuts for the moment, the nodes form a multilevel tree.  The index367key space is strictly subdivided by the nodes in the tree and nodes occur on368fixed levels.  For example::369 370 Level: 0               1               2               3371        =============== =============== =============== ===============372                                                        NODE D373                        NODE B          NODE C  +------>+---+374                +------>+---+   +------>+---+   |       | 0 |375        NODE A  |       | 0 |   |       | 0 |   |       +---+376        +---+   |       +---+   |       +---+   |       :   :377        | 0 |   |       :   :   |       :   :   |       +---+378        +---+   |       +---+   |       +---+   |       | f |379        | 1 |---+       | 3 |---+       | 7 |---+       +---+380        +---+           +---+           +---+381        :   :           :   :           | 8 |---+382        +---+           +---+           +---+   |       NODE E383        | e |---+       | f |           :   :   +------>+---+384        +---+   |       +---+           +---+           | 0 |385        | f |   |                       | f |           +---+386        +---+   |                       +---+           :   :387                |       NODE F                          +---+388                +------>+---+                           | f |389                        | 0 |           NODE G          +---+390                        +---+   +------>+---+391                        :   :   |       | 0 |392                        +---+   |       +---+393                        | 6 |---+       :   :394                        +---+           +---+395                        :   :           | f |396                        +---+           +---+397                        | f |398                        +---+399 400In the above example, there are 7 nodes (A-G), each with 16 slots (0-f).401Assuming no other meta data nodes in the tree, the key space is divided402thusly::403 404    KEY PREFIX      NODE405    ==========      ====406    137*            D407    138*            E408    13[0-69-f]*     C409    1[0-24-f]*      B410    e6*             G411    e[0-57-f]*      F412    [02-df]*        A413 414So, for instance, keys with the following example index keys will be found in415the appropriate nodes::416 417    INDEX KEY       PREFIX  NODE418    =============== ======= ====419    13694892892489  13      C420    13795289025897  137     D421    13889dde88793   138     E422    138bbb89003093  138     E423    1394879524789   12      C424    1458952489      1       B425    9431809de993ba  -       A426    b4542910809cd   -       A427    e5284310def98   e       F428    e68428974237    e6      G429    e7fffcbd443     e       F430    f3842239082     -       A431 432To save memory, if a node can hold all the leaves in its portion of keyspace,433then the node will have all those leaves in it and will not have any metadata434pointers - even if some of those leaves would like to be in the same slot.435 436A node can contain a heterogeneous mix of leaves and metadata pointers.437Metadata pointers must be in the slots that match their subdivisions of key438space.  The leaves can be in any slot not occupied by a metadata pointer.  It439is guaranteed that none of the leaves in a node will match a slot occupied by a440metadata pointer.  If the metadata pointer is there, any leaf whose key matches441the metadata key prefix must be in the subtree that the metadata pointer points442to.443 444In the above example list of index keys, node A will contain::445 446    SLOT    CONTENT         INDEX KEY (PREFIX)447    ====    =============== ==================448    1       PTR TO NODE B   1*449    any     LEAF            9431809de993ba450    any     LEAF            b4542910809cd451    e       PTR TO NODE F   e*452    any     LEAF            f3842239082453 454and node B::455 456    3	PTR TO NODE C	13*457    any	LEAF		1458952489458 459 460Shortcuts461---------462 463Shortcuts are metadata records that jump over a piece of keyspace.  A shortcut464is a replacement for a series of single-occupancy nodes ascending through the465levels.  Shortcuts exist to save memory and to speed up traversal.466 467It is possible for the root of the tree to be a shortcut - say, for example,468the tree contains at least 17 nodes all with key prefix ``1111``.  The469insertion algorithm will insert a shortcut to skip over the ``1111`` keyspace470in a single bound and get to the fourth level where these actually become471different.472 473 474Splitting And Collapsing Nodes475------------------------------476 477Each node has a maximum capacity of 16 leaves and metadata pointers.  If the478insertion algorithm finds that it is trying to insert a 17th object into a479node, that node will be split such that at least two leaves that have a common480key segment at that level end up in a separate node rooted on that slot for481that common key segment.482 483If the leaves in a full node and the leaf that is being inserted are484sufficiently similar, then a shortcut will be inserted into the tree.485 486When the number of objects in the subtree rooted at a node falls to 16 or487fewer, then the subtree will be collapsed down to a single node - and this will488ripple towards the root if possible.489 490 491Non-Recursive Iteration492-----------------------493 494Each node and shortcut contains a back pointer to its parent and the number of495slot in that parent that points to it.  None-recursive iteration uses these to496proceed rootwards through the tree, going to the parent node, slot N + 1 to497make sure progress is made without the need for a stack.498 499The backpointers, however, make simultaneous alteration and iteration tricky.500 501 502Simultaneous Alteration And Iteration503-------------------------------------504 505There are a number of cases to consider:506 5071. Simple insert/replace.  This involves simply replacing a NULL or old508   matching leaf pointer with the pointer to the new leaf after a barrier.509   The metadata blocks don't change otherwise.  An old leaf won't be freed510   until after the RCU grace period.511 5122. Simple delete.  This involves just clearing an old matching leaf.  The513   metadata blocks don't change otherwise.  The old leaf won't be freed until514   after the RCU grace period.515 5163. Insertion replacing part of a subtree that we haven't yet entered.  This517   may involve replacement of part of that subtree - but that won't affect518   the iteration as we won't have reached the pointer to it yet and the519   ancestry blocks are not replaced (the layout of those does not change).520 5214. Insertion replacing nodes that we're actively processing.  This isn't a522   problem as we've passed the anchoring pointer and won't switch onto the523   new layout until we follow the back pointers - at which point we've524   already examined the leaves in the replaced node (we iterate over all the525   leaves in a node before following any of its metadata pointers).526 527   We might, however, re-see some leaves that have been split out into a new528   branch that's in a slot further along than we were at.529 5305. Insertion replacing nodes that we're processing a dependent branch of.531   This won't affect us until we follow the back pointers.  Similar to (4).532 5336. Deletion collapsing a branch under us.  This doesn't affect us because the534   back pointers will get us back to the parent of the new node before we535   could see the new node.  The entire collapsed subtree is thrown away536   unchanged - and will still be rooted on the same slot, so we shouldn't537   process it a second time as we'll go back to slot + 1.538 539.. note::540 541   Under some circumstances, we need to simultaneously change the parent542   pointer and the parent slot pointer on a node (say, for example, we543   inserted another node before it and moved it up a level).  We cannot do544   this without locking against a read - so we have to replace that node too.545 546   However, when we're changing a shortcut into a node this isn't a problem547   as shortcuts only have one slot and so the parent slot number isn't used548   when traversing backwards over one.  This means that it's okay to change549   the slot number first - provided suitable barriers are used to make sure550   the parent slot number is read after the back pointer.551 552Obsolete blocks and leaves are freed up after an RCU grace period has passed,553so as long as anyone doing walking or iteration holds the RCU read lock, the554old superstructure should not go away on them.555