xref: /qemu/subprojects/libvhost-user/include/atomic.h (revision 70ce076fa6dff60585c229a4b641b13e64bf03cf)
1 /*
2  * Simple interface for atomic operations.
3  *
4  * Copyright (C) 2013 Red Hat, Inc.
5  *
6  * Author: Paolo Bonzini <pbonzini@redhat.com>
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/devel/atomics.rst 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
17 
18 #include "compiler.h"
19 
20 /* Compiler barrier */
21 #define barrier()   ({ asm volatile("" ::: "memory"); (void)0; })
22 
23 #ifndef __ATOMIC_RELAXED
24 #error "Expecting C11 atomic ops"
25 #endif
26 
27 /* Manual memory barriers
28  *
29  *__atomic_thread_fence does not include a compiler barrier; instead,
30  * the barrier is part of __atomic_load/__atomic_store's "volatile-like"
31  * semantics. If smp_wmb() is a no-op, absence of the barrier means that
32  * the compiler is free to reorder stores on each side of the barrier.
33  * Add one here, and similarly in smp_rmb() and smp_read_barrier_depends().
34  */
35 
36 #define smp_mb()                     ({ barrier(); __atomic_thread_fence(__ATOMIC_SEQ_CST); })
37 #define smp_mb_release()             ({ barrier(); __atomic_thread_fence(__ATOMIC_RELEASE); })
38 #define smp_mb_acquire()             ({ barrier(); __atomic_thread_fence(__ATOMIC_ACQUIRE); })
39 
40 /* Most compilers currently treat consume and acquire the same, but really
41  * no processors except Alpha need a barrier here.  Leave it in if
42  * using Thread Sanitizer to avoid warnings, otherwise optimize it away.
43  */
44 #ifdef QEMU_SANITIZE_THREAD
45 #define smp_read_barrier_depends()   ({ barrier(); __atomic_thread_fence(__ATOMIC_CONSUME); })
46 #elif defined(__alpha__)
47 #define smp_read_barrier_depends()   asm volatile("mb":::"memory")
48 #else
49 #define smp_read_barrier_depends()   barrier()
50 #endif
51 
52 /*
53  * A signal barrier forces all pending local memory ops to be observed before
54  * a SIGSEGV is delivered to the *same* thread.  In practice this is exactly
55  * the same as barrier(), but since we have the correct builtin, use it.
56  */
57 #define signal_barrier()    __atomic_signal_fence(__ATOMIC_SEQ_CST)
58 
59 /*
60  * Sanity check that the size of an atomic operation isn't "overly large".
61  * Despite the fact that e.g. i686 has 64-bit atomic operations, we do not
62  * want to use them because we ought not need them, and this lets us do a
63  * bit of sanity checking that other 32-bit hosts might build.
64  */
65 #define ATOMIC_REG_SIZE  sizeof(void *)
66 
67 /* Weak atomic operations prevent the compiler moving other
68  * loads/stores past the atomic operation load/store. However there is
69  * no explicit memory barrier for the processor.
70  *
71  * The C11 memory model says that variables that are accessed from
72  * different threads should at least be done with __ATOMIC_RELAXED
73  * primitives or the result is undefined. Generally this has little to
74  * no effect on the generated code but not using the atomic primitives
75  * will get flagged by sanitizers as a violation.
76  */
77 #define qatomic_read__nocheck(ptr) \
78     __atomic_load_n(ptr, __ATOMIC_RELAXED)
79 
80 #define qatomic_read(ptr)                              \
81     ({                                                 \
82     qemu_build_assert(sizeof(*ptr) <= ATOMIC_REG_SIZE); \
83     qatomic_read__nocheck(ptr);                        \
84     })
85 
86 #define qatomic_set__nocheck(ptr, i) \
87     __atomic_store_n(ptr, i, __ATOMIC_RELAXED)
88 
89 #define qatomic_set(ptr, i)  do {                      \
90     qemu_build_assert(sizeof(*ptr) <= ATOMIC_REG_SIZE); \
91     qatomic_set__nocheck(ptr, i);                      \
92 } while(0)
93 
94 /* See above: most compilers currently treat consume and acquire the
95  * same, but this slows down qatomic_rcu_read unnecessarily.
96  */
97 #ifdef QEMU_SANITIZE_THREAD
98 #define qatomic_rcu_read__nocheck(ptr, valptr)           \
99     __atomic_load(ptr, valptr, __ATOMIC_CONSUME);
100 #else
101 #define qatomic_rcu_read__nocheck(ptr, valptr)           \
102     __atomic_load(ptr, valptr, __ATOMIC_RELAXED);        \
103     smp_read_barrier_depends();
104 #endif
105 
106 /*
107  * Preprocessor sorcery ahead: use a different identifier for the
108  * local variable in each expansion, so we can nest macro calls
109  * without shadowing variables.
110  */
111 #define qatomic_rcu_read_internal(ptr, _val)            \
112     ({                                                  \
113     qemu_build_assert(sizeof(*ptr) <= ATOMIC_REG_SIZE); \
114     typeof_strip_qual(*ptr) _val;                       \
115     qatomic_rcu_read__nocheck(ptr, &_val);              \
116     _val;                                               \
117     })
118 #define qatomic_rcu_read(ptr) \
119     qatomic_rcu_read_internal((ptr), MAKE_IDENTIFIER(_val))
120 
121 #define qatomic_rcu_set(ptr, i) do {                   \
122     qemu_build_assert(sizeof(*ptr) <= ATOMIC_REG_SIZE); \
123     __atomic_store_n(ptr, i, __ATOMIC_RELEASE);        \
124 } while(0)
125 
126 #define qatomic_load_acquire(ptr)                       \
127     ({                                                  \
128     qemu_build_assert(sizeof(*ptr) <= ATOMIC_REG_SIZE); \
129     typeof_strip_qual(*ptr) _val;                       \
130     __atomic_load(ptr, &_val, __ATOMIC_ACQUIRE);        \
131     _val;                                               \
132     })
133 
134 #define qatomic_store_release(ptr, i)  do {             \
135     qemu_build_assert(sizeof(*ptr) <= ATOMIC_REG_SIZE); \
136     __atomic_store_n(ptr, i, __ATOMIC_RELEASE);         \
137 } while(0)
138 
139 
140 /* All the remaining operations are fully sequentially consistent */
141 
142 #define qatomic_xchg__nocheck(ptr, i)    ({                 \
143     __atomic_exchange_n(ptr, (i), __ATOMIC_SEQ_CST);        \
144 })
145 
146 #define qatomic_xchg(ptr, i)    ({                          \
147     qemu_build_assert(sizeof(*ptr) <= ATOMIC_REG_SIZE);     \
148     qatomic_xchg__nocheck(ptr, i);                          \
149 })
150 
151 /* Returns the old value of '*ptr' (whether the cmpxchg failed or not) */
152 #define qatomic_cmpxchg__nocheck(ptr, old, new)    ({                   \
153     typeof_strip_qual(*ptr) _old = (old);                               \
154     (void)__atomic_compare_exchange_n(ptr, &_old, new, false,           \
155                               __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);      \
156     _old;                                                               \
157 })
158 
159 #define qatomic_cmpxchg(ptr, old, new)    ({                            \
160     qemu_build_assert(sizeof(*ptr) <= ATOMIC_REG_SIZE);                 \
161     qatomic_cmpxchg__nocheck(ptr, old, new);                            \
162 })
163 
164 /* Provide shorter names for GCC atomic builtins, return old value */
165 #define qatomic_fetch_inc(ptr)  __atomic_fetch_add(ptr, 1, __ATOMIC_SEQ_CST)
166 #define qatomic_fetch_dec(ptr)  __atomic_fetch_sub(ptr, 1, __ATOMIC_SEQ_CST)
167 
168 #define qatomic_fetch_add(ptr, n) __atomic_fetch_add(ptr, n, __ATOMIC_SEQ_CST)
169 #define qatomic_fetch_sub(ptr, n) __atomic_fetch_sub(ptr, n, __ATOMIC_SEQ_CST)
170 #define qatomic_fetch_and(ptr, n) __atomic_fetch_and(ptr, n, __ATOMIC_SEQ_CST)
171 #define qatomic_fetch_or(ptr, n)  __atomic_fetch_or(ptr, n, __ATOMIC_SEQ_CST)
172 #define qatomic_fetch_xor(ptr, n) __atomic_fetch_xor(ptr, n, __ATOMIC_SEQ_CST)
173 
174 #define qatomic_inc_fetch(ptr)    __atomic_add_fetch(ptr, 1, __ATOMIC_SEQ_CST)
175 #define qatomic_dec_fetch(ptr)    __atomic_sub_fetch(ptr, 1, __ATOMIC_SEQ_CST)
176 #define qatomic_add_fetch(ptr, n) __atomic_add_fetch(ptr, n, __ATOMIC_SEQ_CST)
177 #define qatomic_sub_fetch(ptr, n) __atomic_sub_fetch(ptr, n, __ATOMIC_SEQ_CST)
178 #define qatomic_and_fetch(ptr, n) __atomic_and_fetch(ptr, n, __ATOMIC_SEQ_CST)
179 #define qatomic_or_fetch(ptr, n)  __atomic_or_fetch(ptr, n, __ATOMIC_SEQ_CST)
180 #define qatomic_xor_fetch(ptr, n) __atomic_xor_fetch(ptr, n, __ATOMIC_SEQ_CST)
181 
182 /* And even shorter names that return void.  */
183 #define qatomic_inc(ptr) \
184     ((void) __atomic_fetch_add(ptr, 1, __ATOMIC_SEQ_CST))
185 #define qatomic_dec(ptr) \
186     ((void) __atomic_fetch_sub(ptr, 1, __ATOMIC_SEQ_CST))
187 #define qatomic_add(ptr, n) \
188     ((void) __atomic_fetch_add(ptr, n, __ATOMIC_SEQ_CST))
189 #define qatomic_sub(ptr, n) \
190     ((void) __atomic_fetch_sub(ptr, n, __ATOMIC_SEQ_CST))
191 #define qatomic_and(ptr, n) \
192     ((void) __atomic_fetch_and(ptr, n, __ATOMIC_SEQ_CST))
193 #define qatomic_or(ptr, n) \
194     ((void) __atomic_fetch_or(ptr, n, __ATOMIC_SEQ_CST))
195 #define qatomic_xor(ptr, n) \
196     ((void) __atomic_fetch_xor(ptr, n, __ATOMIC_SEQ_CST))
197 
198 #define smp_wmb()   smp_mb_release()
199 #define smp_rmb()   smp_mb_acquire()
200 
201 /*
202  * SEQ_CST is weaker than the older __sync_* builtins and Linux
203  * kernel read-modify-write atomics.  Provide a macro to obtain
204  * the same semantics.
205  */
206 #if !defined(QEMU_SANITIZE_THREAD) && \
207     (defined(__i386__) || defined(__x86_64__) || defined(__s390x__))
208 # define smp_mb__before_rmw() signal_barrier()
209 # define smp_mb__after_rmw() signal_barrier()
210 #else
211 # define smp_mb__before_rmw() smp_mb()
212 # define smp_mb__after_rmw() smp_mb()
213 #endif
214 
215 /*
216  * On some architectures, qatomic_set_mb is more efficient than a store
217  * plus a fence.
218  */
219 
220 #if !defined(QEMU_SANITIZE_THREAD) && \
221     (defined(__i386__) || defined(__x86_64__) || defined(__s390x__))
222 # define qatomic_set_mb(ptr, i) \
223     ({ (void)qatomic_xchg(ptr, i); smp_mb__after_rmw(); })
224 #else
225 # define qatomic_set_mb(ptr, i) \
226    ({ qatomic_store_release(ptr, i); smp_mb(); })
227 #endif
228 
229 #define qatomic_fetch_inc_nonzero(ptr) ({                               \
230     typeof_strip_qual(*ptr) _oldn = qatomic_read(ptr);                  \
231     while (_oldn && qatomic_cmpxchg(ptr, _oldn, _oldn + 1) != _oldn) {  \
232         _oldn = qatomic_read(ptr);                                      \
233     }                                                                   \
234     _oldn;                                                              \
235 })
236 
237 /*
238  * Abstractions to access atomically (i.e. "once") i64/u64 variables.
239  *
240  * The i386 abi is odd in that by default members are only aligned to
241  * 4 bytes, which means that 8-byte types can wind up mis-aligned.
242  * Clang will then warn about this, and emit a call into libatomic.
243  *
244  * Use of these types in structures when they will be used with atomic
245  * operations can avoid this.
246  */
247 typedef int64_t aligned_int64_t __attribute__((aligned(8)));
248 typedef uint64_t aligned_uint64_t __attribute__((aligned(8)));
249 
250 #ifdef CONFIG_ATOMIC64
251 /* Use __nocheck because sizeof(void *) might be < sizeof(u64) */
252 #define qatomic_read_i64(P) \
253     _Generic(*(P), int64_t: qatomic_read__nocheck(P))
254 #define qatomic_read_u64(P) \
255     _Generic(*(P), uint64_t: qatomic_read__nocheck(P))
256 #define qatomic_set_i64(P, V) \
257     _Generic(*(P), int64_t: qatomic_set__nocheck(P, V))
258 #define qatomic_set_u64(P, V) \
259     _Generic(*(P), uint64_t: qatomic_set__nocheck(P, V))
260 
261 static inline void qatomic64_init(void)
262 {
263 }
264 #else /* !CONFIG_ATOMIC64 */
265 int64_t  qatomic_read_i64(const int64_t *ptr);
266 uint64_t qatomic_read_u64(const uint64_t *ptr);
267 void qatomic_set_i64(int64_t *ptr, int64_t val);
268 void qatomic_set_u64(uint64_t *ptr, uint64_t val);
269 void qatomic64_init(void);
270 #endif /* !CONFIG_ATOMIC64 */
271 
272 #endif /* QEMU_ATOMIC_H */
273