/src/abseil-cpp/absl/base/internal/spinlock.h
Line | Count | Source |
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 two situations: |
19 | | // - for use by Abseil internal code that Mutex itself depends on |
20 | | // - for async signal safety (see below) |
21 | | |
22 | | // SpinLock with a SchedulingMode::SCHEDULE_KERNEL_ONLY is async |
23 | | // signal safe. If a spinlock is used within a signal handler, all code that |
24 | | // acquires the lock must ensure that the signal cannot arrive while they are |
25 | | // holding the lock. Typically, this is done by blocking the signal. |
26 | | // |
27 | | // Threads waiting on a SpinLock may be woken in an arbitrary order. |
28 | | |
29 | | #ifndef ABSL_BASE_INTERNAL_SPINLOCK_H_ |
30 | | #define ABSL_BASE_INTERNAL_SPINLOCK_H_ |
31 | | |
32 | | #include <atomic> |
33 | | #include <cstdint> |
34 | | #include <type_traits> |
35 | | |
36 | | #include "absl/base/attributes.h" |
37 | | #include "absl/base/config.h" |
38 | | #include "absl/base/const_init.h" |
39 | | #include "absl/base/internal/low_level_scheduling.h" |
40 | | #include "absl/base/internal/raw_logging.h" |
41 | | #include "absl/base/internal/scheduling_mode.h" |
42 | | #include "absl/base/internal/tsan_mutex_interface.h" |
43 | | #include "absl/base/macros.h" |
44 | | #include "absl/base/thread_annotations.h" |
45 | | |
46 | | namespace tcmalloc { |
47 | | namespace tcmalloc_internal { |
48 | | |
49 | | class AllocationGuardSpinLockHolder; |
50 | | class Static; |
51 | | |
52 | | } // namespace tcmalloc_internal |
53 | | } // namespace tcmalloc |
54 | | |
55 | | namespace absl { |
56 | | ABSL_NAMESPACE_BEGIN |
57 | | namespace base_internal { |
58 | | |
59 | | class ABSL_LOCKABLE ABSL_ATTRIBUTE_WARN_UNUSED SpinLock { |
60 | | public: |
61 | 0 | constexpr SpinLock() : lockword_(kSpinLockCooperative) { RegisterWithTsan(); } |
62 | | |
63 | | // Constructors that allow non-cooperative spinlocks to be created for use |
64 | | // inside thread schedulers. Normal clients should not use these. |
65 | | constexpr explicit SpinLock(SchedulingMode mode) |
66 | 8 | : lockword_(IsCooperative(mode) ? kSpinLockCooperative : 0) { |
67 | 8 | RegisterWithTsan(); |
68 | 8 | } |
69 | | |
70 | | #if ABSL_HAVE_ATTRIBUTE(enable_if) && !defined(_WIN32) |
71 | | // Constructor to inline users of the default scheduling mode. |
72 | | // |
73 | | // This only needs to exists for inliner runs, but doesn't work correctly in |
74 | | // clang+windows builds, likely due to mangling differences. |
75 | | ABSL_DEPRECATE_AND_INLINE() |
76 | | constexpr explicit SpinLock(SchedulingMode mode) |
77 | | __attribute__((enable_if(mode == SCHEDULE_COOPERATIVE_AND_KERNEL, |
78 | | "Cooperative use default constructor"))) |
79 | 0 | : SpinLock() {} |
80 | | #endif |
81 | | |
82 | | // Constructor for global SpinLock instances. See absl/base/const_init.h. |
83 | | ABSL_DEPRECATE_AND_INLINE() |
84 | | constexpr SpinLock(absl::ConstInitType, SchedulingMode mode) |
85 | 0 | : SpinLock(mode) {} |
86 | | |
87 | | // For global SpinLock instances prefer trivial destructor when possible. |
88 | | // Default but non-trivial destructor in some build configurations causes an |
89 | | // extra static initializer. |
90 | | #ifdef ABSL_INTERNAL_HAVE_TSAN_INTERFACE |
91 | | ~SpinLock() { ABSL_TSAN_MUTEX_DESTROY(this, __tsan_mutex_not_static); } |
92 | | #else |
93 | | ~SpinLock() = default; |
94 | | #endif |
95 | | |
96 | | // Acquire this SpinLock. |
97 | 9.78M | inline void lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() { |
98 | 9.78M | ABSL_TSAN_MUTEX_PRE_LOCK(this, 0); |
99 | 9.78M | if (!TryLockImpl()) { |
100 | 0 | SlowLock(); |
101 | 0 | } |
102 | 9.78M | ABSL_TSAN_MUTEX_POST_LOCK(this, 0, 0); |
103 | 9.78M | } |
104 | | |
105 | | ABSL_DEPRECATE_AND_INLINE() |
106 | 0 | inline void Lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() { return lock(); } |
107 | | |
108 | | // Try to acquire this SpinLock without blocking and return true if the |
109 | | // acquisition was successful. If the lock was not acquired, false is |
110 | | // returned. If this SpinLock is free at the time of the call, try_lock will |
111 | | // return true with high probability. |
112 | 0 | [[nodiscard]] inline bool try_lock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true) { |
113 | 0 | ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_try_lock); |
114 | 0 | bool res = TryLockImpl(); |
115 | 0 | ABSL_TSAN_MUTEX_POST_LOCK( |
116 | 0 | this, __tsan_mutex_try_lock | (res ? 0 : __tsan_mutex_try_lock_failed), |
117 | 0 | 0); |
118 | 0 | return res; |
119 | 0 | } |
120 | | |
121 | | ABSL_DEPRECATE_AND_INLINE() |
122 | 0 | [[nodiscard]] inline bool TryLock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true) { |
123 | 0 | return try_lock(); |
124 | 0 | } |
125 | | |
126 | | // Release this SpinLock, which must be held by the calling thread. |
127 | 9.78M | inline void unlock() ABSL_UNLOCK_FUNCTION() { |
128 | 9.78M | ABSL_TSAN_MUTEX_PRE_UNLOCK(this, 0); |
129 | 9.78M | uint32_t lock_value = lockword_.load(std::memory_order_relaxed); |
130 | 9.78M | lock_value = lockword_.exchange(lock_value & kSpinLockCooperative, |
131 | 9.78M | std::memory_order_release); |
132 | | |
133 | 9.78M | if ((lock_value & kSpinLockDisabledScheduling) != 0) { |
134 | 0 | SchedulingGuard::EnableRescheduling(true); |
135 | 0 | } |
136 | 9.78M | if ((lock_value & kWaitTimeMask) != 0) { |
137 | | // Collect contentionz profile info, and speed the wakeup of any waiter. |
138 | | // The wait_cycles value indicates how long this thread spent waiting |
139 | | // for the lock. |
140 | 0 | SlowUnlock(lock_value); |
141 | 0 | } |
142 | 9.78M | ABSL_TSAN_MUTEX_POST_UNLOCK(this, 0); |
143 | 9.78M | } |
144 | | |
145 | | ABSL_DEPRECATE_AND_INLINE() |
146 | 0 | inline void Unlock() ABSL_UNLOCK_FUNCTION() { unlock(); } |
147 | | |
148 | | // Determine if the lock is held. When the lock is held by the invoking |
149 | | // thread, true will always be returned. Intended to be used as |
150 | | // CHECK(lock.IsHeld()). |
151 | 0 | [[nodiscard]] inline bool IsHeld() const { |
152 | 0 | return (lockword_.load(std::memory_order_relaxed) & kSpinLockHeld) != 0; |
153 | 0 | } |
154 | | |
155 | | // Return immediately if this thread holds the SpinLock exclusively. |
156 | | // Otherwise, report an error by crashing with a diagnostic. |
157 | 0 | inline void AssertHeld() const ABSL_ASSERT_EXCLUSIVE_LOCK() { |
158 | 0 | if (!IsHeld()) { |
159 | 0 | ABSL_RAW_LOG(FATAL, "thread should hold the lock on SpinLock"); |
160 | 0 | } |
161 | 0 | } |
162 | | |
163 | | protected: |
164 | | // These should not be exported except for testing. |
165 | | |
166 | | // Store number of cycles between wait_start_time and wait_end_time in a |
167 | | // lock value. |
168 | | static uint32_t EncodeWaitCycles(int64_t wait_start_time, |
169 | | int64_t wait_end_time); |
170 | | |
171 | | // Extract number of wait cycles in a lock value. |
172 | | static int64_t DecodeWaitCycles(uint32_t lock_value); |
173 | | |
174 | | // Provide access to protected method above. Use for testing only. |
175 | | friend struct SpinLockTest; |
176 | | friend class tcmalloc::tcmalloc_internal::AllocationGuardSpinLockHolder; |
177 | | friend class tcmalloc::tcmalloc_internal::Static; |
178 | | |
179 | 0 | static int GetAdaptiveSpinCount() { |
180 | 0 | return adaptive_spin_count_.load(std::memory_order_relaxed); |
181 | 0 | } |
182 | 0 | static void SetAdaptiveSpinCount(int count) { |
183 | 0 | adaptive_spin_count_.store(count, std::memory_order_relaxed); |
184 | 0 | } |
185 | | |
186 | | static std::atomic<int> adaptive_spin_count_; |
187 | | |
188 | | private: |
189 | | // lockword_ is used to store the following: |
190 | | // |
191 | | // bit[0] encodes whether a lock is being held. |
192 | | // bit[1] encodes whether a lock uses cooperative scheduling. |
193 | | // bit[2] encodes whether the current lock holder disabled scheduling when |
194 | | // acquiring the lock. Only set when kSpinLockHeld is also set. |
195 | | // bit[3:31] encodes time a lock spent on waiting as a 29-bit unsigned int. |
196 | | // This is set by the lock holder to indicate how long it waited on |
197 | | // the lock before eventually acquiring it. The number of cycles is |
198 | | // encoded as a 29-bit unsigned int, or in the case that the current |
199 | | // holder did not wait but another waiter is queued, the LSB |
200 | | // (kSpinLockSleeper) is set. The implementation does not explicitly |
201 | | // track the number of queued waiters beyond this. It must always be |
202 | | // assumed that waiters may exist if the current holder was required to |
203 | | // queue. |
204 | | // |
205 | | // Invariant: if the lock is not held, the value is either 0 or |
206 | | // kSpinLockCooperative. |
207 | | static constexpr uint32_t kSpinLockHeld = 1; |
208 | | static constexpr uint32_t kSpinLockCooperative = 2; |
209 | | static constexpr uint32_t kSpinLockDisabledScheduling = 4; |
210 | | static constexpr uint32_t kSpinLockSleeper = 8; |
211 | | // Includes kSpinLockSleeper. |
212 | | static constexpr uint32_t kWaitTimeMask = |
213 | | ~(kSpinLockHeld | kSpinLockCooperative | kSpinLockDisabledScheduling); |
214 | | |
215 | | // Returns true if the provided scheduling mode is cooperative. |
216 | 8 | static constexpr bool IsCooperative(SchedulingMode scheduling_mode) { |
217 | 8 | return scheduling_mode == SCHEDULE_COOPERATIVE_AND_KERNEL; |
218 | 8 | } |
219 | | |
220 | 8 | constexpr void RegisterWithTsan() { |
221 | 8 | #if ABSL_HAVE_BUILTIN(__builtin_is_constant_evaluated) |
222 | 8 | if (!__builtin_is_constant_evaluated()) { |
223 | 8 | ABSL_TSAN_MUTEX_CREATE(this, __tsan_mutex_not_static); |
224 | 8 | } |
225 | 8 | #endif |
226 | 8 | } |
227 | | |
228 | 0 | bool IsCooperative() const { |
229 | 0 | return lockword_.load(std::memory_order_relaxed) & kSpinLockCooperative; |
230 | 0 | } |
231 | | |
232 | | uint32_t TryLockInternal(uint32_t lock_value, uint32_t wait_cycles); |
233 | | void SlowLock() ABSL_ATTRIBUTE_COLD; |
234 | | void SlowUnlock(uint32_t lock_value) ABSL_ATTRIBUTE_COLD; |
235 | | uint32_t SpinLoop(); |
236 | | |
237 | 9.78M | inline bool TryLockImpl() { |
238 | 9.78M | uint32_t lock_value = lockword_.load(std::memory_order_relaxed); |
239 | 9.78M | return (TryLockInternal(lock_value, 0) & kSpinLockHeld) == 0; |
240 | 9.78M | } |
241 | | |
242 | | std::atomic<uint32_t> lockword_; |
243 | | |
244 | | SpinLock(const SpinLock&) = delete; |
245 | | SpinLock& operator=(const SpinLock&) = delete; |
246 | | }; |
247 | | |
248 | | // Corresponding locker object that arranges to acquire a spinlock for |
249 | | // the duration of a C++ scope. |
250 | | class ABSL_SCOPED_LOCKABLE [[nodiscard]] SpinLockHolder { |
251 | | public: |
252 | | inline explicit SpinLockHolder( |
253 | | SpinLock& l ABSL_INTERNAL_ATTRIBUTE_CAPTURED_BY(this)) |
254 | | ABSL_EXCLUSIVE_LOCK_FUNCTION(l) |
255 | 9.78M | : lock_(l) { |
256 | 9.78M | l.lock(); |
257 | 9.78M | } |
258 | | ABSL_DEPRECATE_AND_INLINE() |
259 | | inline explicit SpinLockHolder(SpinLock* l) ABSL_EXCLUSIVE_LOCK_FUNCTION(l) |
260 | 0 | : SpinLockHolder(*l) {} |
261 | | |
262 | 9.78M | inline ~SpinLockHolder() ABSL_UNLOCK_FUNCTION() { lock_.unlock(); } |
263 | | |
264 | | SpinLockHolder(const SpinLockHolder&) = delete; |
265 | | SpinLockHolder& operator=(const SpinLockHolder&) = delete; |
266 | | |
267 | | private: |
268 | | SpinLock& lock_; |
269 | | }; |
270 | | |
271 | | // Register a hook for profiling support. |
272 | | // |
273 | | // The function pointer registered here will be called whenever a spinlock is |
274 | | // contended. The callback is given an opaque handle to the contended spinlock |
275 | | // and the number of wait cycles. This is thread-safe, but only a single |
276 | | // profiler can be registered. It is an error to call this function multiple |
277 | | // times with different arguments. |
278 | | void RegisterSpinLockProfiler(void (*fn)(const void* lock, |
279 | | int64_t wait_cycles)); |
280 | | |
281 | | //------------------------------------------------------------------------------ |
282 | | // Public interface ends here. |
283 | | //------------------------------------------------------------------------------ |
284 | | |
285 | | // If (result & kSpinLockHeld) == 0, then *this was successfully locked. |
286 | | // Otherwise, returns last observed value for lockword_. |
287 | | inline uint32_t SpinLock::TryLockInternal(uint32_t lock_value, |
288 | 9.78M | uint32_t wait_cycles) { |
289 | 9.78M | if ((lock_value & kSpinLockHeld) != 0) { |
290 | 0 | return lock_value; |
291 | 0 | } |
292 | | |
293 | 9.78M | uint32_t sched_disabled_bit = 0; |
294 | 9.78M | if ((lock_value & kSpinLockCooperative) == 0) { |
295 | | // For non-cooperative locks we must make sure we mark ourselves as |
296 | | // non-reschedulable before we attempt to CompareAndSwap. |
297 | 9.78M | if (SchedulingGuard::DisableRescheduling()) { |
298 | 0 | sched_disabled_bit = kSpinLockDisabledScheduling; |
299 | 0 | } |
300 | 9.78M | } |
301 | | |
302 | 9.78M | if (!lockword_.compare_exchange_strong( |
303 | 9.78M | lock_value, |
304 | 9.78M | kSpinLockHeld | lock_value | wait_cycles | sched_disabled_bit, |
305 | 9.78M | std::memory_order_acquire, std::memory_order_relaxed)) { |
306 | 0 | SchedulingGuard::EnableRescheduling(sched_disabled_bit != 0); |
307 | 0 | } |
308 | | |
309 | 9.78M | return lock_value; |
310 | 9.78M | } |
311 | | |
312 | | } // namespace base_internal |
313 | | ABSL_NAMESPACE_END |
314 | | } // namespace absl |
315 | | |
316 | | #endif // ABSL_BASE_INTERNAL_SPINLOCK_H_ |