atomic_ops.txt 16 KB

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