atomic_ops.txt 15 KB

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