atomic_ops.txt 19 KB

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