1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "absl/synchronization/mutex.h"
16
17 #ifdef _WIN32
18 #include <windows.h>
19 #ifdef ERROR
20 #undef ERROR
21 #endif
22 #else
23 #include <fcntl.h>
24 #include <pthread.h>
25 #include <sched.h>
26 #include <sys/time.h>
27 #endif
28
29 #include <assert.h>
30 #include <errno.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <time.h>
35
36 #include <algorithm>
37 #include <atomic>
38 #include <cstddef>
39 #include <cstdlib>
40 #include <cstring>
41 #include <thread> // NOLINT(build/c++11)
42
43 #include "absl/base/attributes.h"
44 #include "absl/base/call_once.h"
45 #include "absl/base/config.h"
46 #include "absl/base/dynamic_annotations.h"
47 #include "absl/base/internal/atomic_hook.h"
48 #include "absl/base/internal/cycleclock.h"
49 #include "absl/base/internal/hide_ptr.h"
50 #include "absl/base/internal/low_level_alloc.h"
51 #include "absl/base/internal/raw_logging.h"
52 #include "absl/base/internal/spinlock.h"
53 #include "absl/base/internal/sysinfo.h"
54 #include "absl/base/internal/thread_identity.h"
55 #include "absl/base/internal/tsan_mutex_interface.h"
56 #include "absl/base/optimization.h"
57 #include "absl/debugging/stacktrace.h"
58 #include "absl/debugging/symbolize.h"
59 #include "absl/synchronization/internal/graphcycles.h"
60 #include "absl/synchronization/internal/per_thread_sem.h"
61 #include "absl/time/time.h"
62
63 using absl::base_internal::CurrentThreadIdentityIfPresent;
64 using absl::base_internal::CycleClock;
65 using absl::base_internal::PerThreadSynch;
66 using absl::base_internal::SchedulingGuard;
67 using absl::base_internal::ThreadIdentity;
68 using absl::synchronization_internal::GetOrCreateCurrentThreadIdentity;
69 using absl::synchronization_internal::GraphCycles;
70 using absl::synchronization_internal::GraphId;
71 using absl::synchronization_internal::InvalidGraphId;
72 using absl::synchronization_internal::KernelTimeout;
73 using absl::synchronization_internal::PerThreadSem;
74
75 extern "C" {
ABSL_INTERNAL_C_SYMBOL(AbslInternalMutexYield)76 ABSL_ATTRIBUTE_WEAK void ABSL_INTERNAL_C_SYMBOL(AbslInternalMutexYield)() {
77 std::this_thread::yield();
78 }
79 } // extern "C"
80
81 namespace absl {
82 ABSL_NAMESPACE_BEGIN
83
84 namespace {
85
86 #if defined(ABSL_HAVE_THREAD_SANITIZER)
87 constexpr OnDeadlockCycle kDeadlockDetectionDefault = OnDeadlockCycle::kIgnore;
88 #else
89 constexpr OnDeadlockCycle kDeadlockDetectionDefault = OnDeadlockCycle::kAbort;
90 #endif
91
92 ABSL_CONST_INIT std::atomic<OnDeadlockCycle> synch_deadlock_detection(
93 kDeadlockDetectionDefault);
94 ABSL_CONST_INIT std::atomic<bool> synch_check_invariants(false);
95
96 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES
97 absl::base_internal::AtomicHook<void (*)(int64_t wait_cycles)>
98 submit_profile_data;
99 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES absl::base_internal::AtomicHook<void (*)(
100 const char* msg, const void* obj, int64_t wait_cycles)>
101 mutex_tracer;
102 ABSL_INTERNAL_ATOMIC_HOOK_ATTRIBUTES
103 absl::base_internal::AtomicHook<void (*)(const char* msg, const void* cv)>
104 cond_var_tracer;
105
106 } // namespace
107
108 static inline bool EvalConditionAnnotated(const Condition* cond, Mutex* mu,
109 bool locking, bool trylock,
110 bool read_lock);
111
RegisterMutexProfiler(void (* fn)(int64_t wait_cycles))112 void RegisterMutexProfiler(void (*fn)(int64_t wait_cycles)) {
113 submit_profile_data.Store(fn);
114 }
115
RegisterMutexTracer(void (* fn)(const char * msg,const void * obj,int64_t wait_cycles))116 void RegisterMutexTracer(void (*fn)(const char* msg, const void* obj,
117 int64_t wait_cycles)) {
118 mutex_tracer.Store(fn);
119 }
120
RegisterCondVarTracer(void (* fn)(const char * msg,const void * cv))121 void RegisterCondVarTracer(void (*fn)(const char* msg, const void* cv)) {
122 cond_var_tracer.Store(fn);
123 }
124
125 namespace {
126 // Represents the strategy for spin and yield.
127 // See the comment in GetMutexGlobals() for more information.
128 enum DelayMode { AGGRESSIVE, GENTLE };
129
130 struct ABSL_CACHELINE_ALIGNED MutexGlobals {
131 absl::once_flag once;
132 // Note: this variable is initialized separately in Mutex::LockSlow,
133 // so that Mutex::Lock does not have a stack frame in optimized build.
134 std::atomic<int> spinloop_iterations{0};
135 int32_t mutex_sleep_spins[2] = {};
136 absl::Duration mutex_sleep_time;
137 };
138
139 ABSL_CONST_INIT static MutexGlobals globals;
140
MeasureTimeToYield()141 absl::Duration MeasureTimeToYield() {
142 absl::Time before = absl::Now();
143 ABSL_INTERNAL_C_SYMBOL(AbslInternalMutexYield)();
144 return absl::Now() - before;
145 }
146
GetMutexGlobals()147 const MutexGlobals& GetMutexGlobals() {
148 absl::base_internal::LowLevelCallOnce(&globals.once, [&]() {
149 if (absl::base_internal::NumCPUs() > 1) {
150 // If the mode is aggressive then spin many times before yielding.
151 // If the mode is gentle then spin only a few times before yielding.
152 // Aggressive spinning is used to ensure that an Unlock() call,
153 // which must get the spin lock for any thread to make progress gets it
154 // without undue delay.
155 globals.mutex_sleep_spins[AGGRESSIVE] = 5000;
156 globals.mutex_sleep_spins[GENTLE] = 250;
157 globals.mutex_sleep_time = absl::Microseconds(10);
158 } else {
159 // If this a uniprocessor, only yield/sleep. Real-time threads are often
160 // unable to yield, so the sleep time needs to be long enough to keep
161 // the calling thread asleep until scheduling happens.
162 globals.mutex_sleep_spins[AGGRESSIVE] = 0;
163 globals.mutex_sleep_spins[GENTLE] = 0;
164 globals.mutex_sleep_time = MeasureTimeToYield() * 5;
165 globals.mutex_sleep_time =
166 std::min(globals.mutex_sleep_time, absl::Milliseconds(1));
167 globals.mutex_sleep_time =
168 std::max(globals.mutex_sleep_time, absl::Microseconds(10));
169 }
170 });
171 return globals;
172 }
173 } // namespace
174
175 namespace synchronization_internal {
176 // Returns the Mutex delay on iteration `c` depending on the given `mode`.
177 // The returned value should be used as `c` for the next call to `MutexDelay`.
MutexDelay(int32_t c,int mode)178 int MutexDelay(int32_t c, int mode) {
179 const int32_t limit = GetMutexGlobals().mutex_sleep_spins[mode];
180 const absl::Duration sleep_time = GetMutexGlobals().mutex_sleep_time;
181 if (c < limit) {
182 // Spin.
183 c++;
184 } else {
185 SchedulingGuard::ScopedEnable enable_rescheduling;
186 ABSL_TSAN_MUTEX_PRE_DIVERT(nullptr, 0);
187 if (c == limit) {
188 // Yield once.
189 ABSL_INTERNAL_C_SYMBOL(AbslInternalMutexYield)();
190 c++;
191 } else {
192 // Then wait.
193 absl::SleepFor(sleep_time);
194 c = 0;
195 }
196 ABSL_TSAN_MUTEX_POST_DIVERT(nullptr, 0);
197 }
198 return c;
199 }
200 } // namespace synchronization_internal
201
202 // --------------------------Generic atomic ops
203 // Ensure that "(*pv & bits) == bits" by doing an atomic update of "*pv" to
204 // "*pv | bits" if necessary. Wait until (*pv & wait_until_clear)==0
205 // before making any change.
206 // Returns true if bits were previously unset and set by the call.
207 // This is used to set flags in mutex and condition variable words.
AtomicSetBits(std::atomic<intptr_t> * pv,intptr_t bits,intptr_t wait_until_clear)208 static bool AtomicSetBits(std::atomic<intptr_t>* pv, intptr_t bits,
209 intptr_t wait_until_clear) {
210 for (;;) {
211 intptr_t v = pv->load(std::memory_order_relaxed);
212 if ((v & bits) == bits) {
213 return false;
214 }
215 if ((v & wait_until_clear) != 0) {
216 continue;
217 }
218 if (pv->compare_exchange_weak(v, v | bits, std::memory_order_release,
219 std::memory_order_relaxed)) {
220 return true;
221 }
222 }
223 }
224
225 //------------------------------------------------------------------
226
227 // Data for doing deadlock detection.
228 ABSL_CONST_INIT static absl::base_internal::SpinLock deadlock_graph_mu(
229 absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY);
230
231 // Graph used to detect deadlocks.
232 ABSL_CONST_INIT static GraphCycles* deadlock_graph
233 ABSL_GUARDED_BY(deadlock_graph_mu) ABSL_PT_GUARDED_BY(deadlock_graph_mu);
234
235 //------------------------------------------------------------------
236 // An event mechanism for debugging mutex use.
237 // It also allows mutexes to be given names for those who can't handle
238 // addresses, and instead like to give their data structures names like
239 // "Henry", "Fido", or "Rupert IV, King of Yondavia".
240
241 namespace { // to prevent name pollution
242 enum { // Mutex and CondVar events passed as "ev" to PostSynchEvent
243 // Mutex events
244 SYNCH_EV_TRYLOCK_SUCCESS,
245 SYNCH_EV_TRYLOCK_FAILED,
246 SYNCH_EV_READERTRYLOCK_SUCCESS,
247 SYNCH_EV_READERTRYLOCK_FAILED,
248 SYNCH_EV_LOCK,
249 SYNCH_EV_LOCK_RETURNING,
250 SYNCH_EV_READERLOCK,
251 SYNCH_EV_READERLOCK_RETURNING,
252 SYNCH_EV_UNLOCK,
253 SYNCH_EV_READERUNLOCK,
254
255 // CondVar events
256 SYNCH_EV_WAIT,
257 SYNCH_EV_WAIT_RETURNING,
258 SYNCH_EV_SIGNAL,
259 SYNCH_EV_SIGNALALL,
260 };
261
262 enum { // Event flags
263 SYNCH_F_R = 0x01, // reader event
264 SYNCH_F_LCK = 0x02, // PostSynchEvent called with mutex held
265 SYNCH_F_TRY = 0x04, // TryLock or ReaderTryLock
266 SYNCH_F_UNLOCK = 0x08, // Unlock or ReaderUnlock
267
268 SYNCH_F_LCK_W = SYNCH_F_LCK,
269 SYNCH_F_LCK_R = SYNCH_F_LCK | SYNCH_F_R,
270 };
271 } // anonymous namespace
272
273 // Properties of the events.
274 static const struct {
275 int flags;
276 const char* msg;
277 } event_properties[] = {
278 {SYNCH_F_LCK_W | SYNCH_F_TRY, "TryLock succeeded "},
279 {0, "TryLock failed "},
280 {SYNCH_F_LCK_R | SYNCH_F_TRY, "ReaderTryLock succeeded "},
281 {0, "ReaderTryLock failed "},
282 {0, "Lock blocking "},
283 {SYNCH_F_LCK_W, "Lock returning "},
284 {0, "ReaderLock blocking "},
285 {SYNCH_F_LCK_R, "ReaderLock returning "},
286 {SYNCH_F_LCK_W | SYNCH_F_UNLOCK, "Unlock "},
287 {SYNCH_F_LCK_R | SYNCH_F_UNLOCK, "ReaderUnlock "},
288 {0, "Wait on "},
289 {0, "Wait unblocked "},
290 {0, "Signal on "},
291 {0, "SignalAll on "},
292 };
293
294 ABSL_CONST_INIT static absl::base_internal::SpinLock synch_event_mu(
295 absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY);
296
297 // Hash table size; should be prime > 2.
298 // Can't be too small, as it's used for deadlock detection information.
299 static constexpr uint32_t kNSynchEvent = 1031;
300
301 static struct SynchEvent { // this is a trivial hash table for the events
302 // struct is freed when refcount reaches 0
303 int refcount ABSL_GUARDED_BY(synch_event_mu);
304
305 // buckets have linear, 0-terminated chains
306 SynchEvent* next ABSL_GUARDED_BY(synch_event_mu);
307
308 // Constant after initialization
309 uintptr_t masked_addr; // object at this address is called "name"
310
311 // No explicit synchronization used. Instead we assume that the
312 // client who enables/disables invariants/logging on a Mutex does so
313 // while the Mutex is not being concurrently accessed by others.
314 void (*invariant)(void* arg); // called on each event
315 void* arg; // first arg to (*invariant)()
316 bool log; // logging turned on
317
318 // Constant after initialization
319 char name[1]; // actually longer---NUL-terminated string
320 }* synch_event[kNSynchEvent] ABSL_GUARDED_BY(synch_event_mu);
321
322 // Ensure that the object at "addr" has a SynchEvent struct associated with it,
323 // set "bits" in the word there (waiting until lockbit is clear before doing
324 // so), and return a refcounted reference that will remain valid until
325 // UnrefSynchEvent() is called. If a new SynchEvent is allocated,
326 // the string name is copied into it.
327 // When used with a mutex, the caller should also ensure that kMuEvent
328 // is set in the mutex word, and similarly for condition variables and kCVEvent.
EnsureSynchEvent(std::atomic<intptr_t> * addr,const char * name,intptr_t bits,intptr_t lockbit)329 static SynchEvent* EnsureSynchEvent(std::atomic<intptr_t>* addr,
330 const char* name, intptr_t bits,
331 intptr_t lockbit) {
332 uint32_t h = reinterpret_cast<uintptr_t>(addr) % kNSynchEvent;
333 synch_event_mu.Lock();
334 // When a Mutex/CondVar is destroyed, we don't remove the associated
335 // SynchEvent to keep destructors empty in release builds for performance
336 // reasons. If the current call is the first to set bits (kMuEvent/kCVEvent),
337 // we don't look up the existing even because (if it exists, it must be for
338 // the previous Mutex/CondVar that existed at the same address).
339 // The leaking events must not be a problem for tests, which should create
340 // bounded amount of events. And debug logging is not supposed to be enabled
341 // in production. However, if it's accidentally enabled, or briefly enabled
342 // for some debugging, we don't want to crash the program. Instead we drop
343 // all events, if we accumulated too many of them. Size of a single event
344 // is ~48 bytes, so 100K events is ~5 MB.
345 // Additionally we could delete the old event for the same address,
346 // but it would require a better hashmap (if we accumulate too many events,
347 // linked lists will grow and traversing them will be very slow).
348 constexpr size_t kMaxSynchEventCount = 100 << 10;
349 // Total number of live synch events.
350 static size_t synch_event_count ABSL_GUARDED_BY(synch_event_mu);
351 if (++synch_event_count > kMaxSynchEventCount) {
352 synch_event_count = 0;
353 ABSL_RAW_LOG(ERROR,
354 "Accumulated %zu Mutex debug objects. If you see this"
355 " in production, it may mean that the production code"
356 " accidentally calls "
357 "Mutex/CondVar::EnableDebugLog/EnableInvariantDebugging.",
358 kMaxSynchEventCount);
359 for (auto*& head : synch_event) {
360 for (auto* e = head; e != nullptr;) {
361 SynchEvent* next = e->next;
362 if (--(e->refcount) == 0) {
363 base_internal::LowLevelAlloc::Free(e);
364 }
365 e = next;
366 }
367 head = nullptr;
368 }
369 }
370 SynchEvent* e = nullptr;
371 if (!AtomicSetBits(addr, bits, lockbit)) {
372 for (e = synch_event[h];
373 e != nullptr && e->masked_addr != base_internal::HidePtr(addr);
374 e = e->next) {
375 }
376 }
377 if (e == nullptr) { // no SynchEvent struct found; make one.
378 if (name == nullptr) {
379 name = "";
380 }
381 size_t l = strlen(name);
382 e = reinterpret_cast<SynchEvent*>(
383 base_internal::LowLevelAlloc::Alloc(sizeof(*e) + l));
384 e->refcount = 2; // one for return value, one for linked list
385 e->masked_addr = base_internal::HidePtr(addr);
386 e->invariant = nullptr;
387 e->arg = nullptr;
388 e->log = false;
389 strcpy(e->name, name); // NOLINT(runtime/printf)
390 e->next = synch_event[h];
391 synch_event[h] = e;
392 } else {
393 e->refcount++; // for return value
394 }
395 synch_event_mu.Unlock();
396 return e;
397 }
398
399 // Decrement the reference count of *e, or do nothing if e==null.
UnrefSynchEvent(SynchEvent * e)400 static void UnrefSynchEvent(SynchEvent* e) {
401 if (e != nullptr) {
402 synch_event_mu.Lock();
403 bool del = (--(e->refcount) == 0);
404 synch_event_mu.Unlock();
405 if (del) {
406 base_internal::LowLevelAlloc::Free(e);
407 }
408 }
409 }
410
411 // Return a refcounted reference to the SynchEvent of the object at address
412 // "addr", if any. The pointer returned is valid until the UnrefSynchEvent() is
413 // called.
GetSynchEvent(const void * addr)414 static SynchEvent* GetSynchEvent(const void* addr) {
415 uint32_t h = reinterpret_cast<uintptr_t>(addr) % kNSynchEvent;
416 SynchEvent* e;
417 synch_event_mu.Lock();
418 for (e = synch_event[h];
419 e != nullptr && e->masked_addr != base_internal::HidePtr(addr);
420 e = e->next) {
421 }
422 if (e != nullptr) {
423 e->refcount++;
424 }
425 synch_event_mu.Unlock();
426 return e;
427 }
428
429 // Called when an event "ev" occurs on a Mutex of CondVar "obj"
430 // if event recording is on
PostSynchEvent(void * obj,int ev)431 static void PostSynchEvent(void* obj, int ev) {
432 SynchEvent* e = GetSynchEvent(obj);
433 // logging is on if event recording is on and either there's no event struct,
434 // or it explicitly says to log
435 if (e == nullptr || e->log) {
436 void* pcs[40];
437 int n = absl::GetStackTrace(pcs, ABSL_ARRAYSIZE(pcs), 1);
438 // A buffer with enough space for the ASCII for all the PCs, even on a
439 // 64-bit machine.
440 char buffer[ABSL_ARRAYSIZE(pcs) * 24];
441 int pos = snprintf(buffer, sizeof(buffer), " @");
442 for (int i = 0; i != n; i++) {
443 int b = snprintf(&buffer[pos], sizeof(buffer) - static_cast<size_t>(pos),
444 " %p", pcs[i]);
445 if (b < 0 ||
446 static_cast<size_t>(b) >= sizeof(buffer) - static_cast<size_t>(pos)) {
447 break;
448 }
449 pos += b;
450 }
451 ABSL_RAW_LOG(INFO, "%s%p %s %s", event_properties[ev].msg, obj,
452 (e == nullptr ? "" : e->name), buffer);
453 }
454 const int flags = event_properties[ev].flags;
455 if ((flags & SYNCH_F_LCK) != 0 && e != nullptr && e->invariant != nullptr) {
456 // Calling the invariant as is causes problems under ThreadSanitizer.
457 // We are currently inside of Mutex Lock/Unlock and are ignoring all
458 // memory accesses and synchronization. If the invariant transitively
459 // synchronizes something else and we ignore the synchronization, we will
460 // get false positive race reports later.
461 // Reuse EvalConditionAnnotated to properly call into user code.
462 struct local {
463 static bool pred(SynchEvent* ev) {
464 (*ev->invariant)(ev->arg);
465 return false;
466 }
467 };
468 Condition cond(&local::pred, e);
469 Mutex* mu = static_cast<Mutex*>(obj);
470 const bool locking = (flags & SYNCH_F_UNLOCK) == 0;
471 const bool trylock = (flags & SYNCH_F_TRY) != 0;
472 const bool read_lock = (flags & SYNCH_F_R) != 0;
473 EvalConditionAnnotated(&cond, mu, locking, trylock, read_lock);
474 }
475 UnrefSynchEvent(e);
476 }
477
478 //------------------------------------------------------------------
479
480 // The SynchWaitParams struct encapsulates the way in which a thread is waiting:
481 // whether it has a timeout, the condition, exclusive/shared, and whether a
482 // condition variable wait has an associated Mutex (as opposed to another
483 // type of lock). It also points to the PerThreadSynch struct of its thread.
484 // cv_word tells Enqueue() to enqueue on a CondVar using CondVarEnqueue().
485 //
486 // This structure is held on the stack rather than directly in
487 // PerThreadSynch because a thread can be waiting on multiple Mutexes if,
488 // while waiting on one Mutex, the implementation calls a client callback
489 // (such as a Condition function) that acquires another Mutex. We don't
490 // strictly need to allow this, but programmers become confused if we do not
491 // allow them to use functions such a LOG() within Condition functions. The
492 // PerThreadSynch struct points at the most recent SynchWaitParams struct when
493 // the thread is on a Mutex's waiter queue.
494 struct SynchWaitParams {
SynchWaitParamsabsl::SynchWaitParams495 SynchWaitParams(Mutex::MuHow how_arg, const Condition* cond_arg,
496 KernelTimeout timeout_arg, Mutex* cvmu_arg,
497 PerThreadSynch* thread_arg,
498 std::atomic<intptr_t>* cv_word_arg)
499 : how(how_arg),
500 cond(cond_arg),
501 timeout(timeout_arg),
502 cvmu(cvmu_arg),
503 thread(thread_arg),
504 cv_word(cv_word_arg),
505 contention_start_cycles(CycleClock::Now()),
506 should_submit_contention_data(false) {}
507
508 const Mutex::MuHow how; // How this thread needs to wait.
509 const Condition* cond; // The condition that this thread is waiting for.
510 // In Mutex, this field is set to zero if a timeout
511 // expires.
512 KernelTimeout timeout; // timeout expiry---absolute time
513 // In Mutex, this field is set to zero if a timeout
514 // expires.
515 Mutex* const cvmu; // used for transfer from cond var to mutex
516 PerThreadSynch* const thread; // thread that is waiting
517
518 // If not null, thread should be enqueued on the CondVar whose state
519 // word is cv_word instead of queueing normally on the Mutex.
520 std::atomic<intptr_t>* cv_word;
521
522 int64_t contention_start_cycles; // Time (in cycles) when this thread started
523 // to contend for the mutex.
524 bool should_submit_contention_data;
525 };
526
527 struct SynchLocksHeld {
528 int n; // number of valid entries in locks[]
529 bool overflow; // true iff we overflowed the array at some point
530 struct {
531 Mutex* mu; // lock acquired
532 int32_t count; // times acquired
533 GraphId id; // deadlock_graph id of acquired lock
534 } locks[40];
535 // If a thread overfills the array during deadlock detection, we
536 // continue, discarding information as needed. If no overflow has
537 // taken place, we can provide more error checking, such as
538 // detecting when a thread releases a lock it does not hold.
539 };
540
541 // A sentinel value in lists that is not 0.
542 // A 0 value is used to mean "not on a list".
543 static PerThreadSynch* const kPerThreadSynchNull =
544 reinterpret_cast<PerThreadSynch*>(1);
545
LocksHeldAlloc()546 static SynchLocksHeld* LocksHeldAlloc() {
547 SynchLocksHeld* ret = reinterpret_cast<SynchLocksHeld*>(
548 base_internal::LowLevelAlloc::Alloc(sizeof(SynchLocksHeld)));
549 ret->n = 0;
550 ret->overflow = false;
551 return ret;
552 }
553
554 // Return the PerThreadSynch-struct for this thread.
Synch_GetPerThread()555 static PerThreadSynch* Synch_GetPerThread() {
556 ThreadIdentity* identity = GetOrCreateCurrentThreadIdentity();
557 return &identity->per_thread_synch;
558 }
559
Synch_GetPerThreadAnnotated(Mutex * mu)560 static PerThreadSynch* Synch_GetPerThreadAnnotated(Mutex* mu) {
561 if (mu) {
562 ABSL_TSAN_MUTEX_PRE_DIVERT(mu, 0);
563 }
564 PerThreadSynch* w = Synch_GetPerThread();
565 if (mu) {
566 ABSL_TSAN_MUTEX_POST_DIVERT(mu, 0);
567 }
568 return w;
569 }
570
Synch_GetAllLocks()571 static SynchLocksHeld* Synch_GetAllLocks() {
572 PerThreadSynch* s = Synch_GetPerThread();
573 if (s->all_locks == nullptr) {
574 s->all_locks = LocksHeldAlloc(); // Freed by ReclaimThreadIdentity.
575 }
576 return s->all_locks;
577 }
578
579 // Post on "w"'s associated PerThreadSem.
IncrementSynchSem(Mutex * mu,PerThreadSynch * w)580 void Mutex::IncrementSynchSem(Mutex* mu, PerThreadSynch* w) {
581 static_cast<void>(mu); // Prevent unused param warning in non-TSAN builds.
582 ABSL_TSAN_MUTEX_PRE_DIVERT(mu, 0);
583 // We miss synchronization around passing PerThreadSynch between threads
584 // since it happens inside of the Mutex code, so we need to ignore all
585 // accesses to the object.
586 ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN();
587 PerThreadSem::Post(w->thread_identity());
588 ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_END();
589 ABSL_TSAN_MUTEX_POST_DIVERT(mu, 0);
590 }
591
592 // Wait on "w"'s associated PerThreadSem; returns false if timeout expired.
DecrementSynchSem(Mutex * mu,PerThreadSynch * w,KernelTimeout t)593 bool Mutex::DecrementSynchSem(Mutex* mu, PerThreadSynch* w, KernelTimeout t) {
594 static_cast<void>(mu); // Prevent unused param warning in non-TSAN builds.
595 ABSL_TSAN_MUTEX_PRE_DIVERT(mu, 0);
596 assert(w == Synch_GetPerThread());
597 static_cast<void>(w);
598 bool res = PerThreadSem::Wait(t);
599 ABSL_TSAN_MUTEX_POST_DIVERT(mu, 0);
600 return res;
601 }
602
603 // We're in a fatal signal handler that hopes to use Mutex and to get
604 // lucky by not deadlocking. We try to improve its chances of success
605 // by effectively disabling some of the consistency checks. This will
606 // prevent certain ABSL_RAW_CHECK() statements from being triggered when
607 // re-rentry is detected. The ABSL_RAW_CHECK() statements are those in the
608 // Mutex code checking that the "waitp" field has not been reused.
InternalAttemptToUseMutexInFatalSignalHandler()609 void Mutex::InternalAttemptToUseMutexInFatalSignalHandler() {
610 // Fix the per-thread state only if it exists.
611 ThreadIdentity* identity = CurrentThreadIdentityIfPresent();
612 if (identity != nullptr) {
613 identity->per_thread_synch.suppress_fatal_errors = true;
614 }
615 // Don't do deadlock detection when we are already failing.
616 synch_deadlock_detection.store(OnDeadlockCycle::kIgnore,
617 std::memory_order_release);
618 }
619
620 // --------------------------Mutexes
621
622 // In the layout below, the msb of the bottom byte is currently unused. Also,
623 // the following constraints were considered in choosing the layout:
624 // o Both the debug allocator's "uninitialized" and "freed" patterns (0xab and
625 // 0xcd) are illegal: reader and writer lock both held.
626 // o kMuWriter and kMuEvent should exceed kMuDesig and kMuWait, to enable the
627 // bit-twiddling trick in Mutex::Unlock().
628 // o kMuWriter / kMuReader == kMuWrWait / kMuWait,
629 // to enable the bit-twiddling trick in CheckForMutexCorruption().
630 static const intptr_t kMuReader = 0x0001L; // a reader holds the lock
631 // There's a designated waker.
632 // INVARIANT1: there's a thread that was blocked on the mutex, is
633 // no longer, yet has not yet acquired the mutex. If there's a
634 // designated waker, all threads can avoid taking the slow path in
635 // unlock because the designated waker will subsequently acquire
636 // the lock and wake someone. To maintain INVARIANT1 the bit is
637 // set when a thread is unblocked(INV1a), and threads that were
638 // unblocked reset the bit when they either acquire or re-block (INV1b).
639 static const intptr_t kMuDesig = 0x0002L;
640 static const intptr_t kMuWait = 0x0004L; // threads are waiting
641 static const intptr_t kMuWriter = 0x0008L; // a writer holds the lock
642 static const intptr_t kMuEvent = 0x0010L; // record this mutex's events
643 // Runnable writer is waiting for a reader.
644 // If set, new readers will not lock the mutex to avoid writer starvation.
645 // Note: if a reader has higher priority than the writer, it will still lock
646 // the mutex ahead of the waiting writer, but in a very inefficient manner:
647 // the reader will first queue itself and block, but then the last unlocking
648 // reader will wake it.
649 static const intptr_t kMuWrWait = 0x0020L;
650 static const intptr_t kMuSpin = 0x0040L; // spinlock protects wait list
651 static const intptr_t kMuLow = 0x00ffL; // mask all mutex bits
652 static const intptr_t kMuHigh = ~kMuLow; // mask pointer/reader count
653
654 // Hack to make constant values available to gdb pretty printer
655 enum {
656 kGdbMuSpin = kMuSpin,
657 kGdbMuEvent = kMuEvent,
658 kGdbMuWait = kMuWait,
659 kGdbMuWriter = kMuWriter,
660 kGdbMuDesig = kMuDesig,
661 kGdbMuWrWait = kMuWrWait,
662 kGdbMuReader = kMuReader,
663 kGdbMuLow = kMuLow,
664 };
665
666 // kMuWrWait implies kMuWait.
667 // kMuReader and kMuWriter are mutually exclusive.
668 // If kMuReader is zero, there are no readers.
669 // Otherwise, if kMuWait is zero, the high order bits contain a count of the
670 // number of readers. Otherwise, the reader count is held in
671 // PerThreadSynch::readers of the most recently queued waiter, again in the
672 // bits above kMuLow.
673 static const intptr_t kMuOne = 0x0100; // a count of one reader
674
675 // flags passed to Enqueue and LockSlow{,WithTimeout,Loop}
676 static const int kMuHasBlocked = 0x01; // already blocked (MUST == 1)
677 static const int kMuIsCond = 0x02; // conditional waiter (CV or Condition)
678 static const int kMuIsFer = 0x04; // wait morphing from a CondVar
679
680 static_assert(PerThreadSynch::kAlignment > kMuLow,
681 "PerThreadSynch::kAlignment must be greater than kMuLow");
682
683 // This struct contains various bitmasks to be used in
684 // acquiring and releasing a mutex in a particular mode.
685 struct MuHowS {
686 // if all the bits in fast_need_zero are zero, the lock can be acquired by
687 // adding fast_add and oring fast_or. The bit kMuDesig should be reset iff
688 // this is the designated waker.
689 intptr_t fast_need_zero;
690 intptr_t fast_or;
691 intptr_t fast_add;
692
693 intptr_t slow_need_zero; // fast_need_zero with events (e.g. logging)
694
695 intptr_t slow_inc_need_zero; // if all the bits in slow_inc_need_zero are
696 // zero a reader can acquire a read share by
697 // setting the reader bit and incrementing
698 // the reader count (in last waiter since
699 // we're now slow-path). kMuWrWait be may
700 // be ignored if we already waited once.
701 };
702
703 static const MuHowS kSharedS = {
704 // shared or read lock
705 kMuWriter | kMuWait | kMuEvent, // fast_need_zero
706 kMuReader, // fast_or
707 kMuOne, // fast_add
708 kMuWriter | kMuWait, // slow_need_zero
709 kMuSpin | kMuWriter | kMuWrWait, // slow_inc_need_zero
710 };
711 static const MuHowS kExclusiveS = {
712 // exclusive or write lock
713 kMuWriter | kMuReader | kMuEvent, // fast_need_zero
714 kMuWriter, // fast_or
715 0, // fast_add
716 kMuWriter | kMuReader, // slow_need_zero
717 ~static_cast<intptr_t>(0), // slow_inc_need_zero
718 };
719 static const Mutex::MuHow kShared = &kSharedS; // shared lock
720 static const Mutex::MuHow kExclusive = &kExclusiveS; // exclusive lock
721
722 #ifdef NDEBUG
723 static constexpr bool kDebugMode = false;
724 #else
725 static constexpr bool kDebugMode = true;
726 #endif
727
728 #ifdef ABSL_INTERNAL_HAVE_TSAN_INTERFACE
TsanFlags(Mutex::MuHow how)729 static unsigned TsanFlags(Mutex::MuHow how) {
730 return how == kShared ? __tsan_mutex_read_lock : 0;
731 }
732 #endif
733
734 #if defined(__APPLE__) || defined(ABSL_BUILD_DLL)
735 // When building a dll symbol export lists may reference the destructor
736 // and want it to be an exported symbol rather than an inline function.
737 // Some apple builds also do dynamic library build but don't say it explicitly.
~Mutex()738 Mutex::~Mutex() { Dtor(); }
739 #endif
740
741 #if !defined(NDEBUG) || defined(ABSL_HAVE_THREAD_SANITIZER)
Dtor()742 void Mutex::Dtor() {
743 if (kDebugMode) {
744 this->ForgetDeadlockInfo();
745 }
746 ABSL_TSAN_MUTEX_DESTROY(this, __tsan_mutex_not_static);
747 }
748 #endif
749
EnableDebugLog(const char * name)750 void Mutex::EnableDebugLog(const char* name) {
751 SynchEvent* e = EnsureSynchEvent(&this->mu_, name, kMuEvent, kMuSpin);
752 e->log = true;
753 UnrefSynchEvent(e);
754 // This prevents "error: undefined symbol: absl::Mutex::~Mutex()"
755 // in a release build (NDEBUG defined) when a test does "#undef NDEBUG"
756 // to use assert macro. In such case, the test does not get the dtor
757 // definition because it's supposed to be outline when NDEBUG is not defined,
758 // and this source file does not define one either because NDEBUG is defined.
759 // Since it's not possible to take address of a destructor, we move the
760 // actual destructor code into the separate Dtor function and force the
761 // compiler to emit this function even if it's inline by taking its address.
762 ABSL_ATTRIBUTE_UNUSED volatile auto dtor = &Mutex::Dtor;
763 }
764
EnableMutexInvariantDebugging(bool enabled)765 void EnableMutexInvariantDebugging(bool enabled) {
766 synch_check_invariants.store(enabled, std::memory_order_release);
767 }
768
EnableInvariantDebugging(void (* invariant)(void *),void * arg)769 void Mutex::EnableInvariantDebugging(void (*invariant)(void*), void* arg) {
770 if (synch_check_invariants.load(std::memory_order_acquire) &&
771 invariant != nullptr) {
772 SynchEvent* e = EnsureSynchEvent(&this->mu_, nullptr, kMuEvent, kMuSpin);
773 e->invariant = invariant;
774 e->arg = arg;
775 UnrefSynchEvent(e);
776 }
777 }
778
SetMutexDeadlockDetectionMode(OnDeadlockCycle mode)779 void SetMutexDeadlockDetectionMode(OnDeadlockCycle mode) {
780 synch_deadlock_detection.store(mode, std::memory_order_release);
781 }
782
783 // Return true iff threads x and y are part of the same equivalence
784 // class of waiters. An equivalence class is defined as the set of
785 // waiters with the same condition, type of lock, and thread priority.
786 //
787 // Requires that x and y be waiting on the same Mutex queue.
MuEquivalentWaiter(PerThreadSynch * x,PerThreadSynch * y)788 static bool MuEquivalentWaiter(PerThreadSynch* x, PerThreadSynch* y) {
789 return x->waitp->how == y->waitp->how && x->priority == y->priority &&
790 Condition::GuaranteedEqual(x->waitp->cond, y->waitp->cond);
791 }
792
793 // Given the contents of a mutex word containing a PerThreadSynch pointer,
794 // return the pointer.
GetPerThreadSynch(intptr_t v)795 static inline PerThreadSynch* GetPerThreadSynch(intptr_t v) {
796 return reinterpret_cast<PerThreadSynch*>(v & kMuHigh);
797 }
798
799 // The next several routines maintain the per-thread next and skip fields
800 // used in the Mutex waiter queue.
801 // The queue is a circular singly-linked list, of which the "head" is the
802 // last element, and head->next if the first element.
803 // The skip field has the invariant:
804 // For thread x, x->skip is one of:
805 // - invalid (iff x is not in a Mutex wait queue),
806 // - null, or
807 // - a pointer to a distinct thread waiting later in the same Mutex queue
808 // such that all threads in [x, x->skip] have the same condition, priority
809 // and lock type (MuEquivalentWaiter() is true for all pairs in [x,
810 // x->skip]).
811 // In addition, if x->skip is valid, (x->may_skip || x->skip == null)
812 //
813 // By the spec of MuEquivalentWaiter(), it is not necessary when removing the
814 // first runnable thread y from the front a Mutex queue to adjust the skip
815 // field of another thread x because if x->skip==y, x->skip must (have) become
816 // invalid before y is removed. The function TryRemove can remove a specified
817 // thread from an arbitrary position in the queue whether runnable or not, so
818 // it fixes up skip fields that would otherwise be left dangling.
819 // The statement
820 // if (x->may_skip && MuEquivalentWaiter(x, x->next)) { x->skip = x->next; }
821 // maintains the invariant provided x is not the last waiter in a Mutex queue
822 // The statement
823 // if (x->skip != null) { x->skip = x->skip->skip; }
824 // maintains the invariant.
825
826 // Returns the last thread y in a mutex waiter queue such that all threads in
827 // [x, y] inclusive share the same condition. Sets skip fields of some threads
828 // in that range to optimize future evaluation of Skip() on x values in
829 // the range. Requires thread x is in a mutex waiter queue.
830 // The locking is unusual. Skip() is called under these conditions:
831 // - spinlock is held in call from Enqueue(), with maybe_unlocking == false
832 // - Mutex is held in call from UnlockSlow() by last unlocker, with
833 // maybe_unlocking == true
834 // - both Mutex and spinlock are held in call from DequeueAllWakeable() (from
835 // UnlockSlow()) and TryRemove()
836 // These cases are mutually exclusive, so Skip() never runs concurrently
837 // with itself on the same Mutex. The skip chain is used in these other places
838 // that cannot occur concurrently:
839 // - FixSkip() (from TryRemove()) - spinlock and Mutex are held)
840 // - Dequeue() (with spinlock and Mutex held)
841 // - UnlockSlow() (with spinlock and Mutex held)
842 // A more complex case is Enqueue()
843 // - Enqueue() (with spinlock held and maybe_unlocking == false)
844 // This is the first case in which Skip is called, above.
845 // - Enqueue() (without spinlock held; but queue is empty and being freshly
846 // formed)
847 // - Enqueue() (with spinlock held and maybe_unlocking == true)
848 // The first case has mutual exclusion, and the second isolation through
849 // working on an otherwise unreachable data structure.
850 // In the last case, Enqueue() is required to change no skip/next pointers
851 // except those in the added node and the former "head" node. This implies
852 // that the new node is added after head, and so must be the new head or the
853 // new front of the queue.
Skip(PerThreadSynch * x)854 static PerThreadSynch* Skip(PerThreadSynch* x) {
855 PerThreadSynch* x0 = nullptr;
856 PerThreadSynch* x1 = x;
857 PerThreadSynch* x2 = x->skip;
858 if (x2 != nullptr) {
859 // Each iteration attempts to advance sequence (x0,x1,x2) to next sequence
860 // such that x1 == x0->skip && x2 == x1->skip
861 while ((x0 = x1, x1 = x2, x2 = x2->skip) != nullptr) {
862 x0->skip = x2; // short-circuit skip from x0 to x2
863 }
864 x->skip = x1; // short-circuit skip from x to result
865 }
866 return x1;
867 }
868
869 // "ancestor" appears before "to_be_removed" in the same Mutex waiter queue.
870 // The latter is going to be removed out of order, because of a timeout.
871 // Check whether "ancestor" has a skip field pointing to "to_be_removed",
872 // and fix it if it does.
FixSkip(PerThreadSynch * ancestor,PerThreadSynch * to_be_removed)873 static void FixSkip(PerThreadSynch* ancestor, PerThreadSynch* to_be_removed) {
874 if (ancestor->skip == to_be_removed) { // ancestor->skip left dangling
875 if (to_be_removed->skip != nullptr) {
876 ancestor->skip = to_be_removed->skip; // can skip past to_be_removed
877 } else if (ancestor->next != to_be_removed) { // they are not adjacent
878 ancestor->skip = ancestor->next; // can skip one past ancestor
879 } else {
880 ancestor->skip = nullptr; // can't skip at all
881 }
882 }
883 }
884
885 static void CondVarEnqueue(SynchWaitParams* waitp);
886
887 // Enqueue thread "waitp->thread" on a waiter queue.
888 // Called with mutex spinlock held if head != nullptr
889 // If head==nullptr and waitp->cv_word==nullptr, then Enqueue() is
890 // idempotent; it alters no state associated with the existing (empty)
891 // queue.
892 //
893 // If waitp->cv_word == nullptr, queue the thread at either the front or
894 // the end (according to its priority) of the circular mutex waiter queue whose
895 // head is "head", and return the new head. mu is the previous mutex state,
896 // which contains the reader count (perhaps adjusted for the operation in
897 // progress) if the list was empty and a read lock held, and the holder hint if
898 // the list was empty and a write lock held. (flags & kMuIsCond) indicates
899 // whether this thread was transferred from a CondVar or is waiting for a
900 // non-trivial condition. In this case, Enqueue() never returns nullptr
901 //
902 // If waitp->cv_word != nullptr, CondVarEnqueue() is called, and "head" is
903 // returned. This mechanism is used by CondVar to queue a thread on the
904 // condition variable queue instead of the mutex queue in implementing Wait().
905 // In this case, Enqueue() can return nullptr (if head==nullptr).
Enqueue(PerThreadSynch * head,SynchWaitParams * waitp,intptr_t mu,int flags)906 static PerThreadSynch* Enqueue(PerThreadSynch* head, SynchWaitParams* waitp,
907 intptr_t mu, int flags) {
908 // If we have been given a cv_word, call CondVarEnqueue() and return
909 // the previous head of the Mutex waiter queue.
910 if (waitp->cv_word != nullptr) {
911 CondVarEnqueue(waitp);
912 return head;
913 }
914
915 PerThreadSynch* s = waitp->thread;
916 ABSL_RAW_CHECK(
917 s->waitp == nullptr || // normal case
918 s->waitp == waitp || // Fer()---transfer from condition variable
919 s->suppress_fatal_errors,
920 "detected illegal recursion into Mutex code");
921 s->waitp = waitp;
922 s->skip = nullptr; // maintain skip invariant (see above)
923 s->may_skip = true; // always true on entering queue
924 s->wake = false; // not being woken
925 s->cond_waiter = ((flags & kMuIsCond) != 0);
926 #ifdef ABSL_HAVE_PTHREAD_GETSCHEDPARAM
927 if ((flags & kMuIsFer) == 0) {
928 assert(s == Synch_GetPerThread());
929 int64_t now_cycles = CycleClock::Now();
930 if (s->next_priority_read_cycles < now_cycles) {
931 // Every so often, update our idea of the thread's priority.
932 // pthread_getschedparam() is 5% of the block/wakeup time;
933 // CycleClock::Now() is 0.5%.
934 int policy;
935 struct sched_param param;
936 const int err = pthread_getschedparam(pthread_self(), &policy, ¶m);
937 if (err != 0) {
938 ABSL_RAW_LOG(ERROR, "pthread_getschedparam failed: %d", err);
939 } else {
940 s->priority = param.sched_priority;
941 s->next_priority_read_cycles =
942 now_cycles + static_cast<int64_t>(CycleClock::Frequency());
943 }
944 }
945 }
946 #endif
947 if (head == nullptr) { // s is the only waiter
948 s->next = s; // it's the only entry in the cycle
949 s->readers = mu; // reader count is from mu word
950 s->maybe_unlocking = false; // no one is searching an empty list
951 head = s; // s is new head
952 } else {
953 PerThreadSynch* enqueue_after = nullptr; // we'll put s after this element
954 #ifdef ABSL_HAVE_PTHREAD_GETSCHEDPARAM
955 if (s->priority > head->priority) { // s's priority is above head's
956 // try to put s in priority-fifo order, or failing that at the front.
957 if (!head->maybe_unlocking) {
958 // No unlocker can be scanning the queue, so we can insert into the
959 // middle of the queue.
960 //
961 // Within a skip chain, all waiters have the same priority, so we can
962 // skip forward through the chains until we find one with a lower
963 // priority than the waiter to be enqueued.
964 PerThreadSynch* advance_to = head; // next value of enqueue_after
965 do {
966 enqueue_after = advance_to;
967 // (side-effect: optimizes skip chain)
968 advance_to = Skip(enqueue_after->next);
969 } while (s->priority <= advance_to->priority);
970 // termination guaranteed because s->priority > head->priority
971 // and head is the end of a skip chain
972 } else if (waitp->how == kExclusive && waitp->cond == nullptr) {
973 // An unlocker could be scanning the queue, but we know it will recheck
974 // the queue front for writers that have no condition, which is what s
975 // is, so an insert at front is safe.
976 enqueue_after = head; // add after head, at front
977 }
978 }
979 #endif
980 if (enqueue_after != nullptr) {
981 s->next = enqueue_after->next;
982 enqueue_after->next = s;
983
984 // enqueue_after can be: head, Skip(...), or cur.
985 // The first two imply enqueue_after->skip == nullptr, and
986 // the last is used only if MuEquivalentWaiter(s, cur).
987 // We require this because clearing enqueue_after->skip
988 // is impossible; enqueue_after's predecessors might also
989 // incorrectly skip over s if we were to allow other
990 // insertion points.
991 ABSL_RAW_CHECK(enqueue_after->skip == nullptr ||
992 MuEquivalentWaiter(enqueue_after, s),
993 "Mutex Enqueue failure");
994
995 if (enqueue_after != head && enqueue_after->may_skip &&
996 MuEquivalentWaiter(enqueue_after, enqueue_after->next)) {
997 // enqueue_after can skip to its new successor, s
998 enqueue_after->skip = enqueue_after->next;
999 }
1000 if (MuEquivalentWaiter(s, s->next)) { // s->may_skip is known to be true
1001 s->skip = s->next; // s may skip to its successor
1002 }
1003 } else if ((flags & kMuHasBlocked) &&
1004 (s->priority >= head->next->priority) &&
1005 (!head->maybe_unlocking ||
1006 (waitp->how == kExclusive &&
1007 Condition::GuaranteedEqual(waitp->cond, nullptr)))) {
1008 // This thread has already waited, then was woken, then failed to acquire
1009 // the mutex and now tries to requeue. Try to requeue it at head,
1010 // otherwise it can suffer bad latency (wait whole queue several times).
1011 // However, we need to be conservative. First, we need to ensure that we
1012 // respect priorities. Then, we need to be careful to not break wait
1013 // queue invariants: we require either that unlocker is not scanning
1014 // the queue or that the current thread is a writer with no condition
1015 // (unlocker will recheck the queue for such waiters).
1016 s->next = head->next;
1017 head->next = s;
1018 if (MuEquivalentWaiter(s, s->next)) { // s->may_skip is known to be true
1019 s->skip = s->next; // s may skip to its successor
1020 }
1021 } else { // enqueue not done any other way, so
1022 // we're inserting s at the back
1023 // s will become new head; copy data from head into it
1024 s->next = head->next; // add s after head
1025 head->next = s;
1026 s->readers = head->readers; // reader count is from previous head
1027 s->maybe_unlocking = head->maybe_unlocking; // same for unlock hint
1028 if (head->may_skip && MuEquivalentWaiter(head, s)) {
1029 // head now has successor; may skip
1030 head->skip = s;
1031 }
1032 head = s; // s is new head
1033 }
1034 }
1035 s->state.store(PerThreadSynch::kQueued, std::memory_order_relaxed);
1036 return head;
1037 }
1038
1039 // Dequeue the successor pw->next of thread pw from the Mutex waiter queue
1040 // whose last element is head. The new head element is returned, or null
1041 // if the list is made empty.
1042 // Dequeue is called with both spinlock and Mutex held.
Dequeue(PerThreadSynch * head,PerThreadSynch * pw)1043 static PerThreadSynch* Dequeue(PerThreadSynch* head, PerThreadSynch* pw) {
1044 PerThreadSynch* w = pw->next;
1045 pw->next = w->next; // snip w out of list
1046 if (head == w) { // we removed the head
1047 head = (pw == w) ? nullptr : pw; // either emptied list, or pw is new head
1048 } else if (pw != head && MuEquivalentWaiter(pw, pw->next)) {
1049 // pw can skip to its new successor
1050 if (pw->next->skip !=
1051 nullptr) { // either skip to its successors skip target
1052 pw->skip = pw->next->skip;
1053 } else { // or to pw's successor
1054 pw->skip = pw->next;
1055 }
1056 }
1057 return head;
1058 }
1059
1060 // Traverse the elements [ pw->next, h] of the circular list whose last element
1061 // is head.
1062 // Remove all elements with wake==true and place them in the
1063 // singly-linked list wake_list in the order found. Assumes that
1064 // there is only one such element if the element has how == kExclusive.
1065 // Return the new head.
DequeueAllWakeable(PerThreadSynch * head,PerThreadSynch * pw,PerThreadSynch ** wake_tail)1066 static PerThreadSynch* DequeueAllWakeable(PerThreadSynch* head,
1067 PerThreadSynch* pw,
1068 PerThreadSynch** wake_tail) {
1069 PerThreadSynch* orig_h = head;
1070 PerThreadSynch* w = pw->next;
1071 bool skipped = false;
1072 do {
1073 if (w->wake) { // remove this element
1074 ABSL_RAW_CHECK(pw->skip == nullptr, "bad skip in DequeueAllWakeable");
1075 // we're removing pw's successor so either pw->skip is zero or we should
1076 // already have removed pw since if pw->skip!=null, pw has the same
1077 // condition as w.
1078 head = Dequeue(head, pw);
1079 w->next = *wake_tail; // keep list terminated
1080 *wake_tail = w; // add w to wake_list;
1081 wake_tail = &w->next; // next addition to end
1082 if (w->waitp->how == kExclusive) { // wake at most 1 writer
1083 break;
1084 }
1085 } else { // not waking this one; skip
1086 pw = Skip(w); // skip as much as possible
1087 skipped = true;
1088 }
1089 w = pw->next;
1090 // We want to stop processing after we've considered the original head,
1091 // orig_h. We can't test for w==orig_h in the loop because w may skip over
1092 // it; we are guaranteed only that w's predecessor will not skip over
1093 // orig_h. When we've considered orig_h, either we've processed it and
1094 // removed it (so orig_h != head), or we considered it and skipped it (so
1095 // skipped==true && pw == head because skipping from head always skips by
1096 // just one, leaving pw pointing at head). So we want to
1097 // continue the loop with the negation of that expression.
1098 } while (orig_h == head && (pw != head || !skipped));
1099 return head;
1100 }
1101
1102 // Try to remove thread s from the list of waiters on this mutex.
1103 // Does nothing if s is not on the waiter list.
TryRemove(PerThreadSynch * s)1104 void Mutex::TryRemove(PerThreadSynch* s) {
1105 SchedulingGuard::ScopedDisable disable_rescheduling;
1106 intptr_t v = mu_.load(std::memory_order_relaxed);
1107 // acquire spinlock & lock
1108 if ((v & (kMuWait | kMuSpin | kMuWriter | kMuReader)) == kMuWait &&
1109 mu_.compare_exchange_strong(v, v | kMuSpin | kMuWriter,
1110 std::memory_order_acquire,
1111 std::memory_order_relaxed)) {
1112 PerThreadSynch* h = GetPerThreadSynch(v);
1113 if (h != nullptr) {
1114 PerThreadSynch* pw = h; // pw is w's predecessor
1115 PerThreadSynch* w;
1116 if ((w = pw->next) != s) { // search for thread,
1117 do { // processing at least one element
1118 // If the current element isn't equivalent to the waiter to be
1119 // removed, we can skip the entire chain.
1120 if (!MuEquivalentWaiter(s, w)) {
1121 pw = Skip(w); // so skip all that won't match
1122 // we don't have to worry about dangling skip fields
1123 // in the threads we skipped; none can point to s
1124 // because they are in a different equivalence class.
1125 } else { // seeking same condition
1126 FixSkip(w, s); // fix up any skip pointer from w to s
1127 pw = w;
1128 }
1129 // don't search further if we found the thread, or we're about to
1130 // process the first thread again.
1131 } while ((w = pw->next) != s && pw != h);
1132 }
1133 if (w == s) { // found thread; remove it
1134 // pw->skip may be non-zero here; the loop above ensured that
1135 // no ancestor of s can skip to s, so removal is safe anyway.
1136 h = Dequeue(h, pw);
1137 s->next = nullptr;
1138 s->state.store(PerThreadSynch::kAvailable, std::memory_order_release);
1139 }
1140 }
1141 intptr_t nv;
1142 do { // release spinlock and lock
1143 v = mu_.load(std::memory_order_relaxed);
1144 nv = v & (kMuDesig | kMuEvent);
1145 if (h != nullptr) {
1146 nv |= kMuWait | reinterpret_cast<intptr_t>(h);
1147 h->readers = 0; // we hold writer lock
1148 h->maybe_unlocking = false; // finished unlocking
1149 }
1150 } while (!mu_.compare_exchange_weak(v, nv, std::memory_order_release,
1151 std::memory_order_relaxed));
1152 }
1153 }
1154
1155 // Wait until thread "s", which must be the current thread, is removed from the
1156 // this mutex's waiter queue. If "s->waitp->timeout" has a timeout, wake up
1157 // if the wait extends past the absolute time specified, even if "s" is still
1158 // on the mutex queue. In this case, remove "s" from the queue and return
1159 // true, otherwise return false.
Block(PerThreadSynch * s)1160 void Mutex::Block(PerThreadSynch* s) {
1161 while (s->state.load(std::memory_order_acquire) == PerThreadSynch::kQueued) {
1162 if (!DecrementSynchSem(this, s, s->waitp->timeout)) {
1163 // After a timeout, we go into a spin loop until we remove ourselves
1164 // from the queue, or someone else removes us. We can't be sure to be
1165 // able to remove ourselves in a single lock acquisition because this
1166 // mutex may be held, and the holder has the right to read the centre
1167 // of the waiter queue without holding the spinlock.
1168 this->TryRemove(s);
1169 int c = 0;
1170 while (s->next != nullptr) {
1171 c = synchronization_internal::MutexDelay(c, GENTLE);
1172 this->TryRemove(s);
1173 }
1174 if (kDebugMode) {
1175 // This ensures that we test the case that TryRemove() is called when s
1176 // is not on the queue.
1177 this->TryRemove(s);
1178 }
1179 s->waitp->timeout = KernelTimeout::Never(); // timeout is satisfied
1180 s->waitp->cond = nullptr; // condition no longer relevant for wakeups
1181 }
1182 }
1183 ABSL_RAW_CHECK(s->waitp != nullptr || s->suppress_fatal_errors,
1184 "detected illegal recursion in Mutex code");
1185 s->waitp = nullptr;
1186 }
1187
1188 // Wake thread w, and return the next thread in the list.
Wakeup(PerThreadSynch * w)1189 PerThreadSynch* Mutex::Wakeup(PerThreadSynch* w) {
1190 PerThreadSynch* next = w->next;
1191 w->next = nullptr;
1192 w->state.store(PerThreadSynch::kAvailable, std::memory_order_release);
1193 IncrementSynchSem(this, w);
1194
1195 return next;
1196 }
1197
GetGraphIdLocked(Mutex * mu)1198 static GraphId GetGraphIdLocked(Mutex* mu)
1199 ABSL_EXCLUSIVE_LOCKS_REQUIRED(deadlock_graph_mu) {
1200 if (!deadlock_graph) { // (re)create the deadlock graph.
1201 deadlock_graph =
1202 new (base_internal::LowLevelAlloc::Alloc(sizeof(*deadlock_graph)))
1203 GraphCycles;
1204 }
1205 return deadlock_graph->GetId(mu);
1206 }
1207
GetGraphId(Mutex * mu)1208 static GraphId GetGraphId(Mutex* mu) ABSL_LOCKS_EXCLUDED(deadlock_graph_mu) {
1209 deadlock_graph_mu.Lock();
1210 GraphId id = GetGraphIdLocked(mu);
1211 deadlock_graph_mu.Unlock();
1212 return id;
1213 }
1214
1215 // Record a lock acquisition. This is used in debug mode for deadlock
1216 // detection. The held_locks pointer points to the relevant data
1217 // structure for each case.
LockEnter(Mutex * mu,GraphId id,SynchLocksHeld * held_locks)1218 static void LockEnter(Mutex* mu, GraphId id, SynchLocksHeld* held_locks) {
1219 int n = held_locks->n;
1220 int i = 0;
1221 while (i != n && held_locks->locks[i].id != id) {
1222 i++;
1223 }
1224 if (i == n) {
1225 if (n == ABSL_ARRAYSIZE(held_locks->locks)) {
1226 held_locks->overflow = true; // lost some data
1227 } else { // we have room for lock
1228 held_locks->locks[i].mu = mu;
1229 held_locks->locks[i].count = 1;
1230 held_locks->locks[i].id = id;
1231 held_locks->n = n + 1;
1232 }
1233 } else {
1234 held_locks->locks[i].count++;
1235 }
1236 }
1237
1238 // Record a lock release. Each call to LockEnter(mu, id, x) should be
1239 // eventually followed by a call to LockLeave(mu, id, x) by the same thread.
1240 // It does not process the event if is not needed when deadlock detection is
1241 // disabled.
LockLeave(Mutex * mu,GraphId id,SynchLocksHeld * held_locks)1242 static void LockLeave(Mutex* mu, GraphId id, SynchLocksHeld* held_locks) {
1243 int n = held_locks->n;
1244 int i = 0;
1245 while (i != n && held_locks->locks[i].id != id) {
1246 i++;
1247 }
1248 if (i == n) {
1249 if (!held_locks->overflow) {
1250 // The deadlock id may have been reassigned after ForgetDeadlockInfo,
1251 // but in that case mu should still be present.
1252 i = 0;
1253 while (i != n && held_locks->locks[i].mu != mu) {
1254 i++;
1255 }
1256 if (i == n) { // mu missing means releasing unheld lock
1257 SynchEvent* mu_events = GetSynchEvent(mu);
1258 ABSL_RAW_LOG(FATAL,
1259 "thread releasing lock it does not hold: %p %s; "
1260 ,
1261 static_cast<void*>(mu),
1262 mu_events == nullptr ? "" : mu_events->name);
1263 }
1264 }
1265 } else if (held_locks->locks[i].count == 1) {
1266 held_locks->n = n - 1;
1267 held_locks->locks[i] = held_locks->locks[n - 1];
1268 held_locks->locks[n - 1].id = InvalidGraphId();
1269 held_locks->locks[n - 1].mu =
1270 nullptr; // clear mu to please the leak detector.
1271 } else {
1272 assert(held_locks->locks[i].count > 0);
1273 held_locks->locks[i].count--;
1274 }
1275 }
1276
1277 // Call LockEnter() if in debug mode and deadlock detection is enabled.
DebugOnlyLockEnter(Mutex * mu)1278 static inline void DebugOnlyLockEnter(Mutex* mu) {
1279 if (kDebugMode) {
1280 if (synch_deadlock_detection.load(std::memory_order_acquire) !=
1281 OnDeadlockCycle::kIgnore) {
1282 LockEnter(mu, GetGraphId(mu), Synch_GetAllLocks());
1283 }
1284 }
1285 }
1286
1287 // Call LockEnter() if in debug mode and deadlock detection is enabled.
DebugOnlyLockEnter(Mutex * mu,GraphId id)1288 static inline void DebugOnlyLockEnter(Mutex* mu, GraphId id) {
1289 if (kDebugMode) {
1290 if (synch_deadlock_detection.load(std::memory_order_acquire) !=
1291 OnDeadlockCycle::kIgnore) {
1292 LockEnter(mu, id, Synch_GetAllLocks());
1293 }
1294 }
1295 }
1296
1297 // Call LockLeave() if in debug mode and deadlock detection is enabled.
DebugOnlyLockLeave(Mutex * mu)1298 static inline void DebugOnlyLockLeave(Mutex* mu) {
1299 if (kDebugMode) {
1300 if (synch_deadlock_detection.load(std::memory_order_acquire) !=
1301 OnDeadlockCycle::kIgnore) {
1302 LockLeave(mu, GetGraphId(mu), Synch_GetAllLocks());
1303 }
1304 }
1305 }
1306
StackString(void ** pcs,int n,char * buf,int maxlen,bool symbolize)1307 static char* StackString(void** pcs, int n, char* buf, int maxlen,
1308 bool symbolize) {
1309 static constexpr int kSymLen = 200;
1310 char sym[kSymLen];
1311 int len = 0;
1312 for (int i = 0; i != n; i++) {
1313 if (len >= maxlen)
1314 return buf;
1315 size_t count = static_cast<size_t>(maxlen - len);
1316 if (symbolize) {
1317 if (!absl::Symbolize(pcs[i], sym, kSymLen)) {
1318 sym[0] = '\0';
1319 }
1320 snprintf(buf + len, count, "%s\t@ %p %s\n", (i == 0 ? "\n" : ""), pcs[i],
1321 sym);
1322 } else {
1323 snprintf(buf + len, count, " %p", pcs[i]);
1324 }
1325 len += strlen(&buf[len]);
1326 }
1327 return buf;
1328 }
1329
CurrentStackString(char * buf,int maxlen,bool symbolize)1330 static char* CurrentStackString(char* buf, int maxlen, bool symbolize) {
1331 void* pcs[40];
1332 return StackString(pcs, absl::GetStackTrace(pcs, ABSL_ARRAYSIZE(pcs), 2), buf,
1333 maxlen, symbolize);
1334 }
1335
1336 namespace {
1337 enum {
1338 kMaxDeadlockPathLen = 10
1339 }; // maximum length of a deadlock cycle;
1340 // a path this long would be remarkable
1341 // Buffers required to report a deadlock.
1342 // We do not allocate them on stack to avoid large stack frame.
1343 struct DeadlockReportBuffers {
1344 char buf[6100];
1345 GraphId path[kMaxDeadlockPathLen];
1346 };
1347
1348 struct ScopedDeadlockReportBuffers {
ScopedDeadlockReportBuffersabsl::__anonde02e7400a11::ScopedDeadlockReportBuffers1349 ScopedDeadlockReportBuffers() {
1350 b = reinterpret_cast<DeadlockReportBuffers*>(
1351 base_internal::LowLevelAlloc::Alloc(sizeof(*b)));
1352 }
~ScopedDeadlockReportBuffersabsl::__anonde02e7400a11::ScopedDeadlockReportBuffers1353 ~ScopedDeadlockReportBuffers() { base_internal::LowLevelAlloc::Free(b); }
1354 DeadlockReportBuffers* b;
1355 };
1356
1357 // Helper to pass to GraphCycles::UpdateStackTrace.
GetStack(void ** stack,int max_depth)1358 int GetStack(void** stack, int max_depth) {
1359 return absl::GetStackTrace(stack, max_depth, 3);
1360 }
1361 } // anonymous namespace
1362
1363 // Called in debug mode when a thread is about to acquire a lock in a way that
1364 // may block.
DeadlockCheck(Mutex * mu)1365 static GraphId DeadlockCheck(Mutex* mu) {
1366 if (synch_deadlock_detection.load(std::memory_order_acquire) ==
1367 OnDeadlockCycle::kIgnore) {
1368 return InvalidGraphId();
1369 }
1370
1371 SynchLocksHeld* all_locks = Synch_GetAllLocks();
1372
1373 absl::base_internal::SpinLockHolder lock(&deadlock_graph_mu);
1374 const GraphId mu_id = GetGraphIdLocked(mu);
1375
1376 if (all_locks->n == 0) {
1377 // There are no other locks held. Return now so that we don't need to
1378 // call GetSynchEvent(). This way we do not record the stack trace
1379 // for this Mutex. It's ok, since if this Mutex is involved in a deadlock,
1380 // it can't always be the first lock acquired by a thread.
1381 return mu_id;
1382 }
1383
1384 // We prefer to keep stack traces that show a thread holding and acquiring
1385 // as many locks as possible. This increases the chances that a given edge
1386 // in the acquires-before graph will be represented in the stack traces
1387 // recorded for the locks.
1388 deadlock_graph->UpdateStackTrace(mu_id, all_locks->n + 1, GetStack);
1389
1390 // For each other mutex already held by this thread:
1391 for (int i = 0; i != all_locks->n; i++) {
1392 const GraphId other_node_id = all_locks->locks[i].id;
1393 const Mutex* other =
1394 static_cast<const Mutex*>(deadlock_graph->Ptr(other_node_id));
1395 if (other == nullptr) {
1396 // Ignore stale lock
1397 continue;
1398 }
1399
1400 // Add the acquired-before edge to the graph.
1401 if (!deadlock_graph->InsertEdge(other_node_id, mu_id)) {
1402 ScopedDeadlockReportBuffers scoped_buffers;
1403 DeadlockReportBuffers* b = scoped_buffers.b;
1404 static int number_of_reported_deadlocks = 0;
1405 number_of_reported_deadlocks++;
1406 // Symbolize only 2 first deadlock report to avoid huge slowdowns.
1407 bool symbolize = number_of_reported_deadlocks <= 2;
1408 ABSL_RAW_LOG(ERROR, "Potential Mutex deadlock: %s",
1409 CurrentStackString(b->buf, sizeof (b->buf), symbolize));
1410 size_t len = 0;
1411 for (int j = 0; j != all_locks->n; j++) {
1412 void* pr = deadlock_graph->Ptr(all_locks->locks[j].id);
1413 if (pr != nullptr) {
1414 snprintf(b->buf + len, sizeof(b->buf) - len, " %p", pr);
1415 len += strlen(&b->buf[len]);
1416 }
1417 }
1418 ABSL_RAW_LOG(ERROR,
1419 "Acquiring absl::Mutex %p while holding %s; a cycle in the "
1420 "historical lock ordering graph has been observed",
1421 static_cast<void*>(mu), b->buf);
1422 ABSL_RAW_LOG(ERROR, "Cycle: ");
1423 int path_len = deadlock_graph->FindPath(mu_id, other_node_id,
1424 ABSL_ARRAYSIZE(b->path), b->path);
1425 for (int j = 0; j != path_len && j != ABSL_ARRAYSIZE(b->path); j++) {
1426 GraphId id = b->path[j];
1427 Mutex* path_mu = static_cast<Mutex*>(deadlock_graph->Ptr(id));
1428 if (path_mu == nullptr) continue;
1429 void** stack;
1430 int depth = deadlock_graph->GetStackTrace(id, &stack);
1431 snprintf(b->buf, sizeof(b->buf),
1432 "mutex@%p stack: ", static_cast<void*>(path_mu));
1433 StackString(stack, depth, b->buf + strlen(b->buf),
1434 static_cast<int>(sizeof(b->buf) - strlen(b->buf)),
1435 symbolize);
1436 ABSL_RAW_LOG(ERROR, "%s", b->buf);
1437 }
1438 if (path_len > static_cast<int>(ABSL_ARRAYSIZE(b->path))) {
1439 ABSL_RAW_LOG(ERROR, "(long cycle; list truncated)");
1440 }
1441 if (synch_deadlock_detection.load(std::memory_order_acquire) ==
1442 OnDeadlockCycle::kAbort) {
1443 deadlock_graph_mu.Unlock(); // avoid deadlock in fatal sighandler
1444 ABSL_RAW_LOG(FATAL, "dying due to potential deadlock");
1445 return mu_id;
1446 }
1447 break; // report at most one potential deadlock per acquisition
1448 }
1449 }
1450
1451 return mu_id;
1452 }
1453
1454 // Invoke DeadlockCheck() iff we're in debug mode and
1455 // deadlock checking has been enabled.
DebugOnlyDeadlockCheck(Mutex * mu)1456 static inline GraphId DebugOnlyDeadlockCheck(Mutex* mu) {
1457 if (kDebugMode && synch_deadlock_detection.load(std::memory_order_acquire) !=
1458 OnDeadlockCycle::kIgnore) {
1459 return DeadlockCheck(mu);
1460 } else {
1461 return InvalidGraphId();
1462 }
1463 }
1464
ForgetDeadlockInfo()1465 void Mutex::ForgetDeadlockInfo() {
1466 if (kDebugMode && synch_deadlock_detection.load(std::memory_order_acquire) !=
1467 OnDeadlockCycle::kIgnore) {
1468 deadlock_graph_mu.Lock();
1469 if (deadlock_graph != nullptr) {
1470 deadlock_graph->RemoveNode(this);
1471 }
1472 deadlock_graph_mu.Unlock();
1473 }
1474 }
1475
AssertNotHeld() const1476 void Mutex::AssertNotHeld() const {
1477 // We have the data to allow this check only if in debug mode and deadlock
1478 // detection is enabled.
1479 if (kDebugMode &&
1480 (mu_.load(std::memory_order_relaxed) & (kMuWriter | kMuReader)) != 0 &&
1481 synch_deadlock_detection.load(std::memory_order_acquire) !=
1482 OnDeadlockCycle::kIgnore) {
1483 GraphId id = GetGraphId(const_cast<Mutex*>(this));
1484 SynchLocksHeld* locks = Synch_GetAllLocks();
1485 for (int i = 0; i != locks->n; i++) {
1486 if (locks->locks[i].id == id) {
1487 SynchEvent* mu_events = GetSynchEvent(this);
1488 ABSL_RAW_LOG(FATAL, "thread should not hold mutex %p %s",
1489 static_cast<const void*>(this),
1490 (mu_events == nullptr ? "" : mu_events->name));
1491 }
1492 }
1493 }
1494 }
1495
1496 // Attempt to acquire *mu, and return whether successful. The implementation
1497 // may spin for a short while if the lock cannot be acquired immediately.
TryAcquireWithSpinning(std::atomic<intptr_t> * mu)1498 static bool TryAcquireWithSpinning(std::atomic<intptr_t>* mu) {
1499 int c = globals.spinloop_iterations.load(std::memory_order_relaxed);
1500 do { // do/while somewhat faster on AMD
1501 intptr_t v = mu->load(std::memory_order_relaxed);
1502 if ((v & (kMuReader | kMuEvent)) != 0) {
1503 return false; // a reader or tracing -> give up
1504 } else if (((v & kMuWriter) == 0) && // no holder -> try to acquire
1505 mu->compare_exchange_strong(v, kMuWriter | v,
1506 std::memory_order_acquire,
1507 std::memory_order_relaxed)) {
1508 return true;
1509 }
1510 } while (--c > 0);
1511 return false;
1512 }
1513
Lock()1514 void Mutex::Lock() {
1515 ABSL_TSAN_MUTEX_PRE_LOCK(this, 0);
1516 GraphId id = DebugOnlyDeadlockCheck(this);
1517 intptr_t v = mu_.load(std::memory_order_relaxed);
1518 // try fast acquire, then spin loop
1519 if (ABSL_PREDICT_FALSE((v & (kMuWriter | kMuReader | kMuEvent)) != 0) ||
1520 ABSL_PREDICT_FALSE(!mu_.compare_exchange_strong(
1521 v, kMuWriter | v, std::memory_order_acquire,
1522 std::memory_order_relaxed))) {
1523 // try spin acquire, then slow loop
1524 if (ABSL_PREDICT_FALSE(!TryAcquireWithSpinning(&this->mu_))) {
1525 this->LockSlow(kExclusive, nullptr, 0);
1526 }
1527 }
1528 DebugOnlyLockEnter(this, id);
1529 ABSL_TSAN_MUTEX_POST_LOCK(this, 0, 0);
1530 }
1531
ReaderLock()1532 void Mutex::ReaderLock() {
1533 ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_read_lock);
1534 GraphId id = DebugOnlyDeadlockCheck(this);
1535 intptr_t v = mu_.load(std::memory_order_relaxed);
1536 for (;;) {
1537 // If there are non-readers holding the lock, use the slow loop.
1538 if (ABSL_PREDICT_FALSE(v & (kMuWriter | kMuWait | kMuEvent)) != 0) {
1539 this->LockSlow(kShared, nullptr, 0);
1540 break;
1541 }
1542 // We can avoid the loop and only use the CAS when the lock is free or
1543 // only held by readers.
1544 if (ABSL_PREDICT_TRUE(mu_.compare_exchange_strong(
1545 v, (kMuReader | v) + kMuOne, std::memory_order_acquire,
1546 std::memory_order_relaxed))) {
1547 break;
1548 }
1549 }
1550 DebugOnlyLockEnter(this, id);
1551 ABSL_TSAN_MUTEX_POST_LOCK(this, __tsan_mutex_read_lock, 0);
1552 }
1553
LockWhenCommon(const Condition & cond,synchronization_internal::KernelTimeout t,bool write)1554 bool Mutex::LockWhenCommon(const Condition& cond,
1555 synchronization_internal::KernelTimeout t,
1556 bool write) {
1557 MuHow how = write ? kExclusive : kShared;
1558 ABSL_TSAN_MUTEX_PRE_LOCK(this, TsanFlags(how));
1559 GraphId id = DebugOnlyDeadlockCheck(this);
1560 bool res = LockSlowWithDeadline(how, &cond, t, 0);
1561 DebugOnlyLockEnter(this, id);
1562 ABSL_TSAN_MUTEX_POST_LOCK(this, TsanFlags(how), 0);
1563 return res;
1564 }
1565
AwaitCommon(const Condition & cond,KernelTimeout t)1566 bool Mutex::AwaitCommon(const Condition& cond, KernelTimeout t) {
1567 if (kDebugMode) {
1568 this->AssertReaderHeld();
1569 }
1570 if (cond.Eval()) { // condition already true; nothing to do
1571 return true;
1572 }
1573 MuHow how =
1574 (mu_.load(std::memory_order_relaxed) & kMuWriter) ? kExclusive : kShared;
1575 ABSL_TSAN_MUTEX_PRE_UNLOCK(this, TsanFlags(how));
1576 SynchWaitParams waitp(how, &cond, t, nullptr /*no cvmu*/,
1577 Synch_GetPerThreadAnnotated(this),
1578 nullptr /*no cv_word*/);
1579 this->UnlockSlow(&waitp);
1580 this->Block(waitp.thread);
1581 ABSL_TSAN_MUTEX_POST_UNLOCK(this, TsanFlags(how));
1582 ABSL_TSAN_MUTEX_PRE_LOCK(this, TsanFlags(how));
1583 this->LockSlowLoop(&waitp, kMuHasBlocked | kMuIsCond);
1584 bool res = waitp.cond != nullptr || // => cond known true from LockSlowLoop
1585 EvalConditionAnnotated(&cond, this, true, false, how == kShared);
1586 ABSL_TSAN_MUTEX_POST_LOCK(this, TsanFlags(how), 0);
1587 ABSL_RAW_CHECK(res || t.has_timeout(),
1588 "condition untrue on return from Await");
1589 return res;
1590 }
1591
TryLock()1592 bool Mutex::TryLock() {
1593 ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_try_lock);
1594 intptr_t v = mu_.load(std::memory_order_relaxed);
1595 // Try fast acquire.
1596 if (ABSL_PREDICT_TRUE((v & (kMuWriter | kMuReader | kMuEvent)) == 0)) {
1597 if (ABSL_PREDICT_TRUE(mu_.compare_exchange_strong(
1598 v, kMuWriter | v, std::memory_order_acquire,
1599 std::memory_order_relaxed))) {
1600 DebugOnlyLockEnter(this);
1601 ABSL_TSAN_MUTEX_POST_LOCK(this, __tsan_mutex_try_lock, 0);
1602 return true;
1603 }
1604 } else if (ABSL_PREDICT_FALSE((v & kMuEvent) != 0)) {
1605 // We're recording events.
1606 return TryLockSlow();
1607 }
1608 ABSL_TSAN_MUTEX_POST_LOCK(
1609 this, __tsan_mutex_try_lock | __tsan_mutex_try_lock_failed, 0);
1610 return false;
1611 }
1612
TryLockSlow()1613 ABSL_ATTRIBUTE_NOINLINE bool Mutex::TryLockSlow() {
1614 intptr_t v = mu_.load(std::memory_order_relaxed);
1615 if ((v & kExclusive->slow_need_zero) == 0 && // try fast acquire
1616 mu_.compare_exchange_strong(
1617 v, (kExclusive->fast_or | v) + kExclusive->fast_add,
1618 std::memory_order_acquire, std::memory_order_relaxed)) {
1619 DebugOnlyLockEnter(this);
1620 PostSynchEvent(this, SYNCH_EV_TRYLOCK_SUCCESS);
1621 ABSL_TSAN_MUTEX_POST_LOCK(this, __tsan_mutex_try_lock, 0);
1622 return true;
1623 }
1624 PostSynchEvent(this, SYNCH_EV_TRYLOCK_FAILED);
1625 ABSL_TSAN_MUTEX_POST_LOCK(
1626 this, __tsan_mutex_try_lock | __tsan_mutex_try_lock_failed, 0);
1627 return false;
1628 }
1629
ReaderTryLock()1630 bool Mutex::ReaderTryLock() {
1631 ABSL_TSAN_MUTEX_PRE_LOCK(this,
1632 __tsan_mutex_read_lock | __tsan_mutex_try_lock);
1633 intptr_t v = mu_.load(std::memory_order_relaxed);
1634 // Clang tends to unroll the loop when compiling with optimization.
1635 // But in this case it just unnecessary increases code size.
1636 // If CAS is failing due to contention, the jump cost is negligible.
1637 #if defined(__clang__)
1638 #pragma nounroll
1639 #endif
1640 // The while-loops (here and below) iterate only if the mutex word keeps
1641 // changing (typically because the reader count changes) under the CAS.
1642 // We limit the number of attempts to avoid having to think about livelock.
1643 for (int loop_limit = 5; loop_limit != 0; loop_limit--) {
1644 if (ABSL_PREDICT_FALSE((v & (kMuWriter | kMuWait | kMuEvent)) != 0)) {
1645 break;
1646 }
1647 if (ABSL_PREDICT_TRUE(mu_.compare_exchange_strong(
1648 v, (kMuReader | v) + kMuOne, std::memory_order_acquire,
1649 std::memory_order_relaxed))) {
1650 DebugOnlyLockEnter(this);
1651 ABSL_TSAN_MUTEX_POST_LOCK(
1652 this, __tsan_mutex_read_lock | __tsan_mutex_try_lock, 0);
1653 return true;
1654 }
1655 }
1656 if (ABSL_PREDICT_TRUE((v & kMuEvent) == 0)) {
1657 ABSL_TSAN_MUTEX_POST_LOCK(this,
1658 __tsan_mutex_read_lock | __tsan_mutex_try_lock |
1659 __tsan_mutex_try_lock_failed,
1660 0);
1661 return false;
1662 }
1663 // we're recording events
1664 return ReaderTryLockSlow();
1665 }
1666
ReaderTryLockSlow()1667 ABSL_ATTRIBUTE_NOINLINE bool Mutex::ReaderTryLockSlow() {
1668 intptr_t v = mu_.load(std::memory_order_relaxed);
1669 #if defined(__clang__)
1670 #pragma nounroll
1671 #endif
1672 for (int loop_limit = 5; loop_limit != 0; loop_limit--) {
1673 if ((v & kShared->slow_need_zero) == 0 &&
1674 mu_.compare_exchange_strong(v, (kMuReader | v) + kMuOne,
1675 std::memory_order_acquire,
1676 std::memory_order_relaxed)) {
1677 DebugOnlyLockEnter(this);
1678 PostSynchEvent(this, SYNCH_EV_READERTRYLOCK_SUCCESS);
1679 ABSL_TSAN_MUTEX_POST_LOCK(
1680 this, __tsan_mutex_read_lock | __tsan_mutex_try_lock, 0);
1681 return true;
1682 }
1683 }
1684 PostSynchEvent(this, SYNCH_EV_READERTRYLOCK_FAILED);
1685 ABSL_TSAN_MUTEX_POST_LOCK(this,
1686 __tsan_mutex_read_lock | __tsan_mutex_try_lock |
1687 __tsan_mutex_try_lock_failed,
1688 0);
1689 return false;
1690 }
1691
Unlock()1692 void Mutex::Unlock() {
1693 ABSL_TSAN_MUTEX_PRE_UNLOCK(this, 0);
1694 DebugOnlyLockLeave(this);
1695 intptr_t v = mu_.load(std::memory_order_relaxed);
1696
1697 if (kDebugMode && ((v & (kMuWriter | kMuReader)) != kMuWriter)) {
1698 ABSL_RAW_LOG(FATAL, "Mutex unlocked when destroyed or not locked: v=0x%x",
1699 static_cast<unsigned>(v));
1700 }
1701
1702 // should_try_cas is whether we'll try a compare-and-swap immediately.
1703 // NOTE: optimized out when kDebugMode is false.
1704 bool should_try_cas = ((v & (kMuEvent | kMuWriter)) == kMuWriter &&
1705 (v & (kMuWait | kMuDesig)) != kMuWait);
1706 // But, we can use an alternate computation of it, that compilers
1707 // currently don't find on their own. When that changes, this function
1708 // can be simplified.
1709 intptr_t x = (v ^ (kMuWriter | kMuWait)) & (kMuWriter | kMuEvent);
1710 intptr_t y = (v ^ (kMuWriter | kMuWait)) & (kMuWait | kMuDesig);
1711 // Claim: "x == 0 && y > 0" is equal to should_try_cas.
1712 // Also, because kMuWriter and kMuEvent exceed kMuDesig and kMuWait,
1713 // all possible non-zero values for x exceed all possible values for y.
1714 // Therefore, (x == 0 && y > 0) == (x < y).
1715 if (kDebugMode && should_try_cas != (x < y)) {
1716 // We would usually use PRIdPTR here, but is not correctly implemented
1717 // within the android toolchain.
1718 ABSL_RAW_LOG(FATAL, "internal logic error %llx %llx %llx\n",
1719 static_cast<long long>(v), static_cast<long long>(x),
1720 static_cast<long long>(y));
1721 }
1722 if (x < y && mu_.compare_exchange_strong(v, v & ~(kMuWrWait | kMuWriter),
1723 std::memory_order_release,
1724 std::memory_order_relaxed)) {
1725 // fast writer release (writer with no waiters or with designated waker)
1726 } else {
1727 this->UnlockSlow(nullptr /*no waitp*/); // take slow path
1728 }
1729 ABSL_TSAN_MUTEX_POST_UNLOCK(this, 0);
1730 }
1731
1732 // Requires v to represent a reader-locked state.
ExactlyOneReader(intptr_t v)1733 static bool ExactlyOneReader(intptr_t v) {
1734 assert((v & (kMuWriter | kMuReader)) == kMuReader);
1735 assert((v & kMuHigh) != 0);
1736 // The more straightforward "(v & kMuHigh) == kMuOne" also works, but
1737 // on some architectures the following generates slightly smaller code.
1738 // It may be faster too.
1739 constexpr intptr_t kMuMultipleWaitersMask = kMuHigh ^ kMuOne;
1740 return (v & kMuMultipleWaitersMask) == 0;
1741 }
1742
ReaderUnlock()1743 void Mutex::ReaderUnlock() {
1744 ABSL_TSAN_MUTEX_PRE_UNLOCK(this, __tsan_mutex_read_lock);
1745 DebugOnlyLockLeave(this);
1746 intptr_t v = mu_.load(std::memory_order_relaxed);
1747 assert((v & (kMuWriter | kMuReader)) == kMuReader);
1748 for (;;) {
1749 if (ABSL_PREDICT_FALSE((v & (kMuReader | kMuWait | kMuEvent)) !=
1750 kMuReader)) {
1751 this->UnlockSlow(nullptr /*no waitp*/); // take slow path
1752 break;
1753 }
1754 // fast reader release (reader with no waiters)
1755 intptr_t clear = ExactlyOneReader(v) ? kMuReader | kMuOne : kMuOne;
1756 if (ABSL_PREDICT_TRUE(
1757 mu_.compare_exchange_strong(v, v - clear, std::memory_order_release,
1758 std::memory_order_relaxed))) {
1759 break;
1760 }
1761 }
1762 ABSL_TSAN_MUTEX_POST_UNLOCK(this, __tsan_mutex_read_lock);
1763 }
1764
1765 // Clears the designated waker flag in the mutex if this thread has blocked, and
1766 // therefore may be the designated waker.
ClearDesignatedWakerMask(int flag)1767 static intptr_t ClearDesignatedWakerMask(int flag) {
1768 assert(flag >= 0);
1769 assert(flag <= 1);
1770 switch (flag) {
1771 case 0: // not blocked
1772 return ~static_cast<intptr_t>(0);
1773 case 1: // blocked; turn off the designated waker bit
1774 return ~static_cast<intptr_t>(kMuDesig);
1775 }
1776 ABSL_UNREACHABLE();
1777 }
1778
1779 // Conditionally ignores the existence of waiting writers if a reader that has
1780 // already blocked once wakes up.
IgnoreWaitingWritersMask(int flag)1781 static intptr_t IgnoreWaitingWritersMask(int flag) {
1782 assert(flag >= 0);
1783 assert(flag <= 1);
1784 switch (flag) {
1785 case 0: // not blocked
1786 return ~static_cast<intptr_t>(0);
1787 case 1: // blocked; pretend there are no waiting writers
1788 return ~static_cast<intptr_t>(kMuWrWait);
1789 }
1790 ABSL_UNREACHABLE();
1791 }
1792
1793 // Internal version of LockWhen(). See LockSlowWithDeadline()
LockSlow(MuHow how,const Condition * cond,int flags)1794 ABSL_ATTRIBUTE_NOINLINE void Mutex::LockSlow(MuHow how, const Condition* cond,
1795 int flags) {
1796 // Note: we specifically initialize spinloop_iterations after the first use
1797 // in TryAcquireWithSpinning so that Lock function does not have any non-tail
1798 // calls and consequently a stack frame. It's fine to have spinloop_iterations
1799 // uninitialized (meaning no spinning) in all initial uncontended Lock calls
1800 // and in the first contended call. After that we will have
1801 // spinloop_iterations properly initialized.
1802 if (ABSL_PREDICT_FALSE(
1803 globals.spinloop_iterations.load(std::memory_order_relaxed) == 0)) {
1804 if (absl::base_internal::NumCPUs() > 1) {
1805 // If this is multiprocessor, allow spinning.
1806 globals.spinloop_iterations.store(1500, std::memory_order_relaxed);
1807 } else {
1808 // If this a uniprocessor, only yield/sleep.
1809 globals.spinloop_iterations.store(-1, std::memory_order_relaxed);
1810 }
1811 }
1812 ABSL_RAW_CHECK(
1813 this->LockSlowWithDeadline(how, cond, KernelTimeout::Never(), flags),
1814 "condition untrue on return from LockSlow");
1815 }
1816
1817 // Compute cond->Eval() and tell race detectors that we do it under mutex mu.
EvalConditionAnnotated(const Condition * cond,Mutex * mu,bool locking,bool trylock,bool read_lock)1818 static inline bool EvalConditionAnnotated(const Condition* cond, Mutex* mu,
1819 bool locking, bool trylock,
1820 bool read_lock) {
1821 // Delicate annotation dance.
1822 // We are currently inside of read/write lock/unlock operation.
1823 // All memory accesses are ignored inside of mutex operations + for unlock
1824 // operation tsan considers that we've already released the mutex.
1825 bool res = false;
1826 #ifdef ABSL_INTERNAL_HAVE_TSAN_INTERFACE
1827 const uint32_t flags = read_lock ? __tsan_mutex_read_lock : 0;
1828 const uint32_t tryflags = flags | (trylock ? __tsan_mutex_try_lock : 0);
1829 #endif
1830 if (locking) {
1831 // For lock we pretend that we have finished the operation,
1832 // evaluate the predicate, then unlock the mutex and start locking it again
1833 // to match the annotation at the end of outer lock operation.
1834 // Note: we can't simply do POST_LOCK, Eval, PRE_LOCK, because then tsan
1835 // will think the lock acquisition is recursive which will trigger
1836 // deadlock detector.
1837 ABSL_TSAN_MUTEX_POST_LOCK(mu, tryflags, 0);
1838 res = cond->Eval();
1839 // There is no "try" version of Unlock, so use flags instead of tryflags.
1840 ABSL_TSAN_MUTEX_PRE_UNLOCK(mu, flags);
1841 ABSL_TSAN_MUTEX_POST_UNLOCK(mu, flags);
1842 ABSL_TSAN_MUTEX_PRE_LOCK(mu, tryflags);
1843 } else {
1844 // Similarly, for unlock we pretend that we have unlocked the mutex,
1845 // lock the mutex, evaluate the predicate, and start unlocking it again
1846 // to match the annotation at the end of outer unlock operation.
1847 ABSL_TSAN_MUTEX_POST_UNLOCK(mu, flags);
1848 ABSL_TSAN_MUTEX_PRE_LOCK(mu, flags);
1849 ABSL_TSAN_MUTEX_POST_LOCK(mu, flags, 0);
1850 res = cond->Eval();
1851 ABSL_TSAN_MUTEX_PRE_UNLOCK(mu, flags);
1852 }
1853 // Prevent unused param warnings in non-TSAN builds.
1854 static_cast<void>(mu);
1855 static_cast<void>(trylock);
1856 static_cast<void>(read_lock);
1857 return res;
1858 }
1859
1860 // Compute cond->Eval() hiding it from race detectors.
1861 // We are hiding it because inside of UnlockSlow we can evaluate a predicate
1862 // that was just added by a concurrent Lock operation; Lock adds the predicate
1863 // to the internal Mutex list without actually acquiring the Mutex
1864 // (it only acquires the internal spinlock, which is rightfully invisible for
1865 // tsan). As the result there is no tsan-visible synchronization between the
1866 // addition and this thread. So if we would enable race detection here,
1867 // it would race with the predicate initialization.
EvalConditionIgnored(Mutex * mu,const Condition * cond)1868 static inline bool EvalConditionIgnored(Mutex* mu, const Condition* cond) {
1869 // Memory accesses are already ignored inside of lock/unlock operations,
1870 // but synchronization operations are also ignored. When we evaluate the
1871 // predicate we must ignore only memory accesses but not synchronization,
1872 // because missed synchronization can lead to false reports later.
1873 // So we "divert" (which un-ignores both memory accesses and synchronization)
1874 // and then separately turn on ignores of memory accesses.
1875 ABSL_TSAN_MUTEX_PRE_DIVERT(mu, 0);
1876 ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN();
1877 bool res = cond->Eval();
1878 ABSL_ANNOTATE_IGNORE_READS_AND_WRITES_END();
1879 ABSL_TSAN_MUTEX_POST_DIVERT(mu, 0);
1880 static_cast<void>(mu); // Prevent unused param warning in non-TSAN builds.
1881 return res;
1882 }
1883
1884 // Internal equivalent of *LockWhenWithDeadline(), where
1885 // "t" represents the absolute timeout; !t.has_timeout() means "forever".
1886 // "how" is "kShared" (for ReaderLockWhen) or "kExclusive" (for LockWhen)
1887 // In flags, bits are ored together:
1888 // - kMuHasBlocked indicates that the client has already blocked on the call so
1889 // the designated waker bit must be cleared and waiting writers should not
1890 // obstruct this call
1891 // - kMuIsCond indicates that this is a conditional acquire (condition variable,
1892 // Await, LockWhen) so contention profiling should be suppressed.
LockSlowWithDeadline(MuHow how,const Condition * cond,KernelTimeout t,int flags)1893 bool Mutex::LockSlowWithDeadline(MuHow how, const Condition* cond,
1894 KernelTimeout t, int flags) {
1895 intptr_t v = mu_.load(std::memory_order_relaxed);
1896 bool unlock = false;
1897 if ((v & how->fast_need_zero) == 0 && // try fast acquire
1898 mu_.compare_exchange_strong(
1899 v,
1900 (how->fast_or |
1901 (v & ClearDesignatedWakerMask(flags & kMuHasBlocked))) +
1902 how->fast_add,
1903 std::memory_order_acquire, std::memory_order_relaxed)) {
1904 if (cond == nullptr ||
1905 EvalConditionAnnotated(cond, this, true, false, how == kShared)) {
1906 return true;
1907 }
1908 unlock = true;
1909 }
1910 SynchWaitParams waitp(how, cond, t, nullptr /*no cvmu*/,
1911 Synch_GetPerThreadAnnotated(this),
1912 nullptr /*no cv_word*/);
1913 if (cond != nullptr) {
1914 flags |= kMuIsCond;
1915 }
1916 if (unlock) {
1917 this->UnlockSlow(&waitp);
1918 this->Block(waitp.thread);
1919 flags |= kMuHasBlocked;
1920 }
1921 this->LockSlowLoop(&waitp, flags);
1922 return waitp.cond != nullptr || // => cond known true from LockSlowLoop
1923 cond == nullptr ||
1924 EvalConditionAnnotated(cond, this, true, false, how == kShared);
1925 }
1926
1927 // RAW_CHECK_FMT() takes a condition, a printf-style format string, and
1928 // the printf-style argument list. The format string must be a literal.
1929 // Arguments after the first are not evaluated unless the condition is true.
1930 #define RAW_CHECK_FMT(cond, ...) \
1931 do { \
1932 if (ABSL_PREDICT_FALSE(!(cond))) { \
1933 ABSL_RAW_LOG(FATAL, "Check " #cond " failed: " __VA_ARGS__); \
1934 } \
1935 } while (0)
1936
CheckForMutexCorruption(intptr_t v,const char * label)1937 static void CheckForMutexCorruption(intptr_t v, const char* label) {
1938 // Test for either of two situations that should not occur in v:
1939 // kMuWriter and kMuReader
1940 // kMuWrWait and !kMuWait
1941 const uintptr_t w = static_cast<uintptr_t>(v ^ kMuWait);
1942 // By flipping that bit, we can now test for:
1943 // kMuWriter and kMuReader in w
1944 // kMuWrWait and kMuWait in w
1945 // We've chosen these two pairs of values to be so that they will overlap,
1946 // respectively, when the word is left shifted by three. This allows us to
1947 // save a branch in the common (correct) case of them not being coincident.
1948 static_assert(kMuReader << 3 == kMuWriter, "must match");
1949 static_assert(kMuWait << 3 == kMuWrWait, "must match");
1950 if (ABSL_PREDICT_TRUE((w & (w << 3) & (kMuWriter | kMuWrWait)) == 0)) return;
1951 RAW_CHECK_FMT((v & (kMuWriter | kMuReader)) != (kMuWriter | kMuReader),
1952 "%s: Mutex corrupt: both reader and writer lock held: %p",
1953 label, reinterpret_cast<void*>(v));
1954 RAW_CHECK_FMT((v & (kMuWait | kMuWrWait)) != kMuWrWait,
1955 "%s: Mutex corrupt: waiting writer with no waiters: %p", label,
1956 reinterpret_cast<void*>(v));
1957 assert(false);
1958 }
1959
LockSlowLoop(SynchWaitParams * waitp,int flags)1960 void Mutex::LockSlowLoop(SynchWaitParams* waitp, int flags) {
1961 SchedulingGuard::ScopedDisable disable_rescheduling;
1962 int c = 0;
1963 intptr_t v = mu_.load(std::memory_order_relaxed);
1964 if ((v & kMuEvent) != 0) {
1965 PostSynchEvent(
1966 this, waitp->how == kExclusive ? SYNCH_EV_LOCK : SYNCH_EV_READERLOCK);
1967 }
1968 ABSL_RAW_CHECK(
1969 waitp->thread->waitp == nullptr || waitp->thread->suppress_fatal_errors,
1970 "detected illegal recursion into Mutex code");
1971 for (;;) {
1972 v = mu_.load(std::memory_order_relaxed);
1973 CheckForMutexCorruption(v, "Lock");
1974 if ((v & waitp->how->slow_need_zero) == 0) {
1975 if (mu_.compare_exchange_strong(
1976 v,
1977 (waitp->how->fast_or |
1978 (v & ClearDesignatedWakerMask(flags & kMuHasBlocked))) +
1979 waitp->how->fast_add,
1980 std::memory_order_acquire, std::memory_order_relaxed)) {
1981 if (waitp->cond == nullptr ||
1982 EvalConditionAnnotated(waitp->cond, this, true, false,
1983 waitp->how == kShared)) {
1984 break; // we timed out, or condition true, so return
1985 }
1986 this->UnlockSlow(waitp); // got lock but condition false
1987 this->Block(waitp->thread);
1988 flags |= kMuHasBlocked;
1989 c = 0;
1990 }
1991 } else { // need to access waiter list
1992 bool dowait = false;
1993 if ((v & (kMuSpin | kMuWait)) == 0) { // no waiters
1994 // This thread tries to become the one and only waiter.
1995 PerThreadSynch* new_h = Enqueue(nullptr, waitp, v, flags);
1996 intptr_t nv =
1997 (v & ClearDesignatedWakerMask(flags & kMuHasBlocked) & kMuLow) |
1998 kMuWait;
1999 ABSL_RAW_CHECK(new_h != nullptr, "Enqueue to empty list failed");
2000 if (waitp->how == kExclusive && (v & kMuReader) != 0) {
2001 nv |= kMuWrWait;
2002 }
2003 if (mu_.compare_exchange_strong(
2004 v, reinterpret_cast<intptr_t>(new_h) | nv,
2005 std::memory_order_release, std::memory_order_relaxed)) {
2006 dowait = true;
2007 } else { // attempted Enqueue() failed
2008 // zero out the waitp field set by Enqueue()
2009 waitp->thread->waitp = nullptr;
2010 }
2011 } else if ((v & waitp->how->slow_inc_need_zero &
2012 IgnoreWaitingWritersMask(flags & kMuHasBlocked)) == 0) {
2013 // This is a reader that needs to increment the reader count,
2014 // but the count is currently held in the last waiter.
2015 if (mu_.compare_exchange_strong(
2016 v,
2017 (v & ClearDesignatedWakerMask(flags & kMuHasBlocked)) |
2018 kMuSpin | kMuReader,
2019 std::memory_order_acquire, std::memory_order_relaxed)) {
2020 PerThreadSynch* h = GetPerThreadSynch(v);
2021 h->readers += kMuOne; // inc reader count in waiter
2022 do { // release spinlock
2023 v = mu_.load(std::memory_order_relaxed);
2024 } while (!mu_.compare_exchange_weak(v, (v & ~kMuSpin) | kMuReader,
2025 std::memory_order_release,
2026 std::memory_order_relaxed));
2027 if (waitp->cond == nullptr ||
2028 EvalConditionAnnotated(waitp->cond, this, true, false,
2029 waitp->how == kShared)) {
2030 break; // we timed out, or condition true, so return
2031 }
2032 this->UnlockSlow(waitp); // got lock but condition false
2033 this->Block(waitp->thread);
2034 flags |= kMuHasBlocked;
2035 c = 0;
2036 }
2037 } else if ((v & kMuSpin) == 0 && // attempt to queue ourselves
2038 mu_.compare_exchange_strong(
2039 v,
2040 (v & ClearDesignatedWakerMask(flags & kMuHasBlocked)) |
2041 kMuSpin | kMuWait,
2042 std::memory_order_acquire, std::memory_order_relaxed)) {
2043 PerThreadSynch* h = GetPerThreadSynch(v);
2044 PerThreadSynch* new_h = Enqueue(h, waitp, v, flags);
2045 intptr_t wr_wait = 0;
2046 ABSL_RAW_CHECK(new_h != nullptr, "Enqueue to list failed");
2047 if (waitp->how == kExclusive && (v & kMuReader) != 0) {
2048 wr_wait = kMuWrWait; // give priority to a waiting writer
2049 }
2050 do { // release spinlock
2051 v = mu_.load(std::memory_order_relaxed);
2052 } while (!mu_.compare_exchange_weak(
2053 v,
2054 (v & (kMuLow & ~kMuSpin)) | kMuWait | wr_wait |
2055 reinterpret_cast<intptr_t>(new_h),
2056 std::memory_order_release, std::memory_order_relaxed));
2057 dowait = true;
2058 }
2059 if (dowait) {
2060 this->Block(waitp->thread); // wait until removed from list or timeout
2061 flags |= kMuHasBlocked;
2062 c = 0;
2063 }
2064 }
2065 ABSL_RAW_CHECK(
2066 waitp->thread->waitp == nullptr || waitp->thread->suppress_fatal_errors,
2067 "detected illegal recursion into Mutex code");
2068 // delay, then try again
2069 c = synchronization_internal::MutexDelay(c, GENTLE);
2070 }
2071 ABSL_RAW_CHECK(
2072 waitp->thread->waitp == nullptr || waitp->thread->suppress_fatal_errors,
2073 "detected illegal recursion into Mutex code");
2074 if ((v & kMuEvent) != 0) {
2075 PostSynchEvent(this, waitp->how == kExclusive
2076 ? SYNCH_EV_LOCK_RETURNING
2077 : SYNCH_EV_READERLOCK_RETURNING);
2078 }
2079 }
2080
2081 // Unlock this mutex, which is held by the current thread.
2082 // If waitp is non-zero, it must be the wait parameters for the current thread
2083 // which holds the lock but is not runnable because its condition is false
2084 // or it is in the process of blocking on a condition variable; it must requeue
2085 // itself on the mutex/condvar to wait for its condition to become true.
UnlockSlow(SynchWaitParams * waitp)2086 ABSL_ATTRIBUTE_NOINLINE void Mutex::UnlockSlow(SynchWaitParams* waitp) {
2087 SchedulingGuard::ScopedDisable disable_rescheduling;
2088 intptr_t v = mu_.load(std::memory_order_relaxed);
2089 this->AssertReaderHeld();
2090 CheckForMutexCorruption(v, "Unlock");
2091 if ((v & kMuEvent) != 0) {
2092 PostSynchEvent(
2093 this, (v & kMuWriter) != 0 ? SYNCH_EV_UNLOCK : SYNCH_EV_READERUNLOCK);
2094 }
2095 int c = 0;
2096 // the waiter under consideration to wake, or zero
2097 PerThreadSynch* w = nullptr;
2098 // the predecessor to w or zero
2099 PerThreadSynch* pw = nullptr;
2100 // head of the list searched previously, or zero
2101 PerThreadSynch* old_h = nullptr;
2102 // a condition that's known to be false.
2103 PerThreadSynch* wake_list = kPerThreadSynchNull; // list of threads to wake
2104 intptr_t wr_wait = 0; // set to kMuWrWait if we wake a reader and a
2105 // later writer could have acquired the lock
2106 // (starvation avoidance)
2107 ABSL_RAW_CHECK(waitp == nullptr || waitp->thread->waitp == nullptr ||
2108 waitp->thread->suppress_fatal_errors,
2109 "detected illegal recursion into Mutex code");
2110 // This loop finds threads wake_list to wakeup if any, and removes them from
2111 // the list of waiters. In addition, it places waitp.thread on the queue of
2112 // waiters if waitp is non-zero.
2113 for (;;) {
2114 v = mu_.load(std::memory_order_relaxed);
2115 if ((v & kMuWriter) != 0 && (v & (kMuWait | kMuDesig)) != kMuWait &&
2116 waitp == nullptr) {
2117 // fast writer release (writer with no waiters or with designated waker)
2118 if (mu_.compare_exchange_strong(v, v & ~(kMuWrWait | kMuWriter),
2119 std::memory_order_release,
2120 std::memory_order_relaxed)) {
2121 return;
2122 }
2123 } else if ((v & (kMuReader | kMuWait)) == kMuReader && waitp == nullptr) {
2124 // fast reader release (reader with no waiters)
2125 intptr_t clear = ExactlyOneReader(v) ? kMuReader | kMuOne : kMuOne;
2126 if (mu_.compare_exchange_strong(v, v - clear, std::memory_order_release,
2127 std::memory_order_relaxed)) {
2128 return;
2129 }
2130 } else if ((v & kMuSpin) == 0 && // attempt to get spinlock
2131 mu_.compare_exchange_strong(v, v | kMuSpin,
2132 std::memory_order_acquire,
2133 std::memory_order_relaxed)) {
2134 if ((v & kMuWait) == 0) { // no one to wake
2135 intptr_t nv;
2136 bool do_enqueue = true; // always Enqueue() the first time
2137 ABSL_RAW_CHECK(waitp != nullptr,
2138 "UnlockSlow is confused"); // about to sleep
2139 do { // must loop to release spinlock as reader count may change
2140 v = mu_.load(std::memory_order_relaxed);
2141 // decrement reader count if there are readers
2142 intptr_t new_readers = (v >= kMuOne) ? v - kMuOne : v;
2143 PerThreadSynch* new_h = nullptr;
2144 if (do_enqueue) {
2145 // If we are enqueuing on a CondVar (waitp->cv_word != nullptr) then
2146 // we must not retry here. The initial attempt will always have
2147 // succeeded, further attempts would enqueue us against *this due to
2148 // Fer() handling.
2149 do_enqueue = (waitp->cv_word == nullptr);
2150 new_h = Enqueue(nullptr, waitp, new_readers, kMuIsCond);
2151 }
2152 intptr_t clear = kMuWrWait | kMuWriter; // by default clear write bit
2153 if ((v & kMuWriter) == 0 && ExactlyOneReader(v)) { // last reader
2154 clear = kMuWrWait | kMuReader; // clear read bit
2155 }
2156 nv = (v & kMuLow & ~clear & ~kMuSpin);
2157 if (new_h != nullptr) {
2158 nv |= kMuWait | reinterpret_cast<intptr_t>(new_h);
2159 } else { // new_h could be nullptr if we queued ourselves on a
2160 // CondVar
2161 // In that case, we must place the reader count back in the mutex
2162 // word, as Enqueue() did not store it in the new waiter.
2163 nv |= new_readers & kMuHigh;
2164 }
2165 // release spinlock & our lock; retry if reader-count changed
2166 // (writer count cannot change since we hold lock)
2167 } while (!mu_.compare_exchange_weak(v, nv, std::memory_order_release,
2168 std::memory_order_relaxed));
2169 break;
2170 }
2171
2172 // There are waiters.
2173 // Set h to the head of the circular waiter list.
2174 PerThreadSynch* h = GetPerThreadSynch(v);
2175 if ((v & kMuReader) != 0 && (h->readers & kMuHigh) > kMuOne) {
2176 // a reader but not the last
2177 h->readers -= kMuOne; // release our lock
2178 intptr_t nv = v; // normally just release spinlock
2179 if (waitp != nullptr) { // but waitp!=nullptr => must queue ourselves
2180 PerThreadSynch* new_h = Enqueue(h, waitp, v, kMuIsCond);
2181 ABSL_RAW_CHECK(new_h != nullptr,
2182 "waiters disappeared during Enqueue()!");
2183 nv &= kMuLow;
2184 nv |= kMuWait | reinterpret_cast<intptr_t>(new_h);
2185 }
2186 mu_.store(nv, std::memory_order_release); // release spinlock
2187 // can release with a store because there were waiters
2188 break;
2189 }
2190
2191 // Either we didn't search before, or we marked the queue
2192 // as "maybe_unlocking" and no one else should have changed it.
2193 ABSL_RAW_CHECK(old_h == nullptr || h->maybe_unlocking,
2194 "Mutex queue changed beneath us");
2195
2196 // The lock is becoming free, and there's a waiter
2197 if (old_h != nullptr &&
2198 !old_h->may_skip) { // we used old_h as a terminator
2199 old_h->may_skip = true; // allow old_h to skip once more
2200 ABSL_RAW_CHECK(old_h->skip == nullptr, "illegal skip from head");
2201 if (h != old_h && MuEquivalentWaiter(old_h, old_h->next)) {
2202 old_h->skip = old_h->next; // old_h not head & can skip to successor
2203 }
2204 }
2205 if (h->next->waitp->how == kExclusive &&
2206 h->next->waitp->cond == nullptr) {
2207 // easy case: writer with no condition; no need to search
2208 pw = h; // wake w, the successor of h (=pw)
2209 w = h->next;
2210 w->wake = true;
2211 // We are waking up a writer. This writer may be racing against
2212 // an already awake reader for the lock. We want the
2213 // writer to usually win this race,
2214 // because if it doesn't, we can potentially keep taking a reader
2215 // perpetually and writers will starve. Worse than
2216 // that, this can also starve other readers if kMuWrWait gets set
2217 // later.
2218 wr_wait = kMuWrWait;
2219 } else if (w != nullptr && (w->waitp->how == kExclusive || h == old_h)) {
2220 // we found a waiter w to wake on a previous iteration and either it's
2221 // a writer, or we've searched the entire list so we have all the
2222 // readers.
2223 if (pw == nullptr) { // if w's predecessor is unknown, it must be h
2224 pw = h;
2225 }
2226 } else {
2227 // At this point we don't know all the waiters to wake, and the first
2228 // waiter has a condition or is a reader. We avoid searching over
2229 // waiters we've searched on previous iterations by starting at
2230 // old_h if it's set. If old_h==h, there's no one to wakeup at all.
2231 if (old_h == h) { // we've searched before, and nothing's new
2232 // so there's no one to wake.
2233 intptr_t nv = (v & ~(kMuReader | kMuWriter | kMuWrWait));
2234 h->readers = 0;
2235 h->maybe_unlocking = false; // finished unlocking
2236 if (waitp != nullptr) { // we must queue ourselves and sleep
2237 PerThreadSynch* new_h = Enqueue(h, waitp, v, kMuIsCond);
2238 nv &= kMuLow;
2239 if (new_h != nullptr) {
2240 nv |= kMuWait | reinterpret_cast<intptr_t>(new_h);
2241 } // else new_h could be nullptr if we queued ourselves on a
2242 // CondVar
2243 }
2244 // release spinlock & lock
2245 // can release with a store because there were waiters
2246 mu_.store(nv, std::memory_order_release);
2247 break;
2248 }
2249
2250 // set up to walk the list
2251 PerThreadSynch* w_walk; // current waiter during list walk
2252 PerThreadSynch* pw_walk; // previous waiter during list walk
2253 if (old_h != nullptr) { // we've searched up to old_h before
2254 pw_walk = old_h;
2255 w_walk = old_h->next;
2256 } else { // no prior search, start at beginning
2257 pw_walk =
2258 nullptr; // h->next's predecessor may change; don't record it
2259 w_walk = h->next;
2260 }
2261
2262 h->may_skip = false; // ensure we never skip past h in future searches
2263 // even if other waiters are queued after it.
2264 ABSL_RAW_CHECK(h->skip == nullptr, "illegal skip from head");
2265
2266 h->maybe_unlocking = true; // we're about to scan the waiter list
2267 // without the spinlock held.
2268 // Enqueue must be conservative about
2269 // priority queuing.
2270
2271 // We must release the spinlock to evaluate the conditions.
2272 mu_.store(v, std::memory_order_release); // release just spinlock
2273 // can release with a store because there were waiters
2274
2275 // h is the last waiter queued, and w_walk the first unsearched waiter.
2276 // Without the spinlock, the locations mu_ and h->next may now change
2277 // underneath us, but since we hold the lock itself, the only legal
2278 // change is to add waiters between h and w_walk. Therefore, it's safe
2279 // to walk the path from w_walk to h inclusive. (TryRemove() can remove
2280 // a waiter anywhere, but it acquires both the spinlock and the Mutex)
2281
2282 old_h = h; // remember we searched to here
2283
2284 // Walk the path upto and including h looking for waiters we can wake.
2285 while (pw_walk != h) {
2286 w_walk->wake = false;
2287 if (w_walk->waitp->cond ==
2288 nullptr || // no condition => vacuously true OR
2289 // this thread's condition is true
2290 EvalConditionIgnored(this, w_walk->waitp->cond)) {
2291 if (w == nullptr) {
2292 w_walk->wake = true; // can wake this waiter
2293 w = w_walk;
2294 pw = pw_walk;
2295 if (w_walk->waitp->how == kExclusive) {
2296 wr_wait = kMuWrWait;
2297 break; // bail if waking this writer
2298 }
2299 } else if (w_walk->waitp->how == kShared) { // wake if a reader
2300 w_walk->wake = true;
2301 } else { // writer with true condition
2302 wr_wait = kMuWrWait;
2303 }
2304 }
2305 if (w_walk->wake) { // we're waking reader w_walk
2306 pw_walk = w_walk; // don't skip similar waiters
2307 } else { // not waking; skip as much as possible
2308 pw_walk = Skip(w_walk);
2309 }
2310 // If pw_walk == h, then load of pw_walk->next can race with
2311 // concurrent write in Enqueue(). However, at the same time
2312 // we do not need to do the load, because we will bail out
2313 // from the loop anyway.
2314 if (pw_walk != h) {
2315 w_walk = pw_walk->next;
2316 }
2317 }
2318
2319 continue; // restart for(;;)-loop to wakeup w or to find more waiters
2320 }
2321 ABSL_RAW_CHECK(pw->next == w, "pw not w's predecessor");
2322 // The first (and perhaps only) waiter we've chosen to wake is w, whose
2323 // predecessor is pw. If w is a reader, we must wake all the other
2324 // waiters with wake==true as well. We may also need to queue
2325 // ourselves if waitp != null. The spinlock and the lock are still
2326 // held.
2327
2328 // This traverses the list in [ pw->next, h ], where h is the head,
2329 // removing all elements with wake==true and placing them in the
2330 // singly-linked list wake_list. Returns the new head.
2331 h = DequeueAllWakeable(h, pw, &wake_list);
2332
2333 intptr_t nv = (v & kMuEvent) | kMuDesig;
2334 // assume no waiters left,
2335 // set kMuDesig for INV1a
2336
2337 if (waitp != nullptr) { // we must queue ourselves and sleep
2338 h = Enqueue(h, waitp, v, kMuIsCond);
2339 // h is new last waiter; could be null if we queued ourselves on a
2340 // CondVar
2341 }
2342
2343 ABSL_RAW_CHECK(wake_list != kPerThreadSynchNull,
2344 "unexpected empty wake list");
2345
2346 if (h != nullptr) { // there are waiters left
2347 h->readers = 0;
2348 h->maybe_unlocking = false; // finished unlocking
2349 nv |= wr_wait | kMuWait | reinterpret_cast<intptr_t>(h);
2350 }
2351
2352 // release both spinlock & lock
2353 // can release with a store because there were waiters
2354 mu_.store(nv, std::memory_order_release);
2355 break; // out of for(;;)-loop
2356 }
2357 // aggressive here; no one can proceed till we do
2358 c = synchronization_internal::MutexDelay(c, AGGRESSIVE);
2359 } // end of for(;;)-loop
2360
2361 if (wake_list != kPerThreadSynchNull) {
2362 int64_t total_wait_cycles = 0;
2363 int64_t max_wait_cycles = 0;
2364 int64_t now = CycleClock::Now();
2365 do {
2366 // Profile lock contention events only if the waiter was trying to acquire
2367 // the lock, not waiting on a condition variable or Condition.
2368 if (!wake_list->cond_waiter) {
2369 int64_t cycles_waited =
2370 (now - wake_list->waitp->contention_start_cycles);
2371 total_wait_cycles += cycles_waited;
2372 if (max_wait_cycles == 0) max_wait_cycles = cycles_waited;
2373 wake_list->waitp->contention_start_cycles = now;
2374 wake_list->waitp->should_submit_contention_data = true;
2375 }
2376 wake_list = Wakeup(wake_list); // wake waiters
2377 } while (wake_list != kPerThreadSynchNull);
2378 if (total_wait_cycles > 0) {
2379 mutex_tracer("slow release", this, total_wait_cycles);
2380 ABSL_TSAN_MUTEX_PRE_DIVERT(this, 0);
2381 submit_profile_data(total_wait_cycles);
2382 ABSL_TSAN_MUTEX_POST_DIVERT(this, 0);
2383 }
2384 }
2385 }
2386
2387 // Used by CondVar implementation to reacquire mutex after waking from
2388 // condition variable. This routine is used instead of Lock() because the
2389 // waiting thread may have been moved from the condition variable queue to the
2390 // mutex queue without a wakeup, by Trans(). In that case, when the thread is
2391 // finally woken, the woken thread will believe it has been woken from the
2392 // condition variable (i.e. its PC will be in when in the CondVar code), when
2393 // in fact it has just been woken from the mutex. Thus, it must enter the slow
2394 // path of the mutex in the same state as if it had just woken from the mutex.
2395 // That is, it must ensure to clear kMuDesig (INV1b).
Trans(MuHow how)2396 void Mutex::Trans(MuHow how) {
2397 this->LockSlow(how, nullptr, kMuHasBlocked | kMuIsCond);
2398 }
2399
2400 // Used by CondVar implementation to effectively wake thread w from the
2401 // condition variable. If this mutex is free, we simply wake the thread.
2402 // It will later acquire the mutex with high probability. Otherwise, we
2403 // enqueue thread w on this mutex.
Fer(PerThreadSynch * w)2404 void Mutex::Fer(PerThreadSynch* w) {
2405 SchedulingGuard::ScopedDisable disable_rescheduling;
2406 int c = 0;
2407 ABSL_RAW_CHECK(w->waitp->cond == nullptr,
2408 "Mutex::Fer while waiting on Condition");
2409 ABSL_RAW_CHECK(w->waitp->cv_word == nullptr,
2410 "Mutex::Fer with pending CondVar queueing");
2411 // The CondVar timeout is not relevant for the Mutex wait.
2412 w->waitp->timeout = {};
2413 for (;;) {
2414 intptr_t v = mu_.load(std::memory_order_relaxed);
2415 // Note: must not queue if the mutex is unlocked (nobody will wake it).
2416 // For example, we can have only kMuWait (conditional) or maybe
2417 // kMuWait|kMuWrWait.
2418 // conflicting != 0 implies that the waking thread cannot currently take
2419 // the mutex, which in turn implies that someone else has it and can wake
2420 // us if we queue.
2421 const intptr_t conflicting =
2422 kMuWriter | (w->waitp->how == kShared ? 0 : kMuReader);
2423 if ((v & conflicting) == 0) {
2424 w->next = nullptr;
2425 w->state.store(PerThreadSynch::kAvailable, std::memory_order_release);
2426 IncrementSynchSem(this, w);
2427 return;
2428 } else {
2429 if ((v & (kMuSpin | kMuWait)) == 0) { // no waiters
2430 // This thread tries to become the one and only waiter.
2431 PerThreadSynch* new_h =
2432 Enqueue(nullptr, w->waitp, v, kMuIsCond | kMuIsFer);
2433 ABSL_RAW_CHECK(new_h != nullptr,
2434 "Enqueue failed"); // we must queue ourselves
2435 if (mu_.compare_exchange_strong(
2436 v, reinterpret_cast<intptr_t>(new_h) | (v & kMuLow) | kMuWait,
2437 std::memory_order_release, std::memory_order_relaxed)) {
2438 return;
2439 }
2440 } else if ((v & kMuSpin) == 0 &&
2441 mu_.compare_exchange_strong(v, v | kMuSpin | kMuWait)) {
2442 PerThreadSynch* h = GetPerThreadSynch(v);
2443 PerThreadSynch* new_h = Enqueue(h, w->waitp, v, kMuIsCond | kMuIsFer);
2444 ABSL_RAW_CHECK(new_h != nullptr,
2445 "Enqueue failed"); // we must queue ourselves
2446 do {
2447 v = mu_.load(std::memory_order_relaxed);
2448 } while (!mu_.compare_exchange_weak(
2449 v,
2450 (v & kMuLow & ~kMuSpin) | kMuWait |
2451 reinterpret_cast<intptr_t>(new_h),
2452 std::memory_order_release, std::memory_order_relaxed));
2453 return;
2454 }
2455 }
2456 c = synchronization_internal::MutexDelay(c, GENTLE);
2457 }
2458 }
2459
AssertHeld() const2460 void Mutex::AssertHeld() const {
2461 if ((mu_.load(std::memory_order_relaxed) & kMuWriter) == 0) {
2462 SynchEvent* e = GetSynchEvent(this);
2463 ABSL_RAW_LOG(FATAL, "thread should hold write lock on Mutex %p %s",
2464 static_cast<const void*>(this), (e == nullptr ? "" : e->name));
2465 }
2466 }
2467
AssertReaderHeld() const2468 void Mutex::AssertReaderHeld() const {
2469 if ((mu_.load(std::memory_order_relaxed) & (kMuReader | kMuWriter)) == 0) {
2470 SynchEvent* e = GetSynchEvent(this);
2471 ABSL_RAW_LOG(FATAL,
2472 "thread should hold at least a read lock on Mutex %p %s",
2473 static_cast<const void*>(this), (e == nullptr ? "" : e->name));
2474 }
2475 }
2476
2477 // -------------------------------- condition variables
2478 static const intptr_t kCvSpin = 0x0001L; // spinlock protects waiter list
2479 static const intptr_t kCvEvent = 0x0002L; // record events
2480
2481 static const intptr_t kCvLow = 0x0003L; // low order bits of CV
2482
2483 // Hack to make constant values available to gdb pretty printer
2484 enum {
2485 kGdbCvSpin = kCvSpin,
2486 kGdbCvEvent = kCvEvent,
2487 kGdbCvLow = kCvLow,
2488 };
2489
2490 static_assert(PerThreadSynch::kAlignment > kCvLow,
2491 "PerThreadSynch::kAlignment must be greater than kCvLow");
2492
EnableDebugLog(const char * name)2493 void CondVar::EnableDebugLog(const char* name) {
2494 SynchEvent* e = EnsureSynchEvent(&this->cv_, name, kCvEvent, kCvSpin);
2495 e->log = true;
2496 UnrefSynchEvent(e);
2497 }
2498
2499 // Remove thread s from the list of waiters on this condition variable.
Remove(PerThreadSynch * s)2500 void CondVar::Remove(PerThreadSynch* s) {
2501 SchedulingGuard::ScopedDisable disable_rescheduling;
2502 intptr_t v;
2503 int c = 0;
2504 for (v = cv_.load(std::memory_order_relaxed);;
2505 v = cv_.load(std::memory_order_relaxed)) {
2506 if ((v & kCvSpin) == 0 && // attempt to acquire spinlock
2507 cv_.compare_exchange_strong(v, v | kCvSpin, std::memory_order_acquire,
2508 std::memory_order_relaxed)) {
2509 PerThreadSynch* h = reinterpret_cast<PerThreadSynch*>(v & ~kCvLow);
2510 if (h != nullptr) {
2511 PerThreadSynch* w = h;
2512 while (w->next != s && w->next != h) { // search for thread
2513 w = w->next;
2514 }
2515 if (w->next == s) { // found thread; remove it
2516 w->next = s->next;
2517 if (h == s) {
2518 h = (w == s) ? nullptr : w;
2519 }
2520 s->next = nullptr;
2521 s->state.store(PerThreadSynch::kAvailable, std::memory_order_release);
2522 }
2523 }
2524 // release spinlock
2525 cv_.store((v & kCvEvent) | reinterpret_cast<intptr_t>(h),
2526 std::memory_order_release);
2527 return;
2528 } else {
2529 // try again after a delay
2530 c = synchronization_internal::MutexDelay(c, GENTLE);
2531 }
2532 }
2533 }
2534
2535 // Queue thread waitp->thread on condition variable word cv_word using
2536 // wait parameters waitp.
2537 // We split this into a separate routine, rather than simply doing it as part
2538 // of WaitCommon(). If we were to queue ourselves on the condition variable
2539 // before calling Mutex::UnlockSlow(), the Mutex code might be re-entered (via
2540 // the logging code, or via a Condition function) and might potentially attempt
2541 // to block this thread. That would be a problem if the thread were already on
2542 // a condition variable waiter queue. Thus, we use the waitp->cv_word to tell
2543 // the unlock code to call CondVarEnqueue() to queue the thread on the condition
2544 // variable queue just before the mutex is to be unlocked, and (most
2545 // importantly) after any call to an external routine that might re-enter the
2546 // mutex code.
CondVarEnqueue(SynchWaitParams * waitp)2547 static void CondVarEnqueue(SynchWaitParams* waitp) {
2548 // This thread might be transferred to the Mutex queue by Fer() when
2549 // we are woken. To make sure that is what happens, Enqueue() doesn't
2550 // call CondVarEnqueue() again but instead uses its normal code. We
2551 // must do this before we queue ourselves so that cv_word will be null
2552 // when seen by the dequeuer, who may wish immediately to requeue
2553 // this thread on another queue.
2554 std::atomic<intptr_t>* cv_word = waitp->cv_word;
2555 waitp->cv_word = nullptr;
2556
2557 intptr_t v = cv_word->load(std::memory_order_relaxed);
2558 int c = 0;
2559 while ((v & kCvSpin) != 0 || // acquire spinlock
2560 !cv_word->compare_exchange_weak(v, v | kCvSpin,
2561 std::memory_order_acquire,
2562 std::memory_order_relaxed)) {
2563 c = synchronization_internal::MutexDelay(c, GENTLE);
2564 v = cv_word->load(std::memory_order_relaxed);
2565 }
2566 ABSL_RAW_CHECK(waitp->thread->waitp == nullptr, "waiting when shouldn't be");
2567 waitp->thread->waitp = waitp; // prepare ourselves for waiting
2568 PerThreadSynch* h = reinterpret_cast<PerThreadSynch*>(v & ~kCvLow);
2569 if (h == nullptr) { // add this thread to waiter list
2570 waitp->thread->next = waitp->thread;
2571 } else {
2572 waitp->thread->next = h->next;
2573 h->next = waitp->thread;
2574 }
2575 waitp->thread->state.store(PerThreadSynch::kQueued,
2576 std::memory_order_relaxed);
2577 cv_word->store((v & kCvEvent) | reinterpret_cast<intptr_t>(waitp->thread),
2578 std::memory_order_release);
2579 }
2580
WaitCommon(Mutex * mutex,KernelTimeout t)2581 bool CondVar::WaitCommon(Mutex* mutex, KernelTimeout t) {
2582 bool rc = false; // return value; true iff we timed-out
2583
2584 intptr_t mutex_v = mutex->mu_.load(std::memory_order_relaxed);
2585 Mutex::MuHow mutex_how = ((mutex_v & kMuWriter) != 0) ? kExclusive : kShared;
2586 ABSL_TSAN_MUTEX_PRE_UNLOCK(mutex, TsanFlags(mutex_how));
2587
2588 // maybe trace this call
2589 intptr_t v = cv_.load(std::memory_order_relaxed);
2590 cond_var_tracer("Wait", this);
2591 if ((v & kCvEvent) != 0) {
2592 PostSynchEvent(this, SYNCH_EV_WAIT);
2593 }
2594
2595 // Release mu and wait on condition variable.
2596 SynchWaitParams waitp(mutex_how, nullptr, t, mutex,
2597 Synch_GetPerThreadAnnotated(mutex), &cv_);
2598 // UnlockSlow() will call CondVarEnqueue() just before releasing the
2599 // Mutex, thus queuing this thread on the condition variable. See
2600 // CondVarEnqueue() for the reasons.
2601 mutex->UnlockSlow(&waitp);
2602
2603 // wait for signal
2604 while (waitp.thread->state.load(std::memory_order_acquire) ==
2605 PerThreadSynch::kQueued) {
2606 if (!Mutex::DecrementSynchSem(mutex, waitp.thread, t)) {
2607 // DecrementSynchSem returned due to timeout.
2608 // Now we will either (1) remove ourselves from the wait list in Remove
2609 // below, in which case Remove will set thread.state = kAvailable and
2610 // we will not call DecrementSynchSem again; or (2) Signal/SignalAll
2611 // has removed us concurrently and is calling Wakeup, which will set
2612 // thread.state = kAvailable and post to the semaphore.
2613 // It's important to reset the timeout for the case (2) because otherwise
2614 // we can live-lock in this loop since DecrementSynchSem will always
2615 // return immediately due to timeout, but Signal/SignalAll is not
2616 // necessary set thread.state = kAvailable yet (and is not scheduled
2617 // due to thread priorities or other scheduler artifacts).
2618 // Note this could also be resolved if Signal/SignalAll would set
2619 // thread.state = kAvailable while holding the wait list spin lock.
2620 // But this can't be easily done for SignalAll since it grabs the whole
2621 // wait list with a single compare-exchange and does not really grab
2622 // the spin lock.
2623 t = KernelTimeout::Never();
2624 this->Remove(waitp.thread);
2625 rc = true;
2626 }
2627 }
2628
2629 ABSL_RAW_CHECK(waitp.thread->waitp != nullptr, "not waiting when should be");
2630 waitp.thread->waitp = nullptr; // cleanup
2631
2632 // maybe trace this call
2633 cond_var_tracer("Unwait", this);
2634 if ((v & kCvEvent) != 0) {
2635 PostSynchEvent(this, SYNCH_EV_WAIT_RETURNING);
2636 }
2637
2638 // From synchronization point of view Wait is unlock of the mutex followed
2639 // by lock of the mutex. We've annotated start of unlock in the beginning
2640 // of the function. Now, finish unlock and annotate lock of the mutex.
2641 // (Trans is effectively lock).
2642 ABSL_TSAN_MUTEX_POST_UNLOCK(mutex, TsanFlags(mutex_how));
2643 ABSL_TSAN_MUTEX_PRE_LOCK(mutex, TsanFlags(mutex_how));
2644 mutex->Trans(mutex_how); // Reacquire mutex
2645 ABSL_TSAN_MUTEX_POST_LOCK(mutex, TsanFlags(mutex_how), 0);
2646 return rc;
2647 }
2648
Signal()2649 void CondVar::Signal() {
2650 SchedulingGuard::ScopedDisable disable_rescheduling;
2651 ABSL_TSAN_MUTEX_PRE_SIGNAL(nullptr, 0);
2652 intptr_t v;
2653 int c = 0;
2654 for (v = cv_.load(std::memory_order_relaxed); v != 0;
2655 v = cv_.load(std::memory_order_relaxed)) {
2656 if ((v & kCvSpin) == 0 && // attempt to acquire spinlock
2657 cv_.compare_exchange_strong(v, v | kCvSpin, std::memory_order_acquire,
2658 std::memory_order_relaxed)) {
2659 PerThreadSynch* h = reinterpret_cast<PerThreadSynch*>(v & ~kCvLow);
2660 PerThreadSynch* w = nullptr;
2661 if (h != nullptr) { // remove first waiter
2662 w = h->next;
2663 if (w == h) {
2664 h = nullptr;
2665 } else {
2666 h->next = w->next;
2667 }
2668 }
2669 // release spinlock
2670 cv_.store((v & kCvEvent) | reinterpret_cast<intptr_t>(h),
2671 std::memory_order_release);
2672 if (w != nullptr) {
2673 w->waitp->cvmu->Fer(w); // wake waiter, if there was one
2674 cond_var_tracer("Signal wakeup", this);
2675 }
2676 if ((v & kCvEvent) != 0) {
2677 PostSynchEvent(this, SYNCH_EV_SIGNAL);
2678 }
2679 ABSL_TSAN_MUTEX_POST_SIGNAL(nullptr, 0);
2680 return;
2681 } else {
2682 c = synchronization_internal::MutexDelay(c, GENTLE);
2683 }
2684 }
2685 ABSL_TSAN_MUTEX_POST_SIGNAL(nullptr, 0);
2686 }
2687
SignalAll()2688 void CondVar::SignalAll() {
2689 ABSL_TSAN_MUTEX_PRE_SIGNAL(nullptr, 0);
2690 intptr_t v;
2691 int c = 0;
2692 for (v = cv_.load(std::memory_order_relaxed); v != 0;
2693 v = cv_.load(std::memory_order_relaxed)) {
2694 // empty the list if spinlock free
2695 // We do this by simply setting the list to empty using
2696 // compare and swap. We then have the entire list in our hands,
2697 // which cannot be changing since we grabbed it while no one
2698 // held the lock.
2699 if ((v & kCvSpin) == 0 &&
2700 cv_.compare_exchange_strong(v, v & kCvEvent, std::memory_order_acquire,
2701 std::memory_order_relaxed)) {
2702 PerThreadSynch* h = reinterpret_cast<PerThreadSynch*>(v & ~kCvLow);
2703 if (h != nullptr) {
2704 PerThreadSynch* w;
2705 PerThreadSynch* n = h->next;
2706 do { // for every thread, wake it up
2707 w = n;
2708 n = n->next;
2709 w->waitp->cvmu->Fer(w);
2710 } while (w != h);
2711 cond_var_tracer("SignalAll wakeup", this);
2712 }
2713 if ((v & kCvEvent) != 0) {
2714 PostSynchEvent(this, SYNCH_EV_SIGNALALL);
2715 }
2716 ABSL_TSAN_MUTEX_POST_SIGNAL(nullptr, 0);
2717 return;
2718 } else {
2719 // try again after a delay
2720 c = synchronization_internal::MutexDelay(c, GENTLE);
2721 }
2722 }
2723 ABSL_TSAN_MUTEX_POST_SIGNAL(nullptr, 0);
2724 }
2725
Release()2726 void ReleasableMutexLock::Release() {
2727 ABSL_RAW_CHECK(this->mu_ != nullptr,
2728 "ReleasableMutexLock::Release may only be called once");
2729 this->mu_->Unlock();
2730 this->mu_ = nullptr;
2731 }
2732
2733 #ifdef ABSL_HAVE_THREAD_SANITIZER
2734 extern "C" void __tsan_read1(void* addr);
2735 #else
2736 #define __tsan_read1(addr) // do nothing if TSan not enabled
2737 #endif
2738
2739 // A function that just returns its argument, dereferenced
Dereference(void * arg)2740 static bool Dereference(void* arg) {
2741 // ThreadSanitizer does not instrument this file for memory accesses.
2742 // This function dereferences a user variable that can participate
2743 // in a data race, so we need to manually tell TSan about this memory access.
2744 __tsan_read1(arg);
2745 return *(static_cast<bool*>(arg));
2746 }
2747
2748 ABSL_CONST_INIT const Condition Condition::kTrue;
2749
Condition(bool (* func)(void *),void * arg)2750 Condition::Condition(bool (*func)(void*), void* arg)
2751 : eval_(&CallVoidPtrFunction), arg_(arg) {
2752 static_assert(sizeof(&func) <= sizeof(callback_),
2753 "An overlarge function pointer passed to Condition.");
2754 StoreCallback(func);
2755 }
2756
CallVoidPtrFunction(const Condition * c)2757 bool Condition::CallVoidPtrFunction(const Condition* c) {
2758 using FunctionPointer = bool (*)(void*);
2759 FunctionPointer function_pointer;
2760 std::memcpy(&function_pointer, c->callback_, sizeof(function_pointer));
2761 return (*function_pointer)(c->arg_);
2762 }
2763
Condition(const bool * cond)2764 Condition::Condition(const bool* cond)
2765 : eval_(CallVoidPtrFunction),
2766 // const_cast is safe since Dereference does not modify arg
2767 arg_(const_cast<bool*>(cond)) {
2768 using FunctionPointer = bool (*)(void*);
2769 const FunctionPointer dereference = Dereference;
2770 StoreCallback(dereference);
2771 }
2772
Eval() const2773 bool Condition::Eval() const { return (*this->eval_)(this); }
2774
GuaranteedEqual(const Condition * a,const Condition * b)2775 bool Condition::GuaranteedEqual(const Condition* a, const Condition* b) {
2776 if (a == nullptr || b == nullptr) {
2777 return a == b;
2778 }
2779 // Check equality of the representative fields.
2780 return a->eval_ == b->eval_ && a->arg_ == b->arg_ &&
2781 !memcmp(a->callback_, b->callback_, sizeof(a->callback_));
2782 }
2783
2784 ABSL_NAMESPACE_END
2785 } // namespace absl
2786