spinlock.h 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 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. inline bool TryLock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true) {
  78. ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_try_lock);
  79. bool res = TryLockImpl();
  80. ABSL_TSAN_MUTEX_POST_LOCK(
  81. this, __tsan_mutex_try_lock | (res ? 0 : __tsan_mutex_try_lock_failed),
  82. 0);
  83. return res;
  84. }
  85. // Release this SpinLock, which must be held by the calling thread.
  86. inline void Unlock() ABSL_UNLOCK_FUNCTION() {
  87. ABSL_TSAN_MUTEX_PRE_UNLOCK(this, 0);
  88. uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
  89. lock_value = lockword_.exchange(lock_value & kSpinLockCooperative,
  90. std::memory_order_release);
  91. if ((lock_value & kSpinLockDisabledScheduling) != 0) {
  92. base_internal::SchedulingGuard::EnableRescheduling(true);
  93. }
  94. if ((lock_value & kWaitTimeMask) != 0) {
  95. // Collect contentionz profile info, and speed the wakeup of any waiter.
  96. // The wait_cycles value indicates how long this thread spent waiting
  97. // for the lock.
  98. SlowUnlock(lock_value);
  99. }
  100. ABSL_TSAN_MUTEX_POST_UNLOCK(this, 0);
  101. }
  102. // Determine if the lock is held. When the lock is held by the invoking
  103. // thread, true will always be returned. Intended to be used as
  104. // CHECK(lock.IsHeld()).
  105. inline bool IsHeld() const {
  106. return (lockword_.load(std::memory_order_relaxed) & kSpinLockHeld) != 0;
  107. }
  108. // Return immediately if this thread holds the SpinLock exclusively.
  109. // Otherwise, report an error by crashing with a diagnostic.
  110. inline void AssertHeld() const ABSL_ASSERT_EXCLUSIVE_LOCK() {
  111. if (!IsHeld()) {
  112. ABSL_RAW_LOG(FATAL, "thread should hold the lock on SpinLock");
  113. }
  114. }
  115. protected:
  116. // These should not be exported except for testing.
  117. // Store number of cycles between wait_start_time and wait_end_time in a
  118. // lock value.
  119. static uint32_t EncodeWaitCycles(int64_t wait_start_time,
  120. int64_t wait_end_time);
  121. // Extract number of wait cycles in a lock value.
  122. static int64_t DecodeWaitCycles(uint32_t lock_value);
  123. // Provide access to protected method above. Use for testing only.
  124. friend struct SpinLockTest;
  125. friend class tcmalloc::tcmalloc_internal::AllocationGuardSpinLockHolder;
  126. private:
  127. // lockword_ is used to store the following:
  128. //
  129. // bit[0] encodes whether a lock is being held.
  130. // bit[1] encodes whether a lock uses cooperative scheduling.
  131. // bit[2] encodes whether the current lock holder disabled scheduling when
  132. // acquiring the lock. Only set when kSpinLockHeld is also set.
  133. // bit[3:31] encodes time a lock spent on waiting as a 29-bit unsigned int.
  134. // This is set by the lock holder to indicate how long it waited on
  135. // the lock before eventually acquiring it. The number of cycles is
  136. // encoded as a 29-bit unsigned int, or in the case that the current
  137. // holder did not wait but another waiter is queued, the LSB
  138. // (kSpinLockSleeper) is set. The implementation does not explicitly
  139. // track the number of queued waiters beyond this. It must always be
  140. // assumed that waiters may exist if the current holder was required to
  141. // queue.
  142. //
  143. // Invariant: if the lock is not held, the value is either 0 or
  144. // kSpinLockCooperative.
  145. static constexpr uint32_t kSpinLockHeld = 1;
  146. static constexpr uint32_t kSpinLockCooperative = 2;
  147. static constexpr uint32_t kSpinLockDisabledScheduling = 4;
  148. static constexpr uint32_t kSpinLockSleeper = 8;
  149. // Includes kSpinLockSleeper.
  150. static constexpr uint32_t kWaitTimeMask =
  151. ~(kSpinLockHeld | kSpinLockCooperative | kSpinLockDisabledScheduling);
  152. // Returns true if the provided scheduling mode is cooperative.
  153. static constexpr bool IsCooperative(
  154. base_internal::SchedulingMode scheduling_mode) {
  155. return scheduling_mode == base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL;
  156. }
  157. bool IsCooperative() const {
  158. return lockword_.load(std::memory_order_relaxed) & kSpinLockCooperative;
  159. }
  160. uint32_t TryLockInternal(uint32_t lock_value, uint32_t wait_cycles);
  161. void SlowLock() ABSL_ATTRIBUTE_COLD;
  162. void SlowUnlock(uint32_t lock_value) ABSL_ATTRIBUTE_COLD;
  163. uint32_t SpinLoop();
  164. inline bool TryLockImpl() {
  165. uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
  166. return (TryLockInternal(lock_value, 0) & kSpinLockHeld) == 0;
  167. }
  168. std::atomic<uint32_t> lockword_;
  169. SpinLock(const SpinLock&) = delete;
  170. SpinLock& operator=(const SpinLock&) = delete;
  171. };
  172. // Corresponding locker object that arranges to acquire a spinlock for
  173. // the duration of a C++ scope.
  174. class ABSL_SCOPED_LOCKABLE SpinLockHolder {
  175. public:
  176. inline explicit SpinLockHolder(SpinLock* l) ABSL_EXCLUSIVE_LOCK_FUNCTION(l)
  177. : lock_(l) {
  178. l->Lock();
  179. }
  180. inline ~SpinLockHolder() ABSL_UNLOCK_FUNCTION() { lock_->Unlock(); }
  181. SpinLockHolder(const SpinLockHolder&) = delete;
  182. SpinLockHolder& operator=(const SpinLockHolder&) = delete;
  183. private:
  184. SpinLock* lock_;
  185. };
  186. // Register a hook for profiling support.
  187. //
  188. // The function pointer registered here will be called whenever a spinlock is
  189. // contended. The callback is given an opaque handle to the contended spinlock
  190. // and the number of wait cycles. This is thread-safe, but only a single
  191. // profiler can be registered. It is an error to call this function multiple
  192. // times with different arguments.
  193. void RegisterSpinLockProfiler(void (*fn)(const void* lock,
  194. int64_t wait_cycles));
  195. //------------------------------------------------------------------------------
  196. // Public interface ends here.
  197. //------------------------------------------------------------------------------
  198. // If (result & kSpinLockHeld) == 0, then *this was successfully locked.
  199. // Otherwise, returns last observed value for lockword_.
  200. inline uint32_t SpinLock::TryLockInternal(uint32_t lock_value,
  201. uint32_t wait_cycles) {
  202. if ((lock_value & kSpinLockHeld) != 0) {
  203. return lock_value;
  204. }
  205. uint32_t sched_disabled_bit = 0;
  206. if ((lock_value & kSpinLockCooperative) == 0) {
  207. // For non-cooperative locks we must make sure we mark ourselves as
  208. // non-reschedulable before we attempt to CompareAndSwap.
  209. if (base_internal::SchedulingGuard::DisableRescheduling()) {
  210. sched_disabled_bit = kSpinLockDisabledScheduling;
  211. }
  212. }
  213. if (!lockword_.compare_exchange_strong(
  214. lock_value,
  215. kSpinLockHeld | lock_value | wait_cycles | sched_disabled_bit,
  216. std::memory_order_acquire, std::memory_order_relaxed)) {
  217. base_internal::SchedulingGuard::EnableRescheduling(sched_disabled_bit != 0);
  218. }
  219. return lock_value;
  220. }
  221. } // namespace base_internal
  222. ABSL_NAMESPACE_END
  223. } // namespace absl
  224. #endif // ABSL_BASE_INTERNAL_SPINLOCK_H_