mutex.cc 111 KB

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