atomics.rst 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. .. _atomics-ref:
  2. =========================
  3. Atomic operations in QEMU
  4. =========================
  5. CPUs perform independent memory operations effectively in random order.
  6. but this can be a problem for CPU-CPU interaction (including interactions
  7. between QEMU and the guest). Multi-threaded programs use various tools
  8. to instruct the compiler and the CPU to restrict the order to something
  9. that is consistent with the expectations of the programmer.
  10. The most basic tool is locking. Mutexes, condition variables and
  11. semaphores are used in QEMU, and should be the default approach to
  12. synchronization. Anything else is considerably harder, but it's
  13. also justified more often than one would like;
  14. the most performance-critical parts of QEMU in particular require
  15. a very low level approach to concurrency, involving memory barriers
  16. and atomic operations. The semantics of concurrent memory accesses are governed
  17. by the C11 memory model.
  18. QEMU provides a header, ``qemu/atomic.h``, which wraps C11 atomics to
  19. provide better portability and a less verbose syntax. ``qemu/atomic.h``
  20. provides macros that fall in three camps:
  21. - compiler barriers: ``barrier()``;
  22. - weak atomic access and manual memory barriers: ``qatomic_read()``,
  23. ``qatomic_set()``, ``smp_rmb()``, ``smp_wmb()``, ``smp_mb()``,
  24. ``smp_mb_acquire()``, ``smp_mb_release()``, ``smp_read_barrier_depends()``,
  25. ``smp_mb__before_rmw()``, ``smp_mb__after_rmw()``;
  26. - sequentially consistent atomic access: everything else.
  27. In general, use of ``qemu/atomic.h`` should be wrapped with more easily
  28. used data structures (e.g. the lock-free singly-linked list operations
  29. ``QSLIST_INSERT_HEAD_ATOMIC`` and ``QSLIST_MOVE_ATOMIC``) or synchronization
  30. primitives (such as RCU, ``QemuEvent`` or ``QemuLockCnt``). Bare use of
  31. atomic operations and memory barriers should be limited to inter-thread
  32. checking of flags and documented thoroughly.
  33. Compiler memory barrier
  34. =======================
  35. ``barrier()`` prevents the compiler from moving the memory accesses on
  36. either side of it to the other side. The compiler barrier has no direct
  37. effect on the CPU, which may then reorder things however it wishes.
  38. ``barrier()`` is mostly used within ``qemu/atomic.h`` itself. On some
  39. architectures, CPU guarantees are strong enough that blocking compiler
  40. optimizations already ensures the correct order of execution. In this
  41. case, ``qemu/atomic.h`` will reduce stronger memory barriers to simple
  42. compiler barriers.
  43. Still, ``barrier()`` can be useful when writing code that can be interrupted
  44. by signal handlers.
  45. Sequentially consistent atomic access
  46. =====================================
  47. Most of the operations in the ``qemu/atomic.h`` header ensure *sequential
  48. consistency*, where "the result of any execution is the same as if the
  49. operations of all the processors were executed in some sequential order,
  50. and the operations of each individual processor appear in this sequence
  51. in the order specified by its program".
  52. ``qemu/atomic.h`` provides the following set of atomic read-modify-write
  53. operations::
  54. void qatomic_inc(ptr)
  55. void qatomic_dec(ptr)
  56. void qatomic_add(ptr, val)
  57. void qatomic_sub(ptr, val)
  58. void qatomic_and(ptr, val)
  59. void qatomic_or(ptr, val)
  60. typeof(*ptr) qatomic_fetch_inc(ptr)
  61. typeof(*ptr) qatomic_fetch_dec(ptr)
  62. typeof(*ptr) qatomic_fetch_add(ptr, val)
  63. typeof(*ptr) qatomic_fetch_sub(ptr, val)
  64. typeof(*ptr) qatomic_fetch_and(ptr, val)
  65. typeof(*ptr) qatomic_fetch_or(ptr, val)
  66. typeof(*ptr) qatomic_fetch_xor(ptr, val)
  67. typeof(*ptr) qatomic_fetch_inc_nonzero(ptr)
  68. typeof(*ptr) qatomic_xchg(ptr, val)
  69. typeof(*ptr) qatomic_cmpxchg(ptr, old, new)
  70. all of which return the old value of ``*ptr``. These operations are
  71. polymorphic; they operate on any type that is as wide as a pointer or
  72. smaller.
  73. Similar operations return the new value of ``*ptr``::
  74. typeof(*ptr) qatomic_inc_fetch(ptr)
  75. typeof(*ptr) qatomic_dec_fetch(ptr)
  76. typeof(*ptr) qatomic_add_fetch(ptr, val)
  77. typeof(*ptr) qatomic_sub_fetch(ptr, val)
  78. typeof(*ptr) qatomic_and_fetch(ptr, val)
  79. typeof(*ptr) qatomic_or_fetch(ptr, val)
  80. typeof(*ptr) qatomic_xor_fetch(ptr, val)
  81. ``qemu/atomic.h`` also provides an optimized shortcut for
  82. ``qatomic_set`` followed by ``smp_mb``::
  83. void qatomic_set_mb(ptr, val)
  84. Weak atomic access and manual memory barriers
  85. =============================================
  86. Compared to sequentially consistent atomic access, programming with
  87. weaker consistency models can be considerably more complicated.
  88. The only guarantees that you can rely upon in this case are:
  89. - atomic accesses will not cause data races (and hence undefined behavior);
  90. ordinary accesses instead cause data races if they are concurrent with
  91. other accesses of which at least one is a write. In order to ensure this,
  92. the compiler will not optimize accesses out of existence, create unsolicited
  93. accesses, or perform other similar optimizations.
  94. - acquire operations will appear to happen, with respect to the other
  95. components of the system, before all the LOAD or STORE operations
  96. specified afterwards.
  97. - release operations will appear to happen, with respect to the other
  98. components of the system, after all the LOAD or STORE operations
  99. specified before.
  100. - release operations will *synchronize with* acquire operations;
  101. see :ref:`acqrel` for a detailed explanation.
  102. When using this model, variables are accessed with:
  103. - ``qatomic_read()`` and ``qatomic_set()``; these prevent the compiler from
  104. optimizing accesses out of existence and creating unsolicited
  105. accesses, but do not otherwise impose any ordering on loads and
  106. stores: both the compiler and the processor are free to reorder
  107. them.
  108. - ``qatomic_load_acquire()``, which guarantees the LOAD to appear to
  109. happen, with respect to the other components of the system,
  110. before all the LOAD or STORE operations specified afterwards.
  111. Operations coming before ``qatomic_load_acquire()`` can still be
  112. reordered after it.
  113. - ``qatomic_store_release()``, which guarantees the STORE to appear to
  114. happen, with respect to the other components of the system,
  115. after all the LOAD or STORE operations specified before.
  116. Operations coming after ``qatomic_store_release()`` can still be
  117. reordered before it.
  118. Restrictions to the ordering of accesses can also be specified
  119. using the memory barrier macros: ``smp_rmb()``, ``smp_wmb()``, ``smp_mb()``,
  120. ``smp_mb_acquire()``, ``smp_mb_release()``, ``smp_read_barrier_depends()``.
  121. Memory barriers control the order of references to shared memory.
  122. They come in six kinds:
  123. - ``smp_rmb()`` guarantees that all the LOAD operations specified before
  124. the barrier will appear to happen before all the LOAD operations
  125. specified after the barrier with respect to the other components of
  126. the system.
  127. In other words, ``smp_rmb()`` puts a partial ordering on loads, but is not
  128. required to have any effect on stores.
  129. - ``smp_wmb()`` guarantees that all the STORE operations specified before
  130. the barrier will appear to happen before all the STORE operations
  131. specified after the barrier with respect to the other components of
  132. the system.
  133. In other words, ``smp_wmb()`` puts a partial ordering on stores, but is not
  134. required to have any effect on loads.
  135. - ``smp_mb_acquire()`` guarantees that all the LOAD operations specified before
  136. the barrier will appear to happen before all the LOAD or STORE operations
  137. specified after the barrier with respect to the other components of
  138. the system.
  139. - ``smp_mb_release()`` guarantees that all the STORE operations specified *after*
  140. the barrier will appear to happen after all the LOAD or STORE operations
  141. specified *before* the barrier with respect to the other components of
  142. the system.
  143. - ``smp_mb()`` guarantees that all the LOAD and STORE operations specified
  144. before the barrier will appear to happen before all the LOAD and
  145. STORE operations specified after the barrier with respect to the other
  146. components of the system.
  147. ``smp_mb()`` puts a partial ordering on both loads and stores. It is
  148. stronger than both a read and a write memory barrier; it implies both
  149. ``smp_mb_acquire()`` and ``smp_mb_release()``, but it also prevents STOREs
  150. coming before the barrier from overtaking LOADs coming after the
  151. barrier and vice versa.
  152. - ``smp_read_barrier_depends()`` is a weaker kind of read barrier. On
  153. most processors, whenever two loads are performed such that the
  154. second depends on the result of the first (e.g., the first load
  155. retrieves the address to which the second load will be directed),
  156. the processor will guarantee that the first LOAD will appear to happen
  157. before the second with respect to the other components of the system.
  158. Therefore, unlike ``smp_rmb()`` or ``qatomic_load_acquire()``,
  159. ``smp_read_barrier_depends()`` can be just a compiler barrier on
  160. weakly-ordered architectures such as Arm or PPC\ [#alpha]_.
  161. Note that the first load really has to have a _data_ dependency and not
  162. a control dependency. If the address for the second load is dependent
  163. on the first load, but the dependency is through a conditional rather
  164. than actually loading the address itself, then it's a _control_
  165. dependency and a full read barrier or better is required.
  166. .. [#alpha] The DEC Alpha is an exception, because ``smp_read_barrier_depends()``
  167. needs a processor barrier. On strongly-ordered architectures such
  168. as x86 or s390, ``smp_rmb()`` and ``qatomic_load_acquire()`` can
  169. also be compiler barriers only.
  170. Memory barriers and ``qatomic_load_acquire``/``qatomic_store_release`` are
  171. mostly used when a data structure has one thread that is always a writer
  172. and one thread that is always a reader:
  173. +----------------------------------+----------------------------------+
  174. | thread 1 | thread 2 |
  175. +==================================+==================================+
  176. | :: | :: |
  177. | | |
  178. | qatomic_store_release(&a, x); | y = qatomic_load_acquire(&b); |
  179. | qatomic_store_release(&b, y); | x = qatomic_load_acquire(&a); |
  180. +----------------------------------+----------------------------------+
  181. In this case, correctness is easy to check for using the "pairing"
  182. trick that is explained below.
  183. Sometimes, a thread is accessing many variables that are otherwise
  184. unrelated to each other (for example because, apart from the current
  185. thread, exactly one other thread will read or write each of these
  186. variables). In this case, it is possible to "hoist" the barriers
  187. outside a loop. For example:
  188. +------------------------------------------+----------------------------------+
  189. | before | after |
  190. +==========================================+==================================+
  191. | :: | :: |
  192. | | |
  193. | n = 0; | n = 0; |
  194. | for (i = 0; i < 10; i++) | for (i = 0; i < 10; i++) |
  195. | n += qatomic_load_acquire(&a[i]); | n += qatomic_read(&a[i]); |
  196. | | smp_mb_acquire(); |
  197. +------------------------------------------+----------------------------------+
  198. | :: | :: |
  199. | | |
  200. | | smp_mb_release(); |
  201. | for (i = 0; i < 10; i++) | for (i = 0; i < 10; i++) |
  202. | qatomic_store_release(&a[i], false); | qatomic_set(&a[i], false); |
  203. +------------------------------------------+----------------------------------+
  204. Splitting a loop can also be useful to reduce the number of barriers:
  205. +------------------------------------------+----------------------------------+
  206. | before | after |
  207. +==========================================+==================================+
  208. | :: | :: |
  209. | | |
  210. | n = 0; | smp_mb_release(); |
  211. | for (i = 0; i < 10; i++) { | for (i = 0; i < 10; i++) |
  212. | qatomic_store_release(&a[i], false); | qatomic_set(&a[i], false); |
  213. | smp_mb(); | smb_mb(); |
  214. | n += qatomic_read(&b[i]); | n = 0; |
  215. | } | for (i = 0; i < 10; i++) |
  216. | | n += qatomic_read(&b[i]); |
  217. +------------------------------------------+----------------------------------+
  218. In this case, a ``smp_mb_release()`` is also replaced with a (possibly cheaper, and clearer
  219. as well) ``smp_wmb()``:
  220. +------------------------------------------+----------------------------------+
  221. | before | after |
  222. +==========================================+==================================+
  223. | :: | :: |
  224. | | |
  225. | | smp_mb_release(); |
  226. | for (i = 0; i < 10; i++) { | for (i = 0; i < 10; i++) |
  227. | qatomic_store_release(&a[i], false); | qatomic_set(&a[i], false); |
  228. | qatomic_store_release(&b[i], false); | smb_wmb(); |
  229. | } | for (i = 0; i < 10; i++) |
  230. | | qatomic_set(&b[i], false); |
  231. +------------------------------------------+----------------------------------+
  232. .. _acqrel:
  233. Acquire/release pairing and the *synchronizes-with* relation
  234. ------------------------------------------------------------
  235. Atomic operations other than ``qatomic_set()`` and ``qatomic_read()`` have
  236. either *acquire* or *release* semantics\ [#rmw]_. This has two effects:
  237. .. [#rmw] Read-modify-write operations can have both---acquire applies to the
  238. read part, and release to the write.
  239. - within a thread, they are ordered either before subsequent operations
  240. (for acquire) or after previous operations (for release).
  241. - if a release operation in one thread *synchronizes with* an acquire operation
  242. in another thread, the ordering constraints propagates from the first to the
  243. second thread. That is, everything before the release operation in the
  244. first thread is guaranteed to *happen before* everything after the
  245. acquire operation in the second thread.
  246. The concept of acquire and release semantics is not exclusive to atomic
  247. operations; almost all higher-level synchronization primitives also have
  248. acquire or release semantics. For example:
  249. - ``pthread_mutex_lock`` has acquire semantics, ``pthread_mutex_unlock`` has
  250. release semantics and synchronizes with a ``pthread_mutex_lock`` for the
  251. same mutex.
  252. - ``pthread_cond_signal`` and ``pthread_cond_broadcast`` have release semantics;
  253. ``pthread_cond_wait`` has both release semantics (synchronizing with
  254. ``pthread_mutex_lock``) and acquire semantics (synchronizing with
  255. ``pthread_mutex_unlock`` and signaling of the condition variable).
  256. - ``pthread_create`` has release semantics and synchronizes with the start
  257. of the new thread; ``pthread_join`` has acquire semantics and synchronizes
  258. with the exiting of the thread.
  259. - ``qemu_event_set`` has release semantics, ``qemu_event_wait`` has
  260. acquire semantics.
  261. For example, in the following example there are no atomic accesses, but still
  262. thread 2 is relying on the *synchronizes-with* relation between ``pthread_exit``
  263. (release) and ``pthread_join`` (acquire):
  264. +----------------------+-------------------------------+
  265. | thread 1 | thread 2 |
  266. +======================+===============================+
  267. | :: | :: |
  268. | | |
  269. | *a = 1; | |
  270. | pthread_exit(a); | pthread_join(thread1, &a); |
  271. | | x = *a; |
  272. +----------------------+-------------------------------+
  273. Synchronization between threads basically descends from this pairing of
  274. a release operation and an acquire operation. Therefore, atomic operations
  275. other than ``qatomic_set()`` and ``qatomic_read()`` will almost always be
  276. paired with another operation of the opposite kind: an acquire operation
  277. will pair with a release operation and vice versa. This rule of thumb is
  278. extremely useful; in the case of QEMU, however, note that the other
  279. operation may actually be in a driver that runs in the guest!
  280. ``smp_read_barrier_depends()``, ``smp_rmb()``, ``smp_mb_acquire()``,
  281. ``qatomic_load_acquire()`` and ``qatomic_rcu_read()`` all count
  282. as acquire operations. ``smp_wmb()``, ``smp_mb_release()``,
  283. ``qatomic_store_release()`` and ``qatomic_rcu_set()`` all count as release
  284. operations. ``smp_mb()`` counts as both acquire and release, therefore
  285. it can pair with any other atomic operation. Here is an example:
  286. +----------------------+------------------------------+
  287. | thread 1 | thread 2 |
  288. +======================+==============================+
  289. | :: | :: |
  290. | | |
  291. | qatomic_set(&a, 1);| |
  292. | smp_wmb(); | |
  293. | qatomic_set(&b, 2);| x = qatomic_read(&b); |
  294. | | smp_rmb(); |
  295. | | y = qatomic_read(&a); |
  296. +----------------------+------------------------------+
  297. Note that a load-store pair only counts if the two operations access the
  298. same variable: that is, a store-release on a variable ``x`` *synchronizes
  299. with* a load-acquire on a variable ``x``, while a release barrier
  300. synchronizes with any acquire operation. The following example shows
  301. correct synchronization:
  302. +--------------------------------+--------------------------------+
  303. | thread 1 | thread 2 |
  304. +================================+================================+
  305. | :: | :: |
  306. | | |
  307. | qatomic_set(&a, 1); | |
  308. | qatomic_store_release(&b, 2);| x = qatomic_load_acquire(&b);|
  309. | | y = qatomic_read(&a); |
  310. +--------------------------------+--------------------------------+
  311. Acquire and release semantics of higher-level primitives can also be
  312. relied upon for the purpose of establishing the *synchronizes with*
  313. relation.
  314. Note that the "writing" thread is accessing the variables in the
  315. opposite order as the "reading" thread. This is expected: stores
  316. before a release operation will normally match the loads after
  317. the acquire operation, and vice versa. In fact, this happened already
  318. in the ``pthread_exit``/``pthread_join`` example above.
  319. Finally, this more complex example has more than two accesses and data
  320. dependency barriers. It also does not use atomic accesses whenever there
  321. cannot be a data race:
  322. +----------------------+------------------------------+
  323. | thread 1 | thread 2 |
  324. +======================+==============================+
  325. | :: | :: |
  326. | | |
  327. | b[2] = 1; | |
  328. | smp_wmb(); | |
  329. | x->i = 2; | |
  330. | smp_wmb(); | |
  331. | qatomic_set(&a, x);| x = qatomic_read(&a); |
  332. | | smp_read_barrier_depends(); |
  333. | | y = x->i; |
  334. | | smp_read_barrier_depends(); |
  335. | | z = b[y]; |
  336. +----------------------+------------------------------+
  337. Comparison with Linux kernel primitives
  338. =======================================
  339. Here is a list of differences between Linux kernel atomic operations
  340. and memory barriers, and the equivalents in QEMU:
  341. - atomic operations in Linux are always on a 32-bit int type and
  342. use a boxed ``atomic_t`` type; atomic operations in QEMU are polymorphic
  343. and use normal C types.
  344. - Originally, ``atomic_read`` and ``atomic_set`` in Linux gave no guarantee
  345. at all. Linux 4.1 updated them to implement volatile
  346. semantics via ``ACCESS_ONCE`` (or the more recent ``READ``/``WRITE_ONCE``).
  347. QEMU's ``qatomic_read`` and ``qatomic_set`` implement C11 atomic relaxed
  348. semantics if the compiler supports it, and volatile semantics otherwise.
  349. Both semantics prevent the compiler from doing certain transformations;
  350. the difference is that atomic accesses are guaranteed to be atomic,
  351. while volatile accesses aren't. Thus, in the volatile case we just cross
  352. our fingers hoping that the compiler will generate atomic accesses,
  353. since we assume the variables passed are machine-word sized and
  354. properly aligned.
  355. No barriers are implied by ``qatomic_read`` and ``qatomic_set`` in either
  356. Linux or QEMU.
  357. - atomic read-modify-write operations in Linux are of three kinds:
  358. ===================== =========================================
  359. ``atomic_OP`` returns void
  360. ``atomic_OP_return`` returns new value of the variable
  361. ``atomic_fetch_OP`` returns the old value of the variable
  362. ``atomic_cmpxchg`` returns the old value of the variable
  363. ===================== =========================================
  364. In QEMU, the second kind is named ``atomic_OP_fetch``.
  365. - different atomic read-modify-write operations in Linux imply
  366. a different set of memory barriers. In QEMU, all of them enforce
  367. sequential consistency: there is a single order in which the
  368. program sees them happen.
  369. - however, according to the C11 memory model that QEMU uses, this order
  370. does not propagate to other memory accesses on either side of the
  371. read-modify-write operation. As far as those are concerned, the
  372. operation consist of just a load-acquire followed by a store-release.
  373. Stores that precede the RMW operation, and loads that follow it, can
  374. still be reordered and will happen *in the middle* of the read-modify-write
  375. operation!
  376. Therefore, the following example is correct in Linux but not in QEMU:
  377. +----------------------------------+--------------------------------+
  378. | Linux (correct) | QEMU (incorrect) |
  379. +==================================+================================+
  380. | :: | :: |
  381. | | |
  382. | a = atomic_fetch_add(&x, 2); | a = qatomic_fetch_add(&x, 2);|
  383. | b = READ_ONCE(&y); | b = qatomic_read(&y); |
  384. +----------------------------------+--------------------------------+
  385. because the read of ``y`` can be moved (by either the processor or the
  386. compiler) before the write of ``x``.
  387. Fixing this requires a full memory barrier between the write of ``x`` and
  388. the read of ``y``. QEMU provides ``smp_mb__before_rmw()`` and
  389. ``smp_mb__after_rmw()``; they act both as an optimization,
  390. avoiding the memory barrier on processors where it is unnecessary,
  391. and as a clarification of this corner case of the C11 memory model:
  392. +--------------------------------+
  393. | QEMU (correct) |
  394. +================================+
  395. | :: |
  396. | |
  397. | a = qatomic_fetch_add(&x, 2);|
  398. | smp_mb__after_rmw(); |
  399. | b = qatomic_read(&y); |
  400. +--------------------------------+
  401. In the common case where only one thread writes ``x``, it is also possible
  402. to write it like this:
  403. +--------------------------------+
  404. | QEMU (correct) |
  405. +================================+
  406. | :: |
  407. | |
  408. | a = qatomic_read(&x); |
  409. | qatomic_set_mb(&x, a + 2); |
  410. | b = qatomic_read(&y); |
  411. +--------------------------------+
  412. Sources
  413. =======
  414. - ``Documentation/memory-barriers.txt`` from the Linux kernel