Coverage Report

Created: 2026-10-28 06:49

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