atomic_ops.txt 16 KB

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