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