atomic.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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.
  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(__FreeBSD__) || defined(__DragonFly__)
  54. #include <errno.h>
  55. // clang-format off
  56. #include <sys/types.h>
  57. #include <machine/atomic.h>
  58. #include <sys/umtx.h>
  59. // clang-format on
  60. typedef struct _usem Lock;
  61. __inline static void unlock(Lock *l) {
  62. __c11_atomic_store((_Atomic(uint32_t) *)&l->_count, 1, __ATOMIC_RELEASE);
  63. __c11_atomic_thread_fence(__ATOMIC_SEQ_CST);
  64. if (l->_has_waiters)
  65. _umtx_op(l, UMTX_OP_SEM_WAKE, 1, 0, 0);
  66. }
  67. __inline static void lock(Lock *l) {
  68. uint32_t old = 1;
  69. while (!__c11_atomic_compare_exchange_weak((_Atomic(uint32_t) *)&l->_count,
  70. &old, 0, __ATOMIC_ACQUIRE,
  71. __ATOMIC_RELAXED)) {
  72. _umtx_op(l, UMTX_OP_SEM_WAIT, 0, 0, 0);
  73. old = 1;
  74. }
  75. }
  76. /// locks for atomic operations
  77. static Lock locks[SPINLOCK_COUNT] = {[0 ... SPINLOCK_COUNT - 1] = {0, 1, 0}};
  78. #elif defined(__APPLE__)
  79. #include <libkern/OSAtomic.h>
  80. typedef OSSpinLock Lock;
  81. __inline static void unlock(Lock *l) { OSSpinLockUnlock(l); }
  82. /// Locks a lock. In the current implementation, this is potentially
  83. /// unbounded in the contended case.
  84. __inline static void lock(Lock *l) { OSSpinLockLock(l); }
  85. static Lock locks[SPINLOCK_COUNT]; // initialized to OS_SPINLOCK_INIT which is 0
  86. #else
  87. _Static_assert(__atomic_always_lock_free(sizeof(uintptr_t), 0),
  88. "Implementation assumes lock-free pointer-size cmpxchg");
  89. typedef _Atomic(uintptr_t) Lock;
  90. /// Unlock a lock. This is a release operation.
  91. __inline static void unlock(Lock *l) {
  92. __c11_atomic_store(l, 0, __ATOMIC_RELEASE);
  93. }
  94. /// Locks a lock. In the current implementation, this is potentially
  95. /// unbounded in the contended case.
  96. __inline static void lock(Lock *l) {
  97. uintptr_t old = 0;
  98. while (!__c11_atomic_compare_exchange_weak(l, &old, 1, __ATOMIC_ACQUIRE,
  99. __ATOMIC_RELAXED))
  100. old = 0;
  101. }
  102. /// locks for atomic operations
  103. static Lock locks[SPINLOCK_COUNT];
  104. #endif
  105. /// Returns a lock to use for a given pointer.
  106. static __inline Lock *lock_for_pointer(void *ptr) {
  107. intptr_t hash = (intptr_t)ptr;
  108. // Disregard the lowest 4 bits. We want all values that may be part of the
  109. // same memory operation to hash to the same value and therefore use the same
  110. // lock.
  111. hash >>= 4;
  112. // Use the next bits as the basis for the hash
  113. intptr_t low = hash & SPINLOCK_MASK;
  114. // Now use the high(er) set of bits to perturb the hash, so that we don't
  115. // get collisions from atomic fields in a single object
  116. hash >>= 16;
  117. hash ^= low;
  118. // Return a pointer to the word to use
  119. return locks + (hash & SPINLOCK_MASK);
  120. }
  121. /// Macros for determining whether a size is lock free.
  122. #define ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(size, p) \
  123. (__atomic_always_lock_free(size, p) || \
  124. (__atomic_always_lock_free(size, 0) && ((uintptr_t)p % size) == 0))
  125. #define IS_LOCK_FREE_1(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(1, p)
  126. #define IS_LOCK_FREE_2(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(2, p)
  127. #define IS_LOCK_FREE_4(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(4, p)
  128. #define IS_LOCK_FREE_8(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(8, p)
  129. #define IS_LOCK_FREE_16(p) ATOMIC_ALWAYS_LOCK_FREE_OR_ALIGNED_LOCK_FREE(16, p)
  130. /// Macro that calls the compiler-generated lock-free versions of functions
  131. /// when they exist.
  132. #define TRY_LOCK_FREE_CASE(n, type, ptr) \
  133. case n: \
  134. if (IS_LOCK_FREE_##n(ptr)) { \
  135. LOCK_FREE_ACTION(type); \
  136. } \
  137. break;
  138. #ifdef __SIZEOF_INT128__
  139. #define TRY_LOCK_FREE_CASE_16(p) TRY_LOCK_FREE_CASE(16, __uint128_t, p)
  140. #else
  141. #define TRY_LOCK_FREE_CASE_16(p) /* __uint128_t not available */
  142. #endif
  143. #define LOCK_FREE_CASES(ptr) \
  144. do { \
  145. switch (size) { \
  146. TRY_LOCK_FREE_CASE(1, uint8_t, ptr) \
  147. TRY_LOCK_FREE_CASE(2, uint16_t, ptr) \
  148. TRY_LOCK_FREE_CASE(4, uint32_t, ptr) \
  149. TRY_LOCK_FREE_CASE(8, uint64_t, ptr) \
  150. TRY_LOCK_FREE_CASE_16(ptr) /* __uint128_t may not be supported */ \
  151. default: \
  152. break; \
  153. } \
  154. } while (0)
  155. /// Whether atomic operations for the given size (and alignment) are lock-free.
  156. bool __atomic_is_lock_free_c(size_t size, void *ptr) {
  157. #define LOCK_FREE_ACTION(type) return true;
  158. LOCK_FREE_CASES(ptr);
  159. #undef LOCK_FREE_ACTION
  160. return false;
  161. }
  162. /// An atomic load operation. This is atomic with respect to the source
  163. /// pointer only.
  164. void __atomic_load_c(int size, void *src, void *dest, int model) {
  165. #define LOCK_FREE_ACTION(type) \
  166. *((type *)dest) = __c11_atomic_load((_Atomic(type) *)src, model); \
  167. return;
  168. LOCK_FREE_CASES(src);
  169. #undef LOCK_FREE_ACTION
  170. Lock *l = lock_for_pointer(src);
  171. lock(l);
  172. memcpy(dest, src, size);
  173. unlock(l);
  174. }
  175. /// An atomic store operation. This is atomic with respect to the destination
  176. /// pointer only.
  177. void __atomic_store_c(int size, void *dest, void *src, int model) {
  178. #define LOCK_FREE_ACTION(type) \
  179. __c11_atomic_store((_Atomic(type) *)dest, *(type *)src, model); \
  180. return;
  181. LOCK_FREE_CASES(dest);
  182. #undef LOCK_FREE_ACTION
  183. Lock *l = lock_for_pointer(dest);
  184. lock(l);
  185. memcpy(dest, src, size);
  186. unlock(l);
  187. }
  188. /// Atomic compare and exchange operation. If the value at *ptr is identical
  189. /// to the value at *expected, then this copies value at *desired to *ptr. If
  190. /// they are not, then this stores the current value from *ptr in *expected.
  191. ///
  192. /// This function returns 1 if the exchange takes place or 0 if it fails.
  193. int __atomic_compare_exchange_c(int size, void *ptr, void *expected,
  194. void *desired, int success, int failure) {
  195. #define LOCK_FREE_ACTION(type) \
  196. return __c11_atomic_compare_exchange_strong( \
  197. (_Atomic(type) *)ptr, (type *)expected, *(type *)desired, success, \
  198. failure)
  199. LOCK_FREE_CASES(ptr);
  200. #undef LOCK_FREE_ACTION
  201. Lock *l = lock_for_pointer(ptr);
  202. lock(l);
  203. if (memcmp(ptr, expected, size) == 0) {
  204. memcpy(ptr, desired, size);
  205. unlock(l);
  206. return 1;
  207. }
  208. memcpy(expected, ptr, size);
  209. unlock(l);
  210. return 0;
  211. }
  212. /// Performs an atomic exchange operation between two pointers. This is atomic
  213. /// with respect to the target address.
  214. void __atomic_exchange_c(int size, void *ptr, void *val, void *old, int model) {
  215. #define LOCK_FREE_ACTION(type) \
  216. *(type *)old = \
  217. __c11_atomic_exchange((_Atomic(type) *)ptr, *(type *)val, model); \
  218. return;
  219. LOCK_FREE_CASES(ptr);
  220. #undef LOCK_FREE_ACTION
  221. Lock *l = lock_for_pointer(ptr);
  222. lock(l);
  223. memcpy(old, ptr, size);
  224. memcpy(ptr, val, size);
  225. unlock(l);
  226. }
  227. ////////////////////////////////////////////////////////////////////////////////
  228. // Where the size is known at compile time, the compiler may emit calls to
  229. // specialised versions of the above functions.
  230. ////////////////////////////////////////////////////////////////////////////////
  231. #ifdef __SIZEOF_INT128__
  232. #define OPTIMISED_CASES \
  233. OPTIMISED_CASE(1, IS_LOCK_FREE_1, uint8_t) \
  234. OPTIMISED_CASE(2, IS_LOCK_FREE_2, uint16_t) \
  235. OPTIMISED_CASE(4, IS_LOCK_FREE_4, uint32_t) \
  236. OPTIMISED_CASE(8, IS_LOCK_FREE_8, uint64_t) \
  237. OPTIMISED_CASE(16, IS_LOCK_FREE_16, __uint128_t)
  238. #else
  239. #define OPTIMISED_CASES \
  240. OPTIMISED_CASE(1, IS_LOCK_FREE_1, uint8_t) \
  241. OPTIMISED_CASE(2, IS_LOCK_FREE_2, uint16_t) \
  242. OPTIMISED_CASE(4, IS_LOCK_FREE_4, uint32_t) \
  243. OPTIMISED_CASE(8, IS_LOCK_FREE_8, uint64_t)
  244. #endif
  245. #define OPTIMISED_CASE(n, lockfree, type) \
  246. type __atomic_load_##n(type *src, int model) { \
  247. if (lockfree(src)) \
  248. return __c11_atomic_load((_Atomic(type) *)src, model); \
  249. Lock *l = lock_for_pointer(src); \
  250. lock(l); \
  251. type val = *src; \
  252. unlock(l); \
  253. return val; \
  254. }
  255. OPTIMISED_CASES
  256. #undef OPTIMISED_CASE
  257. #define OPTIMISED_CASE(n, lockfree, type) \
  258. void __atomic_store_##n(type *dest, type val, int model) { \
  259. if (lockfree(dest)) { \
  260. __c11_atomic_store((_Atomic(type) *)dest, val, model); \
  261. return; \
  262. } \
  263. Lock *l = lock_for_pointer(dest); \
  264. lock(l); \
  265. *dest = val; \
  266. unlock(l); \
  267. return; \
  268. }
  269. OPTIMISED_CASES
  270. #undef OPTIMISED_CASE
  271. #define OPTIMISED_CASE(n, lockfree, type) \
  272. type __atomic_exchange_##n(type *dest, type val, int model) { \
  273. if (lockfree(dest)) \
  274. return __c11_atomic_exchange((_Atomic(type) *)dest, val, model); \
  275. Lock *l = lock_for_pointer(dest); \
  276. lock(l); \
  277. type tmp = *dest; \
  278. *dest = val; \
  279. unlock(l); \
  280. return tmp; \
  281. }
  282. OPTIMISED_CASES
  283. #undef OPTIMISED_CASE
  284. #define OPTIMISED_CASE(n, lockfree, type) \
  285. bool __atomic_compare_exchange_##n(type *ptr, type *expected, type desired, \
  286. int success, int failure) { \
  287. if (lockfree(ptr)) \
  288. return __c11_atomic_compare_exchange_strong( \
  289. (_Atomic(type) *)ptr, expected, desired, success, failure); \
  290. Lock *l = lock_for_pointer(ptr); \
  291. lock(l); \
  292. if (*ptr == *expected) { \
  293. *ptr = desired; \
  294. unlock(l); \
  295. return true; \
  296. } \
  297. *expected = *ptr; \
  298. unlock(l); \
  299. return false; \
  300. }
  301. OPTIMISED_CASES
  302. #undef OPTIMISED_CASE
  303. ////////////////////////////////////////////////////////////////////////////////
  304. // Atomic read-modify-write operations for integers of various sizes.
  305. ////////////////////////////////////////////////////////////////////////////////
  306. #define ATOMIC_RMW(n, lockfree, type, opname, op) \
  307. type __atomic_fetch_##opname##_##n(type *ptr, type val, int model) { \
  308. if (lockfree(ptr)) \
  309. return __c11_atomic_fetch_##opname((_Atomic(type) *)ptr, val, model); \
  310. Lock *l = lock_for_pointer(ptr); \
  311. lock(l); \
  312. type tmp = *ptr; \
  313. *ptr = tmp op val; \
  314. unlock(l); \
  315. return tmp; \
  316. }
  317. #define ATOMIC_RMW_NAND(n, lockfree, type) \
  318. type __atomic_fetch_nand_##n(type *ptr, type val, int model) { \
  319. if (lockfree(ptr)) \
  320. return __c11_atomic_fetch_nand((_Atomic(type) *)ptr, val, model); \
  321. Lock *l = lock_for_pointer(ptr); \
  322. lock(l); \
  323. type tmp = *ptr; \
  324. *ptr = ~(tmp & val); \
  325. unlock(l); \
  326. return tmp; \
  327. }
  328. #define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, add, +)
  329. OPTIMISED_CASES
  330. #undef OPTIMISED_CASE
  331. #define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, sub, -)
  332. OPTIMISED_CASES
  333. #undef OPTIMISED_CASE
  334. #define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, and, &)
  335. OPTIMISED_CASES
  336. #undef OPTIMISED_CASE
  337. #define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, or, |)
  338. OPTIMISED_CASES
  339. #undef OPTIMISED_CASE
  340. #define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW(n, lockfree, type, xor, ^)
  341. OPTIMISED_CASES
  342. #undef OPTIMISED_CASE
  343. // Allow build with clang without __c11_atomic_fetch_nand builtin (pre-14)
  344. #if __has_builtin(__c11_atomic_fetch_nand)
  345. #define OPTIMISED_CASE(n, lockfree, type) ATOMIC_RMW_NAND(n, lockfree, type)
  346. OPTIMISED_CASES
  347. #undef OPTIMISED_CASE
  348. #endif