spinlock.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. //
  2. // Copyright 2017 The Abseil Authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // https://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. // Most users requiring mutual exclusion should use Mutex.
  17. // SpinLock is provided for use in two situations:
  18. // - for use by Abseil internal code that Mutex itself depends on
  19. // - for async signal safety (see below)
  20. // SpinLock with a base_internal::SchedulingMode::SCHEDULE_KERNEL_ONLY is async
  21. // signal safe. If a spinlock is used within a signal handler, all code that
  22. // acquires the lock must ensure that the signal cannot arrive while they are
  23. // holding the lock. Typically, this is done by blocking the signal.
  24. //
  25. // Threads waiting on a SpinLock may be woken in an arbitrary order.
  26. #ifndef ABSL_BASE_INTERNAL_SPINLOCK_H_
  27. #define ABSL_BASE_INTERNAL_SPINLOCK_H_
  28. #include <atomic>
  29. #include <cstdint>
  30. #include "absl/base/attributes.h"
  31. #include "absl/base/const_init.h"
  32. #include "absl/base/dynamic_annotations.h"
  33. #include "absl/base/internal/low_level_scheduling.h"
  34. #include "absl/base/internal/raw_logging.h"
  35. #include "absl/base/internal/scheduling_mode.h"
  36. #include "absl/base/internal/tsan_mutex_interface.h"
  37. #include "absl/base/thread_annotations.h"
  38. namespace tcmalloc {
  39. namespace tcmalloc_internal {
  40. class AllocationGuardSpinLockHolder;
  41. } // namespace tcmalloc_internal
  42. } // namespace tcmalloc
  43. namespace absl {
  44. ABSL_NAMESPACE_BEGIN
  45. namespace base_internal {
  46. class ABSL_LOCKABLE ABSL_ATTRIBUTE_WARN_UNUSED SpinLock {
  47. public:
  48. SpinLock() : lockword_(kSpinLockCooperative) {
  49. ABSL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static);
  50. }
  51. // Constructors that allow non-cooperative spinlocks to be created for use
  52. // inside thread schedulers. Normal clients should not use these.
  53. explicit SpinLock(base_internal::SchedulingMode mode);
  54. // Constructor for global SpinLock instances. See absl/base/const_init.h.
  55. constexpr SpinLock(absl::ConstInitType, base_internal::SchedulingMode mode)
  56. : lockword_(IsCooperative(mode) ? kSpinLockCooperative : 0) {}
  57. // For global SpinLock instances prefer trivial destructor when possible.
  58. // Default but non-trivial destructor in some build configurations causes an
  59. // extra static initializer.
  60. #ifdef ABSL_INTERNAL_HAVE_TSAN_INTERFACE
  61. ~SpinLock() { ABSL_TSAN_MUTEX_DESTROY(this, __tsan_mutex_not_static); }
  62. #else
  63. ~SpinLock() = default;
  64. #endif
  65. // Acquire this SpinLock.
  66. inline void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() {
  67. ABSL_TSAN_MUTEX_PRE_LOCK(this, 0);
  68. if (!TryLockImpl()) {
  69. SlowLock();
  70. }
  71. ABSL_TSAN_MUTEX_POST_LOCK(this, 0, 0);
  72. }
  73. // Try to acquire this SpinLock without blocking and return true if the
  74. // acquisition was successful. If the lock was not acquired, false is
  75. // returned. If this SpinLock is free at the time of the call, TryLock
  76. // will return true with high probability.
  77. ABSL_MUST_USE_RESULT inline bool TryLock()
  78. ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true) {
  79. ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_try_lock);
  80. bool res = TryLockImpl();
  81. ABSL_TSAN_MUTEX_POST_LOCK(
  82. this, __tsan_mutex_try_lock | (res ? 0 : __tsan_mutex_try_lock_failed),
  83. 0);
  84. return res;
  85. }
  86. // Release this SpinLock, which must be held by the calling thread.
  87. inline void Unlock() ABSL_UNLOCK_FUNCTION() {
  88. ABSL_TSAN_MUTEX_PRE_UNLOCK(this, 0);
  89. uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
  90. lock_value = lockword_.exchange(lock_value & kSpinLockCooperative,
  91. std::memory_order_release);
  92. if ((lock_value & kSpinLockDisabledScheduling) != 0) {
  93. base_internal::SchedulingGuard::EnableRescheduling(true);
  94. }
  95. if ((lock_value & kWaitTimeMask) != 0) {
  96. // Collect contentionz profile info, and speed the wakeup of any waiter.
  97. // The wait_cycles value indicates how long this thread spent waiting
  98. // for the lock.
  99. SlowUnlock(lock_value);
  100. }
  101. ABSL_TSAN_MUTEX_POST_UNLOCK(this, 0);
  102. }
  103. // Determine if the lock is held. When the lock is held by the invoking
  104. // thread, true will always be returned. Intended to be used as
  105. // CHECK(lock.IsHeld()).
  106. ABSL_MUST_USE_RESULT inline bool IsHeld() const {
  107. return (lockword_.load(std::memory_order_relaxed) & kSpinLockHeld) != 0;
  108. }
  109. // Return immediately if this thread holds the SpinLock exclusively.
  110. // Otherwise, report an error by crashing with a diagnostic.
  111. inline void AssertHeld() const ABSL_ASSERT_EXCLUSIVE_LOCK() {
  112. if (!IsHeld()) {
  113. ABSL_RAW_LOG(FATAL, "thread should hold the lock on SpinLock");
  114. }
  115. }
  116. protected:
  117. // These should not be exported except for testing.
  118. // Store number of cycles between wait_start_time and wait_end_time in a
  119. // lock value.
  120. static uint32_t EncodeWaitCycles(int64_t wait_start_time,
  121. int64_t wait_end_time);
  122. // Extract number of wait cycles in a lock value.
  123. static int64_t DecodeWaitCycles(uint32_t lock_value);
  124. // Provide access to protected method above. Use for testing only.
  125. friend struct SpinLockTest;
  126. friend class tcmalloc::tcmalloc_internal::AllocationGuardSpinLockHolder;
  127. private:
  128. // lockword_ is used to store the following:
  129. //
  130. // bit[0] encodes whether a lock is being held.
  131. // bit[1] encodes whether a lock uses cooperative scheduling.
  132. // bit[2] encodes whether the current lock holder disabled scheduling when
  133. // acquiring the lock. Only set when kSpinLockHeld is also set.
  134. // bit[3:31] encodes time a lock spent on waiting as a 29-bit unsigned int.
  135. // This is set by the lock holder to indicate how long it waited on
  136. // the lock before eventually acquiring it. The number of cycles is
  137. // encoded as a 29-bit unsigned int, or in the case that the current
  138. // holder did not wait but another waiter is queued, the LSB
  139. // (kSpinLockSleeper) is set. The implementation does not explicitly
  140. // track the number of queued waiters beyond this. It must always be
  141. // assumed that waiters may exist if the current holder was required to
  142. // queue.
  143. //
  144. // Invariant: if the lock is not held, the value is either 0 or
  145. // kSpinLockCooperative.
  146. static constexpr uint32_t kSpinLockHeld = 1;
  147. static constexpr uint32_t kSpinLockCooperative = 2;
  148. static constexpr uint32_t kSpinLockDisabledScheduling = 4;
  149. static constexpr uint32_t kSpinLockSleeper = 8;
  150. // Includes kSpinLockSleeper.
  151. static constexpr uint32_t kWaitTimeMask =
  152. ~(kSpinLockHeld | kSpinLockCooperative | kSpinLockDisabledScheduling);
  153. // Returns true if the provided scheduling mode is cooperative.
  154. static constexpr bool IsCooperative(
  155. base_internal::SchedulingMode scheduling_mode) {
  156. return scheduling_mode == base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL;
  157. }
  158. bool IsCooperative() const {
  159. return lockword_.load(std::memory_order_relaxed) & kSpinLockCooperative;
  160. }
  161. uint32_t TryLockInternal(uint32_t lock_value, uint32_t wait_cycles);
  162. void SlowLock() ABSL_ATTRIBUTE_COLD;
  163. void SlowUnlock(uint32_t lock_value) ABSL_ATTRIBUTE_COLD;
  164. uint32_t SpinLoop();
  165. inline bool TryLockImpl() {
  166. uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
  167. return (TryLockInternal(lock_value, 0) & kSpinLockHeld) == 0;
  168. }
  169. std::atomic<uint32_t> lockword_;
  170. SpinLock(const SpinLock&) = delete;
  171. SpinLock& operator=(const SpinLock&) = delete;
  172. };
  173. // Corresponding locker object that arranges to acquire a spinlock for
  174. // the duration of a C++ scope.
  175. //
  176. // TODO(b/176172494): Use only [[nodiscard]] when baseline is raised.
  177. // TODO(b/6695610): Remove forward declaration when #ifdef is no longer needed.
  178. #if ABSL_HAVE_CPP_ATTRIBUTE(nodiscard)
  179. class [[nodiscard]] SpinLockHolder;
  180. #else
  181. class ABSL_MUST_USE_RESULT ABSL_ATTRIBUTE_TRIVIAL_ABI SpinLockHolder;
  182. #endif
  183. class ABSL_SCOPED_LOCKABLE SpinLockHolder {
  184. public:
  185. inline explicit SpinLockHolder(SpinLock* l) ABSL_EXCLUSIVE_LOCK_FUNCTION(l)
  186. : lock_(l) {
  187. l->Lock();
  188. }
  189. inline ~SpinLockHolder() ABSL_UNLOCK_FUNCTION() { lock_->Unlock(); }
  190. SpinLockHolder(const SpinLockHolder&) = delete;
  191. SpinLockHolder& operator=(const SpinLockHolder&) = delete;
  192. private:
  193. SpinLock* lock_;
  194. };
  195. // Register a hook for profiling support.
  196. //
  197. // The function pointer registered here will be called whenever a spinlock is
  198. // contended. The callback is given an opaque handle to the contended spinlock
  199. // and the number of wait cycles. This is thread-safe, but only a single
  200. // profiler can be registered. It is an error to call this function multiple
  201. // times with different arguments.
  202. void RegisterSpinLockProfiler(void (*fn)(const void* lock,
  203. int64_t wait_cycles));
  204. //------------------------------------------------------------------------------
  205. // Public interface ends here.
  206. //------------------------------------------------------------------------------
  207. // If (result & kSpinLockHeld) == 0, then *this was successfully locked.
  208. // Otherwise, returns last observed value for lockword_.
  209. inline uint32_t SpinLock::TryLockInternal(uint32_t lock_value,
  210. uint32_t wait_cycles) {
  211. if ((lock_value & kSpinLockHeld) != 0) {
  212. return lock_value;
  213. }
  214. uint32_t sched_disabled_bit = 0;
  215. if ((lock_value & kSpinLockCooperative) == 0) {
  216. // For non-cooperative locks we must make sure we mark ourselves as
  217. // non-reschedulable before we attempt to CompareAndSwap.
  218. if (base_internal::SchedulingGuard::DisableRescheduling()) {
  219. sched_disabled_bit = kSpinLockDisabledScheduling;
  220. }
  221. }
  222. if (!lockword_.compare_exchange_strong(
  223. lock_value,
  224. kSpinLockHeld | lock_value | wait_cycles | sched_disabled_bit,
  225. std::memory_order_acquire, std::memory_order_relaxed)) {
  226. base_internal::SchedulingGuard::EnableRescheduling(sched_disabled_bit != 0);
  227. }
  228. return lock_value;
  229. }
  230. } // namespace base_internal
  231. ABSL_NAMESPACE_END
  232. } // namespace absl
  233. #endif // ABSL_BASE_INTERNAL_SPINLOCK_H_