Coverage Report

Created: 2026-08-13 07:15

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