]> Git Repo - qemu.git/blob - include/qemu/atomic.h
bitops.h: Implement half-shuffle and half-unshuffle ops
[qemu.git] / include / qemu / atomic.h
1 /*
2  * Simple interface for atomic operations.
3  *
4  * Copyright (C) 2013 Red Hat, Inc.
5  *
6  * Author: Paolo Bonzini <[email protected]>
7  *
8  * This work is licensed under the terms of the GNU GPL, version 2 or later.
9  * See the COPYING file in the top-level directory.
10  *
11  * See docs/atomics.txt for discussion about the guarantees each
12  * atomic primitive is meant to provide.
13  */
14
15 #ifndef __QEMU_ATOMIC_H
16 #define __QEMU_ATOMIC_H 1
17
18
19
20 /* Compiler barrier */
21 #define barrier()   ({ asm volatile("" ::: "memory"); (void)0; })
22
23 #ifdef __ATOMIC_RELAXED
24 /* For C11 atomic ops */
25
26 /* Manual memory barriers
27  *
28  *__atomic_thread_fence does not include a compiler barrier; instead,
29  * the barrier is part of __atomic_load/__atomic_store's "volatile-like"
30  * semantics. If smp_wmb() is a no-op, absence of the barrier means that
31  * the compiler is free to reorder stores on each side of the barrier.
32  * Add one here, and similarly in smp_rmb() and smp_read_barrier_depends().
33  */
34
35 #define smp_mb()    ({ barrier(); __atomic_thread_fence(__ATOMIC_SEQ_CST); barrier(); })
36 #define smp_wmb()   ({ barrier(); __atomic_thread_fence(__ATOMIC_RELEASE); barrier(); })
37 #define smp_rmb()   ({ barrier(); __atomic_thread_fence(__ATOMIC_ACQUIRE); barrier(); })
38
39 /* Most compilers currently treat consume and acquire the same, but really
40  * no processors except Alpha need a barrier here.  Leave it in if
41  * using Thread Sanitizer to avoid warnings, otherwise optimize it away.
42  */
43 #if defined(__SANITIZE_THREAD__)
44 #define smp_read_barrier_depends() ({ barrier(); __atomic_thread_fence(__ATOMIC_CONSUME); barrier(); })
45 #elsif defined(__alpha__)
46 #define smp_read_barrier_depends()   asm volatile("mb":::"memory")
47 #else
48 #define smp_read_barrier_depends()   barrier()
49 #endif
50
51
52 /* Weak atomic operations prevent the compiler moving other
53  * loads/stores past the atomic operation load/store. However there is
54  * no explicit memory barrier for the processor.
55  */
56 #define atomic_read(ptr)                              \
57     ({                                                \
58     QEMU_BUILD_BUG_ON(sizeof(*ptr) > sizeof(void *)); \
59     typeof(*ptr) _val;                                \
60      __atomic_load(ptr, &_val, __ATOMIC_RELAXED);     \
61     _val;                                             \
62     })
63
64 #define atomic_set(ptr, i)  do {                      \
65     QEMU_BUILD_BUG_ON(sizeof(*ptr) > sizeof(void *)); \
66     typeof(*ptr) _val = (i);                          \
67     __atomic_store(ptr, &_val, __ATOMIC_RELAXED);     \
68 } while(0)
69
70 /* See above: most compilers currently treat consume and acquire the
71  * same, but this slows down atomic_rcu_read unnecessarily.
72  */
73 #ifdef __SANITIZE_THREAD__
74 #define atomic_rcu_read__nocheck(ptr, valptr)           \
75     __atomic_load(ptr, valptr, __ATOMIC_CONSUME);
76 #else
77 #define atomic_rcu_read__nocheck(ptr, valptr)           \
78     __atomic_load(ptr, valptr, __ATOMIC_RELAXED);       \
79     smp_read_barrier_depends();
80 #endif
81
82 #define atomic_rcu_read(ptr)                          \
83     ({                                                \
84     QEMU_BUILD_BUG_ON(sizeof(*ptr) > sizeof(void *)); \
85     typeof(*ptr) _val;                                \
86     atomic_rcu_read__nocheck(ptr, &_val);             \
87     _val;                                             \
88     })
89
90 #define atomic_rcu_set(ptr, i) do {                   \
91     QEMU_BUILD_BUG_ON(sizeof(*ptr) > sizeof(void *)); \
92     typeof(*ptr) _val = (i);                          \
93     __atomic_store(ptr, &_val, __ATOMIC_RELEASE);     \
94 } while(0)
95
96 /* atomic_mb_read/set semantics map Java volatile variables. They are
97  * less expensive on some platforms (notably POWER & ARMv7) than fully
98  * sequentially consistent operations.
99  *
100  * As long as they are used as paired operations they are safe to
101  * use. See docs/atomic.txt for more discussion.
102  */
103
104 #if defined(_ARCH_PPC)
105 #define atomic_mb_read(ptr)                             \
106     ({                                                  \
107     QEMU_BUILD_BUG_ON(sizeof(*ptr) > sizeof(void *));   \
108     typeof(*ptr) _val;                                  \
109      __atomic_load(ptr, &_val, __ATOMIC_RELAXED);       \
110      smp_rmb();                                         \
111     _val;                                               \
112     })
113
114 #define atomic_mb_set(ptr, i)  do {                     \
115     QEMU_BUILD_BUG_ON(sizeof(*ptr) > sizeof(void *));   \
116     typeof(*ptr) _val = (i);                            \
117     smp_wmb();                                          \
118     __atomic_store(ptr, &_val, __ATOMIC_RELAXED);       \
119     smp_mb();                                           \
120 } while(0)
121 #else
122 #define atomic_mb_read(ptr)                             \
123     ({                                                  \
124     QEMU_BUILD_BUG_ON(sizeof(*ptr) > sizeof(void *));   \
125     typeof(*ptr) _val;                                  \
126     __atomic_load(ptr, &_val, __ATOMIC_SEQ_CST);        \
127     _val;                                               \
128     })
129
130 #define atomic_mb_set(ptr, i)  do {                     \
131     QEMU_BUILD_BUG_ON(sizeof(*ptr) > sizeof(void *));   \
132     typeof(*ptr) _val = (i);                            \
133     __atomic_store(ptr, &_val, __ATOMIC_SEQ_CST);       \
134 } while(0)
135 #endif
136
137
138 /* All the remaining operations are fully sequentially consistent */
139
140 #define atomic_xchg(ptr, i)    ({                           \
141     QEMU_BUILD_BUG_ON(sizeof(*ptr) > sizeof(void *));       \
142     typeof(*ptr) _new = (i), _old;                          \
143     __atomic_exchange(ptr, &_new, &_old, __ATOMIC_SEQ_CST); \
144     _old;                                                   \
145 })
146
147 /* Returns the eventual value, failed or not */
148 #define atomic_cmpxchg(ptr, old, new)                                   \
149     ({                                                                  \
150     QEMU_BUILD_BUG_ON(sizeof(*ptr) > sizeof(void *));                   \
151     typeof(*ptr) _old = (old), _new = (new);                            \
152     __atomic_compare_exchange(ptr, &_old, &_new, false,                 \
153                               __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);      \
154     _old;                                                               \
155     })
156
157 /* Provide shorter names for GCC atomic builtins, return old value */
158 #define atomic_fetch_inc(ptr)  __atomic_fetch_add(ptr, 1, __ATOMIC_SEQ_CST)
159 #define atomic_fetch_dec(ptr)  __atomic_fetch_sub(ptr, 1, __ATOMIC_SEQ_CST)
160 #define atomic_fetch_add(ptr, n) __atomic_fetch_add(ptr, n, __ATOMIC_SEQ_CST)
161 #define atomic_fetch_sub(ptr, n) __atomic_fetch_sub(ptr, n, __ATOMIC_SEQ_CST)
162 #define atomic_fetch_and(ptr, n) __atomic_fetch_and(ptr, n, __ATOMIC_SEQ_CST)
163 #define atomic_fetch_or(ptr, n)  __atomic_fetch_or(ptr, n, __ATOMIC_SEQ_CST)
164
165 /* And even shorter names that return void.  */
166 #define atomic_inc(ptr)    ((void) __atomic_fetch_add(ptr, 1, __ATOMIC_SEQ_CST))
167 #define atomic_dec(ptr)    ((void) __atomic_fetch_sub(ptr, 1, __ATOMIC_SEQ_CST))
168 #define atomic_add(ptr, n) ((void) __atomic_fetch_add(ptr, n, __ATOMIC_SEQ_CST))
169 #define atomic_sub(ptr, n) ((void) __atomic_fetch_sub(ptr, n, __ATOMIC_SEQ_CST))
170 #define atomic_and(ptr, n) ((void) __atomic_fetch_and(ptr, n, __ATOMIC_SEQ_CST))
171 #define atomic_or(ptr, n)  ((void) __atomic_fetch_or(ptr, n, __ATOMIC_SEQ_CST))
172
173 #else /* __ATOMIC_RELAXED */
174
175 /*
176  * We use GCC builtin if it's available, as that can use mfence on
177  * 32-bit as well, e.g. if built with -march=pentium-m. However, on
178  * i386 the spec is buggy, and the implementation followed it until
179  * 4.3 (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=36793).
180  */
181 #if defined(__i386__) || defined(__x86_64__)
182 #if !QEMU_GNUC_PREREQ(4, 4)
183 #if defined __x86_64__
184 #define smp_mb()    ({ asm volatile("mfence" ::: "memory"); (void)0; })
185 #else
186 #define smp_mb()    ({ asm volatile("lock; addl $0,0(%%esp) " ::: "memory"); (void)0; })
187 #endif
188 #endif
189 #endif
190
191
192 #ifdef __alpha__
193 #define smp_read_barrier_depends()   asm volatile("mb":::"memory")
194 #endif
195
196 #if defined(__i386__) || defined(__x86_64__) || defined(__s390x__)
197
198 /*
199  * Because of the strongly ordered storage model, wmb() and rmb() are nops
200  * here (a compiler barrier only).  QEMU doesn't do accesses to write-combining
201  * qemu memory or non-temporal load/stores from C code.
202  */
203 #define smp_wmb()   barrier()
204 #define smp_rmb()   barrier()
205
206 /*
207  * __sync_lock_test_and_set() is documented to be an acquire barrier only,
208  * but it is a full barrier at the hardware level.  Add a compiler barrier
209  * to make it a full barrier also at the compiler level.
210  */
211 #define atomic_xchg(ptr, i)    (barrier(), __sync_lock_test_and_set(ptr, i))
212
213 /*
214  * Load/store with Java volatile semantics.
215  */
216 #define atomic_mb_set(ptr, i)  ((void)atomic_xchg(ptr, i))
217
218 #elif defined(_ARCH_PPC)
219
220 /*
221  * We use an eieio() for wmb() on powerpc.  This assumes we don't
222  * need to order cacheable and non-cacheable stores with respect to
223  * each other.
224  *
225  * smp_mb has the same problem as on x86 for not-very-new GCC
226  * (http://patchwork.ozlabs.org/patch/126184/, Nov 2011).
227  */
228 #define smp_wmb()   ({ asm volatile("eieio" ::: "memory"); (void)0; })
229 #if defined(__powerpc64__)
230 #define smp_rmb()   ({ asm volatile("lwsync" ::: "memory"); (void)0; })
231 #else
232 #define smp_rmb()   ({ asm volatile("sync" ::: "memory"); (void)0; })
233 #endif
234 #define smp_mb()    ({ asm volatile("sync" ::: "memory"); (void)0; })
235
236 #endif /* _ARCH_PPC */
237
238 /*
239  * For (host) platforms we don't have explicit barrier definitions
240  * for, we use the gcc __sync_synchronize() primitive to generate a
241  * full barrier.  This should be safe on all platforms, though it may
242  * be overkill for smp_wmb() and smp_rmb().
243  */
244 #ifndef smp_mb
245 #define smp_mb()    __sync_synchronize()
246 #endif
247
248 #ifndef smp_wmb
249 #define smp_wmb()   __sync_synchronize()
250 #endif
251
252 #ifndef smp_rmb
253 #define smp_rmb()   __sync_synchronize()
254 #endif
255
256 #ifndef smp_read_barrier_depends
257 #define smp_read_barrier_depends()   barrier()
258 #endif
259
260 /* These will only be atomic if the processor does the fetch or store
261  * in a single issue memory operation
262  */
263 #define atomic_read(ptr)       (*(__typeof__(*ptr) volatile*) (ptr))
264 #define atomic_set(ptr, i)     ((*(__typeof__(*ptr) volatile*) (ptr)) = (i))
265
266 /**
267  * atomic_rcu_read - reads a RCU-protected pointer to a local variable
268  * into a RCU read-side critical section. The pointer can later be safely
269  * dereferenced within the critical section.
270  *
271  * This ensures that the pointer copy is invariant thorough the whole critical
272  * section.
273  *
274  * Inserts memory barriers on architectures that require them (currently only
275  * Alpha) and documents which pointers are protected by RCU.
276  *
277  * atomic_rcu_read also includes a compiler barrier to ensure that
278  * value-speculative optimizations (e.g. VSS: Value Speculation
279  * Scheduling) does not perform the data read before the pointer read
280  * by speculating the value of the pointer.
281  *
282  * Should match atomic_rcu_set(), atomic_xchg(), atomic_cmpxchg().
283  */
284 #define atomic_rcu_read(ptr)    ({                \
285     typeof(*ptr) _val = atomic_read(ptr);         \
286     smp_read_barrier_depends();                   \
287     _val;                                         \
288 })
289
290 /**
291  * atomic_rcu_set - assigns (publicizes) a pointer to a new data structure
292  * meant to be read by RCU read-side critical sections.
293  *
294  * Documents which pointers will be dereferenced by RCU read-side critical
295  * sections and adds the required memory barriers on architectures requiring
296  * them. It also makes sure the compiler does not reorder code initializing the
297  * data structure before its publication.
298  *
299  * Should match atomic_rcu_read().
300  */
301 #define atomic_rcu_set(ptr, i)  do {              \
302     smp_wmb();                                    \
303     atomic_set(ptr, i);                           \
304 } while (0)
305
306 /* These have the same semantics as Java volatile variables.
307  * See http://gee.cs.oswego.edu/dl/jmm/cookbook.html:
308  * "1. Issue a StoreStore barrier (wmb) before each volatile store."
309  *  2. Issue a StoreLoad barrier after each volatile store.
310  *     Note that you could instead issue one before each volatile load, but
311  *     this would be slower for typical programs using volatiles in which
312  *     reads greatly outnumber writes. Alternatively, if available, you
313  *     can implement volatile store as an atomic instruction (for example
314  *     XCHG on x86) and omit the barrier. This may be more efficient if
315  *     atomic instructions are cheaper than StoreLoad barriers.
316  *  3. Issue LoadLoad and LoadStore barriers after each volatile load."
317  *
318  * If you prefer to think in terms of "pairing" of memory barriers,
319  * an atomic_mb_read pairs with an atomic_mb_set.
320  *
321  * And for the few ia64 lovers that exist, an atomic_mb_read is a ld.acq,
322  * while an atomic_mb_set is a st.rel followed by a memory barrier.
323  *
324  * These are a bit weaker than __atomic_load/store with __ATOMIC_SEQ_CST
325  * (see docs/atomics.txt), and I'm not sure that __ATOMIC_ACQ_REL is enough.
326  * Just always use the barriers manually by the rules above.
327  */
328 #define atomic_mb_read(ptr)    ({           \
329     typeof(*ptr) _val = atomic_read(ptr);   \
330     smp_rmb();                              \
331     _val;                                   \
332 })
333
334 #ifndef atomic_mb_set
335 #define atomic_mb_set(ptr, i)  do {         \
336     smp_wmb();                              \
337     atomic_set(ptr, i);                     \
338     smp_mb();                               \
339 } while (0)
340 #endif
341
342 #ifndef atomic_xchg
343 #if defined(__clang__)
344 #define atomic_xchg(ptr, i)    __sync_swap(ptr, i)
345 #else
346 /* __sync_lock_test_and_set() is documented to be an acquire barrier only.  */
347 #define atomic_xchg(ptr, i)    (smp_mb(), __sync_lock_test_and_set(ptr, i))
348 #endif
349 #endif
350
351 /* Provide shorter names for GCC atomic builtins.  */
352 #define atomic_fetch_inc(ptr)  __sync_fetch_and_add(ptr, 1)
353 #define atomic_fetch_dec(ptr)  __sync_fetch_and_add(ptr, -1)
354 #define atomic_fetch_add       __sync_fetch_and_add
355 #define atomic_fetch_sub       __sync_fetch_and_sub
356 #define atomic_fetch_and       __sync_fetch_and_and
357 #define atomic_fetch_or        __sync_fetch_and_or
358 #define atomic_cmpxchg         __sync_val_compare_and_swap
359
360 /* And even shorter names that return void.  */
361 #define atomic_inc(ptr)        ((void) __sync_fetch_and_add(ptr, 1))
362 #define atomic_dec(ptr)        ((void) __sync_fetch_and_add(ptr, -1))
363 #define atomic_add(ptr, n)     ((void) __sync_fetch_and_add(ptr, n))
364 #define atomic_sub(ptr, n)     ((void) __sync_fetch_and_sub(ptr, n))
365 #define atomic_and(ptr, n)     ((void) __sync_fetch_and_and(ptr, n))
366 #define atomic_or(ptr, n)      ((void) __sync_fetch_and_or(ptr, n))
367
368 #endif /* __ATOMIC_RELAXED */
369 #endif /* __QEMU_ATOMIC_H */
This page took 0.044155 seconds and 4 git commands to generate.