atomic.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. //===-- atomic.c - Implement support functions for atomic operations.------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // atomic.c defines a set of functions for performing atomic accesses on
  10. // arbitrary-sized memory locations. This design uses locks that should
  11. // be fast in the uncontended case, for two reasons:
  12. //
  13. // 1) This code must work with C programs that do not link to anything
  14. // (including pthreads) and so it should not depend on any pthread
  15. // functions. If the user wishes to opt into using pthreads, they may do so.
  16. // 2) Atomic operations, rather than explicit mutexes, are most commonly used
  17. // on code where contended operations are rate.
  18. //
  19. // To avoid needing a per-object lock, this code allocates an array of
  20. // locks and hashes the object pointers to find the one that it should use.
  21. // For operations that must be atomic on two locations, the lower lock is
  22. // always acquired first, to avoid deadlock.
  23. //
  24. //===----------------------------------------------------------------------===//
  25. #include <stdbool.h>
  26. #include <stddef.h>
  27. #include <stdint.h>
  28. #include "assembly.h"
  29. // We use __builtin_mem* here to avoid dependencies on libc-provided headers.
  30. #define memcpy __builtin_memcpy
  31. #define memcmp __builtin_memcmp
  32. // Clang objects if you redefine a builtin. This little hack allows us to
  33. // define a function with the same name as an intrinsic.
  34. #pragma redefine_extname __atomic_load_c SYMBOL_NAME(__atomic_load)
  35. #pragma redefine_extname __atomic_store_c SYMBOL_NAME(__atomic_store)
  36. #pragma redefine_extname __atomic_exchange_c SYMBOL_NAME(__atomic_exchange)
  37. #pragma redefine_extname __atomic_compare_exchange_c SYMBOL_NAME( \
  38. __atomic_compare_exchange)
  39. #pragma redefine_extname __atomic_is_lock_free_c SYMBOL_NAME( \
  40. __atomic_is_lock_free)
  41. /// Number of locks. This allocates one page on 32-bit platforms, two on
  42. /// 64-bit. This can be specified externally if a different trade between
  43. /// memory usage and contention probability is required for a given platform.
  44. #ifndef SPINLOCK_COUNT
  45. #define SPINLOCK_COUNT (1 << 10)
  46. #endif
  47. static const long SPINLOCK_MASK = SPINLOCK_COUNT - 1;
  48. ////////////////////////////////////////////////////////////////////////////////
  49. // Platform-specific lock implementation. Falls back to spinlocks if none is
  50. // defined. Each platform should define the Lock type, and corresponding
  51. // lock() and unlock() functions.
  52. ////////////////////////////////////////////////////////////////////////////////
  53. #if defined(_LIBATOMIC_USE_PTHREAD)
  54. #include <pthread.h>
  55. typedef pthread_mutex_t Lock;
  56. /// Unlock a lock. This is a release operation.
  57. __inline static void unlock(Lock *l) { pthread_mutex_unlock(l); }
  58. /// Locks a lock.
  59. __inline static void lock(Lock *l) { pthread_mutex_lock(l); }
  60. /// locks for atomic operations
  61. static Lock locks[SPINLOCK_COUNT];
  62. #elif defined(__FreeBSD__) || defined(__DragonFly__)
  63. #include <errno.h>
  64. // clang-format off
  65. #include <sys/types.h>
  66. #include <machine/atomic.h>
  67. #include <sys/umtx.h>
  68. // clang-format on
  69. typedef struct _usem Lock;
  70. __inline static void unlock(Lock *l) {
  71. __c11_atomic_store((_Atomic(uint32_t) *)&l->_count, 1, __ATOMIC_RELEASE);
  72. __c11_atomic_thread_fence(__ATOMIC_SEQ_CST);
  73. if (l->_has_waiters)
  74. _umtx_op(l, UMTX_OP_SEM_WAKE, 1, 0, 0);
  75. }
  76. __inline static void lock(Lock *l) {
  77. uint32_t old = 1;
  78. while (!__c11_atomic_compare_exchange_weak((_Atomic(uint32_t) *)&l->_count,
  79. &old, 0, __ATOMIC_ACQUIRE,
  80. __ATOMIC_RELAXED)) {
  81. _umtx_op(l, UMTX_OP_SEM_WAIT, 0, 0, 0);
  82. old = 1;
  83. }
  84. }
  85. /// locks for atomic operations
  86. static Lock locks[SPINLOCK_COUNT] = {[0 ... SPINLOCK_COUNT - 1] = {0, 1, 0}};
  87. #elif defined(__APPLE__)
  88. #include <libkern/OSAtomic.h>
  89. typedef OSSpinLock Lock;
  90. __inline static void unlock(Lock *l) { OSSpinLockUnlock(l); }
  91. /// Locks a lock. In the current implementation, this is potentially
  92. /// unbounded in the contended case.
  93. __inline static void lock(Lock *l) { OSSpinLockLock(l); }
  94. static Lock locks[SPINLOCK_COUNT]; // initialized to OS_SPINLOCK_INIT which is 0
  95. #else
  96. _Static_assert(__atomic_always_lock_free(sizeof(uintptr_t), 0),
  97. "Implementation assumes lock-free pointer-size cmpxchg");
  98. typedef _Atomic(uintptr_t) Lock;
  99. /// Unlock a lock. This is a release operation.
  100. __inline static void unlock(Lock *l) {
  101. __c11_atomic_store(l, 0, __ATOMIC_RELEASE);
  102. }
  103. /// Locks a lock. In the current implementation, this is potentially
  104. /// unbounded in the contended case.
  105. __inline static void lock(Lock *l) {
  106. uintptr_t old = 0;
  107. while (!__c11_atomic_compare_exchange_weak(l, &old, 1, __ATOMIC_ACQUIRE,
  108. __ATOMIC_RELAXED))
  109. old = 0;
  110. }
  111. /// locks for atomic operations
  112. static Lock locks[SPINLOCK_COUNT];
  113. #endif
  114. /// Returns a lock to use for a given pointer.
  115. static __inline Lock *lock_for_pointer(void *ptr) {
  116. intptr_t hash = (intptr_t)ptr;
  117. // Disregard the lowest 4 bits. We want all values that may be part of the
  118. // same memory operation to hash to the same value and therefore use the same
  119. // lock.
  120. hash >>= 4;
  121. // Use the next bits as the basis for the hash
  122. intptr_t low = hash & SPINLOCK_MASK;
  123. // Now use the high(er) set of bits to perturb the hash, so that we don't
  124. // get collisions from atomic fields in a single object
  125. hash >>= 16;
  126. hash ^= low;
  127. // Return a pointer to the word to use
  128. return locks + (hash & SPINLOCK_MASK);
  129. }
  130. /// Macros for determining whether a size is lock free.
  131. #define ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(size, p) \
  132. (__atomic_always_lock_free(size, p) || \
  133. (__atomic_always_lock_free(size, 0) && ((uintptr_t)p % size) == 0))
  134. #define IS_LOCK_FREE_1(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(1, p)
  135. #define IS_LOCK_FREE_2(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(2, p)
  136. #define IS_LOCK_FREE_4(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(4, p)
  137. #define IS_LOCK_FREE_8(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(8, p)
  138. #define IS_LOCK_FREE_16(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(16, p)
  139. /// Macro that calls the compiler-generated lock-free versions of functions
  140. /// when they exist.
  141. #define TRY_LOCK_FREE_CASE(n, type, ptr) \
  142. case n: \
  143. if (IS_LOCK_FREE_##n(ptr)) { \
  144. LOCK_FREE_ACTION(type); \
  145. } \
  146. break;
  147. #ifdef __SIZEOF_INT128__
  148. #define TRY_LOCK_FREE_CASE_16(p) TRY_LOCK_FREE_CASE(16, __uint128_t, p)
  149. #else
  150. #define TRY_LOCK_FREE_CASE_16(p) /* __uint128_t not available */
  151. #endif
  152. #define LOCK_FREE_CASES(ptr) \
  153. do { \
  154. switch (size) { \
  155. TRY_LOCK_FREE_CASE(1, uint8_t, ptr) \
  156. TRY_LOCK_FREE_CASE(2, uint16_t, ptr) \
  157. TRY_LOCK_FREE_CASE(4, uint32_t, ptr) \
  158. TRY_LOCK_FREE_CASE(8, uint64_t, ptr) \
  159. TRY_LOCK_FREE_CASE_16(ptr) /* __uint128_t may not be supported */ \
  160. default: \
  161. break; \
  162. } \
  163. } while (0)
  164. /// Whether atomic operations for the given size (and alignment) are lock-free.
  165. bool __atomic_is_lock_free_c(size_t size, void *ptr) {
  166. #define LOCK_FREE_ACTION(type) return true;
  167. LOCK_FREE_CASES(ptr);
  168. #undef LOCK_FREE_ACTION
  169. return false;
  170. }
  171. /// An atomic load operation. This is atomic with respect to the source
  172. /// pointer only.
  173. void __atomic_load_c(int size, void *src, void *dest, int model) {
  174. #define LOCK_FREE_ACTION(type) \
  175. *((type *)dest) = __c11_atomic_load((_Atomic(type) *)src, model); \
  176. return;
  177. LOCK_FREE_CASES(src);
  178. #undef LOCK_FREE_ACTION
  179. Lock *l = lock_for_pointer(src);
  180. lock(l);
  181. memcpy(dest, src, size);
  182. unlock(l);
  183. }
  184. /// An atomic store operation. This is atomic with respect to the destination
  185. /// pointer only.
  186. void __atomic_store_c(int size, void *dest, void *src, int model) {
  187. #define LOCK_FREE_ACTION(type) \
  188. __c11_atomic_store((_Atomic(type) *)dest, *(type *)src, model); \
  189. return;
  190. LOCK_FREE_CASES(dest);
  191. #undef LOCK_FREE_ACTION
  192. Lock *l = lock_for_pointer(dest);
  193. lock(l);
  194. memcpy(dest, src, size);
  195. unlock(l);
  196. }
  197. /// Atomic compare and exchange operation. If the value at *ptr is identical
  198. /// to the value at *expected, then this copies value at *desired to *ptr. If
  199. /// they are not, then this stores the current value from *ptr in *expected.
  200. ///
  201. /// This function returns 1 if the exchange takes place or 0 if it fails.
  202. int __atomic_compare_exchange_c(int size, void *ptr, void *expected,
  203. void *desired, int success, int failure) {
  204. #define LOCK_FREE_ACTION(type) \
  205. return __c11_atomic_compare_exchange_strong( \
  206. (_Atomic(type) *)ptr, (type *)expected, *(type *)desired, success, \
  207. failure)
  208. LOCK_FREE_CASES(ptr);
  209. #undef LOCK_FREE_ACTION
  210. Lock *l = lock_for_pointer(ptr);
  211. lock(l);
  212. if (memcmp(ptr, expected, size) == 0) {
  213. memcpy(ptr, desired, size);
  214. unlock(l);
  215. return 1;
  216. }
  217. memcpy(expected, ptr, size);
  218. unlock(l);
  219. return 0;
  220. }
  221. /// Performs an atomic exchange operation between two pointers. This is atomic
  222. /// with respect to the target address.
  223. void __atomic_exchange_c(int size, void *ptr, void *val, void *old, int model) {
  224. #define LOCK_FREE_ACTION(type) \
  225. *(type *)old = \
  226. __c11_atomic_exchange((_Atomic(type) *)ptr, *(type *)val, model); \
  227. return;
  228. LOCK_FREE_CASES(ptr);
  229. #undef LOCK_FREE_ACTION
  230. Lock *l = lock_for_pointer(ptr);
  231. lock(l);
  232. memcpy(old, ptr, size);
  233. memcpy(ptr, val, size);
  234. unlock(l);
  235. }
  236. ////////////////////////////////////////////////////////////////////////////////
  237. // Where the size is known at compile time, the compiler may emit calls to
  238. // specialised versions of the above functions.
  239. ////////////////////////////////////////////////////////////////////////////////
  240. #ifdef __SIZEOF_INT128__
  241. #define OPTIMISED_CASES \
  242. OPTIMISED_CASE(1, IS_LOCK_FREE_1, uint8_t) \
  243. OPTIMISED_CASE(2, IS_LOCK_FREE_2, uint16_t) \
  244. OPTIMISED_CASE(4, IS_LOCK_FREE_4, uint32_t) \
  245. OPTIMISED_CASE(8, IS_LOCK_FREE_8, uint64_t) \
  246. OPTIMISED_CASE(16, IS_LOCK_FREE_16, __uint128_t)
  247. #else
  248. #define OPTIMISED_CASES \
  249. OPTIMISED_CASE(1, IS_LOCK_FREE_1, uint8_t) \
  250. OPTIMISED_CASE(2, IS_LOCK_FREE_2, uint16_t) \
  251. OPTIMISED_CASE(4, IS_LOCK_FREE_4, uint32_t) \
  252. OPTIMISED_CASE(8, IS_LOCK_FREE_8, uint64_t)
  253. #endif
  254. #define OPTIMISED_CASE(n, lockfree, type) \
  255. type __atomic_load_##n(type *src, int model) { \
  256. if (lockfree(src)) \
  257. return __c11_atomic_load((_Atomic(type) *)src, model); \
  258. Lock *l = lock_for_pointer(src); \
  259. lock(l); \
  260. type val = *src; \
  261. unlock(l); \
  262. return val; \
  263. }
  264. OPTIMISED_CASES
  265. #undef OPTIMISED_CASE
  266. #define OPTIMISED_CASE(n, lockfree, type) \
  267. void __atomic_store_##n(type *dest, type val, int model) { \
  268. if (lockfree(dest)) { \
  269. __c11_atomic_store((_Atomic(type) *)dest, val, model); \
  270. return; \
  271. } \
  272. Lock *l = lock_for_pointer(dest); \
  273. lock(l); \
  274. *dest = val; \
  275. unlock(l); \
  276. return; \
  277. }
  278. OPTIMISED_CASES
  279. #undef OPTIMISED_CASE
  280. #define OPTIMISED_CASE(n, lockfree, type) \
  281. type __atomic_exchange_##n(type *dest, type val, int model) { \
  282. if (lockfree(dest)) \
  283. return __c11_atomic_exchange((_Atomic(type) *)dest, val, model); \
  284. Lock *l = lock_for_pointer(dest); \
  285. lock(l); \
  286. type tmp = *dest; \
  287. *dest = val; \
  288. unlock(l); \
  289. return tmp; \
  290. }
  291. OPTIMISED_CASES
  292. #undef OPTIMISED_CASE
  293. #define OPTIMISED_CASE(n, lockfree, type) \
  294. bool __atomic_compare_exchange_##n(type *ptr, type *expected, type desired, \
  295. int success, int failure) { \
  296. if (lockfree(ptr)) \
  297. return __c11_atomic_compare_exchange_strong( \
  298. (_Atomic(type) *)ptr, expected, desired, success, failure); \
  299. Lock *l = lock_for_pointer(ptr); \
  300. lock(l); \
  301. if (*ptr == *expected) { \
  302. *ptr = desired; \
  303. unlock(l); \
  304. return true; \
  305. } \
  306. *expected = *ptr; \
  307. unlock(l); \
  308. return false; \
  309. }
  310. OPTIMISED_CASES
  311. #undef OPTIMISED_CASE
  312. ////////////////////////////////////////////////////////////////////////////////
  313. // Atomic read-modify-write operations for integers of various sizes.
  314. ////////////////////////////////////////////////////////////////////////////////
  315. #define ATOMIC_RMW(n, lockfree, type, opname, op) \
  316. type __atomic_fetch_##opname##_##n(type *ptr, type val, int model) { \
  317. if (lockfree(ptr)) \
  318. return __c11_atomic_fetch_##opname((_Atomic(type) *)ptr, val, model); \
  319. Lock *l = lock_for_pointer(ptr); \
  320. lock(l); \
  321. type tmp = *ptr; \
  322. *ptr = tmp op val; \
  323. unlock(l); \
  324. return tmp; \
  325. }
  326. #define ATOMIC_RMW_NAND(n, lockfree, type) \
  327. type __atomic_fetch_nand_##n(type *ptr, type val, int model) { \
  328. if (lockfree(ptr)) \
  329. return __c11_atomic_fetch_nand((_Atomic(type) *)ptr, val, model); \
  330. Lock *l = lock_for_pointer(ptr); \
  331. lock(l); \
  332. type tmp = *ptr; \
  333. *ptr = ~(tmp & val); \
  334. unlock(l); \
  335. return tmp; \
  336. }
  337. #define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, add, +)
  338. OPTIMISED_CASES
  339. #undef OPTIMISED_CASE
  340. #define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, sub, -)
  341. OPTIMISED_CASES
  342. #undef OPTIMISED_CASE
  343. #define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, and, &)
  344. OPTIMISED_CASES
  345. #undef OPTIMISED_CASE
  346. #define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, or, |)
  347. OPTIMISED_CASES
  348. #undef OPTIMISED_CASE
  349. #define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, xor, ^)
  350. OPTIMISED_CASES
  351. #undef OPTIMISED_CASE
  352. // Allow build with clang without __c11_atomic_fetch_nand builtin (pre-14)
  353. #if __has_builtin(__c11_atomic_fetch_nand)
  354. #define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW_NAND(n, lockfree, type)
  355. OPTIMISED_CASES
  356. #undef OPTIMISED_CASE
  357. #endif