mutex.cc 115 KB

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