spinlock.h 8.7 KB

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