mutex.cc
Go to the documentation of this file.
00001 // Copyright 2017 The Abseil Authors.
00002 //
00003 // Licensed under the Apache License, Version 2.0 (the "License");
00004 // you may not use this file except in compliance with the License.
00005 // You may obtain a copy of the License at
00006 //
00007 //      https://www.apache.org/licenses/LICENSE-2.0
00008 //
00009 // Unless required by applicable law or agreed to in writing, software
00010 // distributed under the License is distributed on an "AS IS" BASIS,
00011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00012 // See the License for the specific language governing permissions and
00013 // limitations under the License.
00014 
00015 #include "absl/synchronization/mutex.h"
00016 
00017 #ifdef _WIN32
00018 #include <windows.h>
00019 #ifdef ERROR
00020 #undef ERROR
00021 #endif
00022 #else
00023 #include <fcntl.h>
00024 #include <pthread.h>
00025 #include <sched.h>
00026 #include <sys/time.h>
00027 #endif
00028 
00029 #include <assert.h>
00030 #include <errno.h>
00031 #include <stdio.h>
00032 #include <stdlib.h>
00033 #include <string.h>
00034 #include <time.h>
00035 
00036 #include <algorithm>
00037 #include <atomic>
00038 #include <cinttypes>
00039 #include <thread>  // NOLINT(build/c++11)
00040 
00041 #include "absl/base/attributes.h"
00042 #include "absl/base/config.h"
00043 #include "absl/base/dynamic_annotations.h"
00044 #include "absl/base/internal/atomic_hook.h"
00045 #include "absl/base/internal/cycleclock.h"
00046 #include "absl/base/internal/hide_ptr.h"
00047 #include "absl/base/internal/low_level_alloc.h"
00048 #include "absl/base/internal/raw_logging.h"
00049 #include "absl/base/internal/spinlock.h"
00050 #include "absl/base/internal/sysinfo.h"
00051 #include "absl/base/internal/thread_identity.h"
00052 #include "absl/base/port.h"
00053 #include "absl/debugging/stacktrace.h"
00054 #include "absl/debugging/symbolize.h"
00055 #include "absl/synchronization/internal/graphcycles.h"
00056 #include "absl/synchronization/internal/per_thread_sem.h"
00057 #include "absl/time/time.h"
00058 
00059 using absl::base_internal::CurrentThreadIdentityIfPresent;
00060 using absl::base_internal::PerThreadSynch;
00061 using absl::base_internal::ThreadIdentity;
00062 using absl::synchronization_internal::GetOrCreateCurrentThreadIdentity;
00063 using absl::synchronization_internal::GraphCycles;
00064 using absl::synchronization_internal::GraphId;
00065 using absl::synchronization_internal::InvalidGraphId;
00066 using absl::synchronization_internal::KernelTimeout;
00067 using absl::synchronization_internal::PerThreadSem;
00068 
00069 extern "C" {
00070 ABSL_ATTRIBUTE_WEAK void AbslInternalMutexYield() { std::this_thread::yield(); }
00071 }  // extern "C"
00072 
00073 namespace absl {
00074 
00075 namespace {
00076 
00077 #if defined(THREAD_SANITIZER)
00078 constexpr OnDeadlockCycle kDeadlockDetectionDefault = OnDeadlockCycle::kIgnore;
00079 #else
00080 constexpr OnDeadlockCycle kDeadlockDetectionDefault = OnDeadlockCycle::kAbort;
00081 #endif
00082 
00083 ABSL_CONST_INIT std::atomic<OnDeadlockCycle> synch_deadlock_detection(
00084     kDeadlockDetectionDefault);
00085 ABSL_CONST_INIT std::atomic<bool> synch_check_invariants(false);
00086 
00087 // ------------------------------------------ spinlock support
00088 
00089 // Make sure read-only globals used in the Mutex code are contained on the
00090 // same cacheline and cacheline aligned to eliminate any false sharing with
00091 // other globals from this and other modules.
00092 static struct MutexGlobals {
00093   MutexGlobals() {
00094     // Find machine-specific data needed for Delay() and
00095     // TryAcquireWithSpinning(). This runs in the global constructor
00096     // sequence, and before that zeros are safe values.
00097     num_cpus = absl::base_internal::NumCPUs();
00098     spinloop_iterations = num_cpus > 1 ? 1500 : 0;
00099   }
00100   int num_cpus;
00101   int spinloop_iterations;
00102   // Pad this struct to a full cacheline to prevent false sharing.
00103   char padding[ABSL_CACHELINE_SIZE - 2 * sizeof(int)];
00104 } ABSL_CACHELINE_ALIGNED mutex_globals;
00105 static_assert(
00106     sizeof(MutexGlobals) == ABSL_CACHELINE_SIZE,
00107     "MutexGlobals must occupy an entire cacheline to prevent false sharing");
00108 
00109 ABSL_CONST_INIT absl::base_internal::AtomicHook<void (*)(int64_t wait_cycles)>
00110     submit_profile_data;
00111 ABSL_CONST_INIT absl::base_internal::AtomicHook<
00112     void (*)(const char *msg, const void *obj, int64_t wait_cycles)> mutex_tracer;
00113 ABSL_CONST_INIT absl::base_internal::AtomicHook<
00114     void (*)(const char *msg, const void *cv)> cond_var_tracer;
00115 ABSL_CONST_INIT absl::base_internal::AtomicHook<
00116     bool (*)(const void *pc, char *out, int out_size)>
00117     symbolizer(absl::Symbolize);
00118 
00119 }  // namespace
00120 
00121 static inline bool EvalConditionAnnotated(const Condition *cond, Mutex *mu,
00122                                           bool locking, bool trylock,
00123                                           bool read_lock);
00124 
00125 void RegisterMutexProfiler(void (*fn)(int64_t wait_timestamp)) {
00126   submit_profile_data.Store(fn);
00127 }
00128 
00129 void RegisterMutexTracer(void (*fn)(const char *msg, const void *obj,
00130                                     int64_t wait_cycles)) {
00131   mutex_tracer.Store(fn);
00132 }
00133 
00134 void RegisterCondVarTracer(void (*fn)(const char *msg, const void *cv)) {
00135   cond_var_tracer.Store(fn);
00136 }
00137 
00138 void RegisterSymbolizer(bool (*fn)(const void *pc, char *out, int out_size)) {
00139   symbolizer.Store(fn);
00140 }
00141 
00142 // spinlock delay on iteration c.  Returns new c.
00143 namespace {
00144   enum DelayMode { AGGRESSIVE, GENTLE };
00145 };
00146 static int Delay(int32_t c, DelayMode mode) {
00147   // If this a uniprocessor, only yield/sleep.  Otherwise, if the mode is
00148   // aggressive then spin many times before yielding.  If the mode is
00149   // gentle then spin only a few times before yielding.  Aggressive spinning is
00150   // used to ensure that an Unlock() call, which  must get the spin lock for
00151   // any thread to make progress gets it without undue delay.
00152   int32_t limit = (mutex_globals.num_cpus > 1) ?
00153       ((mode == AGGRESSIVE) ? 5000 : 250) : 0;
00154   if (c < limit) {
00155     c++;               // spin
00156   } else {
00157     ABSL_TSAN_MUTEX_PRE_DIVERT(nullptr, 0);
00158     if (c == limit) {  // yield once
00159       AbslInternalMutexYield();
00160       c++;
00161     } else {           // then wait
00162       absl::SleepFor(absl::Microseconds(10));
00163       c = 0;
00164     }
00165     ABSL_TSAN_MUTEX_POST_DIVERT(nullptr, 0);
00166   }
00167   return (c);
00168 }
00169 
00170 // --------------------------Generic atomic ops
00171 // Ensure that "(*pv & bits) == bits" by doing an atomic update of "*pv" to
00172 // "*pv | bits" if necessary.  Wait until (*pv & wait_until_clear)==0
00173 // before making any change.
00174 // This is used to set flags in mutex and condition variable words.
00175 static void AtomicSetBits(std::atomic<intptr_t>* pv, intptr_t bits,
00176                           intptr_t wait_until_clear) {
00177   intptr_t v;
00178   do {
00179     v = pv->load(std::memory_order_relaxed);
00180   } while ((v & bits) != bits &&
00181            ((v & wait_until_clear) != 0 ||
00182             !pv->compare_exchange_weak(v, v | bits,
00183                                        std::memory_order_release,
00184                                        std::memory_order_relaxed)));
00185 }
00186 
00187 // Ensure that "(*pv & bits) == 0" by doing an atomic update of "*pv" to
00188 // "*pv & ~bits" if necessary.  Wait until (*pv & wait_until_clear)==0
00189 // before making any change.
00190 // This is used to unset flags in mutex and condition variable words.
00191 static void AtomicClearBits(std::atomic<intptr_t>* pv, intptr_t bits,
00192                             intptr_t wait_until_clear) {
00193   intptr_t v;
00194   do {
00195     v = pv->load(std::memory_order_relaxed);
00196   } while ((v & bits) != 0 &&
00197            ((v & wait_until_clear) != 0 ||
00198             !pv->compare_exchange_weak(v, v & ~bits,
00199                                        std::memory_order_release,
00200                                        std::memory_order_relaxed)));
00201 }
00202 
00203 //------------------------------------------------------------------
00204 
00205 // Data for doing deadlock detection.
00206 static absl::base_internal::SpinLock deadlock_graph_mu(
00207     absl::base_internal::kLinkerInitialized);
00208 
00209 // graph used to detect deadlocks.
00210 static GraphCycles *deadlock_graph GUARDED_BY(deadlock_graph_mu)
00211     PT_GUARDED_BY(deadlock_graph_mu);
00212 
00213 //------------------------------------------------------------------
00214 // An event mechanism for debugging mutex use.
00215 // It also allows mutexes to be given names for those who can't handle
00216 // addresses, and instead like to give their data structures names like
00217 // "Henry", "Fido", or "Rupert IV, King of Yondavia".
00218 
00219 namespace {  // to prevent name pollution
00220 enum {       // Mutex and CondVar events passed as "ev" to PostSynchEvent
00221              // Mutex events
00222   SYNCH_EV_TRYLOCK_SUCCESS,
00223   SYNCH_EV_TRYLOCK_FAILED,
00224   SYNCH_EV_READERTRYLOCK_SUCCESS,
00225   SYNCH_EV_READERTRYLOCK_FAILED,
00226   SYNCH_EV_LOCK,
00227   SYNCH_EV_LOCK_RETURNING,
00228   SYNCH_EV_READERLOCK,
00229   SYNCH_EV_READERLOCK_RETURNING,
00230   SYNCH_EV_UNLOCK,
00231   SYNCH_EV_READERUNLOCK,
00232 
00233   // CondVar events
00234   SYNCH_EV_WAIT,
00235   SYNCH_EV_WAIT_RETURNING,
00236   SYNCH_EV_SIGNAL,
00237   SYNCH_EV_SIGNALALL,
00238 };
00239 
00240 enum {                    // Event flags
00241   SYNCH_F_R = 0x01,       // reader event
00242   SYNCH_F_LCK = 0x02,     // PostSynchEvent called with mutex held
00243   SYNCH_F_TRY = 0x04,     // TryLock or ReaderTryLock
00244   SYNCH_F_UNLOCK = 0x08,  // Unlock or ReaderUnlock
00245 
00246   SYNCH_F_LCK_W = SYNCH_F_LCK,
00247   SYNCH_F_LCK_R = SYNCH_F_LCK | SYNCH_F_R,
00248 };
00249 }  // anonymous namespace
00250 
00251 // Properties of the events.
00252 static const struct {
00253   int flags;
00254   const char *msg;
00255 } event_properties[] = {
00256     {SYNCH_F_LCK_W | SYNCH_F_TRY, "TryLock succeeded "},
00257     {0, "TryLock failed "},
00258     {SYNCH_F_LCK_R | SYNCH_F_TRY, "ReaderTryLock succeeded "},
00259     {0, "ReaderTryLock failed "},
00260     {0, "Lock blocking "},
00261     {SYNCH_F_LCK_W, "Lock returning "},
00262     {0, "ReaderLock blocking "},
00263     {SYNCH_F_LCK_R, "ReaderLock returning "},
00264     {SYNCH_F_LCK_W | SYNCH_F_UNLOCK, "Unlock "},
00265     {SYNCH_F_LCK_R | SYNCH_F_UNLOCK, "ReaderUnlock "},
00266     {0, "Wait on "},
00267     {0, "Wait unblocked "},
00268     {0, "Signal on "},
00269     {0, "SignalAll on "},
00270 };
00271 
00272 static absl::base_internal::SpinLock synch_event_mu(
00273     absl::base_internal::kLinkerInitialized);
00274 // protects synch_event
00275 
00276 // Hash table size; should be prime > 2.
00277 // Can't be too small, as it's used for deadlock detection information.
00278 static const uint32_t kNSynchEvent = 1031;
00279 
00280 static struct SynchEvent {     // this is a trivial hash table for the events
00281   // struct is freed when refcount reaches 0
00282   int refcount GUARDED_BY(synch_event_mu);
00283 
00284   // buckets have linear, 0-terminated  chains
00285   SynchEvent *next GUARDED_BY(synch_event_mu);
00286 
00287   // Constant after initialization
00288   uintptr_t masked_addr;  // object at this address is called "name"
00289 
00290   // No explicit synchronization used.  Instead we assume that the
00291   // client who enables/disables invariants/logging on a Mutex does so
00292   // while the Mutex is not being concurrently accessed by others.
00293   void (*invariant)(void *arg);  // called on each event
00294   void *arg;            // first arg to (*invariant)()
00295   bool log;             // logging turned on
00296 
00297   // Constant after initialization
00298   char name[1];         // actually longer---null-terminated std::string
00299 } *synch_event[kNSynchEvent] GUARDED_BY(synch_event_mu);
00300 
00301 // Ensure that the object at "addr" has a SynchEvent struct associated with it,
00302 // set "bits" in the word there (waiting until lockbit is clear before doing
00303 // so), and return a refcounted reference that will remain valid until
00304 // UnrefSynchEvent() is called.  If a new SynchEvent is allocated,
00305 // the string name is copied into it.
00306 // When used with a mutex, the caller should also ensure that kMuEvent
00307 // is set in the mutex word, and similarly for condition variables and kCVEvent.
00308 static SynchEvent *EnsureSynchEvent(std::atomic<intptr_t> *addr,
00309                                     const char *name, intptr_t bits,
00310                                     intptr_t lockbit) {
00311   uint32_t h = reinterpret_cast<intptr_t>(addr) % kNSynchEvent;
00312   SynchEvent *e;
00313   // first look for existing SynchEvent struct..
00314   synch_event_mu.Lock();
00315   for (e = synch_event[h];
00316        e != nullptr && e->masked_addr != base_internal::HidePtr(addr);
00317        e = e->next) {
00318   }
00319   if (e == nullptr) {  // no SynchEvent struct found; make one.
00320     if (name == nullptr) {
00321       name = "";
00322     }
00323     size_t l = strlen(name);
00324     e = reinterpret_cast<SynchEvent *>(
00325         base_internal::LowLevelAlloc::Alloc(sizeof(*e) + l));
00326     e->refcount = 2;    // one for return value, one for linked list
00327     e->masked_addr = base_internal::HidePtr(addr);
00328     e->invariant = nullptr;
00329     e->arg = nullptr;
00330     e->log = false;
00331     strcpy(e->name, name);  // NOLINT(runtime/printf)
00332     e->next = synch_event[h];
00333     AtomicSetBits(addr, bits, lockbit);
00334     synch_event[h] = e;
00335   } else {
00336     e->refcount++;      // for return value
00337   }
00338   synch_event_mu.Unlock();
00339   return e;
00340 }
00341 
00342 // Deallocate the SynchEvent *e, whose refcount has fallen to zero.
00343 static void DeleteSynchEvent(SynchEvent *e) {
00344   base_internal::LowLevelAlloc::Free(e);
00345 }
00346 
00347 // Decrement the reference count of *e, or do nothing if e==null.
00348 static void UnrefSynchEvent(SynchEvent *e) {
00349   if (e != nullptr) {
00350     synch_event_mu.Lock();
00351     bool del = (--(e->refcount) == 0);
00352     synch_event_mu.Unlock();
00353     if (del) {
00354       DeleteSynchEvent(e);
00355     }
00356   }
00357 }
00358 
00359 // Forget the mapping from the object (Mutex or CondVar) at address addr
00360 // to SynchEvent object, and clear "bits" in its word (waiting until lockbit
00361 // is clear before doing so).
00362 static void ForgetSynchEvent(std::atomic<intptr_t> *addr, intptr_t bits,
00363                              intptr_t lockbit) {
00364   uint32_t h = reinterpret_cast<intptr_t>(addr) % kNSynchEvent;
00365   SynchEvent **pe;
00366   SynchEvent *e;
00367   synch_event_mu.Lock();
00368   for (pe = &synch_event[h];
00369        (e = *pe) != nullptr && e->masked_addr != base_internal::HidePtr(addr);
00370        pe = &e->next) {
00371   }
00372   bool del = false;
00373   if (e != nullptr) {
00374     *pe = e->next;
00375     del = (--(e->refcount) == 0);
00376   }
00377   AtomicClearBits(addr, bits, lockbit);
00378   synch_event_mu.Unlock();
00379   if (del) {
00380     DeleteSynchEvent(e);
00381   }
00382 }
00383 
00384 // Return a refcounted reference to the SynchEvent of the object at address
00385 // "addr", if any.  The pointer returned is valid until the UnrefSynchEvent() is
00386 // called.
00387 static SynchEvent *GetSynchEvent(const void *addr) {
00388   uint32_t h = reinterpret_cast<intptr_t>(addr) % kNSynchEvent;
00389   SynchEvent *e;
00390   synch_event_mu.Lock();
00391   for (e = synch_event[h];
00392        e != nullptr && e->masked_addr != base_internal::HidePtr(addr);
00393        e = e->next) {
00394   }
00395   if (e != nullptr) {
00396     e->refcount++;
00397   }
00398   synch_event_mu.Unlock();
00399   return e;
00400 }
00401 
00402 // Called when an event "ev" occurs on a Mutex of CondVar "obj"
00403 // if event recording is on
00404 static void PostSynchEvent(void *obj, int ev) {
00405   SynchEvent *e = GetSynchEvent(obj);
00406   // logging is on if event recording is on and either there's no event struct,
00407   // or it explicitly says to log
00408   if (e == nullptr || e->log) {
00409     void *pcs[40];
00410     int n = absl::GetStackTrace(pcs, ABSL_ARRAYSIZE(pcs), 1);
00411     // A buffer with enough space for the ASCII for all the PCs, even on a
00412     // 64-bit machine.
00413     char buffer[ABSL_ARRAYSIZE(pcs) * 24];
00414     int pos = snprintf(buffer, sizeof (buffer), " @");
00415     for (int i = 0; i != n; i++) {
00416       pos += snprintf(&buffer[pos], sizeof (buffer) - pos, " %p", pcs[i]);
00417     }
00418     ABSL_RAW_LOG(INFO, "%s%p %s %s", event_properties[ev].msg, obj,
00419                  (e == nullptr ? "" : e->name), buffer);
00420   }
00421   const int flags = event_properties[ev].flags;
00422   if ((flags & SYNCH_F_LCK) != 0 && e != nullptr && e->invariant != nullptr) {
00423     // Calling the invariant as is causes problems under ThreadSanitizer.
00424     // We are currently inside of Mutex Lock/Unlock and are ignoring all
00425     // memory accesses and synchronization. If the invariant transitively
00426     // synchronizes something else and we ignore the synchronization, we will
00427     // get false positive race reports later.
00428     // Reuse EvalConditionAnnotated to properly call into user code.
00429     struct local {
00430       static bool pred(SynchEvent *ev) {
00431         (*ev->invariant)(ev->arg);
00432         return false;
00433       }
00434     };
00435     Condition cond(&local::pred, e);
00436     Mutex *mu = static_cast<Mutex *>(obj);
00437     const bool locking = (flags & SYNCH_F_UNLOCK) == 0;
00438     const bool trylock = (flags & SYNCH_F_TRY) != 0;
00439     const bool read_lock = (flags & SYNCH_F_R) != 0;
00440     EvalConditionAnnotated(&cond, mu, locking, trylock, read_lock);
00441   }
00442   UnrefSynchEvent(e);
00443 }
00444 
00445 //------------------------------------------------------------------
00446 
00447 // The SynchWaitParams struct encapsulates the way in which a thread is waiting:
00448 // whether it has a timeout, the condition, exclusive/shared, and whether a
00449 // condition variable wait has an associated Mutex (as opposed to another
00450 // type of lock).  It also points to the PerThreadSynch struct of its thread.
00451 // cv_word tells Enqueue() to enqueue on a CondVar using CondVarEnqueue().
00452 //
00453 // This structure is held on the stack rather than directly in
00454 // PerThreadSynch because a thread can be waiting on multiple Mutexes if,
00455 // while waiting on one Mutex, the implementation calls a client callback
00456 // (such as a Condition function) that acquires another Mutex. We don't
00457 // strictly need to allow this, but programmers become confused if we do not
00458 // allow them to use functions such a LOG() within Condition functions.  The
00459 // PerThreadSynch struct points at the most recent SynchWaitParams struct when
00460 // the thread is on a Mutex's waiter queue.
00461 struct SynchWaitParams {
00462   SynchWaitParams(Mutex::MuHow how_arg, const Condition *cond_arg,
00463                   KernelTimeout timeout_arg, Mutex *cvmu_arg,
00464                   PerThreadSynch *thread_arg,
00465                   std::atomic<intptr_t> *cv_word_arg)
00466       : how(how_arg),
00467         cond(cond_arg),
00468         timeout(timeout_arg),
00469         cvmu(cvmu_arg),
00470         thread(thread_arg),
00471         cv_word(cv_word_arg),
00472         contention_start_cycles(base_internal::CycleClock::Now()) {}
00473 
00474   const Mutex::MuHow how;  // How this thread needs to wait.
00475   const Condition *cond;  // The condition that this thread is waiting for.
00476                           // In Mutex, this field is set to zero if a timeout
00477                           // expires.
00478   KernelTimeout timeout;  // timeout expiry---absolute time
00479                           // In Mutex, this field is set to zero if a timeout
00480                           // expires.
00481   Mutex *const cvmu;      // used for transfer from cond var to mutex
00482   PerThreadSynch *const thread;  // thread that is waiting
00483 
00484   // If not null, thread should be enqueued on the CondVar whose state
00485   // word is cv_word instead of queueing normally on the Mutex.
00486   std::atomic<intptr_t> *cv_word;
00487 
00488   int64_t contention_start_cycles;  // Time (in cycles) when this thread started
00489                                   // to contend for the mutex.
00490 };
00491 
00492 struct SynchLocksHeld {
00493   int n;              // number of valid entries in locks[]
00494   bool overflow;      // true iff we overflowed the array at some point
00495   struct {
00496     Mutex *mu;        // lock acquired
00497     int32_t count;      // times acquired
00498     GraphId id;       // deadlock_graph id of acquired lock
00499   } locks[40];
00500   // If a thread overfills the array during deadlock detection, we
00501   // continue, discarding information as needed.  If no overflow has
00502   // taken place, we can provide more error checking, such as
00503   // detecting when a thread releases a lock it does not hold.
00504 };
00505 
00506 // A sentinel value in lists that is not 0.
00507 // A 0 value is used to mean "not on a list".
00508 static PerThreadSynch *const kPerThreadSynchNull =
00509   reinterpret_cast<PerThreadSynch *>(1);
00510 
00511 static SynchLocksHeld *LocksHeldAlloc() {
00512   SynchLocksHeld *ret = reinterpret_cast<SynchLocksHeld *>(
00513       base_internal::LowLevelAlloc::Alloc(sizeof(SynchLocksHeld)));
00514   ret->n = 0;
00515   ret->overflow = false;
00516   return ret;
00517 }
00518 
00519 // Return the PerThreadSynch-struct for this thread.
00520 static PerThreadSynch *Synch_GetPerThread() {
00521   ThreadIdentity *identity = GetOrCreateCurrentThreadIdentity();
00522   return &identity->per_thread_synch;
00523 }
00524 
00525 static PerThreadSynch *Synch_GetPerThreadAnnotated(Mutex *mu) {
00526   if (mu) {
00527     ABSL_TSAN_MUTEX_PRE_DIVERT(mu, 0);
00528   }
00529   PerThreadSynch *w = Synch_GetPerThread();
00530   if (mu) {
00531     ABSL_TSAN_MUTEX_POST_DIVERT(mu, 0);
00532   }
00533   return w;
00534 }
00535 
00536 static SynchLocksHeld *Synch_GetAllLocks() {
00537   PerThreadSynch *s = Synch_GetPerThread();
00538   if (s->all_locks == nullptr) {
00539     s->all_locks = LocksHeldAlloc();  // Freed by ReclaimThreadIdentity.
00540   }
00541   return s->all_locks;
00542 }
00543 
00544 // Post on "w"'s associated PerThreadSem.
00545 inline void Mutex::IncrementSynchSem(Mutex *mu, PerThreadSynch *w) {
00546   if (mu) {
00547     ABSL_TSAN_MUTEX_PRE_DIVERT(mu, 0);
00548   }
00549   PerThreadSem::Post(w->thread_identity());
00550   if (mu) {
00551     ABSL_TSAN_MUTEX_POST_DIVERT(mu, 0);
00552   }
00553 }
00554 
00555 // Wait on "w"'s associated PerThreadSem; returns false if timeout expired.
00556 bool Mutex::DecrementSynchSem(Mutex *mu, PerThreadSynch *w, KernelTimeout t) {
00557   if (mu) {
00558     ABSL_TSAN_MUTEX_PRE_DIVERT(mu, 0);
00559   }
00560   assert(w == Synch_GetPerThread());
00561   static_cast<void>(w);
00562   bool res = PerThreadSem::Wait(t);
00563   if (mu) {
00564     ABSL_TSAN_MUTEX_POST_DIVERT(mu, 0);
00565   }
00566   return res;
00567 }
00568 
00569 // We're in a fatal signal handler that hopes to use Mutex and to get
00570 // lucky by not deadlocking.  We try to improve its chances of success
00571 // by effectively disabling some of the consistency checks.  This will
00572 // prevent certain ABSL_RAW_CHECK() statements from being triggered when
00573 // re-rentry is detected.  The ABSL_RAW_CHECK() statements are those in the
00574 // Mutex code checking that the "waitp" field has not been reused.
00575 void Mutex::InternalAttemptToUseMutexInFatalSignalHandler() {
00576   // Fix the per-thread state only if it exists.
00577   ThreadIdentity *identity = CurrentThreadIdentityIfPresent();
00578   if (identity != nullptr) {
00579     identity->per_thread_synch.suppress_fatal_errors = true;
00580   }
00581   // Don't do deadlock detection when we are already failing.
00582   synch_deadlock_detection.store(OnDeadlockCycle::kIgnore,
00583                                  std::memory_order_release);
00584 }
00585 
00586 // --------------------------time support
00587 
00588 // Return the current time plus the timeout.  Use the same clock as
00589 // PerThreadSem::Wait() for consistency.  Unfortunately, we don't have
00590 // such a choice when a deadline is given directly.
00591 static absl::Time DeadlineFromTimeout(absl::Duration timeout) {
00592 #ifndef _WIN32
00593   struct timeval tv;
00594   gettimeofday(&tv, nullptr);
00595   return absl::TimeFromTimeval(tv) + timeout;
00596 #else
00597   return absl::Now() + timeout;
00598 #endif
00599 }
00600 
00601 // --------------------------Mutexes
00602 
00603 // In the layout below, the msb of the bottom byte is currently unused.  Also,
00604 // the following constraints were considered in choosing the layout:
00605 //  o Both the debug allocator's "uninitialized" and "freed" patterns (0xab and
00606 //    0xcd) are illegal: reader and writer lock both held.
00607 //  o kMuWriter and kMuEvent should exceed kMuDesig and kMuWait, to enable the
00608 //    bit-twiddling trick in Mutex::Unlock().
00609 //  o kMuWriter / kMuReader == kMuWrWait / kMuWait,
00610 //    to enable the bit-twiddling trick in CheckForMutexCorruption().
00611 static const intptr_t kMuReader      = 0x0001L;  // a reader holds the lock
00612 static const intptr_t kMuDesig       = 0x0002L;  // there's a designated waker
00613 static const intptr_t kMuWait        = 0x0004L;  // threads are waiting
00614 static const intptr_t kMuWriter      = 0x0008L;  // a writer holds the lock
00615 static const intptr_t kMuEvent       = 0x0010L;  // record this mutex's events
00616 // INVARIANT1:  there's a thread that was blocked on the mutex, is
00617 // no longer, yet has not yet acquired the mutex.  If there's a
00618 // designated waker, all threads can avoid taking the slow path in
00619 // unlock because the designated waker will subsequently acquire
00620 // the lock and wake someone.  To maintain INVARIANT1 the bit is
00621 // set when a thread is unblocked(INV1a), and threads that were
00622 // unblocked reset the bit when they either acquire or re-block
00623 // (INV1b).
00624 static const intptr_t kMuWrWait      = 0x0020L;  // runnable writer is waiting
00625                                                  // for a reader
00626 static const intptr_t kMuSpin        = 0x0040L;  // spinlock protects wait list
00627 static const intptr_t kMuLow         = 0x00ffL;  // mask all mutex bits
00628 static const intptr_t kMuHigh        = ~kMuLow;  // mask pointer/reader count
00629 
00630 // Hack to make constant values available to gdb pretty printer
00631 enum {
00632   kGdbMuSpin = kMuSpin,
00633   kGdbMuEvent = kMuEvent,
00634   kGdbMuWait = kMuWait,
00635   kGdbMuWriter = kMuWriter,
00636   kGdbMuDesig = kMuDesig,
00637   kGdbMuWrWait = kMuWrWait,
00638   kGdbMuReader = kMuReader,
00639   kGdbMuLow = kMuLow,
00640 };
00641 
00642 // kMuWrWait implies kMuWait.
00643 // kMuReader and kMuWriter are mutually exclusive.
00644 // If kMuReader is zero, there are no readers.
00645 // Otherwise, if kMuWait is zero, the high order bits contain a count of the
00646 // number of readers.  Otherwise, the reader count is held in
00647 // PerThreadSynch::readers of the most recently queued waiter, again in the
00648 // bits above kMuLow.
00649 static const intptr_t kMuOne = 0x0100;  // a count of one reader
00650 
00651 // flags passed to Enqueue and LockSlow{,WithTimeout,Loop}
00652 static const int kMuHasBlocked = 0x01;  // already blocked (MUST == 1)
00653 static const int kMuIsCond = 0x02;      // conditional waiter (CV or Condition)
00654 
00655 static_assert(PerThreadSynch::kAlignment > kMuLow,
00656               "PerThreadSynch::kAlignment must be greater than kMuLow");
00657 
00658 // This struct contains various bitmasks to be used in
00659 // acquiring and releasing a mutex in a particular mode.
00660 struct MuHowS {
00661   // if all the bits in fast_need_zero are zero, the lock can be acquired by
00662   // adding fast_add and oring fast_or.  The bit kMuDesig should be reset iff
00663   // this is the designated waker.
00664   intptr_t fast_need_zero;
00665   intptr_t fast_or;
00666   intptr_t fast_add;
00667 
00668   intptr_t slow_need_zero;  // fast_need_zero with events (e.g. logging)
00669 
00670   intptr_t slow_inc_need_zero;  // if all the bits in slow_inc_need_zero are
00671                                 // zero a reader can acquire a read share by
00672                                 // setting the reader bit and incrementing
00673                                 // the reader count (in last waiter since
00674                                 // we're now slow-path).  kMuWrWait be may
00675                                 // be ignored if we already waited once.
00676 };
00677 
00678 static const MuHowS kSharedS = {
00679     // shared or read lock
00680     kMuWriter | kMuWait | kMuEvent,   // fast_need_zero
00681     kMuReader,                        // fast_or
00682     kMuOne,                           // fast_add
00683     kMuWriter | kMuWait,              // slow_need_zero
00684     kMuSpin | kMuWriter | kMuWrWait,  // slow_inc_need_zero
00685 };
00686 static const MuHowS kExclusiveS = {
00687     // exclusive or write lock
00688     kMuWriter | kMuReader | kMuEvent,  // fast_need_zero
00689     kMuWriter,                         // fast_or
00690     0,                                 // fast_add
00691     kMuWriter | kMuReader,             // slow_need_zero
00692     ~static_cast<intptr_t>(0),         // slow_inc_need_zero
00693 };
00694 static const Mutex::MuHow kShared = &kSharedS;        // shared lock
00695 static const Mutex::MuHow kExclusive = &kExclusiveS;  // exclusive lock
00696 
00697 #ifdef NDEBUG
00698 static constexpr bool kDebugMode = false;
00699 #else
00700 static constexpr bool kDebugMode = true;
00701 #endif
00702 
00703 #ifdef THREAD_SANITIZER
00704 static unsigned TsanFlags(Mutex::MuHow how) {
00705   return how == kShared ? __tsan_mutex_read_lock : 0;
00706 }
00707 #endif
00708 
00709 static bool DebugOnlyIsExiting() {
00710   return false;
00711 }
00712 
00713 Mutex::~Mutex() {
00714   intptr_t v = mu_.load(std::memory_order_relaxed);
00715   if ((v & kMuEvent) != 0 && !DebugOnlyIsExiting()) {
00716     ForgetSynchEvent(&this->mu_, kMuEvent, kMuSpin);
00717   }
00718   if (kDebugMode) {
00719     this->ForgetDeadlockInfo();
00720   }
00721   ABSL_TSAN_MUTEX_DESTROY(this, __tsan_mutex_not_static);
00722 }
00723 
00724 void Mutex::EnableDebugLog(const char *name) {
00725   SynchEvent *e = EnsureSynchEvent(&this->mu_, name, kMuEvent, kMuSpin);
00726   e->log = true;
00727   UnrefSynchEvent(e);
00728 }
00729 
00730 void EnableMutexInvariantDebugging(bool enabled) {
00731   synch_check_invariants.store(enabled, std::memory_order_release);
00732 }
00733 
00734 void Mutex::EnableInvariantDebugging(void (*invariant)(void *),
00735                                      void *arg) {
00736   if (synch_check_invariants.load(std::memory_order_acquire) &&
00737       invariant != nullptr) {
00738     SynchEvent *e = EnsureSynchEvent(&this->mu_, nullptr, kMuEvent, kMuSpin);
00739     e->invariant = invariant;
00740     e->arg = arg;
00741     UnrefSynchEvent(e);
00742   }
00743 }
00744 
00745 void SetMutexDeadlockDetectionMode(OnDeadlockCycle mode) {
00746   synch_deadlock_detection.store(mode, std::memory_order_release);
00747 }
00748 
00749 // Return true iff threads x and y are waiting on the same condition for the
00750 // same type of lock.  Requires that x and y be waiting on the same Mutex
00751 // queue.
00752 static bool MuSameCondition(PerThreadSynch *x, PerThreadSynch *y) {
00753   return x->waitp->how == y->waitp->how &&
00754          Condition::GuaranteedEqual(x->waitp->cond, y->waitp->cond);
00755 }
00756 
00757 // Given the contents of a mutex word containing a PerThreadSynch pointer,
00758 // return the pointer.
00759 static inline PerThreadSynch *GetPerThreadSynch(intptr_t v) {
00760   return reinterpret_cast<PerThreadSynch *>(v & kMuHigh);
00761 }
00762 
00763 // The next several routines maintain the per-thread next and skip fields
00764 // used in the Mutex waiter queue.
00765 // The queue is a circular singly-linked list, of which the "head" is the
00766 // last element, and head->next if the first element.
00767 // The skip field has the invariant:
00768 //   For thread x, x->skip is one of:
00769 //     - invalid (iff x is not in a Mutex wait queue),
00770 //     - null, or
00771 //     - a pointer to a distinct thread waiting later in the same Mutex queue
00772 //       such that all threads in [x, x->skip] have the same condition and
00773 //       lock type (MuSameCondition() is true for all pairs in [x, x->skip]).
00774 // In addition, if x->skip is  valid, (x->may_skip || x->skip == null)
00775 //
00776 // By the spec of MuSameCondition(), it is not necessary when removing the
00777 // first runnable thread y from the front a Mutex queue to adjust the skip
00778 // field of another thread x because if x->skip==y, x->skip must (have) become
00779 // invalid before y is removed.  The function TryRemove can remove a specified
00780 // thread from an arbitrary position in the queue whether runnable or not, so
00781 // it fixes up skip fields that would otherwise be left dangling.
00782 // The statement
00783 //     if (x->may_skip && MuSameCondition(x, x->next)) { x->skip = x->next; }
00784 // maintains the invariant provided x is not the last waiter in a Mutex queue
00785 // The statement
00786 //          if (x->skip != null) { x->skip = x->skip->skip; }
00787 // maintains the invariant.
00788 
00789 // Returns the last thread y in a mutex waiter queue such that all threads in
00790 // [x, y] inclusive share the same condition.  Sets skip fields of some threads
00791 // in that range to optimize future evaluation of Skip() on x values in
00792 // the range.  Requires thread x is in a mutex waiter queue.
00793 // The locking is unusual.  Skip() is called under these conditions:
00794 //   - spinlock is held in call from Enqueue(), with maybe_unlocking == false
00795 //   - Mutex is held in call from UnlockSlow() by last unlocker, with
00796 //     maybe_unlocking == true
00797 //   - both Mutex and spinlock are held in call from DequeueAllWakeable() (from
00798 //     UnlockSlow()) and TryRemove()
00799 // These cases are mutually exclusive, so Skip() never runs concurrently
00800 // with itself on the same Mutex.   The skip chain is used in these other places
00801 // that cannot occur concurrently:
00802 //   - FixSkip() (from TryRemove()) - spinlock and Mutex are held)
00803 //   - Dequeue() (with spinlock and Mutex held)
00804 //   - UnlockSlow() (with spinlock and Mutex held)
00805 // A more complex case is Enqueue()
00806 //   - Enqueue() (with spinlock held and maybe_unlocking == false)
00807 //               This is the first case in which Skip is called, above.
00808 //   - Enqueue() (without spinlock held; but queue is empty and being freshly
00809 //                formed)
00810 //   - Enqueue() (with spinlock held and maybe_unlocking == true)
00811 // The first case has mutual exclusion, and the second isolation through
00812 // working on an otherwise unreachable data structure.
00813 // In the last case, Enqueue() is required to change no skip/next pointers
00814 // except those in the added node and the former "head" node.  This implies
00815 // that the new node is added after head, and so must be the new head or the
00816 // new front of the queue.
00817 static PerThreadSynch *Skip(PerThreadSynch *x) {
00818   PerThreadSynch *x0 = nullptr;
00819   PerThreadSynch *x1 = x;
00820   PerThreadSynch *x2 = x->skip;
00821   if (x2 != nullptr) {
00822     // Each iteration attempts to advance sequence (x0,x1,x2) to next sequence
00823     // such that   x1 == x0->skip && x2 == x1->skip
00824     while ((x0 = x1, x1 = x2, x2 = x2->skip) != nullptr) {
00825       x0->skip = x2;      // short-circuit skip from x0 to x2
00826     }
00827     x->skip = x1;         // short-circuit skip from x to result
00828   }
00829   return x1;
00830 }
00831 
00832 // "ancestor" appears before "to_be_removed" in the same Mutex waiter queue.
00833 // The latter is going to be removed out of order, because of a timeout.
00834 // Check whether "ancestor" has a skip field pointing to "to_be_removed",
00835 // and fix it if it does.
00836 static void FixSkip(PerThreadSynch *ancestor, PerThreadSynch *to_be_removed) {
00837   if (ancestor->skip == to_be_removed) {  // ancestor->skip left dangling
00838     if (to_be_removed->skip != nullptr) {
00839       ancestor->skip = to_be_removed->skip;  // can skip past to_be_removed
00840     } else if (ancestor->next != to_be_removed) {  // they are not adjacent
00841       ancestor->skip = ancestor->next;             // can skip one past ancestor
00842     } else {
00843       ancestor->skip = nullptr;  // can't skip at all
00844     }
00845   }
00846 }
00847 
00848 static void CondVarEnqueue(SynchWaitParams *waitp);
00849 
00850 // Enqueue thread "waitp->thread" on a waiter queue.
00851 // Called with mutex spinlock held if head != nullptr
00852 // If head==nullptr and waitp->cv_word==nullptr, then Enqueue() is
00853 // idempotent; it alters no state associated with the existing (empty)
00854 // queue.
00855 //
00856 // If waitp->cv_word == nullptr, queue the thread at either the front or
00857 // the end (according to its priority) of the circular mutex waiter queue whose
00858 // head is "head", and return the new head.  mu is the previous mutex state,
00859 // which contains the reader count (perhaps adjusted for the operation in
00860 // progress) if the list was empty and a read lock held, and the holder hint if
00861 // the list was empty and a write lock held.  (flags & kMuIsCond) indicates
00862 // whether this thread was transferred from a CondVar or is waiting for a
00863 // non-trivial condition.  In this case, Enqueue() never returns nullptr
00864 //
00865 // If waitp->cv_word != nullptr, CondVarEnqueue() is called, and "head" is
00866 // returned. This mechanism is used by CondVar to queue a thread on the
00867 // condition variable queue instead of the mutex queue in implementing Wait().
00868 // In this case, Enqueue() can return nullptr (if head==nullptr).
00869 static PerThreadSynch *Enqueue(PerThreadSynch *head,
00870                                SynchWaitParams *waitp, intptr_t mu, int flags) {
00871   // If we have been given a cv_word, call CondVarEnqueue() and return
00872   // the previous head of the Mutex waiter queue.
00873   if (waitp->cv_word != nullptr) {
00874     CondVarEnqueue(waitp);
00875     return head;
00876   }
00877 
00878   PerThreadSynch *s = waitp->thread;
00879   ABSL_RAW_CHECK(
00880       s->waitp == nullptr ||    // normal case
00881           s->waitp == waitp ||  // Fer()---transfer from condition variable
00882           s->suppress_fatal_errors,
00883       "detected illegal recursion into Mutex code");
00884   s->waitp = waitp;
00885   s->skip = nullptr;             // maintain skip invariant (see above)
00886   s->may_skip = true;            // always true on entering queue
00887   s->wake = false;               // not being woken
00888   s->cond_waiter = ((flags & kMuIsCond) != 0);
00889   if (head == nullptr) {         // s is the only waiter
00890     s->next = s;                 // it's the only entry in the cycle
00891     s->readers = mu;             // reader count is from mu word
00892     s->maybe_unlocking = false;  // no one is searching an empty list
00893     head = s;                    // s is new head
00894   } else {
00895     PerThreadSynch *enqueue_after = nullptr;  // we'll put s after this element
00896 #ifdef ABSL_HAVE_PTHREAD_GETSCHEDPARAM
00897     int64_t now_cycles = base_internal::CycleClock::Now();
00898     if (s->next_priority_read_cycles < now_cycles) {
00899       // Every so often, update our idea of the thread's priority.
00900       // pthread_getschedparam() is 5% of the block/wakeup time;
00901       // base_internal::CycleClock::Now() is 0.5%.
00902       int policy;
00903       struct sched_param param;
00904       const int err = pthread_getschedparam(pthread_self(), &policy, &param);
00905       if (err != 0) {
00906         ABSL_RAW_LOG(ERROR, "pthread_getschedparam failed: %d", err);
00907       } else {
00908         s->priority = param.sched_priority;
00909         s->next_priority_read_cycles =
00910             now_cycles +
00911             static_cast<int64_t>(base_internal::CycleClock::Frequency());
00912       }
00913     }
00914     if (s->priority > head->priority) {  // s's priority is above head's
00915       // try to put s in priority-fifo order, or failing that at the front.
00916       if (!head->maybe_unlocking) {
00917         // No unlocker can be scanning the queue, so we can insert between
00918         // skip-chains, and within a skip-chain if it has the same condition as
00919         // s.  We insert in priority-fifo order, examining the end of every
00920         // skip-chain, plus every element with the same condition as s.
00921         PerThreadSynch *advance_to = head;    // next value of enqueue_after
00922         PerThreadSynch *cur;                  // successor of enqueue_after
00923         do {
00924           enqueue_after = advance_to;
00925           cur = enqueue_after->next;  // this advance ensures progress
00926           advance_to = Skip(cur);   // normally, advance to end of skip chain
00927                                     // (side-effect: optimizes skip chain)
00928           if (advance_to != cur && s->priority > advance_to->priority &&
00929               MuSameCondition(s, cur)) {
00930             // but this skip chain is not a singleton, s has higher priority
00931             // than its tail and has the same condition as the chain,
00932             // so we can insert within the skip-chain
00933             advance_to = cur;         // advance by just one
00934           }
00935         } while (s->priority <= advance_to->priority);
00936               // termination guaranteed because s->priority > head->priority
00937               // and head is the end of a skip chain
00938       } else if (waitp->how == kExclusive &&
00939                  Condition::GuaranteedEqual(waitp->cond, nullptr)) {
00940         // An unlocker could be scanning the queue, but we know it will recheck
00941         // the queue front for writers that have no condition, which is what s
00942         // is, so an insert at front is safe.
00943         enqueue_after = head;       // add after head, at front
00944       }
00945     }
00946 #endif
00947     if (enqueue_after != nullptr) {
00948       s->next = enqueue_after->next;
00949       enqueue_after->next = s;
00950 
00951       // enqueue_after can be: head, Skip(...), or cur.
00952       // The first two imply enqueue_after->skip == nullptr, and
00953       // the last is used only if MuSameCondition(s, cur).
00954       // We require this because clearing enqueue_after->skip
00955       // is impossible; enqueue_after's predecessors might also
00956       // incorrectly skip over s if we were to allow other
00957       // insertion points.
00958       ABSL_RAW_CHECK(
00959           enqueue_after->skip == nullptr || MuSameCondition(enqueue_after, s),
00960           "Mutex Enqueue failure");
00961 
00962       if (enqueue_after != head && enqueue_after->may_skip &&
00963           MuSameCondition(enqueue_after, enqueue_after->next)) {
00964         // enqueue_after can skip to its new successor, s
00965         enqueue_after->skip = enqueue_after->next;
00966       }
00967       if (MuSameCondition(s, s->next)) {  // s->may_skip is known to be true
00968         s->skip = s->next;                // s may skip to its successor
00969       }
00970     } else {   // enqueue not done any other way, so
00971                // we're inserting s at the back
00972       // s will become new head; copy data from head into it
00973       s->next = head->next;        // add s after head
00974       head->next = s;
00975       s->readers = head->readers;  // reader count is from previous head
00976       s->maybe_unlocking = head->maybe_unlocking;  // same for unlock hint
00977       if (head->may_skip && MuSameCondition(head, s)) {
00978         // head now has successor; may skip
00979         head->skip = s;
00980       }
00981       head = s;  // s is new head
00982     }
00983   }
00984   s->state.store(PerThreadSynch::kQueued, std::memory_order_relaxed);
00985   return head;
00986 }
00987 
00988 // Dequeue the successor pw->next of thread pw from the Mutex waiter queue
00989 // whose last element is head.  The new head element is returned, or null
00990 // if the list is made empty.
00991 // Dequeue is called with both spinlock and Mutex held.
00992 static PerThreadSynch *Dequeue(PerThreadSynch *head, PerThreadSynch *pw) {
00993   PerThreadSynch *w = pw->next;
00994   pw->next = w->next;         // snip w out of list
00995   if (head == w) {            // we removed the head
00996     head = (pw == w) ? nullptr : pw;  // either emptied list, or pw is new head
00997   } else if (pw != head && MuSameCondition(pw, pw->next)) {
00998     // pw can skip to its new successor
00999     if (pw->next->skip !=
01000         nullptr) {  // either skip to its successors skip target
01001       pw->skip = pw->next->skip;
01002     } else {                   // or to pw's successor
01003       pw->skip = pw->next;
01004     }
01005   }
01006   return head;
01007 }
01008 
01009 // Traverse the elements [ pw->next, h] of the circular list whose last element
01010 // is head.
01011 // Remove all elements with wake==true and place them in the
01012 // singly-linked list wake_list in the order found.   Assumes that
01013 // there is only one such element if the element has how == kExclusive.
01014 // Return the new head.
01015 static PerThreadSynch *DequeueAllWakeable(PerThreadSynch *head,
01016                                           PerThreadSynch *pw,
01017                                           PerThreadSynch **wake_tail) {
01018   PerThreadSynch *orig_h = head;
01019   PerThreadSynch *w = pw->next;
01020   bool skipped = false;
01021   do {
01022     if (w->wake) {                    // remove this element
01023       ABSL_RAW_CHECK(pw->skip == nullptr, "bad skip in DequeueAllWakeable");
01024       // we're removing pw's successor so either pw->skip is zero or we should
01025       // already have removed pw since if pw->skip!=null, pw has the same
01026       // condition as w.
01027       head = Dequeue(head, pw);
01028       w->next = *wake_tail;           // keep list terminated
01029       *wake_tail = w;                 // add w to wake_list;
01030       wake_tail = &w->next;           // next addition to end
01031       if (w->waitp->how == kExclusive) {  // wake at most 1 writer
01032         break;
01033       }
01034     } else {                // not waking this one; skip
01035       pw = Skip(w);       // skip as much as possible
01036       skipped = true;
01037     }
01038     w = pw->next;
01039     // We want to stop processing after we've considered the original head,
01040     // orig_h.  We can't test for w==orig_h in the loop because w may skip over
01041     // it; we are guaranteed only that w's predecessor will not skip over
01042     // orig_h.  When we've considered orig_h, either we've processed it and
01043     // removed it (so orig_h != head), or we considered it and skipped it (so
01044     // skipped==true && pw == head because skipping from head always skips by
01045     // just one, leaving pw pointing at head).  So we want to
01046     // continue the loop with the negation of that expression.
01047   } while (orig_h == head && (pw != head || !skipped));
01048   return head;
01049 }
01050 
01051 // Try to remove thread s from the list of waiters on this mutex.
01052 // Does nothing if s is not on the waiter list.
01053 void Mutex::TryRemove(PerThreadSynch *s) {
01054   intptr_t v = mu_.load(std::memory_order_relaxed);
01055   // acquire spinlock & lock
01056   if ((v & (kMuWait | kMuSpin | kMuWriter | kMuReader)) == kMuWait &&
01057       mu_.compare_exchange_strong(v, v | kMuSpin | kMuWriter,
01058                                   std::memory_order_acquire,
01059                                   std::memory_order_relaxed)) {
01060     PerThreadSynch *h = GetPerThreadSynch(v);
01061     if (h != nullptr) {
01062       PerThreadSynch *pw = h;   // pw is w's predecessor
01063       PerThreadSynch *w;
01064       if ((w = pw->next) != s) {  // search for thread,
01065         do {                      // processing at least one element
01066           if (!MuSameCondition(s, w)) {  // seeking different condition
01067             pw = Skip(w);                // so skip all that won't match
01068             // we don't have to worry about dangling skip fields
01069             // in the threads we skipped; none can point to s
01070             // because their condition differs from s
01071           } else {          // seeking same condition
01072             FixSkip(w, s);  // fix up any skip pointer from w to s
01073             pw = w;
01074           }
01075           // don't search further if we found the thread, or we're about to
01076           // process the first thread again.
01077         } while ((w = pw->next) != s && pw != h);
01078       }
01079       if (w == s) {                 // found thread; remove it
01080         // pw->skip may be non-zero here; the loop above ensured that
01081         // no ancestor of s can skip to s, so removal is safe anyway.
01082         h = Dequeue(h, pw);
01083         s->next = nullptr;
01084         s->state.store(PerThreadSynch::kAvailable, std::memory_order_release);
01085       }
01086     }
01087     intptr_t nv;
01088     do {                        // release spinlock and lock
01089       v = mu_.load(std::memory_order_relaxed);
01090       nv = v & (kMuDesig | kMuEvent);
01091       if (h != nullptr) {
01092         nv |= kMuWait | reinterpret_cast<intptr_t>(h);
01093         h->readers = 0;            // we hold writer lock
01094         h->maybe_unlocking = false;  // finished unlocking
01095       }
01096     } while (!mu_.compare_exchange_weak(v, nv,
01097                                         std::memory_order_release,
01098                                         std::memory_order_relaxed));
01099   }
01100 }
01101 
01102 // Wait until thread "s", which must be the current thread, is removed from the
01103 // this mutex's waiter queue.  If "s->waitp->timeout" has a timeout, wake up
01104 // if the wait extends past the absolute time specified, even if "s" is still
01105 // on the mutex queue.  In this case, remove "s" from the queue and return
01106 // true, otherwise return false.
01107 ABSL_XRAY_LOG_ARGS(1) void Mutex::Block(PerThreadSynch *s) {
01108   while (s->state.load(std::memory_order_acquire) == PerThreadSynch::kQueued) {
01109     if (!DecrementSynchSem(this, s, s->waitp->timeout)) {
01110       // After a timeout, we go into a spin loop until we remove ourselves
01111       // from the queue, or someone else removes us.  We can't be sure to be
01112       // able to remove ourselves in a single lock acquisition because this
01113       // mutex may be held, and the holder has the right to read the centre
01114       // of the waiter queue without holding the spinlock.
01115       this->TryRemove(s);
01116       int c = 0;
01117       while (s->next != nullptr) {
01118         c = Delay(c, GENTLE);
01119         this->TryRemove(s);
01120       }
01121       if (kDebugMode) {
01122         // This ensures that we test the case that TryRemove() is called when s
01123         // is not on the queue.
01124         this->TryRemove(s);
01125       }
01126       s->waitp->timeout = KernelTimeout::Never();      // timeout is satisfied
01127       s->waitp->cond = nullptr;  // condition no longer relevant for wakeups
01128     }
01129   }
01130   ABSL_RAW_CHECK(s->waitp != nullptr || s->suppress_fatal_errors,
01131                  "detected illegal recursion in Mutex code");
01132   s->waitp = nullptr;
01133 }
01134 
01135 // Wake thread w, and return the next thread in the list.
01136 PerThreadSynch *Mutex::Wakeup(PerThreadSynch *w) {
01137   PerThreadSynch *next = w->next;
01138   w->next = nullptr;
01139   w->state.store(PerThreadSynch::kAvailable, std::memory_order_release);
01140   IncrementSynchSem(this, w);
01141 
01142   return next;
01143 }
01144 
01145 static GraphId GetGraphIdLocked(Mutex *mu)
01146     EXCLUSIVE_LOCKS_REQUIRED(deadlock_graph_mu) {
01147   if (!deadlock_graph) {  // (re)create the deadlock graph.
01148     deadlock_graph =
01149         new (base_internal::LowLevelAlloc::Alloc(sizeof(*deadlock_graph)))
01150             GraphCycles;
01151   }
01152   return deadlock_graph->GetId(mu);
01153 }
01154 
01155 static GraphId GetGraphId(Mutex *mu) LOCKS_EXCLUDED(deadlock_graph_mu) {
01156   deadlock_graph_mu.Lock();
01157   GraphId id = GetGraphIdLocked(mu);
01158   deadlock_graph_mu.Unlock();
01159   return id;
01160 }
01161 
01162 // Record a lock acquisition.  This is used in debug mode for deadlock
01163 // detection.  The held_locks pointer points to the relevant data
01164 // structure for each case.
01165 static void LockEnter(Mutex* mu, GraphId id, SynchLocksHeld *held_locks) {
01166   int n = held_locks->n;
01167   int i = 0;
01168   while (i != n && held_locks->locks[i].id != id) {
01169     i++;
01170   }
01171   if (i == n) {
01172     if (n == ABSL_ARRAYSIZE(held_locks->locks)) {
01173       held_locks->overflow = true;  // lost some data
01174     } else {                        // we have room for lock
01175       held_locks->locks[i].mu = mu;
01176       held_locks->locks[i].count = 1;
01177       held_locks->locks[i].id = id;
01178       held_locks->n = n + 1;
01179     }
01180   } else {
01181     held_locks->locks[i].count++;
01182   }
01183 }
01184 
01185 // Record a lock release.  Each call to LockEnter(mu, id, x) should be
01186 // eventually followed by a call to LockLeave(mu, id, x) by the same thread.
01187 // It does not process the event if is not needed when deadlock detection is
01188 // disabled.
01189 static void LockLeave(Mutex* mu, GraphId id, SynchLocksHeld *held_locks) {
01190   int n = held_locks->n;
01191   int i = 0;
01192   while (i != n && held_locks->locks[i].id != id) {
01193     i++;
01194   }
01195   if (i == n) {
01196     if (!held_locks->overflow) {
01197       // The deadlock id may have been reassigned after ForgetDeadlockInfo,
01198       // but in that case mu should still be present.
01199       i = 0;
01200       while (i != n && held_locks->locks[i].mu != mu) {
01201         i++;
01202       }
01203       if (i == n) {  // mu missing means releasing unheld lock
01204         SynchEvent *mu_events = GetSynchEvent(mu);
01205         ABSL_RAW_LOG(FATAL,
01206                      "thread releasing lock it does not hold: %p %s; "
01207                      ,
01208                      static_cast<void *>(mu),
01209                      mu_events == nullptr ? "" : mu_events->name);
01210       }
01211     }
01212   } else if (held_locks->locks[i].count == 1) {
01213     held_locks->n = n - 1;
01214     held_locks->locks[i] = held_locks->locks[n - 1];
01215     held_locks->locks[n - 1].id = InvalidGraphId();
01216     held_locks->locks[n - 1].mu =
01217         nullptr;  // clear mu to please the leak detector.
01218   } else {
01219     assert(held_locks->locks[i].count > 0);
01220     held_locks->locks[i].count--;
01221   }
01222 }
01223 
01224 // Call LockEnter() if in debug mode and deadlock detection is enabled.
01225 static inline void DebugOnlyLockEnter(Mutex *mu) {
01226   if (kDebugMode) {
01227     if (synch_deadlock_detection.load(std::memory_order_acquire) !=
01228         OnDeadlockCycle::kIgnore) {
01229       LockEnter(mu, GetGraphId(mu), Synch_GetAllLocks());
01230     }
01231   }
01232 }
01233 
01234 // Call LockEnter() if in debug mode and deadlock detection is enabled.
01235 static inline void DebugOnlyLockEnter(Mutex *mu, GraphId id) {
01236   if (kDebugMode) {
01237     if (synch_deadlock_detection.load(std::memory_order_acquire) !=
01238         OnDeadlockCycle::kIgnore) {
01239       LockEnter(mu, id, Synch_GetAllLocks());
01240     }
01241   }
01242 }
01243 
01244 // Call LockLeave() if in debug mode and deadlock detection is enabled.
01245 static inline void DebugOnlyLockLeave(Mutex *mu) {
01246   if (kDebugMode) {
01247     if (synch_deadlock_detection.load(std::memory_order_acquire) !=
01248         OnDeadlockCycle::kIgnore) {
01249       LockLeave(mu, GetGraphId(mu), Synch_GetAllLocks());
01250     }
01251   }
01252 }
01253 
01254 static char *StackString(void **pcs, int n, char *buf, int maxlen,
01255                          bool symbolize) {
01256   static const int kSymLen = 200;
01257   char sym[kSymLen];
01258   int len = 0;
01259   for (int i = 0; i != n; i++) {
01260     if (symbolize) {
01261       if (!symbolizer(pcs[i], sym, kSymLen)) {
01262         sym[0] = '\0';
01263       }
01264       snprintf(buf + len, maxlen - len, "%s\t@ %p %s\n",
01265                (i == 0 ? "\n" : ""),
01266                pcs[i], sym);
01267     } else {
01268       snprintf(buf + len, maxlen - len, " %p", pcs[i]);
01269     }
01270     len += strlen(&buf[len]);
01271   }
01272   return buf;
01273 }
01274 
01275 static char *CurrentStackString(char *buf, int maxlen, bool symbolize) {
01276   void *pcs[40];
01277   return StackString(pcs, absl::GetStackTrace(pcs, ABSL_ARRAYSIZE(pcs), 2), buf,
01278                      maxlen, symbolize);
01279 }
01280 
01281 namespace {
01282 enum { kMaxDeadlockPathLen = 10 };  // maximum length of a deadlock cycle;
01283                                     // a path this long would be remarkable
01284 // Buffers required to report a deadlock.
01285 // We do not allocate them on stack to avoid large stack frame.
01286 struct DeadlockReportBuffers {
01287   char buf[6100];
01288   GraphId path[kMaxDeadlockPathLen];
01289 };
01290 
01291 struct ScopedDeadlockReportBuffers {
01292   ScopedDeadlockReportBuffers() {
01293     b = reinterpret_cast<DeadlockReportBuffers *>(
01294         base_internal::LowLevelAlloc::Alloc(sizeof(*b)));
01295   }
01296   ~ScopedDeadlockReportBuffers() { base_internal::LowLevelAlloc::Free(b); }
01297   DeadlockReportBuffers *b;
01298 };
01299 
01300 // Helper to pass to GraphCycles::UpdateStackTrace.
01301 int GetStack(void** stack, int max_depth) {
01302   return absl::GetStackTrace(stack, max_depth, 3);
01303 }
01304 }  // anonymous namespace
01305 
01306 // Called in debug mode when a thread is about to acquire a lock in a way that
01307 // may block.
01308 static GraphId DeadlockCheck(Mutex *mu) {
01309   if (synch_deadlock_detection.load(std::memory_order_acquire) ==
01310       OnDeadlockCycle::kIgnore) {
01311     return InvalidGraphId();
01312   }
01313 
01314   SynchLocksHeld *all_locks = Synch_GetAllLocks();
01315 
01316   absl::base_internal::SpinLockHolder lock(&deadlock_graph_mu);
01317   const GraphId mu_id = GetGraphIdLocked(mu);
01318 
01319   if (all_locks->n == 0) {
01320     // There are no other locks held. Return now so that we don't need to
01321     // call GetSynchEvent(). This way we do not record the stack trace
01322     // for this Mutex. It's ok, since if this Mutex is involved in a deadlock,
01323     // it can't always be the first lock acquired by a thread.
01324     return mu_id;
01325   }
01326 
01327   // We prefer to keep stack traces that show a thread holding and acquiring
01328   // as many locks as possible.  This increases the chances that a given edge
01329   // in the acquires-before graph will be represented in the stack traces
01330   // recorded for the locks.
01331   deadlock_graph->UpdateStackTrace(mu_id, all_locks->n + 1, GetStack);
01332 
01333   // For each other mutex already held by this thread:
01334   for (int i = 0; i != all_locks->n; i++) {
01335     const GraphId other_node_id = all_locks->locks[i].id;
01336     const Mutex *other =
01337         static_cast<const Mutex *>(deadlock_graph->Ptr(other_node_id));
01338     if (other == nullptr) {
01339       // Ignore stale lock
01340       continue;
01341     }
01342 
01343     // Add the acquired-before edge to the graph.
01344     if (!deadlock_graph->InsertEdge(other_node_id, mu_id)) {
01345       ScopedDeadlockReportBuffers scoped_buffers;
01346       DeadlockReportBuffers *b = scoped_buffers.b;
01347       static int number_of_reported_deadlocks = 0;
01348       number_of_reported_deadlocks++;
01349       // Symbolize only 2 first deadlock report to avoid huge slowdowns.
01350       bool symbolize = number_of_reported_deadlocks <= 2;
01351       ABSL_RAW_LOG(ERROR, "Potential Mutex deadlock: %s",
01352                    CurrentStackString(b->buf, sizeof (b->buf), symbolize));
01353       int len = 0;
01354       for (int j = 0; j != all_locks->n; j++) {
01355         void* pr = deadlock_graph->Ptr(all_locks->locks[j].id);
01356         if (pr != nullptr) {
01357           snprintf(b->buf + len, sizeof (b->buf) - len, " %p", pr);
01358           len += static_cast<int>(strlen(&b->buf[len]));
01359         }
01360       }
01361       ABSL_RAW_LOG(ERROR, "Acquiring %p    Mutexes held: %s",
01362                    static_cast<void *>(mu), b->buf);
01363       ABSL_RAW_LOG(ERROR, "Cycle: ");
01364       int path_len = deadlock_graph->FindPath(
01365           mu_id, other_node_id, ABSL_ARRAYSIZE(b->path), b->path);
01366       for (int j = 0; j != path_len; j++) {
01367         GraphId id = b->path[j];
01368         Mutex *path_mu = static_cast<Mutex *>(deadlock_graph->Ptr(id));
01369         if (path_mu == nullptr) continue;
01370         void** stack;
01371         int depth = deadlock_graph->GetStackTrace(id, &stack);
01372         snprintf(b->buf, sizeof(b->buf),
01373                  "mutex@%p stack: ", static_cast<void *>(path_mu));
01374         StackString(stack, depth, b->buf + strlen(b->buf),
01375                     static_cast<int>(sizeof(b->buf) - strlen(b->buf)),
01376                     symbolize);
01377         ABSL_RAW_LOG(ERROR, "%s", b->buf);
01378       }
01379       if (synch_deadlock_detection.load(std::memory_order_acquire) ==
01380           OnDeadlockCycle::kAbort) {
01381         deadlock_graph_mu.Unlock();  // avoid deadlock in fatal sighandler
01382         ABSL_RAW_LOG(FATAL, "dying due to potential deadlock");
01383         return mu_id;
01384       }
01385       break;   // report at most one potential deadlock per acquisition
01386     }
01387   }
01388 
01389   return mu_id;
01390 }
01391 
01392 // Invoke DeadlockCheck() iff we're in debug mode and
01393 // deadlock checking has been enabled.
01394 static inline GraphId DebugOnlyDeadlockCheck(Mutex *mu) {
01395   if (kDebugMode && synch_deadlock_detection.load(std::memory_order_acquire) !=
01396                         OnDeadlockCycle::kIgnore) {
01397     return DeadlockCheck(mu);
01398   } else {
01399     return InvalidGraphId();
01400   }
01401 }
01402 
01403 void Mutex::ForgetDeadlockInfo() {
01404   if (kDebugMode && synch_deadlock_detection.load(std::memory_order_acquire) !=
01405                         OnDeadlockCycle::kIgnore) {
01406     deadlock_graph_mu.Lock();
01407     if (deadlock_graph != nullptr) {
01408       deadlock_graph->RemoveNode(this);
01409     }
01410     deadlock_graph_mu.Unlock();
01411   }
01412 }
01413 
01414 void Mutex::AssertNotHeld() const {
01415   // We have the data to allow this check only if in debug mode and deadlock
01416   // detection is enabled.
01417   if (kDebugMode &&
01418       (mu_.load(std::memory_order_relaxed) & (kMuWriter | kMuReader)) != 0 &&
01419       synch_deadlock_detection.load(std::memory_order_acquire) !=
01420           OnDeadlockCycle::kIgnore) {
01421     GraphId id = GetGraphId(const_cast<Mutex *>(this));
01422     SynchLocksHeld *locks = Synch_GetAllLocks();
01423     for (int i = 0; i != locks->n; i++) {
01424       if (locks->locks[i].id == id) {
01425         SynchEvent *mu_events = GetSynchEvent(this);
01426         ABSL_RAW_LOG(FATAL, "thread should not hold mutex %p %s",
01427                      static_cast<const void *>(this),
01428                      (mu_events == nullptr ? "" : mu_events->name));
01429       }
01430     }
01431   }
01432 }
01433 
01434 // Attempt to acquire *mu, and return whether successful.  The implementation
01435 // may spin for a short while if the lock cannot be acquired immediately.
01436 static bool TryAcquireWithSpinning(std::atomic<intptr_t>* mu) {
01437   int c = mutex_globals.spinloop_iterations;
01438   int result = -1;  // result of operation:  0=false, 1=true, -1=unknown
01439 
01440   do {  // do/while somewhat faster on AMD
01441     intptr_t v = mu->load(std::memory_order_relaxed);
01442     if ((v & (kMuReader|kMuEvent)) != 0) {  // a reader or tracing -> give up
01443       result = 0;
01444     } else if (((v & kMuWriter) == 0) &&  // no holder -> try to acquire
01445                mu->compare_exchange_strong(v, kMuWriter | v,
01446                                            std::memory_order_acquire,
01447                                            std::memory_order_relaxed)) {
01448       result = 1;
01449     }
01450   } while (result == -1 && --c > 0);
01451   return result == 1;
01452 }
01453 
01454 ABSL_XRAY_LOG_ARGS(1) void Mutex::Lock() {
01455   ABSL_TSAN_MUTEX_PRE_LOCK(this, 0);
01456   GraphId id = DebugOnlyDeadlockCheck(this);
01457   intptr_t v = mu_.load(std::memory_order_relaxed);
01458   // try fast acquire, then spin loop
01459   if ((v & (kMuWriter | kMuReader | kMuEvent)) != 0 ||
01460       !mu_.compare_exchange_strong(v, kMuWriter | v,
01461                                    std::memory_order_acquire,
01462                                    std::memory_order_relaxed)) {
01463     // try spin acquire, then slow loop
01464     if (!TryAcquireWithSpinning(&this->mu_)) {
01465       this->LockSlow(kExclusive, nullptr, 0);
01466     }
01467   }
01468   DebugOnlyLockEnter(this, id);
01469   ABSL_TSAN_MUTEX_POST_LOCK(this, 0, 0);
01470 }
01471 
01472 ABSL_XRAY_LOG_ARGS(1) void Mutex::ReaderLock() {
01473   ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_read_lock);
01474   GraphId id = DebugOnlyDeadlockCheck(this);
01475   intptr_t v = mu_.load(std::memory_order_relaxed);
01476   // try fast acquire, then slow loop
01477   if ((v & (kMuWriter | kMuWait | kMuEvent)) != 0 ||
01478       !mu_.compare_exchange_strong(v, (kMuReader | v) + kMuOne,
01479                                    std::memory_order_acquire,
01480                                    std::memory_order_relaxed)) {
01481     this->LockSlow(kShared, nullptr, 0);
01482   }
01483   DebugOnlyLockEnter(this, id);
01484   ABSL_TSAN_MUTEX_POST_LOCK(this, __tsan_mutex_read_lock, 0);
01485 }
01486 
01487 void Mutex::LockWhen(const Condition &cond) {
01488   ABSL_TSAN_MUTEX_PRE_LOCK(this, 0);
01489   GraphId id = DebugOnlyDeadlockCheck(this);
01490   this->LockSlow(kExclusive, &cond, 0);
01491   DebugOnlyLockEnter(this, id);
01492   ABSL_TSAN_MUTEX_POST_LOCK(this, 0, 0);
01493 }
01494 
01495 bool Mutex::LockWhenWithTimeout(const Condition &cond, absl::Duration timeout) {
01496   return LockWhenWithDeadline(cond, DeadlineFromTimeout(timeout));
01497 }
01498 
01499 bool Mutex::LockWhenWithDeadline(const Condition &cond, absl::Time deadline) {
01500   ABSL_TSAN_MUTEX_PRE_LOCK(this, 0);
01501   GraphId id = DebugOnlyDeadlockCheck(this);
01502   bool res = LockSlowWithDeadline(kExclusive, &cond,
01503                                   KernelTimeout(deadline), 0);
01504   DebugOnlyLockEnter(this, id);
01505   ABSL_TSAN_MUTEX_POST_LOCK(this, 0, 0);
01506   return res;
01507 }
01508 
01509 void Mutex::ReaderLockWhen(const Condition &cond) {
01510   ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_read_lock);
01511   GraphId id = DebugOnlyDeadlockCheck(this);
01512   this->LockSlow(kShared, &cond, 0);
01513   DebugOnlyLockEnter(this, id);
01514   ABSL_TSAN_MUTEX_POST_LOCK(this, __tsan_mutex_read_lock, 0);
01515 }
01516 
01517 bool Mutex::ReaderLockWhenWithTimeout(const Condition &cond,
01518                                       absl::Duration timeout) {
01519   return ReaderLockWhenWithDeadline(cond, DeadlineFromTimeout(timeout));
01520 }
01521 
01522 bool Mutex::ReaderLockWhenWithDeadline(const Condition &cond,
01523                                        absl::Time deadline) {
01524   ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_read_lock);
01525   GraphId id = DebugOnlyDeadlockCheck(this);
01526   bool res = LockSlowWithDeadline(kShared, &cond, KernelTimeout(deadline), 0);
01527   DebugOnlyLockEnter(this, id);
01528   ABSL_TSAN_MUTEX_POST_LOCK(this, __tsan_mutex_read_lock, 0);
01529   return res;
01530 }
01531 
01532 void Mutex::Await(const Condition &cond) {
01533   if (cond.Eval()) {    // condition already true; nothing to do
01534     if (kDebugMode) {
01535       this->AssertReaderHeld();
01536     }
01537   } else {              // normal case
01538     ABSL_RAW_CHECK(this->AwaitCommon(cond, KernelTimeout::Never()),
01539                    "condition untrue on return from Await");
01540   }
01541 }
01542 
01543 bool Mutex::AwaitWithTimeout(const Condition &cond, absl::Duration timeout) {
01544   return AwaitWithDeadline(cond, DeadlineFromTimeout(timeout));
01545 }
01546 
01547 bool Mutex::AwaitWithDeadline(const Condition &cond, absl::Time deadline) {
01548   if (cond.Eval()) {      // condition already true; nothing to do
01549     if (kDebugMode) {
01550       this->AssertReaderHeld();
01551     }
01552     return true;
01553   }
01554 
01555   KernelTimeout t{deadline};
01556   bool res = this->AwaitCommon(cond, t);
01557   ABSL_RAW_CHECK(res || t.has_timeout(),
01558                  "condition untrue on return from Await");
01559   return res;
01560 }
01561 
01562 bool Mutex::AwaitCommon(const Condition &cond, KernelTimeout t) {
01563   this->AssertReaderHeld();
01564   MuHow how =
01565       (mu_.load(std::memory_order_relaxed) & kMuWriter) ? kExclusive : kShared;
01566   ABSL_TSAN_MUTEX_PRE_UNLOCK(this, TsanFlags(how));
01567   SynchWaitParams waitp(
01568       how, &cond, t, nullptr /*no cvmu*/, Synch_GetPerThreadAnnotated(this),
01569       nullptr /*no cv_word*/);
01570   int flags = kMuHasBlocked;
01571   if (!Condition::GuaranteedEqual(&cond, nullptr)) {
01572     flags |= kMuIsCond;
01573   }
01574   this->UnlockSlow(&waitp);
01575   this->Block(waitp.thread);
01576   ABSL_TSAN_MUTEX_POST_UNLOCK(this, TsanFlags(how));
01577   ABSL_TSAN_MUTEX_PRE_LOCK(this, TsanFlags(how));
01578   this->LockSlowLoop(&waitp, flags);
01579   bool res = waitp.cond != nullptr ||  // => cond known true from LockSlowLoop
01580              EvalConditionAnnotated(&cond, this, true, false, how == kShared);
01581   ABSL_TSAN_MUTEX_POST_LOCK(this, TsanFlags(how), 0);
01582   return res;
01583 }
01584 
01585 ABSL_XRAY_LOG_ARGS(1) bool Mutex::TryLock() {
01586   ABSL_TSAN_MUTEX_PRE_LOCK(this, __tsan_mutex_try_lock);
01587   intptr_t v = mu_.load(std::memory_order_relaxed);
01588   if ((v & (kMuWriter | kMuReader | kMuEvent)) == 0 &&  // try fast acquire
01589       mu_.compare_exchange_strong(v, kMuWriter | v,
01590                                   std::memory_order_acquire,
01591                                   std::memory_order_relaxed)) {
01592     DebugOnlyLockEnter(this);
01593     ABSL_TSAN_MUTEX_POST_LOCK(this, __tsan_mutex_try_lock, 0);
01594     return true;
01595   }
01596   if ((v & kMuEvent) != 0) {              // we're recording events
01597     if ((v & kExclusive->slow_need_zero) == 0 &&  // try fast acquire
01598         mu_.compare_exchange_strong(
01599             v, (kExclusive->fast_or | v) + kExclusive->fast_add,
01600             std::memory_order_acquire, std::memory_order_relaxed)) {
01601       DebugOnlyLockEnter(this);
01602       PostSynchEvent(this, SYNCH_EV_TRYLOCK_SUCCESS);
01603       ABSL_TSAN_MUTEX_POST_LOCK(this, __tsan_mutex_try_lock, 0);
01604       return true;
01605     } else {
01606       PostSynchEvent(this, SYNCH_EV_TRYLOCK_FAILED);
01607     }
01608   }
01609   ABSL_TSAN_MUTEX_POST_LOCK(
01610       this, __tsan_mutex_try_lock | __tsan_mutex_try_lock_failed, 0);
01611   return false;
01612 }
01613 
01614 ABSL_XRAY_LOG_ARGS(1) bool Mutex::ReaderTryLock() {
01615   ABSL_TSAN_MUTEX_PRE_LOCK(this,
01616                            __tsan_mutex_read_lock | __tsan_mutex_try_lock);
01617   intptr_t v = mu_.load(std::memory_order_relaxed);
01618   // The while-loops (here and below) iterate only if the mutex word keeps
01619   // changing (typically because the reader count changes) under the CAS.  We
01620   // limit the number of attempts to avoid having to think about livelock.
01621   int loop_limit = 5;
01622   while ((v & (kMuWriter|kMuWait|kMuEvent)) == 0 && loop_limit != 0) {
01623     if (mu_.compare_exchange_strong(v, (kMuReader | v) + kMuOne,
01624                                     std::memory_order_acquire,
01625                                     std::memory_order_relaxed)) {
01626       DebugOnlyLockEnter(this);
01627       ABSL_TSAN_MUTEX_POST_LOCK(
01628           this, __tsan_mutex_read_lock | __tsan_mutex_try_lock, 0);
01629       return true;
01630     }
01631     loop_limit--;
01632     v = mu_.load(std::memory_order_relaxed);
01633   }
01634   if ((v & kMuEvent) != 0) {   // we're recording events
01635     loop_limit = 5;
01636     while ((v & kShared->slow_need_zero) == 0 && loop_limit != 0) {
01637       if (mu_.compare_exchange_strong(v, (kMuReader | v) + kMuOne,
01638                                       std::memory_order_acquire,
01639                                       std::memory_order_relaxed)) {
01640         DebugOnlyLockEnter(this);
01641         PostSynchEvent(this, SYNCH_EV_READERTRYLOCK_SUCCESS);
01642         ABSL_TSAN_MUTEX_POST_LOCK(
01643             this, __tsan_mutex_read_lock | __tsan_mutex_try_lock, 0);
01644         return true;
01645       }
01646       loop_limit--;
01647       v = mu_.load(std::memory_order_relaxed);
01648     }
01649     if ((v & kMuEvent) != 0) {
01650       PostSynchEvent(this, SYNCH_EV_READERTRYLOCK_FAILED);
01651     }
01652   }
01653   ABSL_TSAN_MUTEX_POST_LOCK(this,
01654                             __tsan_mutex_read_lock | __tsan_mutex_try_lock |
01655                                 __tsan_mutex_try_lock_failed,
01656                             0);
01657   return false;
01658 }
01659 
01660 ABSL_XRAY_LOG_ARGS(1) void Mutex::Unlock() {
01661   ABSL_TSAN_MUTEX_PRE_UNLOCK(this, 0);
01662   DebugOnlyLockLeave(this);
01663   intptr_t v = mu_.load(std::memory_order_relaxed);
01664 
01665   if (kDebugMode && ((v & (kMuWriter | kMuReader)) != kMuWriter)) {
01666     ABSL_RAW_LOG(FATAL, "Mutex unlocked when destroyed or not locked: v=0x%x",
01667                  static_cast<unsigned>(v));
01668   }
01669 
01670   // should_try_cas is whether we'll try a compare-and-swap immediately.
01671   // NOTE: optimized out when kDebugMode is false.
01672   bool should_try_cas = ((v & (kMuEvent | kMuWriter)) == kMuWriter &&
01673                           (v & (kMuWait | kMuDesig)) != kMuWait);
01674   // But, we can use an alternate computation of it, that compilers
01675   // currently don't find on their own.  When that changes, this function
01676   // can be simplified.
01677   intptr_t x = (v ^ (kMuWriter | kMuWait)) & (kMuWriter | kMuEvent);
01678   intptr_t y = (v ^ (kMuWriter | kMuWait)) & (kMuWait | kMuDesig);
01679   // Claim: "x == 0 && y > 0" is equal to should_try_cas.
01680   // Also, because kMuWriter and kMuEvent exceed kMuDesig and kMuWait,
01681   // all possible non-zero values for x exceed all possible values for y.
01682   // Therefore, (x == 0 && y > 0) == (x < y).
01683   if (kDebugMode && should_try_cas != (x < y)) {
01684     // We would usually use PRIdPTR here, but is not correctly implemented
01685     // within the android toolchain.
01686     ABSL_RAW_LOG(FATAL, "internal logic error %llx %llx %llx\n",
01687                  static_cast<long long>(v), static_cast<long long>(x),
01688                  static_cast<long long>(y));
01689   }
01690   if (x < y &&
01691       mu_.compare_exchange_strong(v, v & ~(kMuWrWait | kMuWriter),
01692                                   std::memory_order_release,
01693                                   std::memory_order_relaxed)) {
01694     // fast writer release (writer with no waiters or with designated waker)
01695   } else {
01696     this->UnlockSlow(nullptr /*no waitp*/);  // take slow path
01697   }
01698   ABSL_TSAN_MUTEX_POST_UNLOCK(this, 0);
01699 }
01700 
01701 // Requires v to represent a reader-locked state.
01702 static bool ExactlyOneReader(intptr_t v) {
01703   assert((v & (kMuWriter|kMuReader)) == kMuReader);
01704   assert((v & kMuHigh) != 0);
01705   // The more straightforward "(v & kMuHigh) == kMuOne" also works, but
01706   // on some architectures the following generates slightly smaller code.
01707   // It may be faster too.
01708   constexpr intptr_t kMuMultipleWaitersMask = kMuHigh ^ kMuOne;
01709   return (v & kMuMultipleWaitersMask) == 0;
01710 }
01711 
01712 ABSL_XRAY_LOG_ARGS(1) void Mutex::ReaderUnlock() {
01713   ABSL_TSAN_MUTEX_PRE_UNLOCK(this, __tsan_mutex_read_lock);
01714   DebugOnlyLockLeave(this);
01715   intptr_t v = mu_.load(std::memory_order_relaxed);
01716   assert((v & (kMuWriter|kMuReader)) == kMuReader);
01717   if ((v & (kMuReader|kMuWait|kMuEvent)) == kMuReader) {
01718     // fast reader release (reader with no waiters)
01719     intptr_t clear = ExactlyOneReader(v) ? kMuReader|kMuOne : kMuOne;
01720     if (mu_.compare_exchange_strong(v, v - clear,
01721                                     std::memory_order_release,
01722                                     std::memory_order_relaxed)) {
01723       ABSL_TSAN_MUTEX_POST_UNLOCK(this, __tsan_mutex_read_lock);
01724       return;
01725     }
01726   }
01727   this->UnlockSlow(nullptr /*no waitp*/);  // take slow path
01728   ABSL_TSAN_MUTEX_POST_UNLOCK(this, __tsan_mutex_read_lock);
01729 }
01730 
01731 // The zap_desig_waker bitmask is used to clear the designated waker flag in
01732 // the mutex if this thread has blocked, and therefore may be the designated
01733 // waker.
01734 static const intptr_t zap_desig_waker[] = {
01735     ~static_cast<intptr_t>(0),  // not blocked
01736     ~static_cast<intptr_t>(
01737         kMuDesig)  // blocked; turn off the designated waker bit
01738 };
01739 
01740 // The ignore_waiting_writers bitmask is used to ignore the existence
01741 // of waiting writers if a reader that has already blocked once
01742 // wakes up.
01743 static const intptr_t ignore_waiting_writers[] = {
01744     ~static_cast<intptr_t>(0),  // not blocked
01745     ~static_cast<intptr_t>(
01746         kMuWrWait)  // blocked; pretend there are no waiting writers
01747 };
01748 
01749 // Internal version of LockWhen().  See LockSlowWithDeadline()
01750 void Mutex::LockSlow(MuHow how, const Condition *cond, int flags) {
01751   ABSL_RAW_CHECK(
01752       this->LockSlowWithDeadline(how, cond, KernelTimeout::Never(), flags),
01753       "condition untrue on return from LockSlow");
01754 }
01755 
01756 // Compute cond->Eval() and tell race detectors that we do it under mutex mu.
01757 static inline bool EvalConditionAnnotated(const Condition *cond, Mutex *mu,
01758                                           bool locking, bool trylock,
01759                                           bool read_lock) {
01760   // Delicate annotation dance.
01761   // We are currently inside of read/write lock/unlock operation.
01762   // All memory accesses are ignored inside of mutex operations + for unlock
01763   // operation tsan considers that we've already released the mutex.
01764   bool res = false;
01765 #ifdef THREAD_SANITIZER
01766   const int flags = read_lock ? __tsan_mutex_read_lock : 0;
01767   const int tryflags = flags | (trylock ? __tsan_mutex_try_lock : 0);
01768 #endif
01769   if (locking) {
01770     // For lock we pretend that we have finished the operation,
01771     // evaluate the predicate, then unlock the mutex and start locking it again
01772     // to match the annotation at the end of outer lock operation.
01773     // Note: we can't simply do POST_LOCK, Eval, PRE_LOCK, because then tsan
01774     // will think the lock acquisition is recursive which will trigger
01775     // deadlock detector.
01776     ABSL_TSAN_MUTEX_POST_LOCK(mu, tryflags, 0);
01777     res = cond->Eval();
01778     // There is no "try" version of Unlock, so use flags instead of tryflags.
01779     ABSL_TSAN_MUTEX_PRE_UNLOCK(mu, flags);
01780     ABSL_TSAN_MUTEX_POST_UNLOCK(mu, flags);
01781     ABSL_TSAN_MUTEX_PRE_LOCK(mu, tryflags);
01782   } else {
01783     // Similarly, for unlock we pretend that we have unlocked the mutex,
01784     // lock the mutex, evaluate the predicate, and start unlocking it again
01785     // to match the annotation at the end of outer unlock operation.
01786     ABSL_TSAN_MUTEX_POST_UNLOCK(mu, flags);
01787     ABSL_TSAN_MUTEX_PRE_LOCK(mu, flags);
01788     ABSL_TSAN_MUTEX_POST_LOCK(mu, flags, 0);
01789     res = cond->Eval();
01790     ABSL_TSAN_MUTEX_PRE_UNLOCK(mu, flags);
01791   }
01792   // Prevent unused param warnings in non-TSAN builds.
01793   static_cast<void>(mu);
01794   static_cast<void>(trylock);
01795   static_cast<void>(read_lock);
01796   return res;
01797 }
01798 
01799 // Compute cond->Eval() hiding it from race detectors.
01800 // We are hiding it because inside of UnlockSlow we can evaluate a predicate
01801 // that was just added by a concurrent Lock operation; Lock adds the predicate
01802 // to the internal Mutex list without actually acquiring the Mutex
01803 // (it only acquires the internal spinlock, which is rightfully invisible for
01804 // tsan). As the result there is no tsan-visible synchronization between the
01805 // addition and this thread. So if we would enable race detection here,
01806 // it would race with the predicate initialization.
01807 static inline bool EvalConditionIgnored(Mutex *mu, const Condition *cond) {
01808   // Memory accesses are already ignored inside of lock/unlock operations,
01809   // but synchronization operations are also ignored. When we evaluate the
01810   // predicate we must ignore only memory accesses but not synchronization,
01811   // because missed synchronization can lead to false reports later.
01812   // So we "divert" (which un-ignores both memory accesses and synchronization)
01813   // and then separately turn on ignores of memory accesses.
01814   ABSL_TSAN_MUTEX_PRE_DIVERT(mu, 0);
01815   ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN();
01816   bool res = cond->Eval();
01817   ANNOTATE_IGNORE_READS_AND_WRITES_END();
01818   ABSL_TSAN_MUTEX_POST_DIVERT(mu, 0);
01819   static_cast<void>(mu);  // Prevent unused param warning in non-TSAN builds.
01820   return res;
01821 }
01822 
01823 // Internal equivalent of *LockWhenWithDeadline(), where
01824 //   "t" represents the absolute timeout; !t.has_timeout() means "forever".
01825 //   "how" is "kShared" (for ReaderLockWhen) or "kExclusive" (for LockWhen)
01826 // In flags, bits are ored together:
01827 // - kMuHasBlocked indicates that the client has already blocked on the call so
01828 //   the designated waker bit must be cleared and waiting writers should not
01829 //   obstruct this call
01830 // - kMuIsCond indicates that this is a conditional acquire (condition variable,
01831 //   Await,  LockWhen) so contention profiling should be suppressed.
01832 bool Mutex::LockSlowWithDeadline(MuHow how, const Condition *cond,
01833                                  KernelTimeout t, int flags) {
01834   intptr_t v = mu_.load(std::memory_order_relaxed);
01835   bool unlock = false;
01836   if ((v & how->fast_need_zero) == 0 &&  // try fast acquire
01837       mu_.compare_exchange_strong(
01838           v, (how->fast_or | (v & zap_desig_waker[flags & kMuHasBlocked])) +
01839                  how->fast_add,
01840           std::memory_order_acquire, std::memory_order_relaxed)) {
01841     if (cond == nullptr ||
01842         EvalConditionAnnotated(cond, this, true, false, how == kShared)) {
01843       return true;
01844     }
01845     unlock = true;
01846   }
01847   SynchWaitParams waitp(
01848       how, cond, t, nullptr /*no cvmu*/, Synch_GetPerThreadAnnotated(this),
01849       nullptr /*no cv_word*/);
01850   if (!Condition::GuaranteedEqual(cond, nullptr)) {
01851     flags |= kMuIsCond;
01852   }
01853   if (unlock) {
01854     this->UnlockSlow(&waitp);
01855     this->Block(waitp.thread);
01856     flags |= kMuHasBlocked;
01857   }
01858   this->LockSlowLoop(&waitp, flags);
01859   return waitp.cond != nullptr ||  // => cond known true from LockSlowLoop
01860          cond == nullptr ||
01861          EvalConditionAnnotated(cond, this, true, false, how == kShared);
01862 }
01863 
01864 // RAW_CHECK_FMT() takes a condition, a printf-style format string, and
01865 // the printf-style argument list.   The format string must be a literal.
01866 // Arguments after the first are not evaluated unless the condition is true.
01867 #define RAW_CHECK_FMT(cond, ...)                                   \
01868   do {                                                             \
01869     if (ABSL_PREDICT_FALSE(!(cond))) {                             \
01870       ABSL_RAW_LOG(FATAL, "Check " #cond " failed: " __VA_ARGS__); \
01871     }                                                              \
01872   } while (0)
01873 
01874 static void CheckForMutexCorruption(intptr_t v, const char* label) {
01875   // Test for either of two situations that should not occur in v:
01876   //   kMuWriter and kMuReader
01877   //   kMuWrWait and !kMuWait
01878   const uintptr_t w = v ^ kMuWait;
01879   // By flipping that bit, we can now test for:
01880   //   kMuWriter and kMuReader in w
01881   //   kMuWrWait and kMuWait in w
01882   // We've chosen these two pairs of values to be so that they will overlap,
01883   // respectively, when the word is left shifted by three.  This allows us to
01884   // save a branch in the common (correct) case of them not being coincident.
01885   static_assert(kMuReader << 3 == kMuWriter, "must match");
01886   static_assert(kMuWait << 3 == kMuWrWait, "must match");
01887   if (ABSL_PREDICT_TRUE((w & (w << 3) & (kMuWriter | kMuWrWait)) == 0)) return;
01888   RAW_CHECK_FMT((v & (kMuWriter | kMuReader)) != (kMuWriter | kMuReader),
01889                 "%s: Mutex corrupt: both reader and writer lock held: %p",
01890                 label, reinterpret_cast<void *>(v));
01891   RAW_CHECK_FMT((v & (kMuWait | kMuWrWait)) != kMuWrWait,
01892                 "%s: Mutex corrupt: waiting writer with no waiters: %p",
01893                 label, reinterpret_cast<void *>(v));
01894   assert(false);
01895 }
01896 
01897 void Mutex::LockSlowLoop(SynchWaitParams *waitp, int flags) {
01898   int c = 0;
01899   intptr_t v = mu_.load(std::memory_order_relaxed);
01900   if ((v & kMuEvent) != 0) {
01901     PostSynchEvent(this,
01902          waitp->how == kExclusive?  SYNCH_EV_LOCK: SYNCH_EV_READERLOCK);
01903   }
01904   ABSL_RAW_CHECK(
01905       waitp->thread->waitp == nullptr || waitp->thread->suppress_fatal_errors,
01906       "detected illegal recursion into Mutex code");
01907   for (;;) {
01908     v = mu_.load(std::memory_order_relaxed);
01909     CheckForMutexCorruption(v, "Lock");
01910     if ((v & waitp->how->slow_need_zero) == 0) {
01911       if (mu_.compare_exchange_strong(
01912               v, (waitp->how->fast_or |
01913                   (v & zap_desig_waker[flags & kMuHasBlocked])) +
01914                      waitp->how->fast_add,
01915               std::memory_order_acquire, std::memory_order_relaxed)) {
01916         if (waitp->cond == nullptr ||
01917             EvalConditionAnnotated(waitp->cond, this, true, false,
01918                                    waitp->how == kShared)) {
01919           break;  // we timed out, or condition true, so return
01920         }
01921         this->UnlockSlow(waitp);  // got lock but condition false
01922         this->Block(waitp->thread);
01923         flags |= kMuHasBlocked;
01924         c = 0;
01925       }
01926     } else {                      // need to access waiter list
01927       bool dowait = false;
01928       if ((v & (kMuSpin|kMuWait)) == 0) {   // no waiters
01929         // This thread tries to become the one and only waiter.
01930         PerThreadSynch *new_h = Enqueue(nullptr, waitp, v, flags);
01931         intptr_t nv = (v & zap_desig_waker[flags & kMuHasBlocked] & kMuLow) |
01932                       kMuWait;
01933         ABSL_RAW_CHECK(new_h != nullptr, "Enqueue to empty list failed");
01934         if (waitp->how == kExclusive && (v & kMuReader) != 0) {
01935           nv |= kMuWrWait;
01936         }
01937         if (mu_.compare_exchange_strong(
01938                 v, reinterpret_cast<intptr_t>(new_h) | nv,
01939                 std::memory_order_release, std::memory_order_relaxed)) {
01940           dowait = true;
01941         } else {            // attempted Enqueue() failed
01942           // zero out the waitp field set by Enqueue()
01943           waitp->thread->waitp = nullptr;
01944         }
01945       } else if ((v & waitp->how->slow_inc_need_zero &
01946                   ignore_waiting_writers[flags & kMuHasBlocked]) == 0) {
01947         // This is a reader that needs to increment the reader count,
01948         // but the count is currently held in the last waiter.
01949         if (mu_.compare_exchange_strong(
01950                 v, (v & zap_desig_waker[flags & kMuHasBlocked]) | kMuSpin |
01951                        kMuReader,
01952                 std::memory_order_acquire, std::memory_order_relaxed)) {
01953           PerThreadSynch *h = GetPerThreadSynch(v);
01954           h->readers += kMuOne;       // inc reader count in waiter
01955           do {                        // release spinlock
01956             v = mu_.load(std::memory_order_relaxed);
01957           } while (!mu_.compare_exchange_weak(v, (v & ~kMuSpin) | kMuReader,
01958                                               std::memory_order_release,
01959                                               std::memory_order_relaxed));
01960           if (waitp->cond == nullptr ||
01961               EvalConditionAnnotated(waitp->cond, this, true, false,
01962                                      waitp->how == kShared)) {
01963             break;  // we timed out, or condition true, so return
01964           }
01965           this->UnlockSlow(waitp);           // got lock but condition false
01966           this->Block(waitp->thread);
01967           flags |= kMuHasBlocked;
01968           c = 0;
01969         }
01970       } else if ((v & kMuSpin) == 0 &&  // attempt to queue ourselves
01971                  mu_.compare_exchange_strong(
01972                      v, (v & zap_desig_waker[flags & kMuHasBlocked]) | kMuSpin |
01973                             kMuWait,
01974                      std::memory_order_acquire, std::memory_order_relaxed)) {
01975         PerThreadSynch *h = GetPerThreadSynch(v);
01976         PerThreadSynch *new_h = Enqueue(h, waitp, v, flags);
01977         intptr_t wr_wait = 0;
01978         ABSL_RAW_CHECK(new_h != nullptr, "Enqueue to list failed");
01979         if (waitp->how == kExclusive && (v & kMuReader) != 0) {
01980           wr_wait = kMuWrWait;      // give priority to a waiting writer
01981         }
01982         do {                        // release spinlock
01983           v = mu_.load(std::memory_order_relaxed);
01984         } while (!mu_.compare_exchange_weak(
01985             v, (v & (kMuLow & ~kMuSpin)) | kMuWait | wr_wait |
01986             reinterpret_cast<intptr_t>(new_h),
01987             std::memory_order_release, std::memory_order_relaxed));
01988         dowait = true;
01989       }
01990       if (dowait) {
01991         this->Block(waitp->thread);  // wait until removed from list or timeout
01992         flags |= kMuHasBlocked;
01993         c = 0;
01994       }
01995     }
01996     ABSL_RAW_CHECK(
01997         waitp->thread->waitp == nullptr || waitp->thread->suppress_fatal_errors,
01998         "detected illegal recursion into Mutex code");
01999     c = Delay(c, GENTLE);          // delay, then try again
02000   }
02001   ABSL_RAW_CHECK(
02002       waitp->thread->waitp == nullptr || waitp->thread->suppress_fatal_errors,
02003       "detected illegal recursion into Mutex code");
02004   if ((v & kMuEvent) != 0) {
02005     PostSynchEvent(this,
02006                    waitp->how == kExclusive? SYNCH_EV_LOCK_RETURNING :
02007                                       SYNCH_EV_READERLOCK_RETURNING);
02008   }
02009 }
02010 
02011 // Unlock this mutex, which is held by the current thread.
02012 // If waitp is non-zero, it must be the wait parameters for the current thread
02013 // which holds the lock but is not runnable because its condition is false
02014 // or it is in the process of blocking on a condition variable; it must requeue
02015 // itself on the mutex/condvar to wait for its condition to become true.
02016 void Mutex::UnlockSlow(SynchWaitParams *waitp) {
02017   intptr_t v = mu_.load(std::memory_order_relaxed);
02018   this->AssertReaderHeld();
02019   CheckForMutexCorruption(v, "Unlock");
02020   if ((v & kMuEvent) != 0) {
02021     PostSynchEvent(this,
02022                 (v & kMuWriter) != 0? SYNCH_EV_UNLOCK: SYNCH_EV_READERUNLOCK);
02023   }
02024   int c = 0;
02025   // the waiter under consideration to wake, or zero
02026   PerThreadSynch *w = nullptr;
02027   // the predecessor to w or zero
02028   PerThreadSynch *pw = nullptr;
02029   // head of the list searched previously, or zero
02030   PerThreadSynch *old_h = nullptr;
02031   // a condition that's known to be false.
02032   const Condition *known_false = nullptr;
02033   PerThreadSynch *wake_list = kPerThreadSynchNull;   // list of threads to wake
02034   intptr_t wr_wait = 0;        // set to kMuWrWait if we wake a reader and a
02035                                // later writer could have acquired the lock
02036                                // (starvation avoidance)
02037   ABSL_RAW_CHECK(waitp == nullptr || waitp->thread->waitp == nullptr ||
02038                      waitp->thread->suppress_fatal_errors,
02039                  "detected illegal recursion into Mutex code");
02040   // This loop finds threads wake_list to wakeup if any, and removes them from
02041   // the list of waiters.  In addition, it places waitp.thread on the queue of
02042   // waiters if waitp is non-zero.
02043   for (;;) {
02044     v = mu_.load(std::memory_order_relaxed);
02045     if ((v & kMuWriter) != 0 && (v & (kMuWait | kMuDesig)) != kMuWait &&
02046         waitp == nullptr) {
02047       // fast writer release (writer with no waiters or with designated waker)
02048       if (mu_.compare_exchange_strong(v, v & ~(kMuWrWait | kMuWriter),
02049                                       std::memory_order_release,
02050                                       std::memory_order_relaxed)) {
02051         return;
02052       }
02053     } else if ((v & (kMuReader | kMuWait)) == kMuReader && waitp == nullptr) {
02054       // fast reader release (reader with no waiters)
02055       intptr_t clear = ExactlyOneReader(v) ? kMuReader | kMuOne : kMuOne;
02056       if (mu_.compare_exchange_strong(v, v - clear,
02057                                       std::memory_order_release,
02058                                       std::memory_order_relaxed)) {
02059         return;
02060       }
02061     } else if ((v & kMuSpin) == 0 &&  // attempt to get spinlock
02062                mu_.compare_exchange_strong(v, v | kMuSpin,
02063                                            std::memory_order_acquire,
02064                                            std::memory_order_relaxed)) {
02065       if ((v & kMuWait) == 0) {       // no one to wake
02066         intptr_t nv;
02067         bool do_enqueue = true;  // always Enqueue() the first time
02068         ABSL_RAW_CHECK(waitp != nullptr,
02069                        "UnlockSlow is confused");  // about to sleep
02070         do {    // must loop to release spinlock as reader count may change
02071           v = mu_.load(std::memory_order_relaxed);
02072           // decrement reader count if there are readers
02073           intptr_t new_readers = (v >= kMuOne)?  v - kMuOne : v;
02074           PerThreadSynch *new_h = nullptr;
02075           if (do_enqueue) {
02076             // If we are enqueuing on a CondVar (waitp->cv_word != nullptr) then
02077             // we must not retry here.  The initial attempt will always have
02078             // succeeded, further attempts would enqueue us against *this due to
02079             // Fer() handling.
02080             do_enqueue = (waitp->cv_word == nullptr);
02081             new_h = Enqueue(nullptr, waitp, new_readers, kMuIsCond);
02082           }
02083           intptr_t clear = kMuWrWait | kMuWriter;  // by default clear write bit
02084           if ((v & kMuWriter) == 0 && ExactlyOneReader(v)) {  // last reader
02085             clear = kMuWrWait | kMuReader;                    // clear read bit
02086           }
02087           nv = (v & kMuLow & ~clear & ~kMuSpin);
02088           if (new_h != nullptr) {
02089             nv |= kMuWait | reinterpret_cast<intptr_t>(new_h);
02090           } else {  // new_h could be nullptr if we queued ourselves on a
02091                     // CondVar
02092             // In that case, we must place the reader count back in the mutex
02093             // word, as Enqueue() did not store it in the new waiter.
02094             nv |= new_readers & kMuHigh;
02095           }
02096           // release spinlock & our lock; retry if reader-count changed
02097           // (writer count cannot change since we hold lock)
02098         } while (!mu_.compare_exchange_weak(v, nv,
02099                                             std::memory_order_release,
02100                                             std::memory_order_relaxed));
02101         break;
02102       }
02103 
02104       // There are waiters.
02105       // Set h to the head of the circular waiter list.
02106       PerThreadSynch *h = GetPerThreadSynch(v);
02107       if ((v & kMuReader) != 0 && (h->readers & kMuHigh) > kMuOne) {
02108         // a reader but not the last
02109         h->readers -= kMuOne;  // release our lock
02110         intptr_t nv = v;       // normally just release spinlock
02111         if (waitp != nullptr) {  // but waitp!=nullptr => must queue ourselves
02112           PerThreadSynch *new_h = Enqueue(h, waitp, v, kMuIsCond);
02113           ABSL_RAW_CHECK(new_h != nullptr,
02114                          "waiters disappeared during Enqueue()!");
02115           nv &= kMuLow;
02116           nv |= kMuWait | reinterpret_cast<intptr_t>(new_h);
02117         }
02118         mu_.store(nv, std::memory_order_release);  // release spinlock
02119         // can release with a store because there were waiters
02120         break;
02121       }
02122 
02123       // Either we didn't search before, or we marked the queue
02124       // as "maybe_unlocking" and no one else should have changed it.
02125       ABSL_RAW_CHECK(old_h == nullptr || h->maybe_unlocking,
02126                      "Mutex queue changed beneath us");
02127 
02128       // The lock is becoming free, and there's a waiter
02129       if (old_h != nullptr &&
02130           !old_h->may_skip) {                  // we used old_h as a terminator
02131         old_h->may_skip = true;                // allow old_h to skip once more
02132         ABSL_RAW_CHECK(old_h->skip == nullptr, "illegal skip from head");
02133         if (h != old_h && MuSameCondition(old_h, old_h->next)) {
02134           old_h->skip = old_h->next;  // old_h not head & can skip to successor
02135         }
02136       }
02137       if (h->next->waitp->how == kExclusive &&
02138           Condition::GuaranteedEqual(h->next->waitp->cond, nullptr)) {
02139         // easy case: writer with no condition; no need to search
02140         pw = h;                       // wake w, the successor of h (=pw)
02141         w = h->next;
02142         w->wake = true;
02143         // We are waking up a writer.  This writer may be racing against
02144         // an already awake reader for the lock.  We want the
02145         // writer to usually win this race,
02146         // because if it doesn't, we can potentially keep taking a reader
02147         // perpetually and writers will starve.  Worse than
02148         // that, this can also starve other readers if kMuWrWait gets set
02149         // later.
02150         wr_wait = kMuWrWait;
02151       } else if (w != nullptr && (w->waitp->how == kExclusive || h == old_h)) {
02152         // we found a waiter w to wake on a previous iteration and either it's
02153         // a writer, or we've searched the entire list so we have all the
02154         // readers.
02155         if (pw == nullptr) {  // if w's predecessor is unknown, it must be h
02156           pw = h;
02157         }
02158       } else {
02159         // At this point we don't know all the waiters to wake, and the first
02160         // waiter has a condition or is a reader.  We avoid searching over
02161         // waiters we've searched on previous iterations by starting at
02162         // old_h if it's set.  If old_h==h, there's no one to wakeup at all.
02163         if (old_h == h) {      // we've searched before, and nothing's new
02164                                // so there's no one to wake.
02165           intptr_t nv = (v & ~(kMuReader|kMuWriter|kMuWrWait));
02166           h->readers = 0;
02167           h->maybe_unlocking = false;   // finished unlocking
02168           if (waitp != nullptr) {       // we must queue ourselves and sleep
02169             PerThreadSynch *new_h = Enqueue(h, waitp, v, kMuIsCond);
02170             nv &= kMuLow;
02171             if (new_h != nullptr) {
02172               nv |= kMuWait | reinterpret_cast<intptr_t>(new_h);
02173             }  // else new_h could be nullptr if we queued ourselves on a
02174                // CondVar
02175           }
02176           // release spinlock & lock
02177           // can release with a store because there were waiters
02178           mu_.store(nv, std::memory_order_release);
02179           break;
02180         }
02181 
02182         // set up to walk the list
02183         PerThreadSynch *w_walk;   // current waiter during list walk
02184         PerThreadSynch *pw_walk;  // previous waiter during list walk
02185         if (old_h != nullptr) {  // we've searched up to old_h before
02186           pw_walk = old_h;
02187           w_walk = old_h->next;
02188         } else {            // no prior search, start at beginning
02189           pw_walk =
02190               nullptr;  // h->next's predecessor may change; don't record it
02191           w_walk = h->next;
02192         }
02193 
02194         h->may_skip = false;  // ensure we never skip past h in future searches
02195                               // even if other waiters are queued after it.
02196         ABSL_RAW_CHECK(h->skip == nullptr, "illegal skip from head");
02197 
02198         h->maybe_unlocking = true;  // we're about to scan the waiter list
02199                                     // without the spinlock held.
02200                                     // Enqueue must be conservative about
02201                                     // priority queuing.
02202 
02203         // We must release the spinlock to evaluate the conditions.
02204         mu_.store(v, std::memory_order_release);  // release just spinlock
02205         // can release with a store because there were waiters
02206 
02207         // h is the last waiter queued, and w_walk the first unsearched waiter.
02208         // Without the spinlock, the locations mu_ and h->next may now change
02209         // underneath us, but since we hold the lock itself, the only legal
02210         // change is to add waiters between h and w_walk.  Therefore, it's safe
02211         // to walk the path from w_walk to h inclusive. (TryRemove() can remove
02212         // a waiter anywhere, but it acquires both the spinlock and the Mutex)
02213 
02214         old_h = h;        // remember we searched to here
02215 
02216         // Walk the path upto and including h looking for waiters we can wake.
02217         while (pw_walk != h) {
02218           w_walk->wake = false;
02219           if (w_walk->waitp->cond ==
02220                   nullptr ||  // no condition => vacuously true OR
02221               (w_walk->waitp->cond != known_false &&
02222                // this thread's condition is not known false, AND
02223                //  is in fact true
02224                EvalConditionIgnored(this, w_walk->waitp->cond))) {
02225             if (w == nullptr) {
02226               w_walk->wake = true;    // can wake this waiter
02227               w = w_walk;
02228               pw = pw_walk;
02229               if (w_walk->waitp->how == kExclusive) {
02230                 wr_wait = kMuWrWait;
02231                 break;                // bail if waking this writer
02232               }
02233             } else if (w_walk->waitp->how == kShared) {  // wake if a reader
02234               w_walk->wake = true;
02235             } else {   // writer with true condition
02236               wr_wait = kMuWrWait;
02237             }
02238           } else {                  // can't wake; condition false
02239             known_false = w_walk->waitp->cond;  // remember last false condition
02240           }
02241           if (w_walk->wake) {   // we're waking reader w_walk
02242             pw_walk = w_walk;   // don't skip similar waiters
02243           } else {              // not waking; skip as much as possible
02244             pw_walk = Skip(w_walk);
02245           }
02246           // If pw_walk == h, then load of pw_walk->next can race with
02247           // concurrent write in Enqueue(). However, at the same time
02248           // we do not need to do the load, because we will bail out
02249           // from the loop anyway.
02250           if (pw_walk != h) {
02251             w_walk = pw_walk->next;
02252           }
02253         }
02254 
02255         continue;  // restart for(;;)-loop to wakeup w or to find more waiters
02256       }
02257       ABSL_RAW_CHECK(pw->next == w, "pw not w's predecessor");
02258       // The first (and perhaps only) waiter we've chosen to wake is w, whose
02259       // predecessor is pw.  If w is a reader, we must wake all the other
02260       // waiters with wake==true as well.  We may also need to queue
02261       // ourselves if waitp != null.  The spinlock and the lock are still
02262       // held.
02263 
02264       // This traverses the list in [ pw->next, h ], where h is the head,
02265       // removing all elements with wake==true and placing them in the
02266       // singly-linked list wake_list.  Returns the new head.
02267       h = DequeueAllWakeable(h, pw, &wake_list);
02268 
02269       intptr_t nv = (v & kMuEvent) | kMuDesig;
02270                                              // assume no waiters left,
02271                                              // set kMuDesig for INV1a
02272 
02273       if (waitp != nullptr) {  // we must queue ourselves and sleep
02274         h = Enqueue(h, waitp, v, kMuIsCond);
02275         // h is new last waiter; could be null if we queued ourselves on a
02276         // CondVar
02277       }
02278 
02279       ABSL_RAW_CHECK(wake_list != kPerThreadSynchNull,
02280                      "unexpected empty wake list");
02281 
02282       if (h != nullptr) {  // there are waiters left
02283         h->readers = 0;
02284         h->maybe_unlocking = false;     // finished unlocking
02285         nv |= wr_wait | kMuWait | reinterpret_cast<intptr_t>(h);
02286       }
02287 
02288       // release both spinlock & lock
02289       // can release with a store because there were waiters
02290       mu_.store(nv, std::memory_order_release);
02291       break;  // out of for(;;)-loop
02292     }
02293     c = Delay(c, AGGRESSIVE);  // aggressive here; no one can proceed till we do
02294   }                            // end of for(;;)-loop
02295 
02296   if (wake_list != kPerThreadSynchNull) {
02297     int64_t enqueue_timestamp = wake_list->waitp->contention_start_cycles;
02298     bool cond_waiter = wake_list->cond_waiter;
02299     do {
02300       wake_list = Wakeup(wake_list);              // wake waiters
02301     } while (wake_list != kPerThreadSynchNull);
02302     if (!cond_waiter) {
02303       // Sample lock contention events only if the (first) waiter was trying to
02304       // acquire the lock, not waiting on a condition variable or Condition.
02305       int64_t wait_cycles = base_internal::CycleClock::Now() - enqueue_timestamp;
02306       mutex_tracer("slow release", this, wait_cycles);
02307       ABSL_TSAN_MUTEX_PRE_DIVERT(this, 0);
02308       submit_profile_data(enqueue_timestamp);
02309       ABSL_TSAN_MUTEX_POST_DIVERT(this, 0);
02310     }
02311   }
02312 }
02313 
02314 // Used by CondVar implementation to reacquire mutex after waking from
02315 // condition variable.  This routine is used instead of Lock() because the
02316 // waiting thread may have been moved from the condition variable queue to the
02317 // mutex queue without a wakeup, by Trans().  In that case, when the thread is
02318 // finally woken, the woken thread will believe it has been woken from the
02319 // condition variable (i.e. its PC will be in when in the CondVar code), when
02320 // in fact it has just been woken from the mutex.  Thus, it must enter the slow
02321 // path of the mutex in the same state as if it had just woken from the mutex.
02322 // That is, it must ensure to clear kMuDesig (INV1b).
02323 void Mutex::Trans(MuHow how) {
02324   this->LockSlow(how, nullptr, kMuHasBlocked | kMuIsCond);
02325 }
02326 
02327 // Used by CondVar implementation to effectively wake thread w from the
02328 // condition variable.  If this mutex is free, we simply wake the thread.
02329 // It will later acquire the mutex with high probability.  Otherwise, we
02330 // enqueue thread w on this mutex.
02331 void Mutex::Fer(PerThreadSynch *w) {
02332   int c = 0;
02333   ABSL_RAW_CHECK(w->waitp->cond == nullptr,
02334                  "Mutex::Fer while waiting on Condition");
02335   ABSL_RAW_CHECK(!w->waitp->timeout.has_timeout(),
02336                  "Mutex::Fer while in timed wait");
02337   ABSL_RAW_CHECK(w->waitp->cv_word == nullptr,
02338                  "Mutex::Fer with pending CondVar queueing");
02339   for (;;) {
02340     intptr_t v = mu_.load(std::memory_order_relaxed);
02341     // Note: must not queue if the mutex is unlocked (nobody will wake it).
02342     // For example, we can have only kMuWait (conditional) or maybe
02343     // kMuWait|kMuWrWait.
02344     // conflicting != 0 implies that the waking thread cannot currently take
02345     // the mutex, which in turn implies that someone else has it and can wake
02346     // us if we queue.
02347     const intptr_t conflicting =
02348         kMuWriter | (w->waitp->how == kShared ? 0 : kMuReader);
02349     if ((v & conflicting) == 0) {
02350       w->next = nullptr;
02351       w->state.store(PerThreadSynch::kAvailable, std::memory_order_release);
02352       IncrementSynchSem(this, w);
02353       return;
02354     } else {
02355       if ((v & (kMuSpin|kMuWait)) == 0) {       // no waiters
02356         // This thread tries to become the one and only waiter.
02357         PerThreadSynch *new_h = Enqueue(nullptr, w->waitp, v, kMuIsCond);
02358         ABSL_RAW_CHECK(new_h != nullptr,
02359                        "Enqueue failed");  // we must queue ourselves
02360         if (mu_.compare_exchange_strong(
02361                 v, reinterpret_cast<intptr_t>(new_h) | (v & kMuLow) | kMuWait,
02362                 std::memory_order_release, std::memory_order_relaxed)) {
02363           return;
02364         }
02365       } else if ((v & kMuSpin) == 0 &&
02366                  mu_.compare_exchange_strong(v, v | kMuSpin | kMuWait)) {
02367         PerThreadSynch *h = GetPerThreadSynch(v);
02368         PerThreadSynch *new_h = Enqueue(h, w->waitp, v, kMuIsCond);
02369         ABSL_RAW_CHECK(new_h != nullptr,
02370                        "Enqueue failed");  // we must queue ourselves
02371         do {
02372           v = mu_.load(std::memory_order_relaxed);
02373         } while (!mu_.compare_exchange_weak(
02374             v,
02375             (v & kMuLow & ~kMuSpin) | kMuWait |
02376                 reinterpret_cast<intptr_t>(new_h),
02377             std::memory_order_release, std::memory_order_relaxed));
02378         return;
02379       }
02380     }
02381     c = Delay(c, GENTLE);
02382   }
02383 }
02384 
02385 void Mutex::AssertHeld() const {
02386   if ((mu_.load(std::memory_order_relaxed) & kMuWriter) == 0) {
02387     SynchEvent *e = GetSynchEvent(this);
02388     ABSL_RAW_LOG(FATAL, "thread should hold write lock on Mutex %p %s",
02389                  static_cast<const void *>(this),
02390                  (e == nullptr ? "" : e->name));
02391   }
02392 }
02393 
02394 void Mutex::AssertReaderHeld() const {
02395   if ((mu_.load(std::memory_order_relaxed) & (kMuReader | kMuWriter)) == 0) {
02396     SynchEvent *e = GetSynchEvent(this);
02397     ABSL_RAW_LOG(
02398         FATAL, "thread should hold at least a read lock on Mutex %p %s",
02399         static_cast<const void *>(this), (e == nullptr ? "" : e->name));
02400   }
02401 }
02402 
02403 // -------------------------------- condition variables
02404 static const intptr_t kCvSpin = 0x0001L;   // spinlock protects waiter list
02405 static const intptr_t kCvEvent = 0x0002L;  // record events
02406 
02407 static const intptr_t kCvLow = 0x0003L;  // low order bits of CV
02408 
02409 // Hack to make constant values available to gdb pretty printer
02410 enum { kGdbCvSpin = kCvSpin, kGdbCvEvent = kCvEvent, kGdbCvLow = kCvLow, };
02411 
02412 static_assert(PerThreadSynch::kAlignment > kCvLow,
02413               "PerThreadSynch::kAlignment must be greater than kCvLow");
02414 
02415 void CondVar::EnableDebugLog(const char *name) {
02416   SynchEvent *e = EnsureSynchEvent(&this->cv_, name, kCvEvent, kCvSpin);
02417   e->log = true;
02418   UnrefSynchEvent(e);
02419 }
02420 
02421 CondVar::~CondVar() {
02422   if ((cv_.load(std::memory_order_relaxed) & kCvEvent) != 0) {
02423     ForgetSynchEvent(&this->cv_, kCvEvent, kCvSpin);
02424   }
02425 }
02426 
02427 
02428 // Remove thread s from the list of waiters on this condition variable.
02429 void CondVar::Remove(PerThreadSynch *s) {
02430   intptr_t v;
02431   int c = 0;
02432   for (v = cv_.load(std::memory_order_relaxed);;
02433        v = cv_.load(std::memory_order_relaxed)) {
02434     if ((v & kCvSpin) == 0 &&  // attempt to acquire spinlock
02435         cv_.compare_exchange_strong(v, v | kCvSpin,
02436                                     std::memory_order_acquire,
02437                                     std::memory_order_relaxed)) {
02438       PerThreadSynch *h = reinterpret_cast<PerThreadSynch *>(v & ~kCvLow);
02439       if (h != nullptr) {
02440         PerThreadSynch *w = h;
02441         while (w->next != s && w->next != h) {  // search for thread
02442           w = w->next;
02443         }
02444         if (w->next == s) {           // found thread; remove it
02445           w->next = s->next;
02446           if (h == s) {
02447             h = (w == s) ? nullptr : w;
02448           }
02449           s->next = nullptr;
02450           s->state.store(PerThreadSynch::kAvailable, std::memory_order_release);
02451         }
02452       }
02453                                       // release spinlock
02454       cv_.store((v & kCvEvent) | reinterpret_cast<intptr_t>(h),
02455                 std::memory_order_release);
02456       return;
02457     } else {
02458       c = Delay(c, GENTLE);            // try again after a delay
02459     }
02460   }
02461 }
02462 
02463 // Queue thread waitp->thread on condition variable word cv_word using
02464 // wait parameters waitp.
02465 // We split this into a separate routine, rather than simply doing it as part
02466 // of WaitCommon().  If we were to queue ourselves on the condition variable
02467 // before calling Mutex::UnlockSlow(), the Mutex code might be re-entered (via
02468 // the logging code, or via a Condition function) and might potentially attempt
02469 // to block this thread.  That would be a problem if the thread were already on
02470 // a the condition variable waiter queue.  Thus, we use the waitp->cv_word
02471 // to tell the unlock code to call CondVarEnqueue() to queue the thread on the
02472 // condition variable queue just before the mutex is to be unlocked, and (most
02473 // importantly) after any call to an external routine that might re-enter the
02474 // mutex code.
02475 static void CondVarEnqueue(SynchWaitParams *waitp) {
02476   // This thread might be transferred to the Mutex queue by Fer() when
02477   // we are woken.  To make sure that is what happens, Enqueue() doesn't
02478   // call CondVarEnqueue() again but instead uses its normal code.  We
02479   // must do this before we queue ourselves so that cv_word will be null
02480   // when seen by the dequeuer, who may wish immediately to requeue
02481   // this thread on another queue.
02482   std::atomic<intptr_t> *cv_word = waitp->cv_word;
02483   waitp->cv_word = nullptr;
02484 
02485   intptr_t v = cv_word->load(std::memory_order_relaxed);
02486   int c = 0;
02487   while ((v & kCvSpin) != 0 ||  // acquire spinlock
02488          !cv_word->compare_exchange_weak(v, v | kCvSpin,
02489                                          std::memory_order_acquire,
02490                                          std::memory_order_relaxed)) {
02491     c = Delay(c, GENTLE);
02492     v = cv_word->load(std::memory_order_relaxed);
02493   }
02494   ABSL_RAW_CHECK(waitp->thread->waitp == nullptr, "waiting when shouldn't be");
02495   waitp->thread->waitp = waitp;      // prepare ourselves for waiting
02496   PerThreadSynch *h = reinterpret_cast<PerThreadSynch *>(v & ~kCvLow);
02497   if (h == nullptr) {  // add this thread to waiter list
02498     waitp->thread->next = waitp->thread;
02499   } else {
02500     waitp->thread->next = h->next;
02501     h->next = waitp->thread;
02502   }
02503   waitp->thread->state.store(PerThreadSynch::kQueued,
02504                              std::memory_order_relaxed);
02505   cv_word->store((v & kCvEvent) | reinterpret_cast<intptr_t>(waitp->thread),
02506                  std::memory_order_release);
02507 }
02508 
02509 bool CondVar::WaitCommon(Mutex *mutex, KernelTimeout t) {
02510   bool rc = false;          // return value; true iff we timed-out
02511 
02512   intptr_t mutex_v = mutex->mu_.load(std::memory_order_relaxed);
02513   Mutex::MuHow mutex_how = ((mutex_v & kMuWriter) != 0) ? kExclusive : kShared;
02514   ABSL_TSAN_MUTEX_PRE_UNLOCK(mutex, TsanFlags(mutex_how));
02515 
02516   // maybe trace this call
02517   intptr_t v = cv_.load(std::memory_order_relaxed);
02518   cond_var_tracer("Wait", this);
02519   if ((v & kCvEvent) != 0) {
02520     PostSynchEvent(this, SYNCH_EV_WAIT);
02521   }
02522 
02523   // Release mu and wait on condition variable.
02524   SynchWaitParams waitp(mutex_how, nullptr, t, mutex,
02525                         Synch_GetPerThreadAnnotated(mutex), &cv_);
02526   // UnlockSlow() will call CondVarEnqueue() just before releasing the
02527   // Mutex, thus queuing this thread on the condition variable.  See
02528   // CondVarEnqueue() for the reasons.
02529   mutex->UnlockSlow(&waitp);
02530 
02531   // wait for signal
02532   while (waitp.thread->state.load(std::memory_order_acquire) ==
02533          PerThreadSynch::kQueued) {
02534     if (!Mutex::DecrementSynchSem(mutex, waitp.thread, t)) {
02535       this->Remove(waitp.thread);
02536       rc = true;
02537     }
02538   }
02539 
02540   ABSL_RAW_CHECK(waitp.thread->waitp != nullptr, "not waiting when should be");
02541   waitp.thread->waitp = nullptr;  // cleanup
02542 
02543   // maybe trace this call
02544   cond_var_tracer("Unwait", this);
02545   if ((v & kCvEvent) != 0) {
02546     PostSynchEvent(this, SYNCH_EV_WAIT_RETURNING);
02547   }
02548 
02549   // From synchronization point of view Wait is unlock of the mutex followed
02550   // by lock of the mutex. We've annotated start of unlock in the beginning
02551   // of the function. Now, finish unlock and annotate lock of the mutex.
02552   // (Trans is effectively lock).
02553   ABSL_TSAN_MUTEX_POST_UNLOCK(mutex, TsanFlags(mutex_how));
02554   ABSL_TSAN_MUTEX_PRE_LOCK(mutex, TsanFlags(mutex_how));
02555   mutex->Trans(mutex_how);  // Reacquire mutex
02556   ABSL_TSAN_MUTEX_POST_LOCK(mutex, TsanFlags(mutex_how), 0);
02557   return rc;
02558 }
02559 
02560 bool CondVar::WaitWithTimeout(Mutex *mu, absl::Duration timeout) {
02561   return WaitWithDeadline(mu, DeadlineFromTimeout(timeout));
02562 }
02563 
02564 bool CondVar::WaitWithDeadline(Mutex *mu, absl::Time deadline) {
02565   return WaitCommon(mu, KernelTimeout(deadline));
02566 }
02567 
02568 void CondVar::Wait(Mutex *mu) {
02569   WaitCommon(mu, KernelTimeout::Never());
02570 }
02571 
02572 // Wake thread w
02573 // If it was a timed wait, w will be waiting on w->cv
02574 // Otherwise, if it was not a Mutex mutex, w will be waiting on w->sem
02575 // Otherwise, w is transferred to the Mutex mutex via Mutex::Fer().
02576 void CondVar::Wakeup(PerThreadSynch *w) {
02577   if (w->waitp->timeout.has_timeout() || w->waitp->cvmu == nullptr) {
02578     // The waiting thread only needs to observe "w->state == kAvailable" to be
02579     // released, we must cache "cvmu" before clearing "next".
02580     Mutex *mu = w->waitp->cvmu;
02581     w->next = nullptr;
02582     w->state.store(PerThreadSynch::kAvailable, std::memory_order_release);
02583     Mutex::IncrementSynchSem(mu, w);
02584   } else {
02585     w->waitp->cvmu->Fer(w);
02586   }
02587 }
02588 
02589 void CondVar::Signal() {
02590   ABSL_TSAN_MUTEX_PRE_SIGNAL(nullptr, 0);
02591   intptr_t v;
02592   int c = 0;
02593   for (v = cv_.load(std::memory_order_relaxed); v != 0;
02594        v = cv_.load(std::memory_order_relaxed)) {
02595     if ((v & kCvSpin) == 0 &&  // attempt to acquire spinlock
02596         cv_.compare_exchange_strong(v, v | kCvSpin,
02597                                     std::memory_order_acquire,
02598                                     std::memory_order_relaxed)) {
02599       PerThreadSynch *h = reinterpret_cast<PerThreadSynch *>(v & ~kCvLow);
02600       PerThreadSynch *w = nullptr;
02601       if (h != nullptr) {  // remove first waiter
02602         w = h->next;
02603         if (w == h) {
02604           h = nullptr;
02605         } else {
02606           h->next = w->next;
02607         }
02608       }
02609                                       // release spinlock
02610       cv_.store((v & kCvEvent) | reinterpret_cast<intptr_t>(h),
02611                 std::memory_order_release);
02612       if (w != nullptr) {
02613         CondVar::Wakeup(w);                // wake waiter, if there was one
02614         cond_var_tracer("Signal wakeup", this);
02615       }
02616       if ((v & kCvEvent) != 0) {
02617         PostSynchEvent(this, SYNCH_EV_SIGNAL);
02618       }
02619       ABSL_TSAN_MUTEX_POST_SIGNAL(nullptr, 0);
02620       return;
02621     } else {
02622       c = Delay(c, GENTLE);
02623     }
02624   }
02625   ABSL_TSAN_MUTEX_POST_SIGNAL(nullptr, 0);
02626 }
02627 
02628 void CondVar::SignalAll () {
02629   ABSL_TSAN_MUTEX_PRE_SIGNAL(nullptr, 0);
02630   intptr_t v;
02631   int c = 0;
02632   for (v = cv_.load(std::memory_order_relaxed); v != 0;
02633        v = cv_.load(std::memory_order_relaxed)) {
02634     // empty the list if spinlock free
02635     // We do this by simply setting the list to empty using
02636     // compare and swap.   We then have the entire list in our hands,
02637     // which cannot be changing since we grabbed it while no one
02638     // held the lock.
02639     if ((v & kCvSpin) == 0 &&
02640         cv_.compare_exchange_strong(v, v & kCvEvent, std::memory_order_acquire,
02641                                     std::memory_order_relaxed)) {
02642       PerThreadSynch *h = reinterpret_cast<PerThreadSynch *>(v & ~kCvLow);
02643       if (h != nullptr) {
02644         PerThreadSynch *w;
02645         PerThreadSynch *n = h->next;
02646         do {                          // for every thread, wake it up
02647           w = n;
02648           n = n->next;
02649           CondVar::Wakeup(w);
02650         } while (w != h);
02651         cond_var_tracer("SignalAll wakeup", this);
02652       }
02653       if ((v & kCvEvent) != 0) {
02654         PostSynchEvent(this, SYNCH_EV_SIGNALALL);
02655       }
02656       ABSL_TSAN_MUTEX_POST_SIGNAL(nullptr, 0);
02657       return;
02658     } else {
02659       c = Delay(c, GENTLE);           // try again after a delay
02660     }
02661   }
02662   ABSL_TSAN_MUTEX_POST_SIGNAL(nullptr, 0);
02663 }
02664 
02665 void ReleasableMutexLock::Release() {
02666   ABSL_RAW_CHECK(this->mu_ != nullptr,
02667                  "ReleasableMutexLock::Release may only be called once");
02668   this->mu_->Unlock();
02669   this->mu_ = nullptr;
02670 }
02671 
02672 #ifdef THREAD_SANITIZER
02673 extern "C" void __tsan_read1(void *addr);
02674 #else
02675 #define __tsan_read1(addr)  // do nothing if TSan not enabled
02676 #endif
02677 
02678 // A function that just returns its argument, dereferenced
02679 static bool Dereference(void *arg) {
02680   // ThreadSanitizer does not instrument this file for memory accesses.
02681   // This function dereferences a user variable that can participate
02682   // in a data race, so we need to manually tell TSan about this memory access.
02683   __tsan_read1(arg);
02684   return *(static_cast<bool *>(arg));
02685 }
02686 
02687 Condition::Condition() {}   // null constructor, used for kTrue only
02688 const Condition Condition::kTrue;
02689 
02690 Condition::Condition(bool (*func)(void *), void *arg)
02691     : eval_(&CallVoidPtrFunction),
02692       function_(func),
02693       method_(nullptr),
02694       arg_(arg) {}
02695 
02696 bool Condition::CallVoidPtrFunction(const Condition *c) {
02697   return (*c->function_)(c->arg_);
02698 }
02699 
02700 Condition::Condition(const bool *cond)
02701     : eval_(CallVoidPtrFunction),
02702       function_(Dereference),
02703       method_(nullptr),
02704       // const_cast is safe since Dereference does not modify arg
02705       arg_(const_cast<bool *>(cond)) {}
02706 
02707 bool Condition::Eval() const {
02708   // eval_ == null for kTrue
02709   return (this->eval_ == nullptr) || (*this->eval_)(this);
02710 }
02711 
02712 bool Condition::GuaranteedEqual(const Condition *a, const Condition *b) {
02713   if (a == nullptr) {
02714     return b == nullptr || b->eval_ == nullptr;
02715   }
02716   if (b == nullptr || b->eval_ == nullptr) {
02717     return a->eval_ == nullptr;
02718   }
02719   return a->eval_ == b->eval_ && a->function_ == b->function_ &&
02720          a->arg_ == b->arg_ && a->method_ == b->method_;
02721 }
02722 
02723 }  // namespace absl


abseil_cpp
Author(s):
autogenerated on Wed Jun 19 2019 19:42:15