atomic_ops.txt 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. Semantics and Behavior of Atomic and
  2. Bitmask Operations
  3. David S. Miller
  4. This document is intended to serve as a guide to Linux port
  5. maintainers on how to implement atomic counter, bitops, and spinlock
  6. interfaces properly.
  7. The atomic_t type should be defined as a signed integer and
  8. the atomic_long_t type as a signed long integer. Also, they should
  9. be made opaque such that any kind of cast to a normal C integer type
  10. will fail. Something like the following should suffice:
  11. typedef struct { int counter; } atomic_t;
  12. typedef struct { long counter; } atomic_long_t;
  13. Historically, counter has been declared volatile. This is now discouraged.
  14. See Documentation/volatile-considered-harmful.txt for the complete rationale.
  15. local_t is very similar to atomic_t. If the counter is per CPU and only
  16. updated by one CPU, local_t is probably more appropriate. Please see
  17. Documentation/local_ops.txt for the semantics of local_t.
  18. The first operations to implement for atomic_t's are the initializers and
  19. plain reads.
  20. #define ATOMIC_INIT(i) { (i) }
  21. #define atomic_set(v, i) ((v)->counter = (i))
  22. The first macro is used in definitions, such as:
  23. static atomic_t my_counter = ATOMIC_INIT(1);
  24. The initializer is atomic in that the return values of the atomic operations
  25. are guaranteed to be correct reflecting the initialized value if the
  26. initializer is used before runtime. If the initializer is used at runtime, a
  27. proper implicit or explicit read memory barrier is needed before reading the
  28. value with atomic_read from another thread.
  29. As with all of the atomic_ interfaces, replace the leading "atomic_"
  30. with "atomic_long_" to operate on atomic_long_t.
  31. The second interface can be used at runtime, as in:
  32. struct foo { atomic_t counter; };
  33. ...
  34. struct foo *k;
  35. k = kmalloc(sizeof(*k), GFP_KERNEL);
  36. if (!k)
  37. return -ENOMEM;
  38. atomic_set(&k->counter, 0);
  39. The setting is atomic in that the return values of the atomic operations by
  40. all threads are guaranteed to be correct reflecting either the value that has
  41. been set with this operation or set with another operation. A proper implicit
  42. or explicit memory barrier is needed before the value set with the operation
  43. is guaranteed to be readable with atomic_read from another thread.
  44. Next, we have:
  45. #define atomic_read(v) ((v)->counter)
  46. which simply reads the counter value currently visible to the calling thread.
  47. The read is atomic in that the return value is guaranteed to be one of the
  48. values initialized or modified with the interface operations if a proper
  49. implicit or explicit memory barrier is used after possible runtime
  50. initialization by any other thread and the value is modified only with the
  51. interface operations. atomic_read does not guarantee that the runtime
  52. initialization by any other thread is visible yet, so the user of the
  53. interface must take care of that with a proper implicit or explicit memory
  54. barrier.
  55. *** WARNING: atomic_read() and atomic_set() DO NOT IMPLY BARRIERS! ***
  56. Some architectures may choose to use the volatile keyword, barriers, or inline
  57. assembly to guarantee some degree of immediacy for atomic_read() and
  58. atomic_set(). This is not uniformly guaranteed, and may change in the future,
  59. so all users of atomic_t should treat atomic_read() and atomic_set() as simple
  60. C statements that may be reordered or optimized away entirely by the compiler
  61. or processor, and explicitly invoke the appropriate compiler and/or memory
  62. barrier for each use case. Failure to do so will result in code that may
  63. suddenly break when used with different architectures or compiler
  64. optimizations, or even changes in unrelated code which changes how the
  65. compiler optimizes the section accessing atomic_t variables.
  66. *** YOU HAVE BEEN WARNED! ***
  67. Properly aligned pointers, longs, ints, and chars (and unsigned
  68. equivalents) may be atomically loaded from and stored to in the same
  69. sense as described for atomic_read() and atomic_set(). The ACCESS_ONCE()
  70. macro should be used to prevent the compiler from using optimizations
  71. that might otherwise optimize accesses out of existence on the one hand,
  72. or that might create unsolicited accesses on the other.
  73. For example consider the following code:
  74. while (a > 0)
  75. do_something();
  76. If the compiler can prove that do_something() does not store to the
  77. variable a, then the compiler is within its rights transforming this to
  78. the following:
  79. tmp = a;
  80. if (a > 0)
  81. for (;;)
  82. do_something();
  83. If you don't want the compiler to do this (and you probably don't), then
  84. you should use something like the following:
  85. while (ACCESS_ONCE(a) < 0)
  86. do_something();
  87. Alternatively, you could place a barrier() call in the loop.
  88. For another example, consider the following code:
  89. tmp_a = a;
  90. do_something_with(tmp_a);
  91. do_something_else_with(tmp_a);
  92. If the compiler can prove that do_something_with() does not store to the
  93. variable a, then the compiler is within its rights to manufacture an
  94. additional load as follows:
  95. tmp_a = a;
  96. do_something_with(tmp_a);
  97. tmp_a = a;
  98. do_something_else_with(tmp_a);
  99. This could fatally confuse your code if it expected the same value
  100. to be passed to do_something_with() and do_something_else_with().
  101. The compiler would be likely to manufacture this additional load if
  102. do_something_with() was an inline function that made very heavy use
  103. of registers: reloading from variable a could save a flush to the
  104. stack and later reload. To prevent the compiler from attacking your
  105. code in this manner, write the following:
  106. tmp_a = ACCESS_ONCE(a);
  107. do_something_with(tmp_a);
  108. do_something_else_with(tmp_a);
  109. For a final example, consider the following code, assuming that the
  110. variable a is set at boot time before the second CPU is brought online
  111. and never changed later, so that memory barriers are not needed:
  112. if (a)
  113. b = 9;
  114. else
  115. b = 42;
  116. The compiler is within its rights to manufacture an additional store
  117. by transforming the above code into the following:
  118. b = 42;
  119. if (a)
  120. b = 9;
  121. This could come as a fatal surprise to other code running concurrently
  122. that expected b to never have the value 42 if a was zero. To prevent
  123. the compiler from doing this, write something like:
  124. if (a)
  125. ACCESS_ONCE(b) = 9;
  126. else
  127. ACCESS_ONCE(b) = 42;
  128. Don't even -think- about doing this without proper use of memory barriers,
  129. locks, or atomic operations if variable a can change at runtime!
  130. *** WARNING: ACCESS_ONCE() DOES NOT IMPLY A BARRIER! ***
  131. Now, we move onto the atomic operation interfaces typically implemented with
  132. the help of assembly code.
  133. void atomic_add(int i, atomic_t *v);
  134. void atomic_sub(int i, atomic_t *v);
  135. void atomic_inc(atomic_t *v);
  136. void atomic_dec(atomic_t *v);
  137. These four routines add and subtract integral values to/from the given
  138. atomic_t value. The first two routines pass explicit integers by
  139. which to make the adjustment, whereas the latter two use an implicit
  140. adjustment value of "1".
  141. One very important aspect of these two routines is that they DO NOT
  142. require any explicit memory barriers. They need only perform the
  143. atomic_t counter update in an SMP safe manner.
  144. Next, we have:
  145. int atomic_inc_return(atomic_t *v);
  146. int atomic_dec_return(atomic_t *v);
  147. These routines add 1 and subtract 1, respectively, from the given
  148. atomic_t and return the new counter value after the operation is
  149. performed.
  150. Unlike the above routines, it is required that these primitives
  151. include explicit memory barriers that are performed before and after
  152. the operation. It must be done such that all memory operations before
  153. and after the atomic operation calls are strongly ordered with respect
  154. to the atomic operation itself.
  155. For example, it should behave as if a smp_mb() call existed both
  156. before and after the atomic operation.
  157. If the atomic instructions used in an implementation provide explicit
  158. memory barrier semantics which satisfy the above requirements, that is
  159. fine as well.
  160. Let's move on:
  161. int atomic_add_return(int i, atomic_t *v);
  162. int atomic_sub_return(int i, atomic_t *v);
  163. These behave just like atomic_{inc,dec}_return() except that an
  164. explicit counter adjustment is given instead of the implicit "1".
  165. This means that like atomic_{inc,dec}_return(), the memory barrier
  166. semantics are required.
  167. Next:
  168. int atomic_inc_and_test(atomic_t *v);
  169. int atomic_dec_and_test(atomic_t *v);
  170. These two routines increment and decrement by 1, respectively, the
  171. given atomic counter. They return a boolean indicating whether the
  172. resulting counter value was zero or not.
  173. Again, these primitives provide explicit memory barrier semantics around
  174. the atomic operation.
  175. int atomic_sub_and_test(int i, atomic_t *v);
  176. This is identical to atomic_dec_and_test() except that an explicit
  177. decrement is given instead of the implicit "1". This primitive must
  178. provide explicit memory barrier semantics around the operation.
  179. int atomic_add_negative(int i, atomic_t *v);
  180. The given increment is added to the given atomic counter value. A boolean
  181. is return which indicates whether the resulting counter value is negative.
  182. This primitive must provide explicit memory barrier semantics around
  183. the operation.
  184. Then:
  185. int atomic_xchg(atomic_t *v, int new);
  186. This performs an atomic exchange operation on the atomic variable v, setting
  187. the given new value. It returns the old value that the atomic variable v had
  188. just before the operation.
  189. atomic_xchg must provide explicit memory barriers around the operation.
  190. int atomic_cmpxchg(atomic_t *v, int old, int new);
  191. This performs an atomic compare exchange operation on the atomic value v,
  192. with the given old and new values. Like all atomic_xxx operations,
  193. atomic_cmpxchg will only satisfy its atomicity semantics as long as all
  194. other accesses of *v are performed through atomic_xxx operations.
  195. atomic_cmpxchg must provide explicit memory barriers around the operation,
  196. although if the comparison fails then no memory ordering guarantees are
  197. required.
  198. The semantics for atomic_cmpxchg are the same as those defined for 'cas'
  199. below.
  200. Finally:
  201. int atomic_add_unless(atomic_t *v, int a, int u);
  202. If the atomic value v is not equal to u, this function adds a to v, and
  203. returns non zero. If v is equal to u then it returns zero. This is done as
  204. an atomic operation.
  205. atomic_add_unless must provide explicit memory barriers around the
  206. operation unless it fails (returns 0).
  207. atomic_inc_not_zero, equivalent to atomic_add_unless(v, 1, 0)
  208. If a caller requires memory barrier semantics around an atomic_t
  209. operation which does not return a value, a set of interfaces are
  210. defined which accomplish this:
  211. void smp_mb__before_atomic(void);
  212. void smp_mb__after_atomic(void);
  213. For example, smp_mb__before_atomic() can be used like so:
  214. obj->dead = 1;
  215. smp_mb__before_atomic();
  216. atomic_dec(&obj->ref_count);
  217. It makes sure that all memory operations preceding the atomic_dec()
  218. call are strongly ordered with respect to the atomic counter
  219. operation. In the above example, it guarantees that the assignment of
  220. "1" to obj->dead will be globally visible to other cpus before the
  221. atomic counter decrement.
  222. Without the explicit smp_mb__before_atomic() call, the
  223. implementation could legally allow the atomic counter update visible
  224. to other cpus before the "obj->dead = 1;" assignment.
  225. A missing memory barrier in the cases where they are required by the
  226. atomic_t implementation above can have disastrous results. Here is
  227. an example, which follows a pattern occurring frequently in the Linux
  228. kernel. It is the use of atomic counters to implement reference
  229. counting, and it works such that once the counter falls to zero it can
  230. be guaranteed that no other entity can be accessing the object:
  231. static void obj_list_add(struct obj *obj, struct list_head *head)
  232. {
  233. obj->active = 1;
  234. list_add(&obj->list, head);
  235. }
  236. static void obj_list_del(struct obj *obj)
  237. {
  238. list_del(&obj->list);
  239. obj->active = 0;
  240. }
  241. static void obj_destroy(struct obj *obj)
  242. {
  243. BUG_ON(obj->active);
  244. kfree(obj);
  245. }
  246. struct obj *obj_list_peek(struct list_head *head)
  247. {
  248. if (!list_empty(head)) {
  249. struct obj *obj;
  250. obj = list_entry(head->next, struct obj, list);
  251. atomic_inc(&obj->refcnt);
  252. return obj;
  253. }
  254. return NULL;
  255. }
  256. void obj_poke(void)
  257. {
  258. struct obj *obj;
  259. spin_lock(&global_list_lock);
  260. obj = obj_list_peek(&global_list);
  261. spin_unlock(&global_list_lock);
  262. if (obj) {
  263. obj->ops->poke(obj);
  264. if (atomic_dec_and_test(&obj->refcnt))
  265. obj_destroy(obj);
  266. }
  267. }
  268. void obj_timeout(struct obj *obj)
  269. {
  270. spin_lock(&global_list_lock);
  271. obj_list_del(obj);
  272. spin_unlock(&global_list_lock);
  273. if (atomic_dec_and_test(&obj->refcnt))
  274. obj_destroy(obj);
  275. }
  276. (This is a simplification of the ARP queue management in the
  277. generic neighbour discover code of the networking. Olaf Kirch
  278. found a bug wrt. memory barriers in kfree_skb() that exposed
  279. the atomic_t memory barrier requirements quite clearly.)
  280. Given the above scheme, it must be the case that the obj->active
  281. update done by the obj list deletion be visible to other processors
  282. before the atomic counter decrement is performed.
  283. Otherwise, the counter could fall to zero, yet obj->active would still
  284. be set, thus triggering the assertion in obj_destroy(). The error
  285. sequence looks like this:
  286. cpu 0 cpu 1
  287. obj_poke() obj_timeout()
  288. obj = obj_list_peek();
  289. ... gains ref to obj, refcnt=2
  290. obj_list_del(obj);
  291. obj->active = 0 ...
  292. ... visibility delayed ...
  293. atomic_dec_and_test()
  294. ... refcnt drops to 1 ...
  295. atomic_dec_and_test()
  296. ... refcount drops to 0 ...
  297. obj_destroy()
  298. BUG() triggers since obj->active
  299. still seen as one
  300. obj->active update visibility occurs
  301. With the memory barrier semantics required of the atomic_t operations
  302. which return values, the above sequence of memory visibility can never
  303. happen. Specifically, in the above case the atomic_dec_and_test()
  304. counter decrement would not become globally visible until the
  305. obj->active update does.
  306. As a historical note, 32-bit Sparc used to only allow usage of
  307. 24-bits of its atomic_t type. This was because it used 8 bits
  308. as a spinlock for SMP safety. Sparc32 lacked a "compare and swap"
  309. type instruction. However, 32-bit Sparc has since been moved over
  310. to a "hash table of spinlocks" scheme, that allows the full 32-bit
  311. counter to be realized. Essentially, an array of spinlocks are
  312. indexed into based upon the address of the atomic_t being operated
  313. on, and that lock protects the atomic operation. Parisc uses the
  314. same scheme.
  315. Another note is that the atomic_t operations returning values are
  316. extremely slow on an old 386.
  317. We will now cover the atomic bitmask operations. You will find that
  318. their SMP and memory barrier semantics are similar in shape and scope
  319. to the atomic_t ops above.
  320. Native atomic bit operations are defined to operate on objects aligned
  321. to the size of an "unsigned long" C data type, and are least of that
  322. size. The endianness of the bits within each "unsigned long" are the
  323. native endianness of the cpu.
  324. void set_bit(unsigned long nr, volatile unsigned long *addr);
  325. void clear_bit(unsigned long nr, volatile unsigned long *addr);
  326. void change_bit(unsigned long nr, volatile unsigned long *addr);
  327. These routines set, clear, and change, respectively, the bit number
  328. indicated by "nr" on the bit mask pointed to by "ADDR".
  329. They must execute atomically, yet there are no implicit memory barrier
  330. semantics required of these interfaces.
  331. int test_and_set_bit(unsigned long nr, volatile unsigned long *addr);
  332. int test_and_clear_bit(unsigned long nr, volatile unsigned long *addr);
  333. int test_and_change_bit(unsigned long nr, volatile unsigned long *addr);
  334. Like the above, except that these routines return a boolean which
  335. indicates whether the changed bit was set _BEFORE_ the atomic bit
  336. operation.
  337. WARNING! It is incredibly important that the value be a boolean,
  338. ie. "0" or "1". Do not try to be fancy and save a few instructions by
  339. declaring the above to return "long" and just returning something like
  340. "old_val & mask" because that will not work.
  341. For one thing, this return value gets truncated to int in many code
  342. paths using these interfaces, so on 64-bit if the bit is set in the
  343. upper 32-bits then testers will never see that.
  344. One great example of where this problem crops up are the thread_info
  345. flag operations. Routines such as test_and_set_ti_thread_flag() chop
  346. the return value into an int. There are other places where things
  347. like this occur as well.
  348. These routines, like the atomic_t counter operations returning values,
  349. must provide explicit memory barrier semantics around their execution.
  350. All memory operations before the atomic bit operation call must be
  351. made visible globally before the atomic bit operation is made visible.
  352. Likewise, the atomic bit operation must be visible globally before any
  353. subsequent memory operation is made visible. For example:
  354. obj->dead = 1;
  355. if (test_and_set_bit(0, &obj->flags))
  356. /* ... */;
  357. obj->killed = 1;
  358. The implementation of test_and_set_bit() must guarantee that
  359. "obj->dead = 1;" is visible to cpus before the atomic memory operation
  360. done by test_and_set_bit() becomes visible. Likewise, the atomic
  361. memory operation done by test_and_set_bit() must become visible before
  362. "obj->killed = 1;" is visible.
  363. Finally there is the basic operation:
  364. int test_bit(unsigned long nr, __const__ volatile unsigned long *addr);
  365. Which returns a boolean indicating if bit "nr" is set in the bitmask
  366. pointed to by "addr".
  367. If explicit memory barriers are required around {set,clear}_bit() (which do
  368. not return a value, and thus does not need to provide memory barrier
  369. semantics), two interfaces are provided:
  370. void smp_mb__before_atomic(void);
  371. void smp_mb__after_atomic(void);
  372. They are used as follows, and are akin to their atomic_t operation
  373. brothers:
  374. /* All memory operations before this call will
  375. * be globally visible before the clear_bit().
  376. */
  377. smp_mb__before_atomic();
  378. clear_bit( ... );
  379. /* The clear_bit() will be visible before all
  380. * subsequent memory operations.
  381. */
  382. smp_mb__after_atomic();
  383. There are two special bitops with lock barrier semantics (acquire/release,
  384. same as spinlocks). These operate in the same way as their non-_lock/unlock
  385. postfixed variants, except that they are to provide acquire/release semantics,
  386. respectively. This means they can be used for bit_spin_trylock and
  387. bit_spin_unlock type operations without specifying any more barriers.
  388. int test_and_set_bit_lock(unsigned long nr, unsigned long *addr);
  389. void clear_bit_unlock(unsigned long nr, unsigned long *addr);
  390. void __clear_bit_unlock(unsigned long nr, unsigned long *addr);
  391. The __clear_bit_unlock version is non-atomic, however it still implements
  392. unlock barrier semantics. This can be useful if the lock itself is protecting
  393. the other bits in the word.
  394. Finally, there are non-atomic versions of the bitmask operations
  395. provided. They are used in contexts where some other higher-level SMP
  396. locking scheme is being used to protect the bitmask, and thus less
  397. expensive non-atomic operations may be used in the implementation.
  398. They have names similar to the above bitmask operation interfaces,
  399. except that two underscores are prefixed to the interface name.
  400. void __set_bit(unsigned long nr, volatile unsigned long *addr);
  401. void __clear_bit(unsigned long nr, volatile unsigned long *addr);
  402. void __change_bit(unsigned long nr, volatile unsigned long *addr);
  403. int __test_and_set_bit(unsigned long nr, volatile unsigned long *addr);
  404. int __test_and_clear_bit(unsigned long nr, volatile unsigned long *addr);
  405. int __test_and_change_bit(unsigned long nr, volatile unsigned long *addr);
  406. These non-atomic variants also do not require any special memory
  407. barrier semantics.
  408. The routines xchg() and cmpxchg() must provide the same exact
  409. memory-barrier semantics as the atomic and bit operations returning
  410. values.
  411. Note: If someone wants to use xchg(), cmpxchg() and their variants,
  412. linux/atomic.h should be included rather than asm/cmpxchg.h, unless
  413. the code is in arch/* and can take care of itself.
  414. Spinlocks and rwlocks have memory barrier expectations as well.
  415. The rule to follow is simple:
  416. 1) When acquiring a lock, the implementation must make it globally
  417. visible before any subsequent memory operation.
  418. 2) When releasing a lock, the implementation must make it such that
  419. all previous memory operations are globally visible before the
  420. lock release.
  421. Which finally brings us to _atomic_dec_and_lock(). There is an
  422. architecture-neutral version implemented in lib/dec_and_lock.c,
  423. but most platforms will wish to optimize this in assembler.
  424. int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock);
  425. Atomically decrement the given counter, and if will drop to zero
  426. atomically acquire the given spinlock and perform the decrement
  427. of the counter to zero. If it does not drop to zero, do nothing
  428. with the spinlock.
  429. It is actually pretty simple to get the memory barrier correct.
  430. Simply satisfy the spinlock grab requirements, which is make
  431. sure the spinlock operation is globally visible before any
  432. subsequent memory operation.
  433. We can demonstrate this operation more clearly if we define
  434. an abstract atomic operation:
  435. long cas(long *mem, long old, long new);
  436. "cas" stands for "compare and swap". It atomically:
  437. 1) Compares "old" with the value currently at "mem".
  438. 2) If they are equal, "new" is written to "mem".
  439. 3) Regardless, the current value at "mem" is returned.
  440. As an example usage, here is what an atomic counter update
  441. might look like:
  442. void example_atomic_inc(long *counter)
  443. {
  444. long old, new, ret;
  445. while (1) {
  446. old = *counter;
  447. new = old + 1;
  448. ret = cas(counter, old, new);
  449. if (ret == old)
  450. break;
  451. }
  452. }
  453. Let's use cas() in order to build a pseudo-C atomic_dec_and_lock():
  454. int _atomic_dec_and_lock(atomic_t *atomic, spinlock_t *lock)
  455. {
  456. long old, new, ret;
  457. int went_to_zero;
  458. went_to_zero = 0;
  459. while (1) {
  460. old = atomic_read(atomic);
  461. new = old - 1;
  462. if (new == 0) {
  463. went_to_zero = 1;
  464. spin_lock(lock);
  465. }
  466. ret = cas(atomic, old, new);
  467. if (ret == old)
  468. break;
  469. if (went_to_zero) {
  470. spin_unlock(lock);
  471. went_to_zero = 0;
  472. }
  473. }
  474. return went_to_zero;
  475. }
  476. Now, as far as memory barriers go, as long as spin_lock()
  477. strictly orders all subsequent memory operations (including
  478. the cas()) with respect to itself, things will be fine.
  479. Said another way, _atomic_dec_and_lock() must guarantee that
  480. a counter dropping to zero is never made visible before the
  481. spinlock being acquired.
  482. Note that this also means that for the case where the counter
  483. is not dropping to zero, there are no memory ordering
  484. requirements.