mutex.cc 115 KB

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