spinlock.h 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 is async signal safe. If a spinlock is used within a signal
  21. // handler, all code that acquires the lock must ensure that the signal cannot
  22. // arrive while they are holding the lock. Typically, this is done by blocking
  23. // 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 absl {
  39. ABSL_NAMESPACE_BEGIN
  40. namespace base_internal {
  41. class ABSL_LOCKABLE SpinLock {
  42. public:
  43. SpinLock() : lockword_(kSpinLockCooperative) {
  44. ABSL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static);
  45. }
  46. // Constructors that allow non-cooperative spinlocks to be created for use
  47. // inside thread schedulers. Normal clients should not use these.
  48. explicit SpinLock(base_internal::SchedulingMode mode);
  49. // Constructor for global SpinLock instances. See absl/base/const_init.h.
  50. constexpr SpinLock(absl::ConstInitType, base_internal::SchedulingMode mode)
  51. : lockword_(IsCooperative(mode) ? kSpinLockCooperative : 0) {}
  52. // For global SpinLock instances prefer trivial destructor when possible.
  53. // Default but non-trivial destructor in some build configurations causes an
  54. // extra static initializer.
  55. #ifdef ABSL_INTERNAL_HAVE_TSAN_INTERFACE
  56. ~SpinLock() { ABSL_TSAN_MUTEX_DESTROY(this, __tsan_mutex_not_static); }
  57. #else
  58. ~SpinLock() = default;
  59. #endif
  60. // Acquire this SpinLock.
  61. inline void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() {
  62. ABSL_TSAN_MUTEX_PRE_LOCK(this, 0);
  63. if (!TryLockImpl()) {
  64. SlowLock();
  65. }
  66. ABSL_TSAN_MUTEX_POST_LOCK(this, 0, 0);
  67. }
  68. // Try to acquire this SpinLock without blocking and return true if the
  69. // acquisition was successful. If the lock was not acquired, false is
  70. // returned. If this SpinLock is free at the time of the call, TryLock
  71. // will return true with high probability.
  72. inline bool TryLock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true) {
  73. ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_try_lock);
  74. bool res = TryLockImpl();
  75. ABSL_TSAN_MUTEX_POST_LOCK(
  76. this, __tsan_mutex_try_lock | (res ? 0 : __tsan_mutex_try_lock_failed),
  77. 0);
  78. return res;
  79. }
  80. // Release this SpinLock, which must be held by the calling thread.
  81. inline void Unlock() ABSL_UNLOCK_FUNCTION() {
  82. ABSL_TSAN_MUTEX_PRE_UNLOCK(this, 0);
  83. uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
  84. lock_value = lockword_.exchange(lock_value & kSpinLockCooperative,
  85. std::memory_order_release);
  86. if ((lock_value & kSpinLockDisabledScheduling) != 0) {
  87. base_internal::SchedulingGuard::EnableRescheduling(true);
  88. }
  89. if ((lock_value & kWaitTimeMask) != 0) {
  90. // Collect contentionz profile info, and speed the wakeup of any waiter.
  91. // The wait_cycles value indicates how long this thread spent waiting
  92. // for the lock.
  93. SlowUnlock(lock_value);
  94. }
  95. ABSL_TSAN_MUTEX_POST_UNLOCK(this, 0);
  96. }
  97. // Determine if the lock is held. When the lock is held by the invoking
  98. // thread, true will always be returned. Intended to be used as
  99. // CHECK(lock.IsHeld()).
  100. inline bool IsHeld() const {
  101. return (lockword_.load(std::memory_order_relaxed) & kSpinLockHeld) != 0;
  102. }
  103. // Return immediately if this thread holds the SpinLock exclusively.
  104. // Otherwise, report an error by crashing with a diagnostic.
  105. inline void AssertHeld() const ABSL_ASSERT_EXCLUSIVE_LOCK() {
  106. if (!IsHeld()) {
  107. ABSL_RAW_LOG(FATAL, "thread should hold the lock on SpinLock");
  108. }
  109. }
  110. protected:
  111. // These should not be exported except for testing.
  112. // Store number of cycles between wait_start_time and wait_end_time in a
  113. // lock value.
  114. static uint32_t EncodeWaitCycles(int64_t wait_start_time,
  115. int64_t wait_end_time);
  116. // Extract number of wait cycles in a lock value.
  117. static int64_t DecodeWaitCycles(uint32_t lock_value);
  118. // Provide access to protected method above. Use for testing only.
  119. friend struct SpinLockTest;
  120. private:
  121. // lockword_ is used to store the following:
  122. //
  123. // bit[0] encodes whether a lock is being held.
  124. // bit[1] encodes whether a lock uses cooperative scheduling.
  125. // bit[2] encodes whether the current lock holder disabled scheduling when
  126. // acquiring the lock. Only set when kSpinLockHeld is also set.
  127. // bit[3:31] encodes time a lock spent on waiting as a 29-bit unsigned int.
  128. // This is set by the lock holder to indicate how long it waited on
  129. // the lock before eventually acquiring it. The number of cycles is
  130. // encoded as a 29-bit unsigned int, or in the case that the current
  131. // holder did not wait but another waiter is queued, the LSB
  132. // (kSpinLockSleeper) is set. The implementation does not explicitly
  133. // track the number of queued waiters beyond this. It must always be
  134. // assumed that waiters may exist if the current holder was required to
  135. // queue.
  136. //
  137. // Invariant: if the lock is not held, the value is either 0 or
  138. // kSpinLockCooperative.
  139. static constexpr uint32_t kSpinLockHeld = 1;
  140. static constexpr uint32_t kSpinLockCooperative = 2;
  141. static constexpr uint32_t kSpinLockDisabledScheduling = 4;
  142. static constexpr uint32_t kSpinLockSleeper = 8;
  143. // Includes kSpinLockSleeper.
  144. static constexpr uint32_t kWaitTimeMask =
  145. ~(kSpinLockHeld | kSpinLockCooperative | kSpinLockDisabledScheduling);
  146. // Returns true if the provided scheduling mode is cooperative.
  147. static constexpr bool IsCooperative(
  148. base_internal::SchedulingMode scheduling_mode) {
  149. return scheduling_mode == base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL;
  150. }
  151. uint32_t TryLockInternal(uint32_t lock_value, uint32_t wait_cycles);
  152. void SlowLock() ABSL_ATTRIBUTE_COLD;
  153. void SlowUnlock(uint32_t lock_value) ABSL_ATTRIBUTE_COLD;
  154. uint32_t SpinLoop();
  155. inline bool TryLockImpl() {
  156. uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
  157. return (TryLockInternal(lock_value, 0) & kSpinLockHeld) == 0;
  158. }
  159. std::atomic<uint32_t> lockword_;
  160. SpinLock(const SpinLock&) = delete;
  161. SpinLock& operator=(const SpinLock&) = delete;
  162. };
  163. // Corresponding locker object that arranges to acquire a spinlock for
  164. // the duration of a C++ scope.
  165. class ABSL_SCOPED_LOCKABLE SpinLockHolder {
  166. public:
  167. inline explicit SpinLockHolder(SpinLock* l) ABSL_EXCLUSIVE_LOCK_FUNCTION(l)
  168. : lock_(l) {
  169. l->Lock();
  170. }
  171. inline ~SpinLockHolder() ABSL_UNLOCK_FUNCTION() { lock_->Unlock(); }
  172. SpinLockHolder(const SpinLockHolder&) = delete;
  173. SpinLockHolder& operator=(const SpinLockHolder&) = delete;
  174. private:
  175. SpinLock* lock_;
  176. };
  177. // Register a hook for profiling support.
  178. //
  179. // The function pointer registered here will be called whenever a spinlock is
  180. // contended. The callback is given an opaque handle to the contended spinlock
  181. // and the number of wait cycles. This is thread-safe, but only a single
  182. // profiler can be registered. It is an error to call this function multiple
  183. // times with different arguments.
  184. void RegisterSpinLockProfiler(void (*fn)(const void* lock,
  185. int64_t wait_cycles));
  186. //------------------------------------------------------------------------------
  187. // Public interface ends here.
  188. //------------------------------------------------------------------------------
  189. // If (result & kSpinLockHeld) == 0, then *this was successfully locked.
  190. // Otherwise, returns last observed value for lockword_.
  191. inline uint32_t SpinLock::TryLockInternal(uint32_t lock_value,
  192. uint32_t wait_cycles) {
  193. if ((lock_value & kSpinLockHeld) != 0) {
  194. return lock_value;
  195. }
  196. uint32_t sched_disabled_bit = 0;
  197. if ((lock_value & kSpinLockCooperative) == 0) {
  198. // For non-cooperative locks we must make sure we mark ourselves as
  199. // non-reschedulable before we attempt to CompareAndSwap.
  200. if (base_internal::SchedulingGuard::DisableRescheduling()) {
  201. sched_disabled_bit = kSpinLockDisabledScheduling;
  202. }
  203. }
  204. if (!lockword_.compare_exchange_strong(
  205. lock_value,
  206. kSpinLockHeld | lock_value | wait_cycles | sched_disabled_bit,
  207. std::memory_order_acquire, std::memory_order_relaxed)) {
  208. base_internal::SchedulingGuard::EnableRescheduling(sched_disabled_bit != 0);
  209. }
  210. return lock_value;
  211. }
  212. } // namespace base_internal
  213. ABSL_NAMESPACE_END
  214. } // namespace absl
  215. #endif // ABSL_BASE_INTERNAL_SPINLOCK_H_