···11- ========================================22- GENERIC ASSOCIATIVE ARRAY IMPLEMENTATION33- ========================================44-55-Contents:66-77- - Overview.88-99- - The public API.1010- - Edit script.1111- - Operations table.1212- - Manipulation functions.1313- - Access functions.1414- - Index key form.1515-1616- - Internal workings.1717- - Basic internal tree layout.1818- - Shortcuts.1919- - Splitting and collapsing nodes.2020- - Non-recursive iteration.2121- - Simultaneous alteration and iteration.2222-2323-2424-========2525-OVERVIEW2626-========2727-2828-This associative array implementation is an object container with the following2929-properties:3030-3131- (1) Objects are opaque pointers. The implementation does not care where they3232- point (if anywhere) or what they point to (if anything).3333-3434- [!] NOTE: Pointers to objects _must_ be zero in the least significant bit.3535-3636- (2) Objects do not need to contain linkage blocks for use by the array. This3737- permits an object to be located in multiple arrays simultaneously.3838- Rather, the array is made up of metadata blocks that point to objects.3939-4040- (3) Objects require index keys to locate them within the array.4141-4242- (4) Index keys must be unique. Inserting an object with the same key as one4343- already in the array will replace the old object.4444-4545- (5) Index keys can be of any length and can be of different lengths.4646-4747- (6) Index keys should encode the length early on, before any variation due to4848- length is seen.4949-5050- (7) Index keys can include a hash to scatter objects throughout the array.5151-5252- (8) The array can iterated over. The objects will not necessarily come out in5353- key order.5454-5555- (9) The array can be iterated over whilst it is being modified, provided the5656- RCU readlock is being held by the iterator. Note, however, under these5757- circumstances, some objects may be seen more than once. If this is a5858- problem, the iterator should lock against modification. Objects will not5959- be missed, however, unless deleted.6060-6161-(10) Objects in the array can be looked up by means of their index key.6262-6363-(11) Objects can be looked up whilst the array is being modified, provided the6464- RCU readlock is being held by the thread doing the look up.6565-6666-The implementation uses a tree of 16-pointer nodes internally that are indexed6767-on each level by nibbles from the index key in the same manner as in a radix6868-tree. To improve memory efficiency, shortcuts can be emplaced to skip over6969-what would otherwise be a series of single-occupancy nodes. Further, nodes7070-pack leaf object pointers into spare space in the node rather than making an7171-extra branch until as such time an object needs to be added to a full node.7272-7373-7474-==============7575-THE PUBLIC API7676-==============7777-7878-The public API can be found in <linux/assoc_array.h>. The associative array is7979-rooted on the following structure:8080-8181- struct assoc_array {8282- ...8383- };8484-8585-The code is selected by enabling CONFIG_ASSOCIATIVE_ARRAY.8686-8787-8888-EDIT SCRIPT8989------------9090-9191-The insertion and deletion functions produce an 'edit script' that can later be9292-applied to effect the changes without risking ENOMEM. This retains the9393-preallocated metadata blocks that will be installed in the internal tree and9494-keeps track of the metadata blocks that will be removed from the tree when the9595-script is applied.9696-9797-This is also used to keep track of dead blocks and dead objects after the9898-script has been applied so that they can be freed later. The freeing is done9999-after an RCU grace period has passed - thus allowing access functions to100100-proceed under the RCU read lock.101101-102102-The script appears as outside of the API as a pointer of the type:103103-104104- struct assoc_array_edit;105105-106106-There are two functions for dealing with the script:107107-108108- (1) Apply an edit script.109109-110110- void assoc_array_apply_edit(struct assoc_array_edit *edit);111111-112112- This will perform the edit functions, interpolating various write barriers113113- to permit accesses under the RCU read lock to continue. The edit script114114- will then be passed to call_rcu() to free it and any dead stuff it points115115- to.116116-117117- (2) Cancel an edit script.118118-119119- void assoc_array_cancel_edit(struct assoc_array_edit *edit);120120-121121- This frees the edit script and all preallocated memory immediately. If122122- this was for insertion, the new object is _not_ released by this function,123123- but must rather be released by the caller.124124-125125-These functions are guaranteed not to fail.126126-127127-128128-OPERATIONS TABLE129129-----------------130130-131131-Various functions take a table of operations:132132-133133- struct assoc_array_ops {134134- ...135135- };136136-137137-This points to a number of methods, all of which need to be provided:138138-139139- (1) Get a chunk of index key from caller data:140140-141141- unsigned long (*get_key_chunk)(const void *index_key, int level);142142-143143- This should return a chunk of caller-supplied index key starting at the144144- *bit* position given by the level argument. The level argument will be a145145- multiple of ASSOC_ARRAY_KEY_CHUNK_SIZE and the function should return146146- ASSOC_ARRAY_KEY_CHUNK_SIZE bits. No error is possible.147147-148148-149149- (2) Get a chunk of an object's index key.150150-151151- unsigned long (*get_object_key_chunk)(const void *object, int level);152152-153153- As the previous function, but gets its data from an object in the array154154- rather than from a caller-supplied index key.155155-156156-157157- (3) See if this is the object we're looking for.158158-159159- bool (*compare_object)(const void *object, const void *index_key);160160-161161- Compare the object against an index key and return true if it matches and162162- false if it doesn't.163163-164164-165165- (4) Diff the index keys of two objects.166166-167167- int (*diff_objects)(const void *object, const void *index_key);168168-169169- Return the bit position at which the index key of the specified object170170- differs from the given index key or -1 if they are the same.171171-172172-173173- (5) Free an object.174174-175175- void (*free_object)(void *object);176176-177177- Free the specified object. Note that this may be called an RCU grace178178- period after assoc_array_apply_edit() was called, so synchronize_rcu() may179179- be necessary on module unloading.180180-181181-182182-MANIPULATION FUNCTIONS183183-----------------------184184-185185-There are a number of functions for manipulating an associative array:186186-187187- (1) Initialise an associative array.188188-189189- void assoc_array_init(struct assoc_array *array);190190-191191- This initialises the base structure for an associative array. It can't192192- fail.193193-194194-195195- (2) Insert/replace an object in an associative array.196196-197197- struct assoc_array_edit *198198- assoc_array_insert(struct assoc_array *array,199199- const struct assoc_array_ops *ops,200200- const void *index_key,201201- void *object);202202-203203- This inserts the given object into the array. Note that the least204204- significant bit of the pointer must be zero as it's used to type-mark205205- pointers internally.206206-207207- If an object already exists for that key then it will be replaced with the208208- new object and the old one will be freed automatically.209209-210210- The index_key argument should hold index key information and is211211- passed to the methods in the ops table when they are called.212212-213213- This function makes no alteration to the array itself, but rather returns214214- an edit script that must be applied. -ENOMEM is returned in the case of215215- an out-of-memory error.216216-217217- The caller should lock exclusively against other modifiers of the array.218218-219219-220220- (3) Delete an object from an associative array.221221-222222- struct assoc_array_edit *223223- assoc_array_delete(struct assoc_array *array,224224- const struct assoc_array_ops *ops,225225- const void *index_key);226226-227227- This deletes an object that matches the specified data from the array.228228-229229- The index_key argument should hold index key information and is230230- passed to the methods in the ops table when they are called.231231-232232- This function makes no alteration to the array itself, but rather returns233233- an edit script that must be applied. -ENOMEM is returned in the case of234234- an out-of-memory error. NULL will be returned if the specified object is235235- not found within the array.236236-237237- The caller should lock exclusively against other modifiers of the array.238238-239239-240240- (4) Delete all objects from an associative array.241241-242242- struct assoc_array_edit *243243- assoc_array_clear(struct assoc_array *array,244244- const struct assoc_array_ops *ops);245245-246246- This deletes all the objects from an associative array and leaves it247247- completely empty.248248-249249- This function makes no alteration to the array itself, but rather returns250250- an edit script that must be applied. -ENOMEM is returned in the case of251251- an out-of-memory error.252252-253253- The caller should lock exclusively against other modifiers of the array.254254-255255-256256- (5) Destroy an associative array, deleting all objects.257257-258258- void assoc_array_destroy(struct assoc_array *array,259259- const struct assoc_array_ops *ops);260260-261261- This destroys the contents of the associative array and leaves it262262- completely empty. It is not permitted for another thread to be traversing263263- the array under the RCU read lock at the same time as this function is264264- destroying it as no RCU deferral is performed on memory release -265265- something that would require memory to be allocated.266266-267267- The caller should lock exclusively against other modifiers and accessors268268- of the array.269269-270270-271271- (6) Garbage collect an associative array.272272-273273- int assoc_array_gc(struct assoc_array *array,274274- const struct assoc_array_ops *ops,275275- bool (*iterator)(void *object, void *iterator_data),276276- void *iterator_data);277277-278278- This iterates over the objects in an associative array and passes each one279279- to iterator(). If iterator() returns true, the object is kept. If it280280- returns false, the object will be freed. If the iterator() function281281- returns true, it must perform any appropriate refcount incrementing on the282282- object before returning.283283-284284- The internal tree will be packed down if possible as part of the iteration285285- to reduce the number of nodes in it.286286-287287- The iterator_data is passed directly to iterator() and is otherwise288288- ignored by the function.289289-290290- The function will return 0 if successful and -ENOMEM if there wasn't291291- enough memory.292292-293293- It is possible for other threads to iterate over or search the array under294294- the RCU read lock whilst this function is in progress. The caller should295295- lock exclusively against other modifiers of the array.296296-297297-298298-ACCESS FUNCTIONS299299-----------------300300-301301-There are two functions for accessing an associative array:302302-303303- (1) Iterate over all the objects in an associative array.304304-305305- int assoc_array_iterate(const struct assoc_array *array,306306- int (*iterator)(const void *object,307307- void *iterator_data),308308- void *iterator_data);309309-310310- This passes each object in the array to the iterator callback function.311311- iterator_data is private data for that function.312312-313313- This may be used on an array at the same time as the array is being314314- modified, provided the RCU read lock is held. Under such circumstances,315315- it is possible for the iteration function to see some objects twice. If316316- this is a problem, then modification should be locked against. The317317- iteration algorithm should not, however, miss any objects.318318-319319- The function will return 0 if no objects were in the array or else it will320320- return the result of the last iterator function called. Iteration stops321321- immediately if any call to the iteration function results in a non-zero322322- return.323323-324324-325325- (2) Find an object in an associative array.326326-327327- void *assoc_array_find(const struct assoc_array *array,328328- const struct assoc_array_ops *ops,329329- const void *index_key);330330-331331- This walks through the array's internal tree directly to the object332332- specified by the index key..333333-334334- This may be used on an array at the same time as the array is being335335- modified, provided the RCU read lock is held.336336-337337- The function will return the object if found (and set *_type to the object338338- type) or will return NULL if the object was not found.339339-340340-341341-INDEX KEY FORM342342---------------343343-344344-The index key can be of any form, but since the algorithms aren't told how long345345-the key is, it is strongly recommended that the index key includes its length346346-very early on before any variation due to the length would have an effect on347347-comparisons.348348-349349-This will cause leaves with different length keys to scatter away from each350350-other - and those with the same length keys to cluster together.351351-352352-It is also recommended that the index key begin with a hash of the rest of the353353-key to maximise scattering throughout keyspace.354354-355355-The better the scattering, the wider and lower the internal tree will be.356356-357357-Poor scattering isn't too much of a problem as there are shortcuts and nodes358358-can contain mixtures of leaves and metadata pointers.359359-360360-The index key is read in chunks of machine word. Each chunk is subdivided into361361-one nibble (4 bits) per level, so on a 32-bit CPU this is good for 8 levels and362362-on a 64-bit CPU, 16 levels. Unless the scattering is really poor, it is363363-unlikely that more than one word of any particular index key will have to be364364-used.365365-366366-367367-=================368368-INTERNAL WORKINGS369369-=================370370-371371-The associative array data structure has an internal tree. This tree is372372-constructed of two types of metadata blocks: nodes and shortcuts.373373-374374-A node is an array of slots. Each slot can contain one of four things:375375-376376- (*) A NULL pointer, indicating that the slot is empty.377377-378378- (*) A pointer to an object (a leaf).379379-380380- (*) A pointer to a node at the next level.381381-382382- (*) A pointer to a shortcut.383383-384384-385385-BASIC INTERNAL TREE LAYOUT386386---------------------------387387-388388-Ignoring shortcuts for the moment, the nodes form a multilevel tree. The index389389-key space is strictly subdivided by the nodes in the tree and nodes occur on390390-fixed levels. For example:391391-392392- Level: 0 1 2 3393393- =============== =============== =============== ===============394394- NODE D395395- NODE B NODE C +------>+---+396396- +------>+---+ +------>+---+ | | 0 |397397- NODE A | | 0 | | | 0 | | +---+398398- +---+ | +---+ | +---+ | : :399399- | 0 | | : : | : : | +---+400400- +---+ | +---+ | +---+ | | f |401401- | 1 |---+ | 3 |---+ | 7 |---+ +---+402402- +---+ +---+ +---+403403- : : : : | 8 |---+404404- +---+ +---+ +---+ | NODE E405405- | e |---+ | f | : : +------>+---+406406- +---+ | +---+ +---+ | 0 |407407- | f | | | f | +---+408408- +---+ | +---+ : :409409- | NODE F +---+410410- +------>+---+ | f |411411- | 0 | NODE G +---+412412- +---+ +------>+---+413413- : : | | 0 |414414- +---+ | +---+415415- | 6 |---+ : :416416- +---+ +---+417417- : : | f |418418- +---+ +---+419419- | f |420420- +---+421421-422422-In the above example, there are 7 nodes (A-G), each with 16 slots (0-f).423423-Assuming no other meta data nodes in the tree, the key space is divided thusly:424424-425425- KEY PREFIX NODE426426- ========== ====427427- 137* D428428- 138* E429429- 13[0-69-f]* C430430- 1[0-24-f]* B431431- e6* G432432- e[0-57-f]* F433433- [02-df]* A434434-435435-So, for instance, keys with the following example index keys will be found in436436-the appropriate nodes:437437-438438- INDEX KEY PREFIX NODE439439- =============== ======= ====440440- 13694892892489 13 C441441- 13795289025897 137 D442442- 13889dde88793 138 E443443- 138bbb89003093 138 E444444- 1394879524789 12 C445445- 1458952489 1 B446446- 9431809de993ba - A447447- b4542910809cd - A448448- e5284310def98 e F449449- e68428974237 e6 G450450- e7fffcbd443 e F451451- f3842239082 - A452452-453453-To save memory, if a node can hold all the leaves in its portion of keyspace,454454-then the node will have all those leaves in it and will not have any metadata455455-pointers - even if some of those leaves would like to be in the same slot.456456-457457-A node can contain a heterogeneous mix of leaves and metadata pointers.458458-Metadata pointers must be in the slots that match their subdivisions of key459459-space. The leaves can be in any slot not occupied by a metadata pointer. It460460-is guaranteed that none of the leaves in a node will match a slot occupied by a461461-metadata pointer. If the metadata pointer is there, any leaf whose key matches462462-the metadata key prefix must be in the subtree that the metadata pointer points463463-to.464464-465465-In the above example list of index keys, node A will contain:466466-467467- SLOT CONTENT INDEX KEY (PREFIX)468468- ==== =============== ==================469469- 1 PTR TO NODE B 1*470470- any LEAF 9431809de993ba471471- any LEAF b4542910809cd472472- e PTR TO NODE F e*473473- any LEAF f3842239082474474-475475-and node B:476476-477477- 3 PTR TO NODE C 13*478478- any LEAF 1458952489479479-480480-481481-SHORTCUTS482482----------483483-484484-Shortcuts are metadata records that jump over a piece of keyspace. A shortcut485485-is a replacement for a series of single-occupancy nodes ascending through the486486-levels. Shortcuts exist to save memory and to speed up traversal.487487-488488-It is possible for the root of the tree to be a shortcut - say, for example,489489-the tree contains at least 17 nodes all with key prefix '1111'. The insertion490490-algorithm will insert a shortcut to skip over the '1111' keyspace in a single491491-bound and get to the fourth level where these actually become different.492492-493493-494494-SPLITTING AND COLLAPSING NODES495495-------------------------------496496-497497-Each node has a maximum capacity of 16 leaves and metadata pointers. If the498498-insertion algorithm finds that it is trying to insert a 17th object into a499499-node, that node will be split such that at least two leaves that have a common500500-key segment at that level end up in a separate node rooted on that slot for501501-that common key segment.502502-503503-If the leaves in a full node and the leaf that is being inserted are504504-sufficiently similar, then a shortcut will be inserted into the tree.505505-506506-When the number of objects in the subtree rooted at a node falls to 16 or507507-fewer, then the subtree will be collapsed down to a single node - and this will508508-ripple towards the root if possible.509509-510510-511511-NON-RECURSIVE ITERATION512512------------------------513513-514514-Each node and shortcut contains a back pointer to its parent and the number of515515-slot in that parent that points to it. None-recursive iteration uses these to516516-proceed rootwards through the tree, going to the parent node, slot N + 1 to517517-make sure progress is made without the need for a stack.518518-519519-The backpointers, however, make simultaneous alteration and iteration tricky.520520-521521-522522-SIMULTANEOUS ALTERATION AND ITERATION523523--------------------------------------524524-525525-There are a number of cases to consider:526526-527527- (1) Simple insert/replace. This involves simply replacing a NULL or old528528- matching leaf pointer with the pointer to the new leaf after a barrier.529529- The metadata blocks don't change otherwise. An old leaf won't be freed530530- until after the RCU grace period.531531-532532- (2) Simple delete. This involves just clearing an old matching leaf. The533533- metadata blocks don't change otherwise. The old leaf won't be freed until534534- after the RCU grace period.535535-536536- (3) Insertion replacing part of a subtree that we haven't yet entered. This537537- may involve replacement of part of that subtree - but that won't affect538538- the iteration as we won't have reached the pointer to it yet and the539539- ancestry blocks are not replaced (the layout of those does not change).540540-541541- (4) Insertion replacing nodes that we're actively processing. This isn't a542542- problem as we've passed the anchoring pointer and won't switch onto the543543- new layout until we follow the back pointers - at which point we've544544- already examined the leaves in the replaced node (we iterate over all the545545- leaves in a node before following any of its metadata pointers).546546-547547- We might, however, re-see some leaves that have been split out into a new548548- branch that's in a slot further along than we were at.549549-550550- (5) Insertion replacing nodes that we're processing a dependent branch of.551551- This won't affect us until we follow the back pointers. Similar to (4).552552-553553- (6) Deletion collapsing a branch under us. This doesn't affect us because the554554- back pointers will get us back to the parent of the new node before we555555- could see the new node. The entire collapsed subtree is thrown away556556- unchanged - and will still be rooted on the same slot, so we shouldn't557557- process it a second time as we'll go back to slot + 1.558558-559559-Note:560560-561561- (*) Under some circumstances, we need to simultaneously change the parent562562- pointer and the parent slot pointer on a node (say, for example, we563563- inserted another node before it and moved it up a level). We cannot do564564- this without locking against a read - so we have to replace that node too.565565-566566- However, when we're changing a shortcut into a node this isn't a problem567567- as shortcuts only have one slot and so the parent slot number isn't used568568- when traversing backwards over one. This means that it's okay to change569569- the slot number first - provided suitable barriers are used to make sure570570- the parent slot number is read after the back pointer.571571-572572-Obsolete blocks and leaves are freed up after an RCU grace period has passed,573573-so as long as anyone doing walking or iteration holds the RCU read lock, the574574-old superstructure should not go away on them.
···11- Semantics and Behavior of Atomic and22- Bitmask Operations11+=======================================================22+Semantics and Behavior of Atomic and Bitmask Operations33+=======================================================3444- David S. Miller 55+:Author: David S. Miller5666- This document is intended to serve as a guide to Linux port77+This document is intended to serve as a guide to Linux port78maintainers on how to implement atomic counter, bitops, and spinlock89interfaces properly.9101010- The atomic_t type should be defined as a signed integer and1111+Atomic Type And Operations1212+==========================1313+1414+The atomic_t type should be defined as a signed integer and1115the atomic_long_t type as a signed long integer. Also, they should1216be made opaque such that any kind of cast to a normal C integer type1313-will fail. Something like the following should suffice:1717+will fail. Something like the following should suffice::14181519 typedef struct { int counter; } atomic_t;1620 typedef struct { long counter; } atomic_long_t;17211822Historically, counter has been declared volatile. This is now discouraged.1919-See Documentation/process/volatile-considered-harmful.rst for the complete rationale.2323+See :ref:`Documentation/process/volatile-considered-harmful.rst2424+<volatile_considered_harmful>` for the complete rationale.20252126local_t is very similar to atomic_t. If the counter is per CPU and only2227updated by one CPU, local_t is probably more appropriate. Please see2323-Documentation/local_ops.txt for the semantics of local_t.2828+:ref:`Documentation/core-api/local_ops.rst <local_ops>` for the semantics of2929+local_t.24302531The first operations to implement for atomic_t's are the initializers and2626-plain reads.3232+plain reads. ::27332834 #define ATOMIC_INIT(i) { (i) }2935 #define atomic_set(v, i) ((v)->counter = (i))30363131-The first macro is used in definitions, such as:3737+The first macro is used in definitions, such as::32383333-static atomic_t my_counter = ATOMIC_INIT(1);3939+ static atomic_t my_counter = ATOMIC_INIT(1);34403541The initializer is atomic in that the return values of the atomic operations3642are guaranteed to be correct reflecting the initialized value if the···4438proper implicit or explicit read memory barrier is needed before reading the4539value with atomic_read from another thread.46404747-As with all of the atomic_ interfaces, replace the leading "atomic_"4848-with "atomic_long_" to operate on atomic_long_t.4141+As with all of the ``atomic_`` interfaces, replace the leading ``atomic_``4242+with ``atomic_long_`` to operate on atomic_long_t.49435050-The second interface can be used at runtime, as in:4444+The second interface can be used at runtime, as in::51455246 struct foo { atomic_t counter; };5347 ...···6559or explicit memory barrier is needed before the value set with the operation6660is guaranteed to be readable with atomic_read from another thread.67616868-Next, we have:6262+Next, we have::69637064 #define atomic_read(v) ((v)->counter)7165···7973interface must take care of that with a proper implicit or explicit memory8074barrier.81758282-*** WARNING: atomic_read() and atomic_set() DO NOT IMPLY BARRIERS! ***7676+.. warning::83778484-Some architectures may choose to use the volatile keyword, barriers, or inline8585-assembly to guarantee some degree of immediacy for atomic_read() and8686-atomic_set(). This is not uniformly guaranteed, and may change in the future,8787-so all users of atomic_t should treat atomic_read() and atomic_set() as simple8888-C statements that may be reordered or optimized away entirely by the compiler8989-or processor, and explicitly invoke the appropriate compiler and/or memory9090-barrier for each use case. Failure to do so will result in code that may9191-suddenly break when used with different architectures or compiler9292-optimizations, or even changes in unrelated code which changes how the9393-compiler optimizes the section accessing atomic_t variables.7878+ ``atomic_read()`` and ``atomic_set()`` DO NOT IMPLY BARRIERS!94799595-*** YOU HAVE BEEN WARNED! ***8080+ Some architectures may choose to use the volatile keyword, barriers, or8181+ inline assembly to guarantee some degree of immediacy for atomic_read()8282+ and atomic_set(). This is not uniformly guaranteed, and may change in8383+ the future, so all users of atomic_t should treat atomic_read() and8484+ atomic_set() as simple C statements that may be reordered or optimized8585+ away entirely by the compiler or processor, and explicitly invoke the8686+ appropriate compiler and/or memory barrier for each use case. Failure8787+ to do so will result in code that may suddenly break when used with8888+ different architectures or compiler optimizations, or even changes in8989+ unrelated code which changes how the compiler optimizes the section9090+ accessing atomic_t variables.96919792Properly aligned pointers, longs, ints, and chars (and unsigned9893equivalents) may be atomically loaded from and stored to in the same···10295optimizations that might otherwise optimize accesses out of existence on10396the one hand, or that might create unsolicited accesses on the other.10497105105-For example consider the following code:9898+For example consider the following code::10699107100 while (a > 0)108101 do_something();109102110103If the compiler can prove that do_something() does not store to the111104variable a, then the compiler is within its rights transforming this to112112-the following:105105+the following::113106114107 tmp = a;115108 if (a > 0)···117110 do_something();118111119112If you don't want the compiler to do this (and you probably don't), then120120-you should use something like the following:113113+you should use something like the following::121114122115 while (READ_ONCE(a) < 0)123116 do_something();124117125118Alternatively, you could place a barrier() call in the loop.126119127127-For another example, consider the following code:120120+For another example, consider the following code::128121129122 tmp_a = a;130123 do_something_with(tmp_a);···132125133126If the compiler can prove that do_something_with() does not store to the134127variable a, then the compiler is within its rights to manufacture an135135-additional load as follows:128128+additional load as follows::136129137130 tmp_a = a;138131 do_something_with(tmp_a);···146139do_something_with() was an inline function that made very heavy use147140of registers: reloading from variable a could save a flush to the148141stack and later reload. To prevent the compiler from attacking your149149-code in this manner, write the following:142142+code in this manner, write the following::150143151144 tmp_a = READ_ONCE(a);152145 do_something_with(tmp_a);···154147155148For a final example, consider the following code, assuming that the156149variable a is set at boot time before the second CPU is brought online157157-and never changed later, so that memory barriers are not needed:150150+and never changed later, so that memory barriers are not needed::158151159152 if (a)160153 b = 9;···162155 b = 42;163156164157The compiler is within its rights to manufacture an additional store165165-by transforming the above code into the following:158158+by transforming the above code into the following::166159167160 b = 42;168161 if (a)···170163171164This could come as a fatal surprise to other code running concurrently172165that expected b to never have the value 42 if a was zero. To prevent173173-the compiler from doing this, write something like:166166+the compiler from doing this, write something like::174167175168 if (a)176169 WRITE_ONCE(b, 9);···180173Don't even -think- about doing this without proper use of memory barriers,181174locks, or atomic operations if variable a can change at runtime!182175183183-*** WARNING: READ_ONCE() OR WRITE_ONCE() DO NOT IMPLY A BARRIER! ***176176+.. warning::177177+178178+ ``READ_ONCE()`` OR ``WRITE_ONCE()`` DO NOT IMPLY A BARRIER!184179185180Now, we move onto the atomic operation interfaces typically implemented with186186-the help of assembly code.181181+the help of assembly code. ::187182188183 void atomic_add(int i, atomic_t *v);189184 void atomic_sub(int i, atomic_t *v);···201192require any explicit memory barriers. They need only perform the202193atomic_t counter update in an SMP safe manner.203194204204-Next, we have:195195+Next, we have::205196206197 int atomic_inc_return(atomic_t *v);207198 int atomic_dec_return(atomic_t *v);···223214memory barrier semantics which satisfy the above requirements, that is224215fine as well.225216226226-Let's move on:217217+Let's move on::227218228219 int atomic_add_return(int i, atomic_t *v);229220 int atomic_sub_return(int i, atomic_t *v);···233224This means that like atomic_{inc,dec}_return(), the memory barrier234225semantics are required.235226236236-Next:227227+Next::237228238229 int atomic_inc_and_test(atomic_t *v);239230 int atomic_dec_and_test(atomic_t *v);···243234resulting counter value was zero or not.244235245236Again, these primitives provide explicit memory barrier semantics around246246-the atomic operation.237237+the atomic operation::247238248239 int atomic_sub_and_test(int i, atomic_t *v);249240250241This is identical to atomic_dec_and_test() except that an explicit251242decrement is given instead of the implicit "1". This primitive must252252-provide explicit memory barrier semantics around the operation.243243+provide explicit memory barrier semantics around the operation::253244254245 int atomic_add_negative(int i, atomic_t *v);255246···258249This primitive must provide explicit memory barrier semantics around259250the operation.260251261261-Then:252252+Then::262253263254 int atomic_xchg(atomic_t *v, int new);264255···266257the given new value. It returns the old value that the atomic variable v had267258just before the operation.268259269269-atomic_xchg must provide explicit memory barriers around the operation.260260+atomic_xchg must provide explicit memory barriers around the operation. ::270261271262 int atomic_cmpxchg(atomic_t *v, int old, int new);272263273264This performs an atomic compare exchange operation on the atomic value v,274265with the given old and new values. Like all atomic_xxx operations,275266atomic_cmpxchg will only satisfy its atomicity semantics as long as all276276-other accesses of *v are performed through atomic_xxx operations.267267+other accesses of \*v are performed through atomic_xxx operations.277268278269atomic_cmpxchg must provide explicit memory barriers around the operation,279270although if the comparison fails then no memory ordering guarantees are···282273The semantics for atomic_cmpxchg are the same as those defined for 'cas'283274below.284275285285-Finally:276276+Finally::286277287278 int atomic_add_unless(atomic_t *v, int a, int u);288279···298289299290If a caller requires memory barrier semantics around an atomic_t300291operation which does not return a value, a set of interfaces are301301-defined which accomplish this:292292+defined which accomplish this::302293303294 void smp_mb__before_atomic(void);304295 void smp_mb__after_atomic(void);305296306306-For example, smp_mb__before_atomic() can be used like so:297297+For example, smp_mb__before_atomic() can be used like so::307298308299 obj->dead = 1;309300 smp_mb__before_atomic();···324315an example, which follows a pattern occurring frequently in the Linux325316kernel. It is the use of atomic counters to implement reference326317counting, and it works such that once the counter falls to zero it can327327-be guaranteed that no other entity can be accessing the object:318318+be guaranteed that no other entity can be accessing the object::328319329329-static void obj_list_add(struct obj *obj, struct list_head *head)330330-{331331- obj->active = 1;332332- list_add(&obj->list, head);333333-}320320+ static void obj_list_add(struct obj *obj, struct list_head *head)321321+ {322322+ obj->active = 1;323323+ list_add(&obj->list, head);324324+ }334325335335-static void obj_list_del(struct obj *obj)336336-{337337- list_del(&obj->list);338338- obj->active = 0;339339-}326326+ static void obj_list_del(struct obj *obj)327327+ {328328+ list_del(&obj->list);329329+ obj->active = 0;330330+ }340331341341-static void obj_destroy(struct obj *obj)342342-{343343- BUG_ON(obj->active);344344- kfree(obj);345345-}332332+ static void obj_destroy(struct obj *obj)333333+ {334334+ BUG_ON(obj->active);335335+ kfree(obj);336336+ }346337347347-struct obj *obj_list_peek(struct list_head *head)348348-{349349- if (!list_empty(head)) {338338+ struct obj *obj_list_peek(struct list_head *head)339339+ {340340+ if (!list_empty(head)) {341341+ struct obj *obj;342342+343343+ obj = list_entry(head->next, struct obj, list);344344+ atomic_inc(&obj->refcnt);345345+ return obj;346346+ }347347+ return NULL;348348+ }349349+350350+ void obj_poke(void)351351+ {350352 struct obj *obj;351353352352- obj = list_entry(head->next, struct obj, list);353353- atomic_inc(&obj->refcnt);354354- return obj;354354+ spin_lock(&global_list_lock);355355+ obj = obj_list_peek(&global_list);356356+ spin_unlock(&global_list_lock);357357+358358+ if (obj) {359359+ obj->ops->poke(obj);360360+ if (atomic_dec_and_test(&obj->refcnt))361361+ obj_destroy(obj);362362+ }355363 }356356- return NULL;357357-}358364359359-void obj_poke(void)360360-{361361- struct obj *obj;365365+ void obj_timeout(struct obj *obj)366366+ {367367+ spin_lock(&global_list_lock);368368+ obj_list_del(obj);369369+ spin_unlock(&global_list_lock);362370363363- spin_lock(&global_list_lock);364364- obj = obj_list_peek(&global_list);365365- spin_unlock(&global_list_lock);366366-367367- if (obj) {368368- obj->ops->poke(obj);369371 if (atomic_dec_and_test(&obj->refcnt))370372 obj_destroy(obj);371373 }372372-}373374374374-void obj_timeout(struct obj *obj)375375-{376376- spin_lock(&global_list_lock);377377- obj_list_del(obj);378378- spin_unlock(&global_list_lock);375375+.. note::379376380380- if (atomic_dec_and_test(&obj->refcnt))381381- obj_destroy(obj);382382-}383383-384384-(This is a simplification of the ARP queue management in the385385- generic neighbour discover code of the networking. Olaf Kirch386386- found a bug wrt. memory barriers in kfree_skb() that exposed387387- the atomic_t memory barrier requirements quite clearly.)377377+ This is a simplification of the ARP queue management in the generic378378+ neighbour discover code of the networking. Olaf Kirch found a bug wrt.379379+ memory barriers in kfree_skb() that exposed the atomic_t memory barrier380380+ requirements quite clearly.388381389382Given the above scheme, it must be the case that the obj->active390383update done by the obj list deletion be visible to other processors···394383395384Otherwise, the counter could fall to zero, yet obj->active would still396385be set, thus triggering the assertion in obj_destroy(). The error397397-sequence looks like this:386386+sequence looks like this::398387399388 cpu 0 cpu 1400389 obj_poke() obj_timeout()···431420Another note is that the atomic_t operations returning values are432421extremely slow on an old 386.433422423423+424424+Atomic Bitmask425425+==============426426+434427We will now cover the atomic bitmask operations. You will find that435428their SMP and memory barrier semantics are similar in shape and scope436429to the atomic_t ops above.···442427Native atomic bit operations are defined to operate on objects aligned443428to the size of an "unsigned long" C data type, and are least of that444429size. The endianness of the bits within each "unsigned long" are the445445-native endianness of the cpu.430430+native endianness of the cpu. ::446431447432 void set_bit(unsigned long nr, volatile unsigned long *addr);448433 void clear_bit(unsigned long nr, volatile unsigned long *addr);···452437indicated by "nr" on the bit mask pointed to by "ADDR".453438454439They must execute atomically, yet there are no implicit memory barrier455455-semantics required of these interfaces.440440+semantics required of these interfaces. ::456441457442 int test_and_set_bit(unsigned long nr, volatile unsigned long *addr);458443 int test_and_clear_bit(unsigned long nr, volatile unsigned long *addr);···481466All memory operations before the atomic bit operation call must be482467made visible globally before the atomic bit operation is made visible.483468Likewise, the atomic bit operation must be visible globally before any484484-subsequent memory operation is made visible. For example:469469+subsequent memory operation is made visible. For example::485470486471 obj->dead = 1;487472 if (test_and_set_bit(0, &obj->flags))···494479memory operation done by test_and_set_bit() must become visible before495480"obj->killed = 1;" is visible.496481497497-Finally there is the basic operation:482482+Finally there is the basic operation::498483499484 int test_bit(unsigned long nr, __const__ volatile unsigned long *addr);500485···503488504489If explicit memory barriers are required around {set,clear}_bit() (which do505490not return a value, and thus does not need to provide memory barrier506506-semantics), two interfaces are provided:491491+semantics), two interfaces are provided::507492508493 void smp_mb__before_atomic(void);509494 void smp_mb__after_atomic(void);510495511496They are used as follows, and are akin to their atomic_t operation512512-brothers:497497+brothers::513498514499 /* All memory operations before this call will515500 * be globally visible before the clear_bit().···526511same as spinlocks). These operate in the same way as their non-_lock/unlock527512postfixed variants, except that they are to provide acquire/release semantics,528513respectively. This means they can be used for bit_spin_trylock and529529-bit_spin_unlock type operations without specifying any more barriers.514514+bit_spin_unlock type operations without specifying any more barriers. ::530515531516 int test_and_set_bit_lock(unsigned long nr, unsigned long *addr);532517 void clear_bit_unlock(unsigned long nr, unsigned long *addr);···541526locking scheme is being used to protect the bitmask, and thus less542527expensive non-atomic operations may be used in the implementation.543528They have names similar to the above bitmask operation interfaces,544544-except that two underscores are prefixed to the interface name.529529+except that two underscores are prefixed to the interface name. ::545530546531 void __set_bit(unsigned long nr, volatile unsigned long *addr);547532 void __clear_bit(unsigned long nr, volatile unsigned long *addr);···557542memory-barrier semantics as the atomic and bit operations returning558543values.559544560560-Note: If someone wants to use xchg(), cmpxchg() and their variants,561561-linux/atomic.h should be included rather than asm/cmpxchg.h, unless562562-the code is in arch/* and can take care of itself.545545+.. note::546546+547547+ If someone wants to use xchg(), cmpxchg() and their variants,548548+ linux/atomic.h should be included rather than asm/cmpxchg.h, unless the549549+ code is in arch/* and can take care of itself.563550564551Spinlocks and rwlocks have memory barrier expectations as well.565552The rule to follow is simple:···575558576559Which finally brings us to _atomic_dec_and_lock(). There is an577560architecture-neutral version implemented in lib/dec_and_lock.c,578578-but most platforms will wish to optimize this in assembler.561561+but most platforms will wish to optimize this in assembler. ::579562580563 int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock);581564···590573subsequent memory operation.591574592575We can demonstrate this operation more clearly if we define593593-an abstract atomic operation:576576+an abstract atomic operation::594577595578 long cas(long *mem, long old, long new);596579···6015843) Regardless, the current value at "mem" is returned.602585603586As an example usage, here is what an atomic counter update604604-might look like:587587+might look like::605588606606-void example_atomic_inc(long *counter)607607-{608608- long old, new, ret;589589+ void example_atomic_inc(long *counter)590590+ {591591+ long old, new, ret;609592610610- while (1) {611611- old = *counter;612612- new = old + 1;593593+ while (1) {594594+ old = *counter;595595+ new = old + 1;613596614614- ret = cas(counter, old, new);615615- if (ret == old)616616- break;617617- }618618-}619619-620620-Let's use cas() in order to build a pseudo-C atomic_dec_and_lock():621621-622622-int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock)623623-{624624- long old, new, ret;625625- int went_to_zero;626626-627627- went_to_zero = 0;628628- while (1) {629629- old = atomic_read(atomic);630630- new = old - 1;631631- if (new == 0) {632632- went_to_zero = 1;633633- spin_lock(lock);634634- }635635- ret = cas(atomic, old, new);636636- if (ret == old)637637- break;638638- if (went_to_zero) {639639- spin_unlock(lock);640640- went_to_zero = 0;597597+ ret = cas(counter, old, new);598598+ if (ret == old)599599+ break;641600 }642601 }643602644644- return went_to_zero;645645-}603603+Let's use cas() in order to build a pseudo-C atomic_dec_and_lock()::604604+605605+ int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock)606606+ {607607+ long old, new, ret;608608+ int went_to_zero;609609+610610+ went_to_zero = 0;611611+ while (1) {612612+ old = atomic_read(atomic);613613+ new = old - 1;614614+ if (new == 0) {615615+ went_to_zero = 1;616616+ spin_lock(lock);617617+ }618618+ ret = cas(atomic, old, new);619619+ if (ret == old)620620+ break;621621+ if (went_to_zero) {622622+ spin_unlock(lock);623623+ went_to_zero = 0;624624+ }625625+ }626626+627627+ return went_to_zero;628628+ }646629647630Now, as far as memory barriers go, as long as spin_lock()648631strictly orders all subsequent memory operations (including···652635a counter dropping to zero is never made visible before the653636spinlock being acquired.654637655655-Note that this also means that for the case where the counter656656-is not dropping to zero, there are no memory ordering657657-requirements.638638+.. note::639639+640640+ Note that this also means that for the case where the counter is not641641+ dropping to zero, there are no memory ordering requirements.
+551
Documentation/core-api/assoc_array.rst
···11+========================================22+Generic Associative Array Implementation33+========================================44+55+Overview66+========77+88+This associative array implementation is an object container with the following99+properties:1010+1111+1. Objects are opaque pointers. The implementation does not care where they1212+ point (if anywhere) or what they point to (if anything).1313+.. note:: Pointers to objects _must_ be zero in the least significant bit.**1414+1515+2. Objects do not need to contain linkage blocks for use by the array. This1616+ permits an object to be located in multiple arrays simultaneously.1717+ Rather, the array is made up of metadata blocks that point to objects.1818+1919+3. Objects require index keys to locate them within the array.2020+2121+4. Index keys must be unique. Inserting an object with the same key as one2222+ already in the array will replace the old object.2323+2424+5. Index keys can be of any length and can be of different lengths.2525+2626+6. Index keys should encode the length early on, before any variation due to2727+ length is seen.2828+2929+7. Index keys can include a hash to scatter objects throughout the array.3030+3131+8. The array can iterated over. The objects will not necessarily come out in3232+ key order.3333+3434+9. The array can be iterated over whilst it is being modified, provided the3535+ RCU readlock is being held by the iterator. Note, however, under these3636+ circumstances, some objects may be seen more than once. If this is a3737+ problem, the iterator should lock against modification. Objects will not3838+ be missed, however, unless deleted.3939+4040+10. Objects in the array can be looked up by means of their index key.4141+4242+11. Objects can be looked up whilst the array is being modified, provided the4343+ RCU readlock is being held by the thread doing the look up.4444+4545+The implementation uses a tree of 16-pointer nodes internally that are indexed4646+on each level by nibbles from the index key in the same manner as in a radix4747+tree. To improve memory efficiency, shortcuts can be emplaced to skip over4848+what would otherwise be a series of single-occupancy nodes. Further, nodes4949+pack leaf object pointers into spare space in the node rather than making an5050+extra branch until as such time an object needs to be added to a full node.5151+5252+5353+The Public API5454+==============5555+5656+The public API can be found in ``<linux/assoc_array.h>``. The associative5757+array is rooted on the following structure::5858+5959+ struct assoc_array {6060+ ...6161+ };6262+6363+The code is selected by enabling ``CONFIG_ASSOCIATIVE_ARRAY`` with::6464+6565+ ./script/config -e ASSOCIATIVE_ARRAY6666+6767+6868+Edit Script6969+-----------7070+7171+The insertion and deletion functions produce an 'edit script' that can later be7272+applied to effect the changes without risking ``ENOMEM``. This retains the7373+preallocated metadata blocks that will be installed in the internal tree and7474+keeps track of the metadata blocks that will be removed from the tree when the7575+script is applied.7676+7777+This is also used to keep track of dead blocks and dead objects after the7878+script has been applied so that they can be freed later. The freeing is done7979+after an RCU grace period has passed - thus allowing access functions to8080+proceed under the RCU read lock.8181+8282+The script appears as outside of the API as a pointer of the type::8383+8484+ struct assoc_array_edit;8585+8686+There are two functions for dealing with the script:8787+8888+1. Apply an edit script::8989+9090+ void assoc_array_apply_edit(struct assoc_array_edit *edit);9191+9292+This will perform the edit functions, interpolating various write barriers9393+to permit accesses under the RCU read lock to continue. The edit script9494+will then be passed to ``call_rcu()`` to free it and any dead stuff it points9595+to.9696+9797+2. Cancel an edit script::9898+9999+ void assoc_array_cancel_edit(struct assoc_array_edit *edit);100100+101101+This frees the edit script and all preallocated memory immediately. If102102+this was for insertion, the new object is _not_ released by this function,103103+but must rather be released by the caller.104104+105105+These functions are guaranteed not to fail.106106+107107+108108+Operations Table109109+----------------110110+111111+Various functions take a table of operations::112112+113113+ struct assoc_array_ops {114114+ ...115115+ };116116+117117+This points to a number of methods, all of which need to be provided:118118+119119+1. Get a chunk of index key from caller data::120120+121121+ unsigned long (*get_key_chunk)(const void *index_key, int level);122122+123123+This should return a chunk of caller-supplied index key starting at the124124+*bit* position given by the level argument. The level argument will be a125125+multiple of ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` and the function should return126126+``ASSOC_ARRAY_KEY_CHUNK_SIZE bits``. No error is possible.127127+128128+129129+2. Get a chunk of an object's index key::130130+131131+ unsigned long (*get_object_key_chunk)(const void *object, int level);132132+133133+As the previous function, but gets its data from an object in the array134134+rather than from a caller-supplied index key.135135+136136+137137+3. See if this is the object we're looking for::138138+139139+ bool (*compare_object)(const void *object, const void *index_key);140140+141141+Compare the object against an index key and return ``true`` if it matches and142142+``false`` if it doesn't.143143+144144+145145+4. Diff the index keys of two objects::146146+147147+ int (*diff_objects)(const void *object, const void *index_key);148148+149149+Return the bit position at which the index key of the specified object150150+differs from the given index key or -1 if they are the same.151151+152152+153153+5. Free an object::154154+155155+ void (*free_object)(void *object);156156+157157+Free the specified object. Note that this may be called an RCU grace period158158+after ``assoc_array_apply_edit()`` was called, so ``synchronize_rcu()`` may be159159+necessary on module unloading.160160+161161+162162+Manipulation Functions163163+----------------------164164+165165+There are a number of functions for manipulating an associative array:166166+167167+1. Initialise an associative array::168168+169169+ void assoc_array_init(struct assoc_array *array);170170+171171+This initialises the base structure for an associative array. It can't fail.172172+173173+174174+2. Insert/replace an object in an associative array::175175+176176+ struct assoc_array_edit *177177+ assoc_array_insert(struct assoc_array *array,178178+ const struct assoc_array_ops *ops,179179+ const void *index_key,180180+ void *object);181181+182182+This inserts the given object into the array. Note that the least183183+significant bit of the pointer must be zero as it's used to type-mark184184+pointers internally.185185+186186+If an object already exists for that key then it will be replaced with the187187+new object and the old one will be freed automatically.188188+189189+The ``index_key`` argument should hold index key information and is190190+passed to the methods in the ops table when they are called.191191+192192+This function makes no alteration to the array itself, but rather returns193193+an edit script that must be applied. ``-ENOMEM`` is returned in the case of194194+an out-of-memory error.195195+196196+The caller should lock exclusively against other modifiers of the array.197197+198198+199199+3. Delete an object from an associative array::200200+201201+ struct assoc_array_edit *202202+ assoc_array_delete(struct assoc_array *array,203203+ const struct assoc_array_ops *ops,204204+ const void *index_key);205205+206206+This deletes an object that matches the specified data from the array.207207+208208+The ``index_key`` argument should hold index key information and is209209+passed to the methods in the ops table when they are called.210210+211211+This function makes no alteration to the array itself, but rather returns212212+an edit script that must be applied. ``-ENOMEM`` is returned in the case of213213+an out-of-memory error. ``NULL`` will be returned if the specified object is214214+not found within the array.215215+216216+The caller should lock exclusively against other modifiers of the array.217217+218218+219219+4. Delete all objects from an associative array::220220+221221+ struct assoc_array_edit *222222+ assoc_array_clear(struct assoc_array *array,223223+ const struct assoc_array_ops *ops);224224+225225+This deletes all the objects from an associative array and leaves it226226+completely empty.227227+228228+This function makes no alteration to the array itself, but rather returns229229+an edit script that must be applied. ``-ENOMEM`` is returned in the case of230230+an out-of-memory error.231231+232232+The caller should lock exclusively against other modifiers of the array.233233+234234+235235+5. Destroy an associative array, deleting all objects::236236+237237+ void assoc_array_destroy(struct assoc_array *array,238238+ const struct assoc_array_ops *ops);239239+240240+This destroys the contents of the associative array and leaves it241241+completely empty. It is not permitted for another thread to be traversing242242+the array under the RCU read lock at the same time as this function is243243+destroying it as no RCU deferral is performed on memory release -244244+something that would require memory to be allocated.245245+246246+The caller should lock exclusively against other modifiers and accessors247247+of the array.248248+249249+250250+6. Garbage collect an associative array::251251+252252+ int assoc_array_gc(struct assoc_array *array,253253+ const struct assoc_array_ops *ops,254254+ bool (*iterator)(void *object, void *iterator_data),255255+ void *iterator_data);256256+257257+This iterates over the objects in an associative array and passes each one to258258+``iterator()``. If ``iterator()`` returns ``true``, the object is kept. If it259259+returns ``false``, the object will be freed. If the ``iterator()`` function260260+returns ``true``, it must perform any appropriate refcount incrementing on the261261+object before returning.262262+263263+The internal tree will be packed down if possible as part of the iteration264264+to reduce the number of nodes in it.265265+266266+The ``iterator_data`` is passed directly to ``iterator()`` and is otherwise267267+ignored by the function.268268+269269+The function will return ``0`` if successful and ``-ENOMEM`` if there wasn't270270+enough memory.271271+272272+It is possible for other threads to iterate over or search the array under273273+the RCU read lock whilst this function is in progress. The caller should274274+lock exclusively against other modifiers of the array.275275+276276+277277+Access Functions278278+----------------279279+280280+There are two functions for accessing an associative array:281281+282282+1. Iterate over all the objects in an associative array::283283+284284+ int assoc_array_iterate(const struct assoc_array *array,285285+ int (*iterator)(const void *object,286286+ void *iterator_data),287287+ void *iterator_data);288288+289289+This passes each object in the array to the iterator callback function.290290+``iterator_data`` is private data for that function.291291+292292+This may be used on an array at the same time as the array is being293293+modified, provided the RCU read lock is held. Under such circumstances,294294+it is possible for the iteration function to see some objects twice. If295295+this is a problem, then modification should be locked against. The296296+iteration algorithm should not, however, miss any objects.297297+298298+The function will return ``0`` if no objects were in the array or else it will299299+return the result of the last iterator function called. Iteration stops300300+immediately if any call to the iteration function results in a non-zero301301+return.302302+303303+304304+2. Find an object in an associative array::305305+306306+ void *assoc_array_find(const struct assoc_array *array,307307+ const struct assoc_array_ops *ops,308308+ const void *index_key);309309+310310+This walks through the array's internal tree directly to the object311311+specified by the index key..312312+313313+This may be used on an array at the same time as the array is being314314+modified, provided the RCU read lock is held.315315+316316+The function will return the object if found (and set ``*_type`` to the object317317+type) or will return ``NULL`` if the object was not found.318318+319319+320320+Index Key Form321321+--------------322322+323323+The index key can be of any form, but since the algorithms aren't told how long324324+the key is, it is strongly recommended that the index key includes its length325325+very early on before any variation due to the length would have an effect on326326+comparisons.327327+328328+This will cause leaves with different length keys to scatter away from each329329+other - and those with the same length keys to cluster together.330330+331331+It is also recommended that the index key begin with a hash of the rest of the332332+key to maximise scattering throughout keyspace.333333+334334+The better the scattering, the wider and lower the internal tree will be.335335+336336+Poor scattering isn't too much of a problem as there are shortcuts and nodes337337+can contain mixtures of leaves and metadata pointers.338338+339339+The index key is read in chunks of machine word. Each chunk is subdivided into340340+one nibble (4 bits) per level, so on a 32-bit CPU this is good for 8 levels and341341+on a 64-bit CPU, 16 levels. Unless the scattering is really poor, it is342342+unlikely that more than one word of any particular index key will have to be343343+used.344344+345345+346346+Internal Workings347347+=================348348+349349+The associative array data structure has an internal tree. This tree is350350+constructed of two types of metadata blocks: nodes and shortcuts.351351+352352+A node is an array of slots. Each slot can contain one of four things:353353+354354+* A NULL pointer, indicating that the slot is empty.355355+* A pointer to an object (a leaf).356356+* A pointer to a node at the next level.357357+* A pointer to a shortcut.358358+359359+360360+Basic Internal Tree Layout361361+--------------------------362362+363363+Ignoring shortcuts for the moment, the nodes form a multilevel tree. The index364364+key space is strictly subdivided by the nodes in the tree and nodes occur on365365+fixed levels. For example::366366+367367+ Level: 0 1 2 3368368+ =============== =============== =============== ===============369369+ NODE D370370+ NODE B NODE C +------>+---+371371+ +------>+---+ +------>+---+ | | 0 |372372+ NODE A | | 0 | | | 0 | | +---+373373+ +---+ | +---+ | +---+ | : :374374+ | 0 | | : : | : : | +---+375375+ +---+ | +---+ | +---+ | | f |376376+ | 1 |---+ | 3 |---+ | 7 |---+ +---+377377+ +---+ +---+ +---+378378+ : : : : | 8 |---+379379+ +---+ +---+ +---+ | NODE E380380+ | e |---+ | f | : : +------>+---+381381+ +---+ | +---+ +---+ | 0 |382382+ | f | | | f | +---+383383+ +---+ | +---+ : :384384+ | NODE F +---+385385+ +------>+---+ | f |386386+ | 0 | NODE G +---+387387+ +---+ +------>+---+388388+ : : | | 0 |389389+ +---+ | +---+390390+ | 6 |---+ : :391391+ +---+ +---+392392+ : : | f |393393+ +---+ +---+394394+ | f |395395+ +---+396396+397397+In the above example, there are 7 nodes (A-G), each with 16 slots (0-f).398398+Assuming no other meta data nodes in the tree, the key space is divided399399+thusly::400400+401401+ KEY PREFIX NODE402402+ ========== ====403403+ 137* D404404+ 138* E405405+ 13[0-69-f]* C406406+ 1[0-24-f]* B407407+ e6* G408408+ e[0-57-f]* F409409+ [02-df]* A410410+411411+So, for instance, keys with the following example index keys will be found in412412+the appropriate nodes::413413+414414+ INDEX KEY PREFIX NODE415415+ =============== ======= ====416416+ 13694892892489 13 C417417+ 13795289025897 137 D418418+ 13889dde88793 138 E419419+ 138bbb89003093 138 E420420+ 1394879524789 12 C421421+ 1458952489 1 B422422+ 9431809de993ba - A423423+ b4542910809cd - A424424+ e5284310def98 e F425425+ e68428974237 e6 G426426+ e7fffcbd443 e F427427+ f3842239082 - A428428+429429+To save memory, if a node can hold all the leaves in its portion of keyspace,430430+then the node will have all those leaves in it and will not have any metadata431431+pointers - even if some of those leaves would like to be in the same slot.432432+433433+A node can contain a heterogeneous mix of leaves and metadata pointers.434434+Metadata pointers must be in the slots that match their subdivisions of key435435+space. The leaves can be in any slot not occupied by a metadata pointer. It436436+is guaranteed that none of the leaves in a node will match a slot occupied by a437437+metadata pointer. If the metadata pointer is there, any leaf whose key matches438438+the metadata key prefix must be in the subtree that the metadata pointer points439439+to.440440+441441+In the above example list of index keys, node A will contain::442442+443443+ SLOT CONTENT INDEX KEY (PREFIX)444444+ ==== =============== ==================445445+ 1 PTR TO NODE B 1*446446+ any LEAF 9431809de993ba447447+ any LEAF b4542910809cd448448+ e PTR TO NODE F e*449449+ any LEAF f3842239082450450+451451+and node B::452452+453453+ 3 PTR TO NODE C 13*454454+ any LEAF 1458952489455455+456456+457457+Shortcuts458458+---------459459+460460+Shortcuts are metadata records that jump over a piece of keyspace. A shortcut461461+is a replacement for a series of single-occupancy nodes ascending through the462462+levels. Shortcuts exist to save memory and to speed up traversal.463463+464464+It is possible for the root of the tree to be a shortcut - say, for example,465465+the tree contains at least 17 nodes all with key prefix ``1111``. The466466+insertion algorithm will insert a shortcut to skip over the ``1111`` keyspace467467+in a single bound and get to the fourth level where these actually become468468+different.469469+470470+471471+Splitting And Collapsing Nodes472472+------------------------------473473+474474+Each node has a maximum capacity of 16 leaves and metadata pointers. If the475475+insertion algorithm finds that it is trying to insert a 17th object into a476476+node, that node will be split such that at least two leaves that have a common477477+key segment at that level end up in a separate node rooted on that slot for478478+that common key segment.479479+480480+If the leaves in a full node and the leaf that is being inserted are481481+sufficiently similar, then a shortcut will be inserted into the tree.482482+483483+When the number of objects in the subtree rooted at a node falls to 16 or484484+fewer, then the subtree will be collapsed down to a single node - and this will485485+ripple towards the root if possible.486486+487487+488488+Non-Recursive Iteration489489+-----------------------490490+491491+Each node and shortcut contains a back pointer to its parent and the number of492492+slot in that parent that points to it. None-recursive iteration uses these to493493+proceed rootwards through the tree, going to the parent node, slot N + 1 to494494+make sure progress is made without the need for a stack.495495+496496+The backpointers, however, make simultaneous alteration and iteration tricky.497497+498498+499499+Simultaneous Alteration And Iteration500500+-------------------------------------501501+502502+There are a number of cases to consider:503503+504504+1. Simple insert/replace. This involves simply replacing a NULL or old505505+ matching leaf pointer with the pointer to the new leaf after a barrier.506506+ The metadata blocks don't change otherwise. An old leaf won't be freed507507+ until after the RCU grace period.508508+509509+2. Simple delete. This involves just clearing an old matching leaf. The510510+ metadata blocks don't change otherwise. The old leaf won't be freed until511511+ after the RCU grace period.512512+513513+3. Insertion replacing part of a subtree that we haven't yet entered. This514514+ may involve replacement of part of that subtree - but that won't affect515515+ the iteration as we won't have reached the pointer to it yet and the516516+ ancestry blocks are not replaced (the layout of those does not change).517517+518518+4. Insertion replacing nodes that we're actively processing. This isn't a519519+ problem as we've passed the anchoring pointer and won't switch onto the520520+ new layout until we follow the back pointers - at which point we've521521+ already examined the leaves in the replaced node (we iterate over all the522522+ leaves in a node before following any of its metadata pointers).523523+524524+ We might, however, re-see some leaves that have been split out into a new525525+ branch that's in a slot further along than we were at.526526+527527+5. Insertion replacing nodes that we're processing a dependent branch of.528528+ This won't affect us until we follow the back pointers. Similar to (4).529529+530530+6. Deletion collapsing a branch under us. This doesn't affect us because the531531+ back pointers will get us back to the parent of the new node before we532532+ could see the new node. The entire collapsed subtree is thrown away533533+ unchanged - and will still be rooted on the same slot, so we shouldn't534534+ process it a second time as we'll go back to slot + 1.535535+536536+.. note::537537+538538+ Under some circumstances, we need to simultaneously change the parent539539+ pointer and the parent slot pointer on a node (say, for example, we540540+ inserted another node before it and moved it up a level). We cannot do541541+ this without locking against a read - so we have to replace that node too.542542+543543+ However, when we're changing a shortcut into a node this isn't a problem544544+ as shortcuts only have one slot and so the parent slot number isn't used545545+ when traversing backwards over one. This means that it's okay to change546546+ the slot number first - provided suitable barriers are used to make sure547547+ the parent slot number is read after the back pointer.548548+549549+Obsolete blocks and leaves are freed up after an RCU grace period has passed,550550+so as long as anyone doing walking or iteration holds the RCU read lock, the551551+old superstructure should not go away on them.
···11+22+.. _local_ops:33+44+=================================================55+Semantics and Behavior of Local Atomic Operations66+=================================================77+88+:Author: Mathieu Desnoyers99+1010+1111+This document explains the purpose of the local atomic operations, how1212+to implement them for any given architecture and shows how they can be used1313+properly. It also stresses on the precautions that must be taken when reading1414+those local variables across CPUs when the order of memory writes matters.1515+1616+.. note::1717+1818+ Note that ``local_t`` based operations are not recommended for general1919+ kernel use. Please use the ``this_cpu`` operations instead unless there is2020+ really a special purpose. Most uses of ``local_t`` in the kernel have been2121+ replaced by ``this_cpu`` operations. ``this_cpu`` operations combine the2222+ relocation with the ``local_t`` like semantics in a single instruction and2323+ yield more compact and faster executing code.2424+2525+2626+Purpose of local atomic operations2727+==================================2828+2929+Local atomic operations are meant to provide fast and highly reentrant per CPU3030+counters. They minimize the performance cost of standard atomic operations by3131+removing the LOCK prefix and memory barriers normally required to synchronize3232+across CPUs.3333+3434+Having fast per CPU atomic counters is interesting in many cases: it does not3535+require disabling interrupts to protect from interrupt handlers and it permits3636+coherent counters in NMI handlers. It is especially useful for tracing purposes3737+and for various performance monitoring counters.3838+3939+Local atomic operations only guarantee variable modification atomicity wrt the4040+CPU which owns the data. Therefore, care must taken to make sure that only one4141+CPU writes to the ``local_t`` data. This is done by using per cpu data and4242+making sure that we modify it from within a preemption safe context. It is4343+however permitted to read ``local_t`` data from any CPU: it will then appear to4444+be written out of order wrt other memory writes by the owner CPU.4545+4646+4747+Implementation for a given architecture4848+=======================================4949+5050+It can be done by slightly modifying the standard atomic operations: only5151+their UP variant must be kept. It typically means removing LOCK prefix (on5252+i386 and x86_64) and any SMP synchronization barrier. If the architecture does5353+not have a different behavior between SMP and UP, including5454+``asm-generic/local.h`` in your architecture's ``local.h`` is sufficient.5555+5656+The ``local_t`` type is defined as an opaque ``signed long`` by embedding an5757+``atomic_long_t`` inside a structure. This is made so a cast from this type to5858+a ``long`` fails. The definition looks like::5959+6060+ typedef struct { atomic_long_t a; } local_t;6161+6262+6363+Rules to follow when using local atomic operations6464+==================================================6565+6666+* Variables touched by local ops must be per cpu variables.6767+* *Only* the CPU owner of these variables must write to them.6868+* This CPU can use local ops from any context (process, irq, softirq, nmi, ...)6969+ to update its ``local_t`` variables.7070+* Preemption (or interrupts) must be disabled when using local ops in7171+ process context to make sure the process won't be migrated to a7272+ different CPU between getting the per-cpu variable and doing the7373+ actual local op.7474+* When using local ops in interrupt context, no special care must be7575+ taken on a mainline kernel, since they will run on the local CPU with7676+ preemption already disabled. I suggest, however, to explicitly7777+ disable preemption anyway to make sure it will still work correctly on7878+ -rt kernels.7979+* Reading the local cpu variable will provide the current copy of the8080+ variable.8181+* Reads of these variables can be done from any CPU, because updates to8282+ "``long``", aligned, variables are always atomic. Since no memory8383+ synchronization is done by the writer CPU, an outdated copy of the8484+ variable can be read when reading some *other* cpu's variables.8585+8686+8787+How to use local atomic operations8888+==================================8989+9090+::9191+9292+ #include <linux/percpu.h>9393+ #include <asm/local.h>9494+9595+ static DEFINE_PER_CPU(local_t, counters) = LOCAL_INIT(0);9696+9797+9898+Counting9999+========100100+101101+Counting is done on all the bits of a signed long.102102+103103+In preemptible context, use ``get_cpu_var()`` and ``put_cpu_var()`` around104104+local atomic operations: it makes sure that preemption is disabled around write105105+access to the per cpu variable. For instance::106106+107107+ local_inc(&get_cpu_var(counters));108108+ put_cpu_var(counters);109109+110110+If you are already in a preemption-safe context, you can use111111+``this_cpu_ptr()`` instead::112112+113113+ local_inc(this_cpu_ptr(&counters));114114+115115+116116+117117+Reading the counters118118+====================119119+120120+Those local counters can be read from foreign CPUs to sum the count. Note that121121+the data seen by local_read across CPUs must be considered to be out of order122122+relatively to other memory writes happening on the CPU that owns the data::123123+124124+ long sum = 0;125125+ for_each_online_cpu(cpu)126126+ sum += local_read(&per_cpu(counters, cpu));127127+128128+If you want to use a remote local_read to synchronize access to a resource129129+between CPUs, explicit ``smp_wmb()`` and ``smp_rmb()`` memory barriers must be used130130+respectively on the writer and the reader CPUs. It would be the case if you use131131+the ``local_t`` variable as a counter of bytes written in a buffer: there should132132+be a ``smp_wmb()`` between the buffer write and the counter increment and also a133133+``smp_rmb()`` between the counter read and the buffer read.134134+135135+136136+Here is a sample module which implements a basic per cpu counter using137137+``local.h``::138138+139139+ /* test-local.c140140+ *141141+ * Sample module for local.h usage.142142+ */143143+144144+145145+ #include <asm/local.h>146146+ #include <linux/module.h>147147+ #include <linux/timer.h>148148+149149+ static DEFINE_PER_CPU(local_t, counters) = LOCAL_INIT(0);150150+151151+ static struct timer_list test_timer;152152+153153+ /* IPI called on each CPU. */154154+ static void test_each(void *info)155155+ {156156+ /* Increment the counter from a non preemptible context */157157+ printk("Increment on cpu %d\n", smp_processor_id());158158+ local_inc(this_cpu_ptr(&counters));159159+160160+ /* This is what incrementing the variable would look like within a161161+ * preemptible context (it disables preemption) :162162+ *163163+ * local_inc(&get_cpu_var(counters));164164+ * put_cpu_var(counters);165165+ */166166+ }167167+168168+ static void do_test_timer(unsigned long data)169169+ {170170+ int cpu;171171+172172+ /* Increment the counters */173173+ on_each_cpu(test_each, NULL, 1);174174+ /* Read all the counters */175175+ printk("Counters read from CPU %d\n", smp_processor_id());176176+ for_each_online_cpu(cpu) {177177+ printk("Read : CPU %d, count %ld\n", cpu,178178+ local_read(&per_cpu(counters, cpu)));179179+ }180180+ del_timer(&test_timer);181181+ test_timer.expires = jiffies + 1000;182182+ add_timer(&test_timer);183183+ }184184+185185+ static int __init test_init(void)186186+ {187187+ /* initialize the timer that will increment the counter */188188+ init_timer(&test_timer);189189+ test_timer.function = do_test_timer;190190+ test_timer.expires = jiffies + 1;191191+ add_timer(&test_timer);192192+193193+ return 0;194194+ }195195+196196+ static void __exit test_exit(void)197197+ {198198+ del_timer_sync(&test_timer);199199+ }200200+201201+ module_init(test_init);202202+ module_exit(test_exit);203203+204204+ MODULE_LICENSE("GPL");205205+ MODULE_AUTHOR("Mathieu Desnoyers");206206+ MODULE_DESCRIPTION("Local Atomic Ops");
-191
Documentation/local_ops.txt
···11- Semantics and Behavior of Local Atomic Operations22-33- Mathieu Desnoyers44-55-66- This document explains the purpose of the local atomic operations, how77-to implement them for any given architecture and shows how they can be used88-properly. It also stresses on the precautions that must be taken when reading99-those local variables across CPUs when the order of memory writes matters.1010-1111-Note that local_t based operations are not recommended for general kernel use.1212-Please use the this_cpu operations instead unless there is really a special purpose.1313-Most uses of local_t in the kernel have been replaced by this_cpu operations.1414-this_cpu operations combine the relocation with the local_t like semantics in1515-a single instruction and yield more compact and faster executing code.1616-1717-1818-* Purpose of local atomic operations1919-2020-Local atomic operations are meant to provide fast and highly reentrant per CPU2121-counters. They minimize the performance cost of standard atomic operations by2222-removing the LOCK prefix and memory barriers normally required to synchronize2323-across CPUs.2424-2525-Having fast per CPU atomic counters is interesting in many cases : it does not2626-require disabling interrupts to protect from interrupt handlers and it permits2727-coherent counters in NMI handlers. It is especially useful for tracing purposes2828-and for various performance monitoring counters.2929-3030-Local atomic operations only guarantee variable modification atomicity wrt the3131-CPU which owns the data. Therefore, care must taken to make sure that only one3232-CPU writes to the local_t data. This is done by using per cpu data and making3333-sure that we modify it from within a preemption safe context. It is however3434-permitted to read local_t data from any CPU : it will then appear to be written3535-out of order wrt other memory writes by the owner CPU.3636-3737-3838-* Implementation for a given architecture3939-4040-It can be done by slightly modifying the standard atomic operations : only4141-their UP variant must be kept. It typically means removing LOCK prefix (on4242-i386 and x86_64) and any SMP synchronization barrier. If the architecture does4343-not have a different behavior between SMP and UP, including asm-generic/local.h4444-in your architecture's local.h is sufficient.4545-4646-The local_t type is defined as an opaque signed long by embedding an4747-atomic_long_t inside a structure. This is made so a cast from this type to a4848-long fails. The definition looks like :4949-5050-typedef struct { atomic_long_t a; } local_t;5151-5252-5353-* Rules to follow when using local atomic operations5454-5555-- Variables touched by local ops must be per cpu variables.5656-- _Only_ the CPU owner of these variables must write to them.5757-- This CPU can use local ops from any context (process, irq, softirq, nmi, ...)5858- to update its local_t variables.5959-- Preemption (or interrupts) must be disabled when using local ops in6060- process context to make sure the process won't be migrated to a6161- different CPU between getting the per-cpu variable and doing the6262- actual local op.6363-- When using local ops in interrupt context, no special care must be6464- taken on a mainline kernel, since they will run on the local CPU with6565- preemption already disabled. I suggest, however, to explicitly6666- disable preemption anyway to make sure it will still work correctly on6767- -rt kernels.6868-- Reading the local cpu variable will provide the current copy of the6969- variable.7070-- Reads of these variables can be done from any CPU, because updates to7171- "long", aligned, variables are always atomic. Since no memory7272- synchronization is done by the writer CPU, an outdated copy of the7373- variable can be read when reading some _other_ cpu's variables.7474-7575-7676-* How to use local atomic operations7777-7878-#include <linux/percpu.h>7979-#include <asm/local.h>8080-8181-static DEFINE_PER_CPU(local_t, counters) = LOCAL_INIT(0);8282-8383-8484-* Counting8585-8686-Counting is done on all the bits of a signed long.8787-8888-In preemptible context, use get_cpu_var() and put_cpu_var() around local atomic8989-operations : it makes sure that preemption is disabled around write access to9090-the per cpu variable. For instance :9191-9292- local_inc(&get_cpu_var(counters));9393- put_cpu_var(counters);9494-9595-If you are already in a preemption-safe context, you can use9696-this_cpu_ptr() instead.9797-9898- local_inc(this_cpu_ptr(&counters));9999-100100-101101-102102-* Reading the counters103103-104104-Those local counters can be read from foreign CPUs to sum the count. Note that105105-the data seen by local_read across CPUs must be considered to be out of order106106-relatively to other memory writes happening on the CPU that owns the data.107107-108108- long sum = 0;109109- for_each_online_cpu(cpu)110110- sum += local_read(&per_cpu(counters, cpu));111111-112112-If you want to use a remote local_read to synchronize access to a resource113113-between CPUs, explicit smp_wmb() and smp_rmb() memory barriers must be used114114-respectively on the writer and the reader CPUs. It would be the case if you use115115-the local_t variable as a counter of bytes written in a buffer : there should116116-be a smp_wmb() between the buffer write and the counter increment and also a117117-smp_rmb() between the counter read and the buffer read.118118-119119-120120-Here is a sample module which implements a basic per cpu counter using local.h.121121-122122---- BEGIN ---123123-/* test-local.c124124- *125125- * Sample module for local.h usage.126126- */127127-128128-129129-#include <asm/local.h>130130-#include <linux/module.h>131131-#include <linux/timer.h>132132-133133-static DEFINE_PER_CPU(local_t, counters) = LOCAL_INIT(0);134134-135135-static struct timer_list test_timer;136136-137137-/* IPI called on each CPU. */138138-static void test_each(void *info)139139-{140140- /* Increment the counter from a non preemptible context */141141- printk("Increment on cpu %d\n", smp_processor_id());142142- local_inc(this_cpu_ptr(&counters));143143-144144- /* This is what incrementing the variable would look like within a145145- * preemptible context (it disables preemption) :146146- *147147- * local_inc(&get_cpu_var(counters));148148- * put_cpu_var(counters);149149- */150150-}151151-152152-static void do_test_timer(unsigned long data)153153-{154154- int cpu;155155-156156- /* Increment the counters */157157- on_each_cpu(test_each, NULL, 1);158158- /* Read all the counters */159159- printk("Counters read from CPU %d\n", smp_processor_id());160160- for_each_online_cpu(cpu) {161161- printk("Read : CPU %d, count %ld\n", cpu,162162- local_read(&per_cpu(counters, cpu)));163163- }164164- del_timer(&test_timer);165165- test_timer.expires = jiffies + 1000;166166- add_timer(&test_timer);167167-}168168-169169-static int __init test_init(void)170170-{171171- /* initialize the timer that will increment the counter */172172- init_timer(&test_timer);173173- test_timer.function = do_test_timer;174174- test_timer.expires = jiffies + 1;175175- add_timer(&test_timer);176176-177177- return 0;178178-}179179-180180-static void __exit test_exit(void)181181-{182182- del_timer_sync(&test_timer);183183-}184184-185185-module_init(test_init);186186-module_exit(test_exit);187187-188188-MODULE_LICENSE("GPL");189189-MODULE_AUTHOR("Mathieu Desnoyers");190190-MODULE_DESCRIPTION("Local Atomic Ops");191191---- END ---