Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

Merge branch 'silvio' into docs-next

+930 -914
-574
Documentation/assoc_array.txt
··· 1 - ======================================== 2 - GENERIC ASSOCIATIVE ARRAY IMPLEMENTATION 3 - ======================================== 4 - 5 - Contents: 6 - 7 - - Overview. 8 - 9 - - The public API. 10 - - Edit script. 11 - - Operations table. 12 - - Manipulation functions. 13 - - Access functions. 14 - - Index key form. 15 - 16 - - Internal workings. 17 - - Basic internal tree layout. 18 - - Shortcuts. 19 - - Splitting and collapsing nodes. 20 - - Non-recursive iteration. 21 - - Simultaneous alteration and iteration. 22 - 23 - 24 - ======== 25 - OVERVIEW 26 - ======== 27 - 28 - This associative array implementation is an object container with the following 29 - properties: 30 - 31 - (1) Objects are opaque pointers. The implementation does not care where they 32 - point (if anywhere) or what they point to (if anything). 33 - 34 - [!] NOTE: Pointers to objects _must_ be zero in the least significant bit. 35 - 36 - (2) Objects do not need to contain linkage blocks for use by the array. This 37 - permits an object to be located in multiple arrays simultaneously. 38 - Rather, the array is made up of metadata blocks that point to objects. 39 - 40 - (3) Objects require index keys to locate them within the array. 41 - 42 - (4) Index keys must be unique. Inserting an object with the same key as one 43 - already in the array will replace the old object. 44 - 45 - (5) Index keys can be of any length and can be of different lengths. 46 - 47 - (6) Index keys should encode the length early on, before any variation due to 48 - length is seen. 49 - 50 - (7) Index keys can include a hash to scatter objects throughout the array. 51 - 52 - (8) The array can iterated over. The objects will not necessarily come out in 53 - key order. 54 - 55 - (9) The array can be iterated over whilst it is being modified, provided the 56 - RCU readlock is being held by the iterator. Note, however, under these 57 - circumstances, some objects may be seen more than once. If this is a 58 - problem, the iterator should lock against modification. Objects will not 59 - be missed, however, unless deleted. 60 - 61 - (10) Objects in the array can be looked up by means of their index key. 62 - 63 - (11) Objects can be looked up whilst the array is being modified, provided the 64 - RCU readlock is being held by the thread doing the look up. 65 - 66 - The implementation uses a tree of 16-pointer nodes internally that are indexed 67 - on each level by nibbles from the index key in the same manner as in a radix 68 - tree. To improve memory efficiency, shortcuts can be emplaced to skip over 69 - what would otherwise be a series of single-occupancy nodes. Further, nodes 70 - pack leaf object pointers into spare space in the node rather than making an 71 - extra branch until as such time an object needs to be added to a full node. 72 - 73 - 74 - ============== 75 - THE PUBLIC API 76 - ============== 77 - 78 - The public API can be found in <linux/assoc_array.h>. The associative array is 79 - rooted on the following structure: 80 - 81 - struct assoc_array { 82 - ... 83 - }; 84 - 85 - The code is selected by enabling CONFIG_ASSOCIATIVE_ARRAY. 86 - 87 - 88 - EDIT SCRIPT 89 - ----------- 90 - 91 - The insertion and deletion functions produce an 'edit script' that can later be 92 - applied to effect the changes without risking ENOMEM. This retains the 93 - preallocated metadata blocks that will be installed in the internal tree and 94 - keeps track of the metadata blocks that will be removed from the tree when the 95 - script is applied. 96 - 97 - This is also used to keep track of dead blocks and dead objects after the 98 - script has been applied so that they can be freed later. The freeing is done 99 - after an RCU grace period has passed - thus allowing access functions to 100 - proceed under the RCU read lock. 101 - 102 - The script appears as outside of the API as a pointer of the type: 103 - 104 - struct assoc_array_edit; 105 - 106 - There are two functions for dealing with the script: 107 - 108 - (1) Apply an edit script. 109 - 110 - void assoc_array_apply_edit(struct assoc_array_edit *edit); 111 - 112 - This will perform the edit functions, interpolating various write barriers 113 - to permit accesses under the RCU read lock to continue. The edit script 114 - will then be passed to call_rcu() to free it and any dead stuff it points 115 - to. 116 - 117 - (2) Cancel an edit script. 118 - 119 - void assoc_array_cancel_edit(struct assoc_array_edit *edit); 120 - 121 - This frees the edit script and all preallocated memory immediately. If 122 - this was for insertion, the new object is _not_ released by this function, 123 - but must rather be released by the caller. 124 - 125 - These functions are guaranteed not to fail. 126 - 127 - 128 - OPERATIONS TABLE 129 - ---------------- 130 - 131 - Various functions take a table of operations: 132 - 133 - struct assoc_array_ops { 134 - ... 135 - }; 136 - 137 - This points to a number of methods, all of which need to be provided: 138 - 139 - (1) Get a chunk of index key from caller data: 140 - 141 - unsigned long (*get_key_chunk)(const void *index_key, int level); 142 - 143 - This should return a chunk of caller-supplied index key starting at the 144 - *bit* position given by the level argument. The level argument will be a 145 - multiple of ASSOC_ARRAY_KEY_CHUNK_SIZE and the function should return 146 - ASSOC_ARRAY_KEY_CHUNK_SIZE bits. No error is possible. 147 - 148 - 149 - (2) Get a chunk of an object's index key. 150 - 151 - unsigned long (*get_object_key_chunk)(const void *object, int level); 152 - 153 - As the previous function, but gets its data from an object in the array 154 - rather than from a caller-supplied index key. 155 - 156 - 157 - (3) See if this is the object we're looking for. 158 - 159 - bool (*compare_object)(const void *object, const void *index_key); 160 - 161 - Compare the object against an index key and return true if it matches and 162 - false if it doesn't. 163 - 164 - 165 - (4) Diff the index keys of two objects. 166 - 167 - int (*diff_objects)(const void *object, const void *index_key); 168 - 169 - Return the bit position at which the index key of the specified object 170 - differs from the given index key or -1 if they are the same. 171 - 172 - 173 - (5) Free an object. 174 - 175 - void (*free_object)(void *object); 176 - 177 - Free the specified object. Note that this may be called an RCU grace 178 - period after assoc_array_apply_edit() was called, so synchronize_rcu() may 179 - be necessary on module unloading. 180 - 181 - 182 - MANIPULATION FUNCTIONS 183 - ---------------------- 184 - 185 - There are a number of functions for manipulating an associative array: 186 - 187 - (1) Initialise an associative array. 188 - 189 - void assoc_array_init(struct assoc_array *array); 190 - 191 - This initialises the base structure for an associative array. It can't 192 - fail. 193 - 194 - 195 - (2) Insert/replace an object in an associative array. 196 - 197 - struct assoc_array_edit * 198 - assoc_array_insert(struct assoc_array *array, 199 - const struct assoc_array_ops *ops, 200 - const void *index_key, 201 - void *object); 202 - 203 - This inserts the given object into the array. Note that the least 204 - significant bit of the pointer must be zero as it's used to type-mark 205 - pointers internally. 206 - 207 - If an object already exists for that key then it will be replaced with the 208 - new object and the old one will be freed automatically. 209 - 210 - The index_key argument should hold index key information and is 211 - passed to the methods in the ops table when they are called. 212 - 213 - This function makes no alteration to the array itself, but rather returns 214 - an edit script that must be applied. -ENOMEM is returned in the case of 215 - an out-of-memory error. 216 - 217 - The caller should lock exclusively against other modifiers of the array. 218 - 219 - 220 - (3) Delete an object from an associative array. 221 - 222 - struct assoc_array_edit * 223 - assoc_array_delete(struct assoc_array *array, 224 - const struct assoc_array_ops *ops, 225 - const void *index_key); 226 - 227 - This deletes an object that matches the specified data from the array. 228 - 229 - The index_key argument should hold index key information and is 230 - passed to the methods in the ops table when they are called. 231 - 232 - This function makes no alteration to the array itself, but rather returns 233 - an edit script that must be applied. -ENOMEM is returned in the case of 234 - an out-of-memory error. NULL will be returned if the specified object is 235 - not found within the array. 236 - 237 - The caller should lock exclusively against other modifiers of the array. 238 - 239 - 240 - (4) Delete all objects from an associative array. 241 - 242 - struct assoc_array_edit * 243 - assoc_array_clear(struct assoc_array *array, 244 - const struct assoc_array_ops *ops); 245 - 246 - This deletes all the objects from an associative array and leaves it 247 - completely empty. 248 - 249 - This function makes no alteration to the array itself, but rather returns 250 - an edit script that must be applied. -ENOMEM is returned in the case of 251 - an out-of-memory error. 252 - 253 - The caller should lock exclusively against other modifiers of the array. 254 - 255 - 256 - (5) Destroy an associative array, deleting all objects. 257 - 258 - void assoc_array_destroy(struct assoc_array *array, 259 - const struct assoc_array_ops *ops); 260 - 261 - This destroys the contents of the associative array and leaves it 262 - completely empty. It is not permitted for another thread to be traversing 263 - the array under the RCU read lock at the same time as this function is 264 - destroying it as no RCU deferral is performed on memory release - 265 - something that would require memory to be allocated. 266 - 267 - The caller should lock exclusively against other modifiers and accessors 268 - of the array. 269 - 270 - 271 - (6) Garbage collect an associative array. 272 - 273 - int assoc_array_gc(struct assoc_array *array, 274 - const struct assoc_array_ops *ops, 275 - bool (*iterator)(void *object, void *iterator_data), 276 - void *iterator_data); 277 - 278 - This iterates over the objects in an associative array and passes each one 279 - to iterator(). If iterator() returns true, the object is kept. If it 280 - returns false, the object will be freed. If the iterator() function 281 - returns true, it must perform any appropriate refcount incrementing on the 282 - object before returning. 283 - 284 - The internal tree will be packed down if possible as part of the iteration 285 - to reduce the number of nodes in it. 286 - 287 - The iterator_data is passed directly to iterator() and is otherwise 288 - ignored by the function. 289 - 290 - The function will return 0 if successful and -ENOMEM if there wasn't 291 - enough memory. 292 - 293 - It is possible for other threads to iterate over or search the array under 294 - the RCU read lock whilst this function is in progress. The caller should 295 - lock exclusively against other modifiers of the array. 296 - 297 - 298 - ACCESS FUNCTIONS 299 - ---------------- 300 - 301 - There are two functions for accessing an associative array: 302 - 303 - (1) Iterate over all the objects in an associative array. 304 - 305 - int assoc_array_iterate(const struct assoc_array *array, 306 - int (*iterator)(const void *object, 307 - void *iterator_data), 308 - void *iterator_data); 309 - 310 - This passes each object in the array to the iterator callback function. 311 - iterator_data is private data for that function. 312 - 313 - This may be used on an array at the same time as the array is being 314 - modified, provided the RCU read lock is held. Under such circumstances, 315 - it is possible for the iteration function to see some objects twice. If 316 - this is a problem, then modification should be locked against. The 317 - iteration algorithm should not, however, miss any objects. 318 - 319 - The function will return 0 if no objects were in the array or else it will 320 - return the result of the last iterator function called. Iteration stops 321 - immediately if any call to the iteration function results in a non-zero 322 - return. 323 - 324 - 325 - (2) Find an object in an associative array. 326 - 327 - void *assoc_array_find(const struct assoc_array *array, 328 - const struct assoc_array_ops *ops, 329 - const void *index_key); 330 - 331 - This walks through the array's internal tree directly to the object 332 - specified by the index key.. 333 - 334 - This may be used on an array at the same time as the array is being 335 - modified, provided the RCU read lock is held. 336 - 337 - The function will return the object if found (and set *_type to the object 338 - type) or will return NULL if the object was not found. 339 - 340 - 341 - INDEX KEY FORM 342 - -------------- 343 - 344 - The index key can be of any form, but since the algorithms aren't told how long 345 - the key is, it is strongly recommended that the index key includes its length 346 - very early on before any variation due to the length would have an effect on 347 - comparisons. 348 - 349 - This will cause leaves with different length keys to scatter away from each 350 - other - and those with the same length keys to cluster together. 351 - 352 - It is also recommended that the index key begin with a hash of the rest of the 353 - key to maximise scattering throughout keyspace. 354 - 355 - The better the scattering, the wider and lower the internal tree will be. 356 - 357 - Poor scattering isn't too much of a problem as there are shortcuts and nodes 358 - can contain mixtures of leaves and metadata pointers. 359 - 360 - The index key is read in chunks of machine word. Each chunk is subdivided into 361 - one nibble (4 bits) per level, so on a 32-bit CPU this is good for 8 levels and 362 - on a 64-bit CPU, 16 levels. Unless the scattering is really poor, it is 363 - unlikely that more than one word of any particular index key will have to be 364 - used. 365 - 366 - 367 - ================= 368 - INTERNAL WORKINGS 369 - ================= 370 - 371 - The associative array data structure has an internal tree. This tree is 372 - constructed of two types of metadata blocks: nodes and shortcuts. 373 - 374 - A node is an array of slots. Each slot can contain one of four things: 375 - 376 - (*) A NULL pointer, indicating that the slot is empty. 377 - 378 - (*) A pointer to an object (a leaf). 379 - 380 - (*) A pointer to a node at the next level. 381 - 382 - (*) A pointer to a shortcut. 383 - 384 - 385 - BASIC INTERNAL TREE LAYOUT 386 - -------------------------- 387 - 388 - Ignoring shortcuts for the moment, the nodes form a multilevel tree. The index 389 - key space is strictly subdivided by the nodes in the tree and nodes occur on 390 - fixed levels. For example: 391 - 392 - Level: 0 1 2 3 393 - =============== =============== =============== =============== 394 - NODE D 395 - NODE B NODE C +------>+---+ 396 - +------>+---+ +------>+---+ | | 0 | 397 - NODE A | | 0 | | | 0 | | +---+ 398 - +---+ | +---+ | +---+ | : : 399 - | 0 | | : : | : : | +---+ 400 - +---+ | +---+ | +---+ | | f | 401 - | 1 |---+ | 3 |---+ | 7 |---+ +---+ 402 - +---+ +---+ +---+ 403 - : : : : | 8 |---+ 404 - +---+ +---+ +---+ | NODE E 405 - | e |---+ | f | : : +------>+---+ 406 - +---+ | +---+ +---+ | 0 | 407 - | f | | | f | +---+ 408 - +---+ | +---+ : : 409 - | NODE F +---+ 410 - +------>+---+ | f | 411 - | 0 | NODE G +---+ 412 - +---+ +------>+---+ 413 - : : | | 0 | 414 - +---+ | +---+ 415 - | 6 |---+ : : 416 - +---+ +---+ 417 - : : | f | 418 - +---+ +---+ 419 - | f | 420 - +---+ 421 - 422 - In the above example, there are 7 nodes (A-G), each with 16 slots (0-f). 423 - Assuming no other meta data nodes in the tree, the key space is divided thusly: 424 - 425 - KEY PREFIX NODE 426 - ========== ==== 427 - 137* D 428 - 138* E 429 - 13[0-69-f]* C 430 - 1[0-24-f]* B 431 - e6* G 432 - e[0-57-f]* F 433 - [02-df]* A 434 - 435 - So, for instance, keys with the following example index keys will be found in 436 - the appropriate nodes: 437 - 438 - INDEX KEY PREFIX NODE 439 - =============== ======= ==== 440 - 13694892892489 13 C 441 - 13795289025897 137 D 442 - 13889dde88793 138 E 443 - 138bbb89003093 138 E 444 - 1394879524789 12 C 445 - 1458952489 1 B 446 - 9431809de993ba - A 447 - b4542910809cd - A 448 - e5284310def98 e F 449 - e68428974237 e6 G 450 - e7fffcbd443 e F 451 - f3842239082 - A 452 - 453 - To save memory, if a node can hold all the leaves in its portion of keyspace, 454 - then the node will have all those leaves in it and will not have any metadata 455 - pointers - even if some of those leaves would like to be in the same slot. 456 - 457 - A node can contain a heterogeneous mix of leaves and metadata pointers. 458 - Metadata pointers must be in the slots that match their subdivisions of key 459 - space. The leaves can be in any slot not occupied by a metadata pointer. It 460 - is guaranteed that none of the leaves in a node will match a slot occupied by a 461 - metadata pointer. If the metadata pointer is there, any leaf whose key matches 462 - the metadata key prefix must be in the subtree that the metadata pointer points 463 - to. 464 - 465 - In the above example list of index keys, node A will contain: 466 - 467 - SLOT CONTENT INDEX KEY (PREFIX) 468 - ==== =============== ================== 469 - 1 PTR TO NODE B 1* 470 - any LEAF 9431809de993ba 471 - any LEAF b4542910809cd 472 - e PTR TO NODE F e* 473 - any LEAF f3842239082 474 - 475 - and node B: 476 - 477 - 3 PTR TO NODE C 13* 478 - any LEAF 1458952489 479 - 480 - 481 - SHORTCUTS 482 - --------- 483 - 484 - Shortcuts are metadata records that jump over a piece of keyspace. A shortcut 485 - is a replacement for a series of single-occupancy nodes ascending through the 486 - levels. Shortcuts exist to save memory and to speed up traversal. 487 - 488 - It is possible for the root of the tree to be a shortcut - say, for example, 489 - the tree contains at least 17 nodes all with key prefix '1111'. The insertion 490 - algorithm will insert a shortcut to skip over the '1111' keyspace in a single 491 - bound and get to the fourth level where these actually become different. 492 - 493 - 494 - SPLITTING AND COLLAPSING NODES 495 - ------------------------------ 496 - 497 - Each node has a maximum capacity of 16 leaves and metadata pointers. If the 498 - insertion algorithm finds that it is trying to insert a 17th object into a 499 - node, that node will be split such that at least two leaves that have a common 500 - key segment at that level end up in a separate node rooted on that slot for 501 - that common key segment. 502 - 503 - If the leaves in a full node and the leaf that is being inserted are 504 - sufficiently similar, then a shortcut will be inserted into the tree. 505 - 506 - When the number of objects in the subtree rooted at a node falls to 16 or 507 - fewer, then the subtree will be collapsed down to a single node - and this will 508 - ripple towards the root if possible. 509 - 510 - 511 - NON-RECURSIVE ITERATION 512 - ----------------------- 513 - 514 - Each node and shortcut contains a back pointer to its parent and the number of 515 - slot in that parent that points to it. None-recursive iteration uses these to 516 - proceed rootwards through the tree, going to the parent node, slot N + 1 to 517 - make sure progress is made without the need for a stack. 518 - 519 - The backpointers, however, make simultaneous alteration and iteration tricky. 520 - 521 - 522 - SIMULTANEOUS ALTERATION AND ITERATION 523 - ------------------------------------- 524 - 525 - There are a number of cases to consider: 526 - 527 - (1) Simple insert/replace. This involves simply replacing a NULL or old 528 - matching leaf pointer with the pointer to the new leaf after a barrier. 529 - The metadata blocks don't change otherwise. An old leaf won't be freed 530 - until after the RCU grace period. 531 - 532 - (2) Simple delete. This involves just clearing an old matching leaf. The 533 - metadata blocks don't change otherwise. The old leaf won't be freed until 534 - after the RCU grace period. 535 - 536 - (3) Insertion replacing part of a subtree that we haven't yet entered. This 537 - may involve replacement of part of that subtree - but that won't affect 538 - the iteration as we won't have reached the pointer to it yet and the 539 - ancestry blocks are not replaced (the layout of those does not change). 540 - 541 - (4) Insertion replacing nodes that we're actively processing. This isn't a 542 - problem as we've passed the anchoring pointer and won't switch onto the 543 - new layout until we follow the back pointers - at which point we've 544 - already examined the leaves in the replaced node (we iterate over all the 545 - leaves in a node before following any of its metadata pointers). 546 - 547 - We might, however, re-see some leaves that have been split out into a new 548 - branch that's in a slot further along than we were at. 549 - 550 - (5) Insertion replacing nodes that we're processing a dependent branch of. 551 - This won't affect us until we follow the back pointers. Similar to (4). 552 - 553 - (6) Deletion collapsing a branch under us. This doesn't affect us because the 554 - back pointers will get us back to the parent of the new node before we 555 - could see the new node. The entire collapsed subtree is thrown away 556 - unchanged - and will still be rooted on the same slot, so we shouldn't 557 - process it a second time as we'll go back to slot + 1. 558 - 559 - Note: 560 - 561 - (*) Under some circumstances, we need to simultaneously change the parent 562 - pointer and the parent slot pointer on a node (say, for example, we 563 - inserted another node before it and moved it up a level). We cannot do 564 - this without locking against a read - so we have to replace that node too. 565 - 566 - However, when we're changing a shortcut into a node this isn't a problem 567 - as shortcuts only have one slot and so the parent slot number isn't used 568 - when traversing backwards over one. This means that it's okay to change 569 - the slot number first - provided suitable barriers are used to make sure 570 - the parent slot number is read after the back pointer. 571 - 572 - Obsolete blocks and leaves are freed up after an RCU grace period has passed, 573 - so as long as anyone doing walking or iteration holds the RCU read lock, the 574 - old superstructure should not go away on them.
+167 -149
Documentation/atomic_ops.txt Documentation/core-api/atomic_ops.rst
··· 1 - Semantics and Behavior of Atomic and 2 - Bitmask Operations 1 + ======================================================= 2 + Semantics and Behavior of Atomic and Bitmask Operations 3 + ======================================================= 3 4 4 - David S. Miller 5 + :Author: David S. Miller 5 6 6 - This document is intended to serve as a guide to Linux port 7 + This document is intended to serve as a guide to Linux port 7 8 maintainers on how to implement atomic counter, bitops, and spinlock 8 9 interfaces properly. 9 10 10 - The atomic_t type should be defined as a signed integer and 11 + Atomic Type And Operations 12 + ========================== 13 + 14 + The atomic_t type should be defined as a signed integer and 11 15 the atomic_long_t type as a signed long integer. Also, they should 12 16 be made opaque such that any kind of cast to a normal C integer type 13 - will fail. Something like the following should suffice: 17 + will fail. Something like the following should suffice:: 14 18 15 19 typedef struct { int counter; } atomic_t; 16 20 typedef struct { long counter; } atomic_long_t; 17 21 18 22 Historically, counter has been declared volatile. This is now discouraged. 19 - See Documentation/process/volatile-considered-harmful.rst for the complete rationale. 23 + See :ref:`Documentation/process/volatile-considered-harmful.rst 24 + <volatile_considered_harmful>` for the complete rationale. 20 25 21 26 local_t is very similar to atomic_t. If the counter is per CPU and only 22 27 updated by one CPU, local_t is probably more appropriate. Please see 23 - Documentation/local_ops.txt for the semantics of local_t. 28 + :ref:`Documentation/core-api/local_ops.rst <local_ops>` for the semantics of 29 + local_t. 24 30 25 31 The first operations to implement for atomic_t's are the initializers and 26 - plain reads. 32 + plain reads. :: 27 33 28 34 #define ATOMIC_INIT(i) { (i) } 29 35 #define atomic_set(v, i) ((v)->counter = (i)) 30 36 31 - The first macro is used in definitions, such as: 37 + The first macro is used in definitions, such as:: 32 38 33 - static atomic_t my_counter = ATOMIC_INIT(1); 39 + static atomic_t my_counter = ATOMIC_INIT(1); 34 40 35 41 The initializer is atomic in that the return values of the atomic operations 36 42 are guaranteed to be correct reflecting the initialized value if the ··· 44 38 proper implicit or explicit read memory barrier is needed before reading the 45 39 value with atomic_read from another thread. 46 40 47 - As with all of the atomic_ interfaces, replace the leading "atomic_" 48 - with "atomic_long_" to operate on atomic_long_t. 41 + As with all of the ``atomic_`` interfaces, replace the leading ``atomic_`` 42 + with ``atomic_long_`` to operate on atomic_long_t. 49 43 50 - The second interface can be used at runtime, as in: 44 + The second interface can be used at runtime, as in:: 51 45 52 46 struct foo { atomic_t counter; }; 53 47 ... ··· 65 59 or explicit memory barrier is needed before the value set with the operation 66 60 is guaranteed to be readable with atomic_read from another thread. 67 61 68 - Next, we have: 62 + Next, we have:: 69 63 70 64 #define atomic_read(v) ((v)->counter) 71 65 ··· 79 73 interface must take care of that with a proper implicit or explicit memory 80 74 barrier. 81 75 82 - *** WARNING: atomic_read() and atomic_set() DO NOT IMPLY BARRIERS! *** 76 + .. warning:: 83 77 84 - Some architectures may choose to use the volatile keyword, barriers, or inline 85 - assembly to guarantee some degree of immediacy for atomic_read() and 86 - atomic_set(). This is not uniformly guaranteed, and may change in the future, 87 - so all users of atomic_t should treat atomic_read() and atomic_set() as simple 88 - C statements that may be reordered or optimized away entirely by the compiler 89 - or processor, and explicitly invoke the appropriate compiler and/or memory 90 - barrier for each use case. Failure to do so will result in code that may 91 - suddenly break when used with different architectures or compiler 92 - optimizations, or even changes in unrelated code which changes how the 93 - compiler optimizes the section accessing atomic_t variables. 78 + ``atomic_read()`` and ``atomic_set()`` DO NOT IMPLY BARRIERS! 94 79 95 - *** YOU HAVE BEEN WARNED! *** 80 + Some architectures may choose to use the volatile keyword, barriers, or 81 + inline assembly to guarantee some degree of immediacy for atomic_read() 82 + and atomic_set(). This is not uniformly guaranteed, and may change in 83 + the future, so all users of atomic_t should treat atomic_read() and 84 + atomic_set() as simple C statements that may be reordered or optimized 85 + away entirely by the compiler or processor, and explicitly invoke the 86 + appropriate compiler and/or memory barrier for each use case. Failure 87 + to do so will result in code that may suddenly break when used with 88 + different architectures or compiler optimizations, or even changes in 89 + unrelated code which changes how the compiler optimizes the section 90 + accessing atomic_t variables. 96 91 97 92 Properly aligned pointers, longs, ints, and chars (and unsigned 98 93 equivalents) may be atomically loaded from and stored to in the same ··· 102 95 optimizations that might otherwise optimize accesses out of existence on 103 96 the one hand, or that might create unsolicited accesses on the other. 104 97 105 - For example consider the following code: 98 + For example consider the following code:: 106 99 107 100 while (a > 0) 108 101 do_something(); 109 102 110 103 If the compiler can prove that do_something() does not store to the 111 104 variable a, then the compiler is within its rights transforming this to 112 - the following: 105 + the following:: 113 106 114 107 tmp = a; 115 108 if (a > 0) ··· 117 110 do_something(); 118 111 119 112 If you don't want the compiler to do this (and you probably don't), then 120 - you should use something like the following: 113 + you should use something like the following:: 121 114 122 115 while (READ_ONCE(a) < 0) 123 116 do_something(); 124 117 125 118 Alternatively, you could place a barrier() call in the loop. 126 119 127 - For another example, consider the following code: 120 + For another example, consider the following code:: 128 121 129 122 tmp_a = a; 130 123 do_something_with(tmp_a); ··· 132 125 133 126 If the compiler can prove that do_something_with() does not store to the 134 127 variable a, then the compiler is within its rights to manufacture an 135 - additional load as follows: 128 + additional load as follows:: 136 129 137 130 tmp_a = a; 138 131 do_something_with(tmp_a); ··· 146 139 do_something_with() was an inline function that made very heavy use 147 140 of registers: reloading from variable a could save a flush to the 148 141 stack and later reload. To prevent the compiler from attacking your 149 - code in this manner, write the following: 142 + code in this manner, write the following:: 150 143 151 144 tmp_a = READ_ONCE(a); 152 145 do_something_with(tmp_a); ··· 154 147 155 148 For a final example, consider the following code, assuming that the 156 149 variable a is set at boot time before the second CPU is brought online 157 - and never changed later, so that memory barriers are not needed: 150 + and never changed later, so that memory barriers are not needed:: 158 151 159 152 if (a) 160 153 b = 9; ··· 162 155 b = 42; 163 156 164 157 The compiler is within its rights to manufacture an additional store 165 - by transforming the above code into the following: 158 + by transforming the above code into the following:: 166 159 167 160 b = 42; 168 161 if (a) ··· 170 163 171 164 This could come as a fatal surprise to other code running concurrently 172 165 that expected b to never have the value 42 if a was zero. To prevent 173 - the compiler from doing this, write something like: 166 + the compiler from doing this, write something like:: 174 167 175 168 if (a) 176 169 WRITE_ONCE(b, 9); ··· 180 173 Don't even -think- about doing this without proper use of memory barriers, 181 174 locks, or atomic operations if variable a can change at runtime! 182 175 183 - *** WARNING: READ_ONCE() OR WRITE_ONCE() DO NOT IMPLY A BARRIER! *** 176 + .. warning:: 177 + 178 + ``READ_ONCE()`` OR ``WRITE_ONCE()`` DO NOT IMPLY A BARRIER! 184 179 185 180 Now, we move onto the atomic operation interfaces typically implemented with 186 - the help of assembly code. 181 + the help of assembly code. :: 187 182 188 183 void atomic_add(int i, atomic_t *v); 189 184 void atomic_sub(int i, atomic_t *v); ··· 201 192 require any explicit memory barriers. They need only perform the 202 193 atomic_t counter update in an SMP safe manner. 203 194 204 - Next, we have: 195 + Next, we have:: 205 196 206 197 int atomic_inc_return(atomic_t *v); 207 198 int atomic_dec_return(atomic_t *v); ··· 223 214 memory barrier semantics which satisfy the above requirements, that is 224 215 fine as well. 225 216 226 - Let's move on: 217 + Let's move on:: 227 218 228 219 int atomic_add_return(int i, atomic_t *v); 229 220 int atomic_sub_return(int i, atomic_t *v); ··· 233 224 This means that like atomic_{inc,dec}_return(), the memory barrier 234 225 semantics are required. 235 226 236 - Next: 227 + Next:: 237 228 238 229 int atomic_inc_and_test(atomic_t *v); 239 230 int atomic_dec_and_test(atomic_t *v); ··· 243 234 resulting counter value was zero or not. 244 235 245 236 Again, these primitives provide explicit memory barrier semantics around 246 - the atomic operation. 237 + the atomic operation:: 247 238 248 239 int atomic_sub_and_test(int i, atomic_t *v); 249 240 250 241 This is identical to atomic_dec_and_test() except that an explicit 251 242 decrement is given instead of the implicit "1". This primitive must 252 - provide explicit memory barrier semantics around the operation. 243 + provide explicit memory barrier semantics around the operation:: 253 244 254 245 int atomic_add_negative(int i, atomic_t *v); 255 246 ··· 258 249 This primitive must provide explicit memory barrier semantics around 259 250 the operation. 260 251 261 - Then: 252 + Then:: 262 253 263 254 int atomic_xchg(atomic_t *v, int new); 264 255 ··· 266 257 the given new value. It returns the old value that the atomic variable v had 267 258 just before the operation. 268 259 269 - atomic_xchg must provide explicit memory barriers around the operation. 260 + atomic_xchg must provide explicit memory barriers around the operation. :: 270 261 271 262 int atomic_cmpxchg(atomic_t *v, int old, int new); 272 263 273 264 This performs an atomic compare exchange operation on the atomic value v, 274 265 with the given old and new values. Like all atomic_xxx operations, 275 266 atomic_cmpxchg will only satisfy its atomicity semantics as long as all 276 - other accesses of *v are performed through atomic_xxx operations. 267 + other accesses of \*v are performed through atomic_xxx operations. 277 268 278 269 atomic_cmpxchg must provide explicit memory barriers around the operation, 279 270 although if the comparison fails then no memory ordering guarantees are ··· 282 273 The semantics for atomic_cmpxchg are the same as those defined for 'cas' 283 274 below. 284 275 285 - Finally: 276 + Finally:: 286 277 287 278 int atomic_add_unless(atomic_t *v, int a, int u); 288 279 ··· 298 289 299 290 If a caller requires memory barrier semantics around an atomic_t 300 291 operation which does not return a value, a set of interfaces are 301 - defined which accomplish this: 292 + defined which accomplish this:: 302 293 303 294 void smp_mb__before_atomic(void); 304 295 void smp_mb__after_atomic(void); 305 296 306 - For example, smp_mb__before_atomic() can be used like so: 297 + For example, smp_mb__before_atomic() can be used like so:: 307 298 308 299 obj->dead = 1; 309 300 smp_mb__before_atomic(); ··· 324 315 an example, which follows a pattern occurring frequently in the Linux 325 316 kernel. It is the use of atomic counters to implement reference 326 317 counting, and it works such that once the counter falls to zero it can 327 - be guaranteed that no other entity can be accessing the object: 318 + be guaranteed that no other entity can be accessing the object:: 328 319 329 - static void obj_list_add(struct obj *obj, struct list_head *head) 330 - { 331 - obj->active = 1; 332 - list_add(&obj->list, head); 333 - } 320 + static void obj_list_add(struct obj *obj, struct list_head *head) 321 + { 322 + obj->active = 1; 323 + list_add(&obj->list, head); 324 + } 334 325 335 - static void obj_list_del(struct obj *obj) 336 - { 337 - list_del(&obj->list); 338 - obj->active = 0; 339 - } 326 + static void obj_list_del(struct obj *obj) 327 + { 328 + list_del(&obj->list); 329 + obj->active = 0; 330 + } 340 331 341 - static void obj_destroy(struct obj *obj) 342 - { 343 - BUG_ON(obj->active); 344 - kfree(obj); 345 - } 332 + static void obj_destroy(struct obj *obj) 333 + { 334 + BUG_ON(obj->active); 335 + kfree(obj); 336 + } 346 337 347 - struct obj *obj_list_peek(struct list_head *head) 348 - { 349 - if (!list_empty(head)) { 338 + struct obj *obj_list_peek(struct list_head *head) 339 + { 340 + if (!list_empty(head)) { 341 + struct obj *obj; 342 + 343 + obj = list_entry(head->next, struct obj, list); 344 + atomic_inc(&obj->refcnt); 345 + return obj; 346 + } 347 + return NULL; 348 + } 349 + 350 + void obj_poke(void) 351 + { 350 352 struct obj *obj; 351 353 352 - obj = list_entry(head->next, struct obj, list); 353 - atomic_inc(&obj->refcnt); 354 - return obj; 354 + spin_lock(&global_list_lock); 355 + obj = obj_list_peek(&global_list); 356 + spin_unlock(&global_list_lock); 357 + 358 + if (obj) { 359 + obj->ops->poke(obj); 360 + if (atomic_dec_and_test(&obj->refcnt)) 361 + obj_destroy(obj); 362 + } 355 363 } 356 - return NULL; 357 - } 358 364 359 - void obj_poke(void) 360 - { 361 - struct obj *obj; 365 + void obj_timeout(struct obj *obj) 366 + { 367 + spin_lock(&global_list_lock); 368 + obj_list_del(obj); 369 + spin_unlock(&global_list_lock); 362 370 363 - spin_lock(&global_list_lock); 364 - obj = obj_list_peek(&global_list); 365 - spin_unlock(&global_list_lock); 366 - 367 - if (obj) { 368 - obj->ops->poke(obj); 369 371 if (atomic_dec_and_test(&obj->refcnt)) 370 372 obj_destroy(obj); 371 373 } 372 - } 373 374 374 - void obj_timeout(struct obj *obj) 375 - { 376 - spin_lock(&global_list_lock); 377 - obj_list_del(obj); 378 - spin_unlock(&global_list_lock); 375 + .. note:: 379 376 380 - if (atomic_dec_and_test(&obj->refcnt)) 381 - obj_destroy(obj); 382 - } 383 - 384 - (This is a simplification of the ARP queue management in the 385 - generic neighbour discover code of the networking. Olaf Kirch 386 - found a bug wrt. memory barriers in kfree_skb() that exposed 387 - the atomic_t memory barrier requirements quite clearly.) 377 + This is a simplification of the ARP queue management in the generic 378 + neighbour discover code of the networking. Olaf Kirch found a bug wrt. 379 + memory barriers in kfree_skb() that exposed the atomic_t memory barrier 380 + requirements quite clearly. 388 381 389 382 Given the above scheme, it must be the case that the obj->active 390 383 update done by the obj list deletion be visible to other processors ··· 394 383 395 384 Otherwise, the counter could fall to zero, yet obj->active would still 396 385 be set, thus triggering the assertion in obj_destroy(). The error 397 - sequence looks like this: 386 + sequence looks like this:: 398 387 399 388 cpu 0 cpu 1 400 389 obj_poke() obj_timeout() ··· 431 420 Another note is that the atomic_t operations returning values are 432 421 extremely slow on an old 386. 433 422 423 + 424 + Atomic Bitmask 425 + ============== 426 + 434 427 We will now cover the atomic bitmask operations. You will find that 435 428 their SMP and memory barrier semantics are similar in shape and scope 436 429 to the atomic_t ops above. ··· 442 427 Native atomic bit operations are defined to operate on objects aligned 443 428 to the size of an "unsigned long" C data type, and are least of that 444 429 size. The endianness of the bits within each "unsigned long" are the 445 - native endianness of the cpu. 430 + native endianness of the cpu. :: 446 431 447 432 void set_bit(unsigned long nr, volatile unsigned long *addr); 448 433 void clear_bit(unsigned long nr, volatile unsigned long *addr); ··· 452 437 indicated by "nr" on the bit mask pointed to by "ADDR". 453 438 454 439 They must execute atomically, yet there are no implicit memory barrier 455 - semantics required of these interfaces. 440 + semantics required of these interfaces. :: 456 441 457 442 int test_and_set_bit(unsigned long nr, volatile unsigned long *addr); 458 443 int test_and_clear_bit(unsigned long nr, volatile unsigned long *addr); ··· 481 466 All memory operations before the atomic bit operation call must be 482 467 made visible globally before the atomic bit operation is made visible. 483 468 Likewise, the atomic bit operation must be visible globally before any 484 - subsequent memory operation is made visible. For example: 469 + subsequent memory operation is made visible. For example:: 485 470 486 471 obj->dead = 1; 487 472 if (test_and_set_bit(0, &obj->flags)) ··· 494 479 memory operation done by test_and_set_bit() must become visible before 495 480 "obj->killed = 1;" is visible. 496 481 497 - Finally there is the basic operation: 482 + Finally there is the basic operation:: 498 483 499 484 int test_bit(unsigned long nr, __const__ volatile unsigned long *addr); 500 485 ··· 503 488 504 489 If explicit memory barriers are required around {set,clear}_bit() (which do 505 490 not return a value, and thus does not need to provide memory barrier 506 - semantics), two interfaces are provided: 491 + semantics), two interfaces are provided:: 507 492 508 493 void smp_mb__before_atomic(void); 509 494 void smp_mb__after_atomic(void); 510 495 511 496 They are used as follows, and are akin to their atomic_t operation 512 - brothers: 497 + brothers:: 513 498 514 499 /* All memory operations before this call will 515 500 * be globally visible before the clear_bit(). ··· 526 511 same as spinlocks). These operate in the same way as their non-_lock/unlock 527 512 postfixed variants, except that they are to provide acquire/release semantics, 528 513 respectively. This means they can be used for bit_spin_trylock and 529 - bit_spin_unlock type operations without specifying any more barriers. 514 + bit_spin_unlock type operations without specifying any more barriers. :: 530 515 531 516 int test_and_set_bit_lock(unsigned long nr, unsigned long *addr); 532 517 void clear_bit_unlock(unsigned long nr, unsigned long *addr); ··· 541 526 locking scheme is being used to protect the bitmask, and thus less 542 527 expensive non-atomic operations may be used in the implementation. 543 528 They have names similar to the above bitmask operation interfaces, 544 - except that two underscores are prefixed to the interface name. 529 + except that two underscores are prefixed to the interface name. :: 545 530 546 531 void __set_bit(unsigned long nr, volatile unsigned long *addr); 547 532 void __clear_bit(unsigned long nr, volatile unsigned long *addr); ··· 557 542 memory-barrier semantics as the atomic and bit operations returning 558 543 values. 559 544 560 - Note: If someone wants to use xchg(), cmpxchg() and their variants, 561 - linux/atomic.h should be included rather than asm/cmpxchg.h, unless 562 - the code is in arch/* and can take care of itself. 545 + .. note:: 546 + 547 + If someone wants to use xchg(), cmpxchg() and their variants, 548 + linux/atomic.h should be included rather than asm/cmpxchg.h, unless the 549 + code is in arch/* and can take care of itself. 563 550 564 551 Spinlocks and rwlocks have memory barrier expectations as well. 565 552 The rule to follow is simple: ··· 575 558 576 559 Which finally brings us to _atomic_dec_and_lock(). There is an 577 560 architecture-neutral version implemented in lib/dec_and_lock.c, 578 - but most platforms will wish to optimize this in assembler. 561 + but most platforms will wish to optimize this in assembler. :: 579 562 580 563 int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock); 581 564 ··· 590 573 subsequent memory operation. 591 574 592 575 We can demonstrate this operation more clearly if we define 593 - an abstract atomic operation: 576 + an abstract atomic operation:: 594 577 595 578 long cas(long *mem, long old, long new); 596 579 ··· 601 584 3) Regardless, the current value at "mem" is returned. 602 585 603 586 As an example usage, here is what an atomic counter update 604 - might look like: 587 + might look like:: 605 588 606 - void example_atomic_inc(long *counter) 607 - { 608 - long old, new, ret; 589 + void example_atomic_inc(long *counter) 590 + { 591 + long old, new, ret; 609 592 610 - while (1) { 611 - old = *counter; 612 - new = old + 1; 593 + while (1) { 594 + old = *counter; 595 + new = old + 1; 613 596 614 - ret = cas(counter, old, new); 615 - if (ret == old) 616 - break; 617 - } 618 - } 619 - 620 - Let's use cas() in order to build a pseudo-C atomic_dec_and_lock(): 621 - 622 - int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock) 623 - { 624 - long old, new, ret; 625 - int went_to_zero; 626 - 627 - went_to_zero = 0; 628 - while (1) { 629 - old = atomic_read(atomic); 630 - new = old - 1; 631 - if (new == 0) { 632 - went_to_zero = 1; 633 - spin_lock(lock); 634 - } 635 - ret = cas(atomic, old, new); 636 - if (ret == old) 637 - break; 638 - if (went_to_zero) { 639 - spin_unlock(lock); 640 - went_to_zero = 0; 597 + ret = cas(counter, old, new); 598 + if (ret == old) 599 + break; 641 600 } 642 601 } 643 602 644 - return went_to_zero; 645 - } 603 + Let's use cas() in order to build a pseudo-C atomic_dec_and_lock():: 604 + 605 + int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock) 606 + { 607 + long old, new, ret; 608 + int went_to_zero; 609 + 610 + went_to_zero = 0; 611 + while (1) { 612 + old = atomic_read(atomic); 613 + new = old - 1; 614 + if (new == 0) { 615 + went_to_zero = 1; 616 + spin_lock(lock); 617 + } 618 + ret = cas(atomic, old, new); 619 + if (ret == old) 620 + break; 621 + if (went_to_zero) { 622 + spin_unlock(lock); 623 + went_to_zero = 0; 624 + } 625 + } 626 + 627 + return went_to_zero; 628 + } 646 629 647 630 Now, as far as memory barriers go, as long as spin_lock() 648 631 strictly orders all subsequent memory operations (including ··· 652 635 a counter dropping to zero is never made visible before the 653 636 spinlock being acquired. 654 637 655 - Note that this also means that for the case where the counter 656 - is not dropping to zero, there are no memory ordering 657 - requirements. 638 + .. note:: 639 + 640 + Note that this also means that for the case where the counter is not 641 + dropping to zero, there are no memory ordering requirements.
+551
Documentation/core-api/assoc_array.rst
··· 1 + ======================================== 2 + Generic Associative Array Implementation 3 + ======================================== 4 + 5 + Overview 6 + ======== 7 + 8 + This associative array implementation is an object container with the following 9 + properties: 10 + 11 + 1. Objects are opaque pointers. The implementation does not care where they 12 + point (if anywhere) or what they point to (if anything). 13 + .. note:: Pointers to objects _must_ be zero in the least significant bit.** 14 + 15 + 2. Objects do not need to contain linkage blocks for use by the array. This 16 + permits an object to be located in multiple arrays simultaneously. 17 + Rather, the array is made up of metadata blocks that point to objects. 18 + 19 + 3. Objects require index keys to locate them within the array. 20 + 21 + 4. Index keys must be unique. Inserting an object with the same key as one 22 + already in the array will replace the old object. 23 + 24 + 5. Index keys can be of any length and can be of different lengths. 25 + 26 + 6. Index keys should encode the length early on, before any variation due to 27 + length is seen. 28 + 29 + 7. Index keys can include a hash to scatter objects throughout the array. 30 + 31 + 8. The array can iterated over. The objects will not necessarily come out in 32 + key order. 33 + 34 + 9. The array can be iterated over whilst it is being modified, provided the 35 + RCU readlock is being held by the iterator. Note, however, under these 36 + circumstances, some objects may be seen more than once. If this is a 37 + problem, the iterator should lock against modification. Objects will not 38 + be missed, however, unless deleted. 39 + 40 + 10. Objects in the array can be looked up by means of their index key. 41 + 42 + 11. Objects can be looked up whilst the array is being modified, provided the 43 + RCU readlock is being held by the thread doing the look up. 44 + 45 + The implementation uses a tree of 16-pointer nodes internally that are indexed 46 + on each level by nibbles from the index key in the same manner as in a radix 47 + tree. To improve memory efficiency, shortcuts can be emplaced to skip over 48 + what would otherwise be a series of single-occupancy nodes. Further, nodes 49 + pack leaf object pointers into spare space in the node rather than making an 50 + extra branch until as such time an object needs to be added to a full node. 51 + 52 + 53 + The Public API 54 + ============== 55 + 56 + The public API can be found in ``<linux/assoc_array.h>``. The associative 57 + array is rooted on the following structure:: 58 + 59 + struct assoc_array { 60 + ... 61 + }; 62 + 63 + The code is selected by enabling ``CONFIG_ASSOCIATIVE_ARRAY`` with:: 64 + 65 + ./script/config -e ASSOCIATIVE_ARRAY 66 + 67 + 68 + Edit Script 69 + ----------- 70 + 71 + The insertion and deletion functions produce an 'edit script' that can later be 72 + applied to effect the changes without risking ``ENOMEM``. This retains the 73 + preallocated metadata blocks that will be installed in the internal tree and 74 + keeps track of the metadata blocks that will be removed from the tree when the 75 + script is applied. 76 + 77 + This is also used to keep track of dead blocks and dead objects after the 78 + script has been applied so that they can be freed later. The freeing is done 79 + after an RCU grace period has passed - thus allowing access functions to 80 + proceed under the RCU read lock. 81 + 82 + The script appears as outside of the API as a pointer of the type:: 83 + 84 + struct assoc_array_edit; 85 + 86 + There are two functions for dealing with the script: 87 + 88 + 1. Apply an edit script:: 89 + 90 + void assoc_array_apply_edit(struct assoc_array_edit *edit); 91 + 92 + This will perform the edit functions, interpolating various write barriers 93 + to permit accesses under the RCU read lock to continue. The edit script 94 + will then be passed to ``call_rcu()`` to free it and any dead stuff it points 95 + to. 96 + 97 + 2. Cancel an edit script:: 98 + 99 + void assoc_array_cancel_edit(struct assoc_array_edit *edit); 100 + 101 + This frees the edit script and all preallocated memory immediately. If 102 + this was for insertion, the new object is _not_ released by this function, 103 + but must rather be released by the caller. 104 + 105 + These functions are guaranteed not to fail. 106 + 107 + 108 + Operations Table 109 + ---------------- 110 + 111 + Various functions take a table of operations:: 112 + 113 + struct assoc_array_ops { 114 + ... 115 + }; 116 + 117 + This points to a number of methods, all of which need to be provided: 118 + 119 + 1. Get a chunk of index key from caller data:: 120 + 121 + unsigned long (*get_key_chunk)(const void *index_key, int level); 122 + 123 + This should return a chunk of caller-supplied index key starting at the 124 + *bit* position given by the level argument. The level argument will be a 125 + multiple of ``ASSOC_ARRAY_KEY_CHUNK_SIZE`` and the function should return 126 + ``ASSOC_ARRAY_KEY_CHUNK_SIZE bits``. No error is possible. 127 + 128 + 129 + 2. Get a chunk of an object's index key:: 130 + 131 + unsigned long (*get_object_key_chunk)(const void *object, int level); 132 + 133 + As the previous function, but gets its data from an object in the array 134 + rather than from a caller-supplied index key. 135 + 136 + 137 + 3. See if this is the object we're looking for:: 138 + 139 + bool (*compare_object)(const void *object, const void *index_key); 140 + 141 + Compare the object against an index key and return ``true`` if it matches and 142 + ``false`` if it doesn't. 143 + 144 + 145 + 4. Diff the index keys of two objects:: 146 + 147 + int (*diff_objects)(const void *object, const void *index_key); 148 + 149 + Return the bit position at which the index key of the specified object 150 + differs from the given index key or -1 if they are the same. 151 + 152 + 153 + 5. Free an object:: 154 + 155 + void (*free_object)(void *object); 156 + 157 + Free the specified object. Note that this may be called an RCU grace period 158 + after ``assoc_array_apply_edit()`` was called, so ``synchronize_rcu()`` may be 159 + necessary on module unloading. 160 + 161 + 162 + Manipulation Functions 163 + ---------------------- 164 + 165 + There are a number of functions for manipulating an associative array: 166 + 167 + 1. Initialise an associative array:: 168 + 169 + void assoc_array_init(struct assoc_array *array); 170 + 171 + This initialises the base structure for an associative array. It can't fail. 172 + 173 + 174 + 2. Insert/replace an object in an associative array:: 175 + 176 + struct assoc_array_edit * 177 + assoc_array_insert(struct assoc_array *array, 178 + const struct assoc_array_ops *ops, 179 + const void *index_key, 180 + void *object); 181 + 182 + This inserts the given object into the array. Note that the least 183 + significant bit of the pointer must be zero as it's used to type-mark 184 + pointers internally. 185 + 186 + If an object already exists for that key then it will be replaced with the 187 + new object and the old one will be freed automatically. 188 + 189 + The ``index_key`` argument should hold index key information and is 190 + passed to the methods in the ops table when they are called. 191 + 192 + This function makes no alteration to the array itself, but rather returns 193 + an edit script that must be applied. ``-ENOMEM`` is returned in the case of 194 + an out-of-memory error. 195 + 196 + The caller should lock exclusively against other modifiers of the array. 197 + 198 + 199 + 3. Delete an object from an associative array:: 200 + 201 + struct assoc_array_edit * 202 + assoc_array_delete(struct assoc_array *array, 203 + const struct assoc_array_ops *ops, 204 + const void *index_key); 205 + 206 + This deletes an object that matches the specified data from the array. 207 + 208 + The ``index_key`` argument should hold index key information and is 209 + passed to the methods in the ops table when they are called. 210 + 211 + This function makes no alteration to the array itself, but rather returns 212 + an edit script that must be applied. ``-ENOMEM`` is returned in the case of 213 + an out-of-memory error. ``NULL`` will be returned if the specified object is 214 + not found within the array. 215 + 216 + The caller should lock exclusively against other modifiers of the array. 217 + 218 + 219 + 4. Delete all objects from an associative array:: 220 + 221 + struct assoc_array_edit * 222 + assoc_array_clear(struct assoc_array *array, 223 + const struct assoc_array_ops *ops); 224 + 225 + This deletes all the objects from an associative array and leaves it 226 + completely empty. 227 + 228 + This function makes no alteration to the array itself, but rather returns 229 + an edit script that must be applied. ``-ENOMEM`` is returned in the case of 230 + an out-of-memory error. 231 + 232 + The caller should lock exclusively against other modifiers of the array. 233 + 234 + 235 + 5. Destroy an associative array, deleting all objects:: 236 + 237 + void assoc_array_destroy(struct assoc_array *array, 238 + const struct assoc_array_ops *ops); 239 + 240 + This destroys the contents of the associative array and leaves it 241 + completely empty. It is not permitted for another thread to be traversing 242 + the array under the RCU read lock at the same time as this function is 243 + destroying it as no RCU deferral is performed on memory release - 244 + something that would require memory to be allocated. 245 + 246 + The caller should lock exclusively against other modifiers and accessors 247 + of the array. 248 + 249 + 250 + 6. Garbage collect an associative array:: 251 + 252 + int assoc_array_gc(struct assoc_array *array, 253 + const struct assoc_array_ops *ops, 254 + bool (*iterator)(void *object, void *iterator_data), 255 + void *iterator_data); 256 + 257 + This iterates over the objects in an associative array and passes each one to 258 + ``iterator()``. If ``iterator()`` returns ``true``, the object is kept. If it 259 + returns ``false``, the object will be freed. If the ``iterator()`` function 260 + returns ``true``, it must perform any appropriate refcount incrementing on the 261 + object before returning. 262 + 263 + The internal tree will be packed down if possible as part of the iteration 264 + to reduce the number of nodes in it. 265 + 266 + The ``iterator_data`` is passed directly to ``iterator()`` and is otherwise 267 + ignored by the function. 268 + 269 + The function will return ``0`` if successful and ``-ENOMEM`` if there wasn't 270 + enough memory. 271 + 272 + It is possible for other threads to iterate over or search the array under 273 + the RCU read lock whilst this function is in progress. The caller should 274 + lock exclusively against other modifiers of the array. 275 + 276 + 277 + Access Functions 278 + ---------------- 279 + 280 + There are two functions for accessing an associative array: 281 + 282 + 1. Iterate over all the objects in an associative array:: 283 + 284 + int assoc_array_iterate(const struct assoc_array *array, 285 + int (*iterator)(const void *object, 286 + void *iterator_data), 287 + void *iterator_data); 288 + 289 + This passes each object in the array to the iterator callback function. 290 + ``iterator_data`` is private data for that function. 291 + 292 + This may be used on an array at the same time as the array is being 293 + modified, provided the RCU read lock is held. Under such circumstances, 294 + it is possible for the iteration function to see some objects twice. If 295 + this is a problem, then modification should be locked against. The 296 + iteration algorithm should not, however, miss any objects. 297 + 298 + The function will return ``0`` if no objects were in the array or else it will 299 + return the result of the last iterator function called. Iteration stops 300 + immediately if any call to the iteration function results in a non-zero 301 + return. 302 + 303 + 304 + 2. Find an object in an associative array:: 305 + 306 + void *assoc_array_find(const struct assoc_array *array, 307 + const struct assoc_array_ops *ops, 308 + const void *index_key); 309 + 310 + This walks through the array's internal tree directly to the object 311 + specified by the index key.. 312 + 313 + This may be used on an array at the same time as the array is being 314 + modified, provided the RCU read lock is held. 315 + 316 + The function will return the object if found (and set ``*_type`` to the object 317 + type) or will return ``NULL`` if the object was not found. 318 + 319 + 320 + Index Key Form 321 + -------------- 322 + 323 + The index key can be of any form, but since the algorithms aren't told how long 324 + the key is, it is strongly recommended that the index key includes its length 325 + very early on before any variation due to the length would have an effect on 326 + comparisons. 327 + 328 + This will cause leaves with different length keys to scatter away from each 329 + other - and those with the same length keys to cluster together. 330 + 331 + It is also recommended that the index key begin with a hash of the rest of the 332 + key to maximise scattering throughout keyspace. 333 + 334 + The better the scattering, the wider and lower the internal tree will be. 335 + 336 + Poor scattering isn't too much of a problem as there are shortcuts and nodes 337 + can contain mixtures of leaves and metadata pointers. 338 + 339 + The index key is read in chunks of machine word. Each chunk is subdivided into 340 + one nibble (4 bits) per level, so on a 32-bit CPU this is good for 8 levels and 341 + on a 64-bit CPU, 16 levels. Unless the scattering is really poor, it is 342 + unlikely that more than one word of any particular index key will have to be 343 + used. 344 + 345 + 346 + Internal Workings 347 + ================= 348 + 349 + The associative array data structure has an internal tree. This tree is 350 + constructed of two types of metadata blocks: nodes and shortcuts. 351 + 352 + A node is an array of slots. Each slot can contain one of four things: 353 + 354 + * A NULL pointer, indicating that the slot is empty. 355 + * A pointer to an object (a leaf). 356 + * A pointer to a node at the next level. 357 + * A pointer to a shortcut. 358 + 359 + 360 + Basic Internal Tree Layout 361 + -------------------------- 362 + 363 + Ignoring shortcuts for the moment, the nodes form a multilevel tree. The index 364 + key space is strictly subdivided by the nodes in the tree and nodes occur on 365 + fixed levels. For example:: 366 + 367 + Level: 0 1 2 3 368 + =============== =============== =============== =============== 369 + NODE D 370 + NODE B NODE C +------>+---+ 371 + +------>+---+ +------>+---+ | | 0 | 372 + NODE A | | 0 | | | 0 | | +---+ 373 + +---+ | +---+ | +---+ | : : 374 + | 0 | | : : | : : | +---+ 375 + +---+ | +---+ | +---+ | | f | 376 + | 1 |---+ | 3 |---+ | 7 |---+ +---+ 377 + +---+ +---+ +---+ 378 + : : : : | 8 |---+ 379 + +---+ +---+ +---+ | NODE E 380 + | e |---+ | f | : : +------>+---+ 381 + +---+ | +---+ +---+ | 0 | 382 + | f | | | f | +---+ 383 + +---+ | +---+ : : 384 + | NODE F +---+ 385 + +------>+---+ | f | 386 + | 0 | NODE G +---+ 387 + +---+ +------>+---+ 388 + : : | | 0 | 389 + +---+ | +---+ 390 + | 6 |---+ : : 391 + +---+ +---+ 392 + : : | f | 393 + +---+ +---+ 394 + | f | 395 + +---+ 396 + 397 + In the above example, there are 7 nodes (A-G), each with 16 slots (0-f). 398 + Assuming no other meta data nodes in the tree, the key space is divided 399 + thusly:: 400 + 401 + KEY PREFIX NODE 402 + ========== ==== 403 + 137* D 404 + 138* E 405 + 13[0-69-f]* C 406 + 1[0-24-f]* B 407 + e6* G 408 + e[0-57-f]* F 409 + [02-df]* A 410 + 411 + So, for instance, keys with the following example index keys will be found in 412 + the appropriate nodes:: 413 + 414 + INDEX KEY PREFIX NODE 415 + =============== ======= ==== 416 + 13694892892489 13 C 417 + 13795289025897 137 D 418 + 13889dde88793 138 E 419 + 138bbb89003093 138 E 420 + 1394879524789 12 C 421 + 1458952489 1 B 422 + 9431809de993ba - A 423 + b4542910809cd - A 424 + e5284310def98 e F 425 + e68428974237 e6 G 426 + e7fffcbd443 e F 427 + f3842239082 - A 428 + 429 + To save memory, if a node can hold all the leaves in its portion of keyspace, 430 + then the node will have all those leaves in it and will not have any metadata 431 + pointers - even if some of those leaves would like to be in the same slot. 432 + 433 + A node can contain a heterogeneous mix of leaves and metadata pointers. 434 + Metadata pointers must be in the slots that match their subdivisions of key 435 + space. The leaves can be in any slot not occupied by a metadata pointer. It 436 + is guaranteed that none of the leaves in a node will match a slot occupied by a 437 + metadata pointer. If the metadata pointer is there, any leaf whose key matches 438 + the metadata key prefix must be in the subtree that the metadata pointer points 439 + to. 440 + 441 + In the above example list of index keys, node A will contain:: 442 + 443 + SLOT CONTENT INDEX KEY (PREFIX) 444 + ==== =============== ================== 445 + 1 PTR TO NODE B 1* 446 + any LEAF 9431809de993ba 447 + any LEAF b4542910809cd 448 + e PTR TO NODE F e* 449 + any LEAF f3842239082 450 + 451 + and node B:: 452 + 453 + 3 PTR TO NODE C 13* 454 + any LEAF 1458952489 455 + 456 + 457 + Shortcuts 458 + --------- 459 + 460 + Shortcuts are metadata records that jump over a piece of keyspace. A shortcut 461 + is a replacement for a series of single-occupancy nodes ascending through the 462 + levels. Shortcuts exist to save memory and to speed up traversal. 463 + 464 + It is possible for the root of the tree to be a shortcut - say, for example, 465 + the tree contains at least 17 nodes all with key prefix ``1111``. The 466 + insertion algorithm will insert a shortcut to skip over the ``1111`` keyspace 467 + in a single bound and get to the fourth level where these actually become 468 + different. 469 + 470 + 471 + Splitting And Collapsing Nodes 472 + ------------------------------ 473 + 474 + Each node has a maximum capacity of 16 leaves and metadata pointers. If the 475 + insertion algorithm finds that it is trying to insert a 17th object into a 476 + node, that node will be split such that at least two leaves that have a common 477 + key segment at that level end up in a separate node rooted on that slot for 478 + that common key segment. 479 + 480 + If the leaves in a full node and the leaf that is being inserted are 481 + sufficiently similar, then a shortcut will be inserted into the tree. 482 + 483 + When the number of objects in the subtree rooted at a node falls to 16 or 484 + fewer, then the subtree will be collapsed down to a single node - and this will 485 + ripple towards the root if possible. 486 + 487 + 488 + Non-Recursive Iteration 489 + ----------------------- 490 + 491 + Each node and shortcut contains a back pointer to its parent and the number of 492 + slot in that parent that points to it. None-recursive iteration uses these to 493 + proceed rootwards through the tree, going to the parent node, slot N + 1 to 494 + make sure progress is made without the need for a stack. 495 + 496 + The backpointers, however, make simultaneous alteration and iteration tricky. 497 + 498 + 499 + Simultaneous Alteration And Iteration 500 + ------------------------------------- 501 + 502 + There are a number of cases to consider: 503 + 504 + 1. Simple insert/replace. This involves simply replacing a NULL or old 505 + matching leaf pointer with the pointer to the new leaf after a barrier. 506 + The metadata blocks don't change otherwise. An old leaf won't be freed 507 + until after the RCU grace period. 508 + 509 + 2. Simple delete. This involves just clearing an old matching leaf. The 510 + metadata blocks don't change otherwise. The old leaf won't be freed until 511 + after the RCU grace period. 512 + 513 + 3. Insertion replacing part of a subtree that we haven't yet entered. This 514 + may involve replacement of part of that subtree - but that won't affect 515 + the iteration as we won't have reached the pointer to it yet and the 516 + ancestry blocks are not replaced (the layout of those does not change). 517 + 518 + 4. Insertion replacing nodes that we're actively processing. This isn't a 519 + problem as we've passed the anchoring pointer and won't switch onto the 520 + new layout until we follow the back pointers - at which point we've 521 + already examined the leaves in the replaced node (we iterate over all the 522 + leaves in a node before following any of its metadata pointers). 523 + 524 + We might, however, re-see some leaves that have been split out into a new 525 + branch that's in a slot further along than we were at. 526 + 527 + 5. Insertion replacing nodes that we're processing a dependent branch of. 528 + This won't affect us until we follow the back pointers. Similar to (4). 529 + 530 + 6. Deletion collapsing a branch under us. This doesn't affect us because the 531 + back pointers will get us back to the parent of the new node before we 532 + could see the new node. The entire collapsed subtree is thrown away 533 + unchanged - and will still be rooted on the same slot, so we shouldn't 534 + process it a second time as we'll go back to slot + 1. 535 + 536 + .. note:: 537 + 538 + Under some circumstances, we need to simultaneously change the parent 539 + pointer and the parent slot pointer on a node (say, for example, we 540 + inserted another node before it and moved it up a level). We cannot do 541 + this without locking against a read - so we have to replace that node too. 542 + 543 + However, when we're changing a shortcut into a node this isn't a problem 544 + as shortcuts only have one slot and so the parent slot number isn't used 545 + when traversing backwards over one. This means that it's okay to change 546 + the slot number first - provided suitable barriers are used to make sure 547 + the parent slot number is read after the back pointer. 548 + 549 + Obsolete blocks and leaves are freed up after an RCU grace period has passed, 550 + so as long as anyone doing walking or iteration holds the RCU read lock, the 551 + old superstructure should not go away on them.
+3
Documentation/core-api/index.rst
··· 11 11 .. toctree:: 12 12 :maxdepth: 1 13 13 14 + assoc_array 15 + atomic_ops 16 + local_ops 14 17 workqueue 15 18 16 19 Interfaces for kernel debugging
+206
Documentation/core-api/local_ops.rst
··· 1 + 2 + .. _local_ops: 3 + 4 + ================================================= 5 + Semantics and Behavior of Local Atomic Operations 6 + ================================================= 7 + 8 + :Author: Mathieu Desnoyers 9 + 10 + 11 + This document explains the purpose of the local atomic operations, how 12 + to implement them for any given architecture and shows how they can be used 13 + properly. It also stresses on the precautions that must be taken when reading 14 + those local variables across CPUs when the order of memory writes matters. 15 + 16 + .. note:: 17 + 18 + Note that ``local_t`` based operations are not recommended for general 19 + kernel use. Please use the ``this_cpu`` operations instead unless there is 20 + really a special purpose. Most uses of ``local_t`` in the kernel have been 21 + replaced by ``this_cpu`` operations. ``this_cpu`` operations combine the 22 + relocation with the ``local_t`` like semantics in a single instruction and 23 + yield more compact and faster executing code. 24 + 25 + 26 + Purpose of local atomic operations 27 + ================================== 28 + 29 + Local atomic operations are meant to provide fast and highly reentrant per CPU 30 + counters. They minimize the performance cost of standard atomic operations by 31 + removing the LOCK prefix and memory barriers normally required to synchronize 32 + across CPUs. 33 + 34 + Having fast per CPU atomic counters is interesting in many cases: it does not 35 + require disabling interrupts to protect from interrupt handlers and it permits 36 + coherent counters in NMI handlers. It is especially useful for tracing purposes 37 + and for various performance monitoring counters. 38 + 39 + Local atomic operations only guarantee variable modification atomicity wrt the 40 + CPU which owns the data. Therefore, care must taken to make sure that only one 41 + CPU writes to the ``local_t`` data. This is done by using per cpu data and 42 + making sure that we modify it from within a preemption safe context. It is 43 + however permitted to read ``local_t`` data from any CPU: it will then appear to 44 + be written out of order wrt other memory writes by the owner CPU. 45 + 46 + 47 + Implementation for a given architecture 48 + ======================================= 49 + 50 + It can be done by slightly modifying the standard atomic operations: only 51 + their UP variant must be kept. It typically means removing LOCK prefix (on 52 + i386 and x86_64) and any SMP synchronization barrier. If the architecture does 53 + not have a different behavior between SMP and UP, including 54 + ``asm-generic/local.h`` in your architecture's ``local.h`` is sufficient. 55 + 56 + The ``local_t`` type is defined as an opaque ``signed long`` by embedding an 57 + ``atomic_long_t`` inside a structure. This is made so a cast from this type to 58 + a ``long`` fails. The definition looks like:: 59 + 60 + typedef struct { atomic_long_t a; } local_t; 61 + 62 + 63 + Rules to follow when using local atomic operations 64 + ================================================== 65 + 66 + * Variables touched by local ops must be per cpu variables. 67 + * *Only* the CPU owner of these variables must write to them. 68 + * This CPU can use local ops from any context (process, irq, softirq, nmi, ...) 69 + to update its ``local_t`` variables. 70 + * Preemption (or interrupts) must be disabled when using local ops in 71 + process context to make sure the process won't be migrated to a 72 + different CPU between getting the per-cpu variable and doing the 73 + actual local op. 74 + * When using local ops in interrupt context, no special care must be 75 + taken on a mainline kernel, since they will run on the local CPU with 76 + preemption already disabled. I suggest, however, to explicitly 77 + disable preemption anyway to make sure it will still work correctly on 78 + -rt kernels. 79 + * Reading the local cpu variable will provide the current copy of the 80 + variable. 81 + * Reads of these variables can be done from any CPU, because updates to 82 + "``long``", aligned, variables are always atomic. Since no memory 83 + synchronization is done by the writer CPU, an outdated copy of the 84 + variable can be read when reading some *other* cpu's variables. 85 + 86 + 87 + How to use local atomic operations 88 + ================================== 89 + 90 + :: 91 + 92 + #include <linux/percpu.h> 93 + #include <asm/local.h> 94 + 95 + static DEFINE_PER_CPU(local_t, counters) = LOCAL_INIT(0); 96 + 97 + 98 + Counting 99 + ======== 100 + 101 + Counting is done on all the bits of a signed long. 102 + 103 + In preemptible context, use ``get_cpu_var()`` and ``put_cpu_var()`` around 104 + local atomic operations: it makes sure that preemption is disabled around write 105 + access to the per cpu variable. For instance:: 106 + 107 + local_inc(&get_cpu_var(counters)); 108 + put_cpu_var(counters); 109 + 110 + If you are already in a preemption-safe context, you can use 111 + ``this_cpu_ptr()`` instead:: 112 + 113 + local_inc(this_cpu_ptr(&counters)); 114 + 115 + 116 + 117 + Reading the counters 118 + ==================== 119 + 120 + Those local counters can be read from foreign CPUs to sum the count. Note that 121 + the data seen by local_read across CPUs must be considered to be out of order 122 + relatively to other memory writes happening on the CPU that owns the data:: 123 + 124 + long sum = 0; 125 + for_each_online_cpu(cpu) 126 + sum += local_read(&per_cpu(counters, cpu)); 127 + 128 + If you want to use a remote local_read to synchronize access to a resource 129 + between CPUs, explicit ``smp_wmb()`` and ``smp_rmb()`` memory barriers must be used 130 + respectively on the writer and the reader CPUs. It would be the case if you use 131 + the ``local_t`` variable as a counter of bytes written in a buffer: there should 132 + be a ``smp_wmb()`` between the buffer write and the counter increment and also a 133 + ``smp_rmb()`` between the counter read and the buffer read. 134 + 135 + 136 + Here is a sample module which implements a basic per cpu counter using 137 + ``local.h``:: 138 + 139 + /* test-local.c 140 + * 141 + * Sample module for local.h usage. 142 + */ 143 + 144 + 145 + #include <asm/local.h> 146 + #include <linux/module.h> 147 + #include <linux/timer.h> 148 + 149 + static DEFINE_PER_CPU(local_t, counters) = LOCAL_INIT(0); 150 + 151 + static struct timer_list test_timer; 152 + 153 + /* IPI called on each CPU. */ 154 + static void test_each(void *info) 155 + { 156 + /* Increment the counter from a non preemptible context */ 157 + printk("Increment on cpu %d\n", smp_processor_id()); 158 + local_inc(this_cpu_ptr(&counters)); 159 + 160 + /* This is what incrementing the variable would look like within a 161 + * preemptible context (it disables preemption) : 162 + * 163 + * local_inc(&get_cpu_var(counters)); 164 + * put_cpu_var(counters); 165 + */ 166 + } 167 + 168 + static void do_test_timer(unsigned long data) 169 + { 170 + int cpu; 171 + 172 + /* Increment the counters */ 173 + on_each_cpu(test_each, NULL, 1); 174 + /* Read all the counters */ 175 + printk("Counters read from CPU %d\n", smp_processor_id()); 176 + for_each_online_cpu(cpu) { 177 + printk("Read : CPU %d, count %ld\n", cpu, 178 + local_read(&per_cpu(counters, cpu))); 179 + } 180 + del_timer(&test_timer); 181 + test_timer.expires = jiffies + 1000; 182 + add_timer(&test_timer); 183 + } 184 + 185 + static int __init test_init(void) 186 + { 187 + /* initialize the timer that will increment the counter */ 188 + init_timer(&test_timer); 189 + test_timer.function = do_test_timer; 190 + test_timer.expires = jiffies + 1; 191 + add_timer(&test_timer); 192 + 193 + return 0; 194 + } 195 + 196 + static void __exit test_exit(void) 197 + { 198 + del_timer_sync(&test_timer); 199 + } 200 + 201 + module_init(test_init); 202 + module_exit(test_exit); 203 + 204 + MODULE_LICENSE("GPL"); 205 + MODULE_AUTHOR("Mathieu Desnoyers"); 206 + MODULE_DESCRIPTION("Local Atomic Ops");
-191
Documentation/local_ops.txt
··· 1 - Semantics and Behavior of Local Atomic Operations 2 - 3 - Mathieu Desnoyers 4 - 5 - 6 - This document explains the purpose of the local atomic operations, how 7 - to implement them for any given architecture and shows how they can be used 8 - properly. It also stresses on the precautions that must be taken when reading 9 - those local variables across CPUs when the order of memory writes matters. 10 - 11 - Note that local_t based operations are not recommended for general kernel use. 12 - Please use the this_cpu operations instead unless there is really a special purpose. 13 - Most uses of local_t in the kernel have been replaced by this_cpu operations. 14 - this_cpu operations combine the relocation with the local_t like semantics in 15 - a single instruction and yield more compact and faster executing code. 16 - 17 - 18 - * Purpose of local atomic operations 19 - 20 - Local atomic operations are meant to provide fast and highly reentrant per CPU 21 - counters. They minimize the performance cost of standard atomic operations by 22 - removing the LOCK prefix and memory barriers normally required to synchronize 23 - across CPUs. 24 - 25 - Having fast per CPU atomic counters is interesting in many cases : it does not 26 - require disabling interrupts to protect from interrupt handlers and it permits 27 - coherent counters in NMI handlers. It is especially useful for tracing purposes 28 - and for various performance monitoring counters. 29 - 30 - Local atomic operations only guarantee variable modification atomicity wrt the 31 - CPU which owns the data. Therefore, care must taken to make sure that only one 32 - CPU writes to the local_t data. This is done by using per cpu data and making 33 - sure that we modify it from within a preemption safe context. It is however 34 - permitted to read local_t data from any CPU : it will then appear to be written 35 - out of order wrt other memory writes by the owner CPU. 36 - 37 - 38 - * Implementation for a given architecture 39 - 40 - It can be done by slightly modifying the standard atomic operations : only 41 - their UP variant must be kept. It typically means removing LOCK prefix (on 42 - i386 and x86_64) and any SMP synchronization barrier. If the architecture does 43 - not have a different behavior between SMP and UP, including asm-generic/local.h 44 - in your architecture's local.h is sufficient. 45 - 46 - The local_t type is defined as an opaque signed long by embedding an 47 - atomic_long_t inside a structure. This is made so a cast from this type to a 48 - long fails. The definition looks like : 49 - 50 - typedef struct { atomic_long_t a; } local_t; 51 - 52 - 53 - * Rules to follow when using local atomic operations 54 - 55 - - Variables touched by local ops must be per cpu variables. 56 - - _Only_ the CPU owner of these variables must write to them. 57 - - This CPU can use local ops from any context (process, irq, softirq, nmi, ...) 58 - to update its local_t variables. 59 - - Preemption (or interrupts) must be disabled when using local ops in 60 - process context to make sure the process won't be migrated to a 61 - different CPU between getting the per-cpu variable and doing the 62 - actual local op. 63 - - When using local ops in interrupt context, no special care must be 64 - taken on a mainline kernel, since they will run on the local CPU with 65 - preemption already disabled. I suggest, however, to explicitly 66 - disable preemption anyway to make sure it will still work correctly on 67 - -rt kernels. 68 - - Reading the local cpu variable will provide the current copy of the 69 - variable. 70 - - Reads of these variables can be done from any CPU, because updates to 71 - "long", aligned, variables are always atomic. Since no memory 72 - synchronization is done by the writer CPU, an outdated copy of the 73 - variable can be read when reading some _other_ cpu's variables. 74 - 75 - 76 - * How to use local atomic operations 77 - 78 - #include <linux/percpu.h> 79 - #include <asm/local.h> 80 - 81 - static DEFINE_PER_CPU(local_t, counters) = LOCAL_INIT(0); 82 - 83 - 84 - * Counting 85 - 86 - Counting is done on all the bits of a signed long. 87 - 88 - In preemptible context, use get_cpu_var() and put_cpu_var() around local atomic 89 - operations : it makes sure that preemption is disabled around write access to 90 - the per cpu variable. For instance : 91 - 92 - local_inc(&get_cpu_var(counters)); 93 - put_cpu_var(counters); 94 - 95 - If you are already in a preemption-safe context, you can use 96 - this_cpu_ptr() instead. 97 - 98 - local_inc(this_cpu_ptr(&counters)); 99 - 100 - 101 - 102 - * Reading the counters 103 - 104 - Those local counters can be read from foreign CPUs to sum the count. Note that 105 - the data seen by local_read across CPUs must be considered to be out of order 106 - relatively to other memory writes happening on the CPU that owns the data. 107 - 108 - long sum = 0; 109 - for_each_online_cpu(cpu) 110 - sum += local_read(&per_cpu(counters, cpu)); 111 - 112 - If you want to use a remote local_read to synchronize access to a resource 113 - between CPUs, explicit smp_wmb() and smp_rmb() memory barriers must be used 114 - respectively on the writer and the reader CPUs. It would be the case if you use 115 - the local_t variable as a counter of bytes written in a buffer : there should 116 - be a smp_wmb() between the buffer write and the counter increment and also a 117 - smp_rmb() between the counter read and the buffer read. 118 - 119 - 120 - Here is a sample module which implements a basic per cpu counter using local.h. 121 - 122 - --- BEGIN --- 123 - /* test-local.c 124 - * 125 - * Sample module for local.h usage. 126 - */ 127 - 128 - 129 - #include <asm/local.h> 130 - #include <linux/module.h> 131 - #include <linux/timer.h> 132 - 133 - static DEFINE_PER_CPU(local_t, counters) = LOCAL_INIT(0); 134 - 135 - static struct timer_list test_timer; 136 - 137 - /* IPI called on each CPU. */ 138 - static void test_each(void *info) 139 - { 140 - /* Increment the counter from a non preemptible context */ 141 - printk("Increment on cpu %d\n", smp_processor_id()); 142 - local_inc(this_cpu_ptr(&counters)); 143 - 144 - /* This is what incrementing the variable would look like within a 145 - * preemptible context (it disables preemption) : 146 - * 147 - * local_inc(&get_cpu_var(counters)); 148 - * put_cpu_var(counters); 149 - */ 150 - } 151 - 152 - static void do_test_timer(unsigned long data) 153 - { 154 - int cpu; 155 - 156 - /* Increment the counters */ 157 - on_each_cpu(test_each, NULL, 1); 158 - /* Read all the counters */ 159 - printk("Counters read from CPU %d\n", smp_processor_id()); 160 - for_each_online_cpu(cpu) { 161 - printk("Read : CPU %d, count %ld\n", cpu, 162 - local_read(&per_cpu(counters, cpu))); 163 - } 164 - del_timer(&test_timer); 165 - test_timer.expires = jiffies + 1000; 166 - add_timer(&test_timer); 167 - } 168 - 169 - static int __init test_init(void) 170 - { 171 - /* initialize the timer that will increment the counter */ 172 - init_timer(&test_timer); 173 - test_timer.function = do_test_timer; 174 - test_timer.expires = jiffies + 1; 175 - add_timer(&test_timer); 176 - 177 - return 0; 178 - } 179 - 180 - static void __exit test_exit(void) 181 - { 182 - del_timer_sync(&test_timer); 183 - } 184 - 185 - module_init(test_init); 186 - module_exit(test_exit); 187 - 188 - MODULE_LICENSE("GPL"); 189 - MODULE_AUTHOR("Mathieu Desnoyers"); 190 - MODULE_DESCRIPTION("Local Atomic Ops"); 191 - --- END ---
+3
Documentation/process/volatile-considered-harmful.rst
··· 1 + 2 + .. _volatile_considered_harmful: 3 + 1 4 Why the "volatile" type class should not be used 2 5 ------------------------------------------------ 3 6