atomic_ops.txt 15 KB

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