mutex.h revision eac4424b3420c280f97ff2f815b5dedd8dac9801
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ART_RUNTIME_BASE_MUTEX_H_
18#define ART_RUNTIME_BASE_MUTEX_H_
19
20#include <pthread.h>
21#include <stdint.h>
22
23#include <iosfwd>
24#include <string>
25
26#include "atomic.h"
27#include "base/logging.h"
28#include "base/macros.h"
29#include "globals.h"
30
31#if defined(__APPLE__)
32#define ART_USE_FUTEXES 0
33#else
34#define ART_USE_FUTEXES 1
35#endif
36
37// Currently Darwin doesn't support locks with timeouts.
38#if !defined(__APPLE__)
39#define HAVE_TIMED_RWLOCK 1
40#else
41#define HAVE_TIMED_RWLOCK 0
42#endif
43
44namespace art {
45
46class LOCKABLE ReaderWriterMutex;
47class LOCKABLE MutatorMutex;
48class ScopedContentionRecorder;
49class Thread;
50
51// LockLevel is used to impose a lock hierarchy [1] where acquisition of a Mutex at a higher or
52// equal level to a lock a thread holds is invalid. The lock hierarchy achieves a cycle free
53// partial ordering and thereby cause deadlock situations to fail checks.
54//
55// [1] http://www.drdobbs.com/parallel/use-lock-hierarchies-to-avoid-deadlock/204801163
56enum LockLevel {
57  kLoggingLock = 0,
58  kMemMapsLock,
59  kSwapMutexesLock,
60  kUnexpectedSignalLock,
61  kThreadSuspendCountLock,
62  kAbortLock,
63  kJdwpSocketLock,
64  kRegionSpaceRegionLock,
65  kTransactionLogLock,
66  kReferenceQueueSoftReferencesLock,
67  kReferenceQueuePhantomReferencesLock,
68  kReferenceQueueFinalizerReferencesLock,
69  kReferenceQueueWeakReferencesLock,
70  kReferenceQueueClearedReferencesLock,
71  kReferenceProcessorLock,
72  kJitCodeCacheLock,
73  kRosAllocGlobalLock,
74  kRosAllocBracketLock,
75  kRosAllocBulkFreeLock,
76  kAllocSpaceLock,
77  kBumpPointerSpaceBlockLock,
78  kArenaPoolLock,
79  kDexFileMethodInlinerLock,
80  kDexFileToMethodInlinerMapLock,
81  kMarkSweepMarkStackLock,
82  kInternTableLock,
83  kOatFileSecondaryLookupLock,
84  kTracingUniqueMethodsLock,
85  kTracingStreamingLock,
86  kDefaultMutexLevel,
87  kMarkSweepLargeObjectLock,
88  kPinTableLock,
89  kJdwpObjectRegistryLock,
90  kModifyLdtLock,
91  kAllocatedThreadIdsLock,
92  kMonitorPoolLock,
93  kMethodVerifiersLock,
94  kClassLinkerClassesLock,
95  kBreakpointLock,
96  kMonitorLock,
97  kMonitorListLock,
98  kJniLoadLibraryLock,
99  kThreadListLock,
100  kAllocTrackerLock,
101  kDeoptimizationLock,
102  kProfilerLock,
103  kJdwpShutdownLock,
104  kJdwpEventListLock,
105  kJdwpAttachLock,
106  kJdwpStartLock,
107  kRuntimeShutdownLock,
108  kTraceLock,
109  kHeapBitmapLock,
110  kMutatorLock,
111  kInstrumentEntrypointsLock,
112  kZygoteCreationLock,
113
114  kLockLevelCount  // Must come last.
115};
116std::ostream& operator<<(std::ostream& os, const LockLevel& rhs);
117
118const bool kDebugLocking = kIsDebugBuild;
119
120// Record Log contention information, dumpable via SIGQUIT.
121#ifdef ART_USE_FUTEXES
122// To enable lock contention logging, set this to true.
123const bool kLogLockContentions = false;
124#else
125// Keep this false as lock contention logging is supported only with
126// futex.
127const bool kLogLockContentions = false;
128#endif
129const size_t kContentionLogSize = 4;
130const size_t kContentionLogDataSize = kLogLockContentions ? 1 : 0;
131const size_t kAllMutexDataSize = kLogLockContentions ? 1 : 0;
132
133// Base class for all Mutex implementations
134class BaseMutex {
135 public:
136  const char* GetName() const {
137    return name_;
138  }
139
140  virtual bool IsMutex() const { return false; }
141  virtual bool IsReaderWriterMutex() const { return false; }
142  virtual bool IsMutatorMutex() const { return false; }
143
144  virtual void Dump(std::ostream& os) const = 0;
145
146  static void DumpAll(std::ostream& os);
147
148 protected:
149  friend class ConditionVariable;
150
151  BaseMutex(const char* name, LockLevel level);
152  virtual ~BaseMutex();
153  void RegisterAsLocked(Thread* self);
154  void RegisterAsUnlocked(Thread* self);
155  void CheckSafeToWait(Thread* self);
156
157  friend class ScopedContentionRecorder;
158
159  void RecordContention(uint64_t blocked_tid, uint64_t owner_tid, uint64_t nano_time_blocked);
160  void DumpContention(std::ostream& os) const;
161
162  const LockLevel level_;  // Support for lock hierarchy.
163  const char* const name_;
164
165  // A log entry that records contention but makes no guarantee that either tid will be held live.
166  struct ContentionLogEntry {
167    ContentionLogEntry() : blocked_tid(0), owner_tid(0) {}
168    uint64_t blocked_tid;
169    uint64_t owner_tid;
170    AtomicInteger count;
171  };
172  struct ContentionLogData {
173    ContentionLogEntry contention_log[kContentionLogSize];
174    // The next entry in the contention log to be updated. Value ranges from 0 to
175    // kContentionLogSize - 1.
176    AtomicInteger cur_content_log_entry;
177    // Number of times the Mutex has been contended.
178    AtomicInteger contention_count;
179    // Sum of time waited by all contenders in ns.
180    Atomic<uint64_t> wait_time;
181    void AddToWaitTime(uint64_t value);
182    ContentionLogData() : wait_time(0) {}
183  };
184  ContentionLogData contention_log_data_[kContentionLogDataSize];
185
186 public:
187  bool HasEverContended() const {
188    if (kLogLockContentions) {
189      return contention_log_data_->contention_count.LoadSequentiallyConsistent() > 0;
190    }
191    return false;
192  }
193};
194
195// A Mutex is used to achieve mutual exclusion between threads. A Mutex can be used to gain
196// exclusive access to what it guards. A Mutex can be in one of two states:
197// - Free - not owned by any thread,
198// - Exclusive - owned by a single thread.
199//
200// The effect of locking and unlocking operations on the state is:
201// State     | ExclusiveLock | ExclusiveUnlock
202// -------------------------------------------
203// Free      | Exclusive     | error
204// Exclusive | Block*        | Free
205// * Mutex is not reentrant and so an attempt to ExclusiveLock on the same thread will result in
206//   an error. Being non-reentrant simplifies Waiting on ConditionVariables.
207std::ostream& operator<<(std::ostream& os, const Mutex& mu);
208class LOCKABLE Mutex : public BaseMutex {
209 public:
210  explicit Mutex(const char* name, LockLevel level = kDefaultMutexLevel, bool recursive = false);
211  ~Mutex();
212
213  virtual bool IsMutex() const { return true; }
214
215  // Block until mutex is free then acquire exclusive access.
216  void ExclusiveLock(Thread* self) EXCLUSIVE_LOCK_FUNCTION();
217  void Lock(Thread* self) EXCLUSIVE_LOCK_FUNCTION() {  ExclusiveLock(self); }
218
219  // Returns true if acquires exclusive access, false otherwise.
220  bool ExclusiveTryLock(Thread* self) EXCLUSIVE_TRYLOCK_FUNCTION(true);
221  bool TryLock(Thread* self) EXCLUSIVE_TRYLOCK_FUNCTION(true) { return ExclusiveTryLock(self); }
222
223  // Release exclusive access.
224  void ExclusiveUnlock(Thread* self) UNLOCK_FUNCTION();
225  void Unlock(Thread* self) UNLOCK_FUNCTION() {  ExclusiveUnlock(self); }
226
227  // Is the current thread the exclusive holder of the Mutex.
228  bool IsExclusiveHeld(const Thread* self) const;
229
230  // Assert that the Mutex is exclusively held by the current thread.
231  void AssertExclusiveHeld(const Thread* self) {
232    if (kDebugLocking && (gAborting == 0)) {
233      CHECK(IsExclusiveHeld(self)) << *this;
234    }
235  }
236  void AssertHeld(const Thread* self) { AssertExclusiveHeld(self); }
237
238  // Assert that the Mutex is not held by the current thread.
239  void AssertNotHeldExclusive(const Thread* self) {
240    if (kDebugLocking && (gAborting == 0)) {
241      CHECK(!IsExclusiveHeld(self)) << *this;
242    }
243  }
244  void AssertNotHeld(const Thread* self) { AssertNotHeldExclusive(self); }
245
246  // Id associated with exclusive owner. No memory ordering semantics if called from a thread other
247  // than the owner.
248  uint64_t GetExclusiveOwnerTid() const;
249
250  // Returns how many times this Mutex has been locked, it is better to use AssertHeld/NotHeld.
251  unsigned int GetDepth() const {
252    return recursion_count_;
253  }
254
255  virtual void Dump(std::ostream& os) const;
256
257 private:
258#if ART_USE_FUTEXES
259  // 0 is unheld, 1 is held.
260  AtomicInteger state_;
261  // Exclusive owner.
262  volatile uint64_t exclusive_owner_;
263  // Number of waiting contenders.
264  AtomicInteger num_contenders_;
265#else
266  pthread_mutex_t mutex_;
267  volatile uint64_t exclusive_owner_;  // Guarded by mutex_.
268#endif
269  const bool recursive_;  // Can the lock be recursively held?
270  unsigned int recursion_count_;
271  friend class ConditionVariable;
272  DISALLOW_COPY_AND_ASSIGN(Mutex);
273};
274
275// A ReaderWriterMutex is used to achieve mutual exclusion between threads, similar to a Mutex.
276// Unlike a Mutex a ReaderWriterMutex can be used to gain exclusive (writer) or shared (reader)
277// access to what it guards. A flaw in relation to a Mutex is that it cannot be used with a
278// condition variable. A ReaderWriterMutex can be in one of three states:
279// - Free - not owned by any thread,
280// - Exclusive - owned by a single thread,
281// - Shared(n) - shared amongst n threads.
282//
283// The effect of locking and unlocking operations on the state is:
284//
285// State     | ExclusiveLock | ExclusiveUnlock | SharedLock       | SharedUnlock
286// ----------------------------------------------------------------------------
287// Free      | Exclusive     | error           | SharedLock(1)    | error
288// Exclusive | Block         | Free            | Block            | error
289// Shared(n) | Block         | error           | SharedLock(n+1)* | Shared(n-1) or Free
290// * for large values of n the SharedLock may block.
291std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu);
292class LOCKABLE ReaderWriterMutex : public BaseMutex {
293 public:
294  explicit ReaderWriterMutex(const char* name, LockLevel level = kDefaultMutexLevel);
295  ~ReaderWriterMutex();
296
297  virtual bool IsReaderWriterMutex() const { return true; }
298
299  // Block until ReaderWriterMutex is free then acquire exclusive access.
300  void ExclusiveLock(Thread* self) EXCLUSIVE_LOCK_FUNCTION();
301  void WriterLock(Thread* self) EXCLUSIVE_LOCK_FUNCTION() {  ExclusiveLock(self); }
302
303  // Release exclusive access.
304  void ExclusiveUnlock(Thread* self) UNLOCK_FUNCTION();
305  void WriterUnlock(Thread* self) UNLOCK_FUNCTION() {  ExclusiveUnlock(self); }
306
307  // Block until ReaderWriterMutex is free and acquire exclusive access. Returns true on success
308  // or false if timeout is reached.
309#if HAVE_TIMED_RWLOCK
310  bool ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns)
311      EXCLUSIVE_TRYLOCK_FUNCTION(true);
312#endif
313
314  // Block until ReaderWriterMutex is shared or free then acquire a share on the access.
315  void SharedLock(Thread* self) SHARED_LOCK_FUNCTION() ALWAYS_INLINE;
316  void ReaderLock(Thread* self) SHARED_LOCK_FUNCTION() { SharedLock(self); }
317
318  // Try to acquire share of ReaderWriterMutex.
319  bool SharedTryLock(Thread* self) EXCLUSIVE_TRYLOCK_FUNCTION(true);
320
321  // Release a share of the access.
322  void SharedUnlock(Thread* self) UNLOCK_FUNCTION() ALWAYS_INLINE;
323  void ReaderUnlock(Thread* self) UNLOCK_FUNCTION() { SharedUnlock(self); }
324
325  // Is the current thread the exclusive holder of the ReaderWriterMutex.
326  bool IsExclusiveHeld(const Thread* self) const;
327
328  // Assert the current thread has exclusive access to the ReaderWriterMutex.
329  void AssertExclusiveHeld(const Thread* self) {
330    if (kDebugLocking && (gAborting == 0)) {
331      CHECK(IsExclusiveHeld(self)) << *this;
332    }
333  }
334  void AssertWriterHeld(const Thread* self) { AssertExclusiveHeld(self); }
335
336  // Assert the current thread doesn't have exclusive access to the ReaderWriterMutex.
337  void AssertNotExclusiveHeld(const Thread* self) {
338    if (kDebugLocking && (gAborting == 0)) {
339      CHECK(!IsExclusiveHeld(self)) << *this;
340    }
341  }
342  void AssertNotWriterHeld(const Thread* self) { AssertNotExclusiveHeld(self); }
343
344  // Is the current thread a shared holder of the ReaderWriterMutex.
345  bool IsSharedHeld(const Thread* self) const;
346
347  // Assert the current thread has shared access to the ReaderWriterMutex.
348  void AssertSharedHeld(const Thread* self) {
349    if (kDebugLocking && (gAborting == 0)) {
350      // TODO: we can only assert this well when self != null.
351      CHECK(IsSharedHeld(self) || self == nullptr) << *this;
352    }
353  }
354  void AssertReaderHeld(const Thread* self) { AssertSharedHeld(self); }
355
356  // Assert the current thread doesn't hold this ReaderWriterMutex either in shared or exclusive
357  // mode.
358  void AssertNotHeld(const Thread* self) {
359    if (kDebugLocking && (gAborting == 0)) {
360      CHECK(!IsSharedHeld(self)) << *this;
361    }
362  }
363
364  // Id associated with exclusive owner. No memory ordering semantics if called from a thread other
365  // than the owner.
366  uint64_t GetExclusiveOwnerTid() const;
367
368  virtual void Dump(std::ostream& os) const;
369
370 private:
371#if ART_USE_FUTEXES
372  // Out-of-inline path for handling contention for a SharedLock.
373  void HandleSharedLockContention(Thread* self, int32_t cur_state);
374
375  // -1 implies held exclusive, +ve shared held by state_ many owners.
376  AtomicInteger state_;
377  // Exclusive owner. Modification guarded by this mutex.
378  volatile uint64_t exclusive_owner_;
379  // Number of contenders waiting for a reader share.
380  AtomicInteger num_pending_readers_;
381  // Number of contenders waiting to be the writer.
382  AtomicInteger num_pending_writers_;
383#else
384  pthread_rwlock_t rwlock_;
385  volatile uint64_t exclusive_owner_;  // Guarded by rwlock_.
386#endif
387  DISALLOW_COPY_AND_ASSIGN(ReaderWriterMutex);
388};
389
390// MutatorMutex is a special kind of ReaderWriterMutex created specifically for the
391// Locks::mutator_lock_ mutex. The behaviour is identical to the ReaderWriterMutex except that
392// thread state changes also play a part in lock ownership. The mutator_lock_ will not be truly
393// held by any mutator threads. However, a thread in the kRunnable state is considered to have
394// shared ownership of the mutator lock and therefore transitions in and out of the kRunnable
395// state have associated implications on lock ownership. Extra methods to handle the state
396// transitions have been added to the interface but are only accessible to the methods dealing
397// with state transitions. The thread state and flags attributes are used to ensure thread state
398// transitions are consistent with the permitted behaviour of the mutex.
399//
400// *) The most important consequence of this behaviour is that all threads must be in one of the
401// suspended states before exclusive ownership of the mutator mutex is sought.
402//
403std::ostream& operator<<(std::ostream& os, const MutatorMutex& mu);
404class LOCKABLE MutatorMutex : public ReaderWriterMutex {
405 public:
406  explicit MutatorMutex(const char* name, LockLevel level = kDefaultMutexLevel)
407    : ReaderWriterMutex(name, level) {}
408  ~MutatorMutex() {}
409
410  virtual bool IsMutatorMutex() const { return true; }
411
412 private:
413  friend class Thread;
414  void TransitionFromRunnableToSuspended(Thread* self) UNLOCK_FUNCTION() ALWAYS_INLINE;
415  void TransitionFromSuspendedToRunnable(Thread* self) SHARED_LOCK_FUNCTION() ALWAYS_INLINE;
416
417  DISALLOW_COPY_AND_ASSIGN(MutatorMutex);
418};
419
420// ConditionVariables allow threads to queue and sleep. Threads may then be resumed individually
421// (Signal) or all at once (Broadcast).
422class ConditionVariable {
423 public:
424  explicit ConditionVariable(const char* name, Mutex& mutex);
425  ~ConditionVariable();
426
427  void Broadcast(Thread* self);
428  void Signal(Thread* self);
429  // TODO: No thread safety analysis on Wait and TimedWait as they call mutex operations via their
430  //       pointer copy, thereby defeating annotalysis.
431  void Wait(Thread* self) NO_THREAD_SAFETY_ANALYSIS;
432  bool TimedWait(Thread* self, int64_t ms, int32_t ns) NO_THREAD_SAFETY_ANALYSIS;
433  // Variant of Wait that should be used with caution. Doesn't validate that no mutexes are held
434  // when waiting.
435  // TODO: remove this.
436  void WaitHoldingLocks(Thread* self) NO_THREAD_SAFETY_ANALYSIS;
437
438 private:
439  const char* const name_;
440  // The Mutex being used by waiters. It is an error to mix condition variables between different
441  // Mutexes.
442  Mutex& guard_;
443#if ART_USE_FUTEXES
444  // A counter that is modified by signals and broadcasts. This ensures that when a waiter gives up
445  // their Mutex and another thread takes it and signals, the waiting thread observes that sequence_
446  // changed and doesn't enter the wait. Modified while holding guard_, but is read by futex wait
447  // without guard_ held.
448  AtomicInteger sequence_;
449  // Number of threads that have come into to wait, not the length of the waiters on the futex as
450  // waiters may have been requeued onto guard_. Guarded by guard_.
451  volatile int32_t num_waiters_;
452#else
453  pthread_cond_t cond_;
454#endif
455  DISALLOW_COPY_AND_ASSIGN(ConditionVariable);
456};
457
458// Scoped locker/unlocker for a regular Mutex that acquires mu upon construction and releases it
459// upon destruction.
460class SCOPED_LOCKABLE MutexLock {
461 public:
462  explicit MutexLock(Thread* self, Mutex& mu) EXCLUSIVE_LOCK_FUNCTION(mu) : self_(self), mu_(mu) {
463    mu_.ExclusiveLock(self_);
464  }
465
466  ~MutexLock() UNLOCK_FUNCTION() {
467    mu_.ExclusiveUnlock(self_);
468  }
469
470 private:
471  Thread* const self_;
472  Mutex& mu_;
473  DISALLOW_COPY_AND_ASSIGN(MutexLock);
474};
475// Catch bug where variable name is omitted. "MutexLock (lock);" instead of "MutexLock mu(lock)".
476#define MutexLock(x) static_assert(0, "MutexLock declaration missing variable name")
477
478// Scoped locker/unlocker for a ReaderWriterMutex that acquires read access to mu upon
479// construction and releases it upon destruction.
480class SCOPED_LOCKABLE ReaderMutexLock {
481 public:
482  explicit ReaderMutexLock(Thread* self, ReaderWriterMutex& mu) EXCLUSIVE_LOCK_FUNCTION(mu) :
483      self_(self), mu_(mu) {
484    mu_.SharedLock(self_);
485  }
486
487  ~ReaderMutexLock() UNLOCK_FUNCTION() {
488    mu_.SharedUnlock(self_);
489  }
490
491 private:
492  Thread* const self_;
493  ReaderWriterMutex& mu_;
494  DISALLOW_COPY_AND_ASSIGN(ReaderMutexLock);
495};
496// Catch bug where variable name is omitted. "ReaderMutexLock (lock);" instead of
497// "ReaderMutexLock mu(lock)".
498#define ReaderMutexLock(x) static_assert(0, "ReaderMutexLock declaration missing variable name")
499
500// Scoped locker/unlocker for a ReaderWriterMutex that acquires write access to mu upon
501// construction and releases it upon destruction.
502class SCOPED_LOCKABLE WriterMutexLock {
503 public:
504  explicit WriterMutexLock(Thread* self, ReaderWriterMutex& mu) EXCLUSIVE_LOCK_FUNCTION(mu) :
505      self_(self), mu_(mu) {
506    mu_.ExclusiveLock(self_);
507  }
508
509  ~WriterMutexLock() UNLOCK_FUNCTION() {
510    mu_.ExclusiveUnlock(self_);
511  }
512
513 private:
514  Thread* const self_;
515  ReaderWriterMutex& mu_;
516  DISALLOW_COPY_AND_ASSIGN(WriterMutexLock);
517};
518// Catch bug where variable name is omitted. "WriterMutexLock (lock);" instead of
519// "WriterMutexLock mu(lock)".
520#define WriterMutexLock(x) static_assert(0, "WriterMutexLock declaration missing variable name")
521
522// Global mutexes corresponding to the levels above.
523class Locks {
524 public:
525  static void Init();
526  static void InitConditions() NO_THREAD_SAFETY_ANALYSIS;  // Condition variables.
527  // Guards allocation entrypoint instrumenting.
528  static Mutex* instrument_entrypoints_lock_;
529
530  // A barrier is used to synchronize the GC/Debugger thread with mutator threads. When GC/Debugger
531  // thread wants to suspend all mutator threads, it needs to wait for all mutator threads to pass
532  // a barrier. Threads that are already suspended will get their barrier passed by the GC/Debugger
533  // thread; threads in the runnable state will pass the barrier when they transit to the suspended
534  // state. GC/Debugger thread will be woken up when all mutator threads are suspended.
535  //
536  // Thread suspension:
537  // mutator thread                                | GC/Debugger
538  //   .. running ..                               |   .. running ..
539  //   .. running ..                               | Request thread suspension by:
540  //   .. running ..                               |   - acquiring thread_suspend_count_lock_
541  //   .. running ..                               |   - incrementing Thread::suspend_count_ on
542  //   .. running ..                               |     all mutator threads
543  //   .. running ..                               |   - releasing thread_suspend_count_lock_
544  //   .. running ..                               | Block wait for all threads to pass a barrier
545  // Poll Thread::suspend_count_ and enter full    |   .. blocked ..
546  // suspend code.                                 |   .. blocked ..
547  // Change state to kSuspended (pass the barrier) | Wake up when all threads pass the barrier
548  // x: Acquire thread_suspend_count_lock_         |   .. running ..
549  // while Thread::suspend_count_ > 0              |   .. running ..
550  //   - wait on Thread::resume_cond_              |   .. running ..
551  //     (releases thread_suspend_count_lock_)     |   .. running ..
552  //   .. waiting ..                               | Request thread resumption by:
553  //   .. waiting ..                               |   - acquiring thread_suspend_count_lock_
554  //   .. waiting ..                               |   - decrementing Thread::suspend_count_ on
555  //   .. waiting ..                               |     all mutator threads
556  //   .. waiting ..                               |   - notifying on Thread::resume_cond_
557  //    - re-acquire thread_suspend_count_lock_    |   - releasing thread_suspend_count_lock_
558  // Release thread_suspend_count_lock_            |  .. running ..
559  // Change to kRunnable                           |  .. running ..
560  //  - this uses a CAS operation to ensure the    |  .. running ..
561  //    suspend request flag isn't raised as the   |  .. running ..
562  //    state is changed                           |  .. running ..
563  //  - if the CAS operation fails then goto x     |  .. running ..
564  //  .. running ..                                |  .. running ..
565  static MutatorMutex* mutator_lock_ ACQUIRED_AFTER(instrument_entrypoints_lock_);
566
567  // Allow reader-writer mutual exclusion on the mark and live bitmaps of the heap.
568  static ReaderWriterMutex* heap_bitmap_lock_ ACQUIRED_AFTER(mutator_lock_);
569
570  // Guards shutdown of the runtime.
571  static Mutex* runtime_shutdown_lock_ ACQUIRED_AFTER(heap_bitmap_lock_);
572
573  // Guards background profiler global state.
574  static Mutex* profiler_lock_ ACQUIRED_AFTER(runtime_shutdown_lock_);
575
576  // Guards trace (ie traceview) requests.
577  static Mutex* trace_lock_ ACQUIRED_AFTER(profiler_lock_);
578
579  // Guards debugger recent allocation records.
580  static Mutex* alloc_tracker_lock_ ACQUIRED_AFTER(trace_lock_);
581
582  // Guards updates to instrumentation to ensure mutual exclusion of
583  // events like deoptimization requests.
584  // TODO: improve name, perhaps instrumentation_update_lock_.
585  static Mutex* deoptimization_lock_ ACQUIRED_AFTER(alloc_tracker_lock_);
586
587  // The thread_list_lock_ guards ThreadList::list_. It is also commonly held to stop threads
588  // attaching and detaching.
589  static Mutex* thread_list_lock_ ACQUIRED_AFTER(deoptimization_lock_);
590
591  // Signaled when threads terminate. Used to determine when all non-daemons have terminated.
592  static ConditionVariable* thread_exit_cond_ GUARDED_BY(Locks::thread_list_lock_);
593
594  // Guards maintaining loading library data structures.
595  static Mutex* jni_libraries_lock_ ACQUIRED_AFTER(thread_list_lock_);
596
597  // Guards breakpoints.
598  static ReaderWriterMutex* breakpoint_lock_ ACQUIRED_AFTER(jni_libraries_lock_);
599
600  // Guards lists of classes within the class linker.
601  static ReaderWriterMutex* classlinker_classes_lock_ ACQUIRED_AFTER(breakpoint_lock_);
602
603  // When declaring any Mutex add DEFAULT_MUTEX_ACQUIRED_AFTER to use annotalysis to check the code
604  // doesn't try to hold a higher level Mutex.
605  #define DEFAULT_MUTEX_ACQUIRED_AFTER ACQUIRED_AFTER(Locks::classlinker_classes_lock_)
606
607  static Mutex* allocated_monitor_ids_lock_ ACQUIRED_AFTER(classlinker_classes_lock_);
608
609  // Guard the allocation/deallocation of thread ids.
610  static Mutex* allocated_thread_ids_lock_ ACQUIRED_AFTER(allocated_monitor_ids_lock_);
611
612  // Guards modification of the LDT on x86.
613  static Mutex* modify_ldt_lock_ ACQUIRED_AFTER(allocated_thread_ids_lock_);
614
615  // Guards intern table.
616  static Mutex* intern_table_lock_ ACQUIRED_AFTER(modify_ldt_lock_);
617
618  // Guards reference processor.
619  static Mutex* reference_processor_lock_ ACQUIRED_AFTER(intern_table_lock_);
620
621  // Guards cleared references queue.
622  static Mutex* reference_queue_cleared_references_lock_ ACQUIRED_AFTER(reference_processor_lock_);
623
624  // Guards weak references queue.
625  static Mutex* reference_queue_weak_references_lock_ ACQUIRED_AFTER(reference_queue_cleared_references_lock_);
626
627  // Guards finalizer references queue.
628  static Mutex* reference_queue_finalizer_references_lock_ ACQUIRED_AFTER(reference_queue_weak_references_lock_);
629
630  // Guards phantom references queue.
631  static Mutex* reference_queue_phantom_references_lock_ ACQUIRED_AFTER(reference_queue_finalizer_references_lock_);
632
633  // Guards soft references queue.
634  static Mutex* reference_queue_soft_references_lock_ ACQUIRED_AFTER(reference_queue_phantom_references_lock_);
635
636  // Have an exclusive aborting thread.
637  static Mutex* abort_lock_ ACQUIRED_AFTER(reference_queue_soft_references_lock_);
638
639  // Allow mutual exclusion when manipulating Thread::suspend_count_.
640  // TODO: Does the trade-off of a per-thread lock make sense?
641  static Mutex* thread_suspend_count_lock_ ACQUIRED_AFTER(abort_lock_);
642
643  // One unexpected signal at a time lock.
644  static Mutex* unexpected_signal_lock_ ACQUIRED_AFTER(thread_suspend_count_lock_);
645
646  // Guards the maps in mem_map.
647  static Mutex* mem_maps_lock_ ACQUIRED_AFTER(unexpected_signal_lock_);
648
649  // Have an exclusive logging thread.
650  static Mutex* logging_lock_ ACQUIRED_AFTER(unexpected_signal_lock_);
651};
652
653}  // namespace art
654
655#endif  // ART_RUNTIME_BASE_MUTEX_H_
656