mutex.cc 115 KB

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