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/const_init.h"
40 #include "absl/base/dynamic_annotations.h"
41 #include "absl/base/internal/low_level_scheduling.h"
42 #include "absl/base/internal/raw_logging.h"
43 #include "absl/base/internal/scheduling_mode.h"
44 #include "absl/base/internal/tsan_mutex_interface.h"
45 #include "absl/base/macros.h"
46 #include "absl/base/port.h"
47 #include "absl/base/thread_annotations.h"
48 
49 namespace absl {
50 ABSL_NAMESPACE_BEGIN
51 namespace base_internal {
52 
53 class ABSL_LOCKABLE SpinLock {
54  public:
SpinLock()55   SpinLock() : lockword_(kSpinLockCooperative) {
56     ABSL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static);
57   }
58 
59   // Constructors that allow non-cooperative spinlocks to be created for use
60   // inside thread schedulers.  Normal clients should not use these.
61   explicit SpinLock(base_internal::SchedulingMode mode);
62 
63   // Constructor for global SpinLock instances.  See absl/base/const_init.h.
SpinLock(absl::ConstInitType,base_internal::SchedulingMode mode)64   constexpr SpinLock(absl::ConstInitType, base_internal::SchedulingMode mode)
65       : lockword_(IsCooperative(mode) ? kSpinLockCooperative : 0) {}
66 
67   // For global SpinLock instances prefer trivial destructor when possible.
68   // Default but non-trivial destructor in some build configurations causes an
69   // extra static initializer.
70 #ifdef ABSL_INTERNAL_HAVE_TSAN_INTERFACE
~SpinLock()71   ~SpinLock() { ABSL_TSAN_MUTEX_DESTROY(this, __tsan_mutex_not_static); }
72 #else
73   ~SpinLock() = default;
74 #endif
75 
76   // Acquire this SpinLock.
Lock()77   inline void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() {
78     ABSL_TSAN_MUTEX_PRE_LOCK(this, 0);
79     if (!TryLockImpl()) {
80       SlowLock();
81     }
82     ABSL_TSAN_MUTEX_POST_LOCK(this, 0, 0);
83   }
84 
85   // Try to acquire this SpinLock without blocking and return true if the
86   // acquisition was successful.  If the lock was not acquired, false is
87   // returned.  If this SpinLock is free at the time of the call, TryLock
88   // will return true with high probability.
TryLock()89   inline bool TryLock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true) {
90     ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_try_lock);
91     bool res = TryLockImpl();
92     ABSL_TSAN_MUTEX_POST_LOCK(
93         this, __tsan_mutex_try_lock | (res ? 0 : __tsan_mutex_try_lock_failed),
94         0);
95     return res;
96   }
97 
98   // Release this SpinLock, which must be held by the calling thread.
Unlock()99   inline void Unlock() ABSL_UNLOCK_FUNCTION() {
100     ABSL_TSAN_MUTEX_PRE_UNLOCK(this, 0);
101     uint32_t lock_value = lockword_.load(std::memory_order_relaxed);
102     lock_value = lockword_.exchange(lock_value & kSpinLockCooperative,
103                                     std::memory_order_release);
104 
105     if ((lock_value & kSpinLockDisabledScheduling) != 0) {
106       base_internal::SchedulingGuard::EnableRescheduling(true);
107     }
108     if ((lock_value & kWaitTimeMask) != 0) {
109       // Collect contentionz profile info, and speed the wakeup of any waiter.
110       // The wait_cycles value indicates how long this thread spent waiting
111       // for the lock.
112       SlowUnlock(lock_value);
113     }
114     ABSL_TSAN_MUTEX_POST_UNLOCK(this, 0);
115   }
116 
117   // Determine if the lock is held.  When the lock is held by the invoking
118   // thread, true will always be returned. Intended to be used as
119   // CHECK(lock.IsHeld()).
IsHeld()120   inline bool IsHeld() const {
121     return (lockword_.load(std::memory_order_relaxed) & kSpinLockHeld) != 0;
122   }
123 
124  protected:
125   // These should not be exported except for testing.
126 
127   // Store number of cycles between wait_start_time and wait_end_time in a
128   // lock value.
129   static uint32_t EncodeWaitCycles(int64_t wait_start_time,
130                                    int64_t wait_end_time);
131 
132   // Extract number of wait cycles in a lock value.
133   static uint64_t DecodeWaitCycles(uint32_t lock_value);
134 
135   // Provide access to protected method above.  Use for testing only.
136   friend struct SpinLockTest;
137 
138  private:
139   // lockword_ is used to store the following:
140   //
141   // bit[0] encodes whether a lock is being held.
142   // bit[1] encodes whether a lock uses cooperative scheduling.
143   // bit[2] encodes whether a lock disables scheduling.
144   // bit[3:31] encodes time a lock spent on waiting as a 29-bit unsigned int.
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 
153   // Returns true if the provided scheduling mode is cooperative.
IsCooperative(base_internal::SchedulingMode scheduling_mode)154   static constexpr bool IsCooperative(
155       base_internal::SchedulingMode scheduling_mode) {
156     return scheduling_mode == base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL;
157   }
158 
159   uint32_t TryLockInternal(uint32_t lock_value, uint32_t wait_cycles);
160   void SlowLock() ABSL_ATTRIBUTE_COLD;
161   void SlowUnlock(uint32_t lock_value) ABSL_ATTRIBUTE_COLD;
162   uint32_t SpinLoop();
163 
TryLockImpl()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 
169   std::atomic<uint32_t> lockword_;
170 
171   SpinLock(const SpinLock&) = delete;
172   SpinLock& operator=(const SpinLock&) = delete;
173 };
174 
175 // Corresponding locker object that arranges to acquire a spinlock for
176 // the duration of a C++ scope.
177 class ABSL_SCOPED_LOCKABLE SpinLockHolder {
178  public:
SpinLockHolder(SpinLock * l)179   inline explicit SpinLockHolder(SpinLock* l) ABSL_EXCLUSIVE_LOCK_FUNCTION(l)
180       : lock_(l) {
181     l->Lock();
182   }
ABSL_UNLOCK_FUNCTION()183   inline ~SpinLockHolder() ABSL_UNLOCK_FUNCTION() { lock_->Unlock(); }
184 
185   SpinLockHolder(const SpinLockHolder&) = delete;
186   SpinLockHolder& operator=(const SpinLockHolder&) = delete;
187 
188  private:
189   SpinLock* lock_;
190 };
191 
192 // Register a hook for profiling support.
193 //
194 // The function pointer registered here will be called whenever a spinlock is
195 // contended.  The callback is given an opaque handle to the contended spinlock
196 // and the number of wait cycles.  This is thread-safe, but only a single
197 // profiler can be registered.  It is an error to call this function multiple
198 // times with different arguments.
199 void RegisterSpinLockProfiler(void (*fn)(const void* lock,
200                                          int64_t wait_cycles));
201 
202 //------------------------------------------------------------------------------
203 // Public interface ends here.
204 //------------------------------------------------------------------------------
205 
206 // If (result & kSpinLockHeld) == 0, then *this was successfully locked.
207 // Otherwise, returns last observed value for lockword_.
TryLockInternal(uint32_t lock_value,uint32_t wait_cycles)208 inline uint32_t SpinLock::TryLockInternal(uint32_t lock_value,
209                                           uint32_t wait_cycles) {
210   if ((lock_value & kSpinLockHeld) != 0) {
211     return lock_value;
212   }
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 
223   if (!lockword_.compare_exchange_strong(
224           lock_value,
225           kSpinLockHeld | lock_value | wait_cycles | sched_disabled_bit,
226           std::memory_order_acquire, std::memory_order_relaxed)) {
227     base_internal::SchedulingGuard::EnableRescheduling(sched_disabled_bit != 0);
228   }
229 
230   return lock_value;
231 }
232 
233 }  // namespace base_internal
234 ABSL_NAMESPACE_END
235 }  // namespace absl
236 
237 #endif  // ABSL_BASE_INTERNAL_SPINLOCK_H_
238