mutex.cc 114 KB

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