mutex.cc 115 KB

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