Coverage Report

Created: 2026-10-28 06:49

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