Coverage Report

Created: 2026-09-14 06:45

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