Coverage Report

Created: 2025-07-11 06:37

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