mutex.cc 114 KB

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