2 * Copyright (C) 2011 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef ART_RUNTIME_BASE_MUTEX_H_
18 #define ART_RUNTIME_BASE_MUTEX_H_
27 #include "base/logging.h"
28 #include "base/macros.h"
31 #if defined(__APPLE__)
32 #define ART_USE_FUTEXES 0
34 #define ART_USE_FUTEXES 1
37 // Currently Darwin doesn't support locks with timeouts.
38 #if !defined(__APPLE__)
39 #define HAVE_TIMED_RWLOCK 1
41 #define HAVE_TIMED_RWLOCK 0
46 class LOCKABLE ReaderWriterMutex;
47 class ScopedContentionRecorder;
50 // LockLevel is used to impose a lock hierarchy [1] where acquisition of a Mutex at a higher or
51 // equal level to a lock a thread holds is invalid. The lock hierarchy achieves a cycle free
52 // partial ordering and thereby cause deadlock situations to fail checks.
54 // [1] http://www.drdobbs.com/parallel/use-lock-hierarchies-to-avoid-deadlock/204801163
59 kUnexpectedSignalLock,
60 kThreadSuspendCountLock,
65 kRosAllocBulkFreeLock,
67 kReferenceProcessorLock,
68 kDexFileMethodInlinerLock,
69 kDexFileToMethodInlinerMapLock,
70 kMarkSweepMarkStackLock,
74 kMarkSweepLargeObjectLock,
77 kJdwpObjectRegistryLock,
79 kAllocatedThreadIdsLock,
81 kClassLinkerClassesLock,
86 kBreakpointInvokeLock,
98 kLockLevelCount // Must come last.
100 std::ostream& operator<<(std::ostream& os, const LockLevel& rhs);
102 const bool kDebugLocking = kIsDebugBuild;
104 // Record Log contention information, dumpable via SIGQUIT.
105 #ifdef ART_USE_FUTEXES
106 // To enable lock contention logging, set this to true.
107 const bool kLogLockContentions = false;
109 // Keep this false as lock contention logging is supported only with
111 const bool kLogLockContentions = false;
113 const size_t kContentionLogSize = 4;
114 const size_t kContentionLogDataSize = kLogLockContentions ? 1 : 0;
115 const size_t kAllMutexDataSize = kLogLockContentions ? 1 : 0;
117 // Base class for all Mutex implementations
120 const char* GetName() const {
124 virtual bool IsMutex() const { return false; }
125 virtual bool IsReaderWriterMutex() const { return false; }
127 virtual void Dump(std::ostream& os) const = 0;
129 static void DumpAll(std::ostream& os);
132 friend class ConditionVariable;
134 BaseMutex(const char* name, LockLevel level);
135 virtual ~BaseMutex();
136 void RegisterAsLocked(Thread* self);
137 void RegisterAsUnlocked(Thread* self);
138 void CheckSafeToWait(Thread* self);
140 friend class ScopedContentionRecorder;
142 void RecordContention(uint64_t blocked_tid, uint64_t owner_tid, uint64_t nano_time_blocked);
143 void DumpContention(std::ostream& os) const;
145 const LockLevel level_; // Support for lock hierarchy.
146 const char* const name_;
148 // A log entry that records contention but makes no guarantee that either tid will be held live.
149 struct ContentionLogEntry {
150 ContentionLogEntry() : blocked_tid(0), owner_tid(0) {}
151 uint64_t blocked_tid;
155 struct ContentionLogData {
156 ContentionLogEntry contention_log[kContentionLogSize];
157 // The next entry in the contention log to be updated. Value ranges from 0 to
158 // kContentionLogSize - 1.
159 AtomicInteger cur_content_log_entry;
160 // Number of times the Mutex has been contended.
161 AtomicInteger contention_count;
162 // Sum of time waited by all contenders in ns.
163 volatile uint64_t wait_time;
164 void AddToWaitTime(uint64_t value);
165 ContentionLogData() : wait_time(0) {}
167 ContentionLogData contention_log_data_[kContentionLogDataSize];
170 bool HasEverContended() const {
171 if (kLogLockContentions) {
172 return contention_log_data_->contention_count.LoadSequentiallyConsistent() > 0;
178 // A Mutex is used to achieve mutual exclusion between threads. A Mutex can be used to gain
179 // exclusive access to what it guards. A Mutex can be in one of two states:
180 // - Free - not owned by any thread,
181 // - Exclusive - owned by a single thread.
183 // The effect of locking and unlocking operations on the state is:
184 // State | ExclusiveLock | ExclusiveUnlock
185 // -------------------------------------------
186 // Free | Exclusive | error
187 // Exclusive | Block* | Free
188 // * Mutex is not reentrant and so an attempt to ExclusiveLock on the same thread will result in
189 // an error. Being non-reentrant simplifies Waiting on ConditionVariables.
190 std::ostream& operator<<(std::ostream& os, const Mutex& mu);
191 class LOCKABLE Mutex : public BaseMutex {
193 explicit Mutex(const char* name, LockLevel level = kDefaultMutexLevel, bool recursive = false);
196 virtual bool IsMutex() const { return true; }
198 // Block until mutex is free then acquire exclusive access.
199 void ExclusiveLock(Thread* self) EXCLUSIVE_LOCK_FUNCTION();
200 void Lock(Thread* self) EXCLUSIVE_LOCK_FUNCTION() { ExclusiveLock(self); }
202 // Returns true if acquires exclusive access, false otherwise.
203 bool ExclusiveTryLock(Thread* self) EXCLUSIVE_TRYLOCK_FUNCTION(true);
204 bool TryLock(Thread* self) EXCLUSIVE_TRYLOCK_FUNCTION(true) { return ExclusiveTryLock(self); }
206 // Release exclusive access.
207 void ExclusiveUnlock(Thread* self) UNLOCK_FUNCTION();
208 void Unlock(Thread* self) UNLOCK_FUNCTION() { ExclusiveUnlock(self); }
210 // Is the current thread the exclusive holder of the Mutex.
211 bool IsExclusiveHeld(const Thread* self) const;
213 // Assert that the Mutex is exclusively held by the current thread.
214 void AssertExclusiveHeld(const Thread* self) {
215 if (kDebugLocking && (gAborting == 0)) {
216 CHECK(IsExclusiveHeld(self)) << *this;
219 void AssertHeld(const Thread* self) { AssertExclusiveHeld(self); }
221 // Assert that the Mutex is not held by the current thread.
222 void AssertNotHeldExclusive(const Thread* self) {
223 if (kDebugLocking && (gAborting == 0)) {
224 CHECK(!IsExclusiveHeld(self)) << *this;
227 void AssertNotHeld(const Thread* self) { AssertNotHeldExclusive(self); }
229 // Id associated with exclusive owner.
230 uint64_t GetExclusiveOwnerTid() const;
232 // Returns how many times this Mutex has been locked, it is better to use AssertHeld/NotHeld.
233 unsigned int GetDepth() const {
234 return recursion_count_;
237 virtual void Dump(std::ostream& os) const;
241 // 0 is unheld, 1 is held.
242 volatile int32_t state_;
244 volatile uint64_t exclusive_owner_;
245 // Number of waiting contenders.
246 AtomicInteger num_contenders_;
248 pthread_mutex_t mutex_;
249 volatile uint64_t exclusive_owner_; // Guarded by mutex_.
251 const bool recursive_; // Can the lock be recursively held?
252 unsigned int recursion_count_;
253 friend class ConditionVariable;
254 DISALLOW_COPY_AND_ASSIGN(Mutex);
257 // A ReaderWriterMutex is used to achieve mutual exclusion between threads, similar to a Mutex.
258 // Unlike a Mutex a ReaderWriterMutex can be used to gain exclusive (writer) or shared (reader)
259 // access to what it guards. A flaw in relation to a Mutex is that it cannot be used with a
260 // condition variable. A ReaderWriterMutex can be in one of three states:
261 // - Free - not owned by any thread,
262 // - Exclusive - owned by a single thread,
263 // - Shared(n) - shared amongst n threads.
265 // The effect of locking and unlocking operations on the state is:
267 // State | ExclusiveLock | ExclusiveUnlock | SharedLock | SharedUnlock
268 // ----------------------------------------------------------------------------
269 // Free | Exclusive | error | SharedLock(1) | error
270 // Exclusive | Block | Free | Block | error
271 // Shared(n) | Block | error | SharedLock(n+1)* | Shared(n-1) or Free
272 // * for large values of n the SharedLock may block.
273 std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu);
274 class LOCKABLE ReaderWriterMutex : public BaseMutex {
276 explicit ReaderWriterMutex(const char* name, LockLevel level = kDefaultMutexLevel);
277 ~ReaderWriterMutex();
279 virtual bool IsReaderWriterMutex() const { return true; }
281 // Block until ReaderWriterMutex is free then acquire exclusive access.
282 void ExclusiveLock(Thread* self) EXCLUSIVE_LOCK_FUNCTION();
283 void WriterLock(Thread* self) EXCLUSIVE_LOCK_FUNCTION() { ExclusiveLock(self); }
285 // Release exclusive access.
286 void ExclusiveUnlock(Thread* self) UNLOCK_FUNCTION();
287 void WriterUnlock(Thread* self) UNLOCK_FUNCTION() { ExclusiveUnlock(self); }
289 // Block until ReaderWriterMutex is free and acquire exclusive access. Returns true on success
290 // or false if timeout is reached.
291 #if HAVE_TIMED_RWLOCK
292 bool ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns)
293 EXCLUSIVE_TRYLOCK_FUNCTION(true);
296 // Block until ReaderWriterMutex is shared or free then acquire a share on the access.
297 void SharedLock(Thread* self) SHARED_LOCK_FUNCTION() ALWAYS_INLINE;
298 void ReaderLock(Thread* self) SHARED_LOCK_FUNCTION() { SharedLock(self); }
300 // Try to acquire share of ReaderWriterMutex.
301 bool SharedTryLock(Thread* self) EXCLUSIVE_TRYLOCK_FUNCTION(true);
303 // Release a share of the access.
304 void SharedUnlock(Thread* self) UNLOCK_FUNCTION() ALWAYS_INLINE;
305 void ReaderUnlock(Thread* self) UNLOCK_FUNCTION() { SharedUnlock(self); }
307 // Is the current thread the exclusive holder of the ReaderWriterMutex.
308 bool IsExclusiveHeld(const Thread* self) const;
310 // Assert the current thread has exclusive access to the ReaderWriterMutex.
311 void AssertExclusiveHeld(const Thread* self) {
312 if (kDebugLocking && (gAborting == 0)) {
313 CHECK(IsExclusiveHeld(self)) << *this;
316 void AssertWriterHeld(const Thread* self) { AssertExclusiveHeld(self); }
318 // Assert the current thread doesn't have exclusive access to the ReaderWriterMutex.
319 void AssertNotExclusiveHeld(const Thread* self) {
320 if (kDebugLocking && (gAborting == 0)) {
321 CHECK(!IsExclusiveHeld(self)) << *this;
324 void AssertNotWriterHeld(const Thread* self) { AssertNotExclusiveHeld(self); }
326 // Is the current thread a shared holder of the ReaderWriterMutex.
327 bool IsSharedHeld(const Thread* self) const;
329 // Assert the current thread has shared access to the ReaderWriterMutex.
330 void AssertSharedHeld(const Thread* self) {
331 if (kDebugLocking && (gAborting == 0)) {
332 // TODO: we can only assert this well when self != NULL.
333 CHECK(IsSharedHeld(self) || self == NULL) << *this;
336 void AssertReaderHeld(const Thread* self) { AssertSharedHeld(self); }
338 // Assert the current thread doesn't hold this ReaderWriterMutex either in shared or exclusive
340 void AssertNotHeld(const Thread* self) {
341 if (kDebugLocking && (gAborting == 0)) {
342 CHECK(!IsSharedHeld(self)) << *this;
346 // Id associated with exclusive owner.
347 uint64_t GetExclusiveOwnerTid() const;
349 virtual void Dump(std::ostream& os) const;
353 // -1 implies held exclusive, +ve shared held by state_ many owners.
354 volatile int32_t state_;
356 volatile uint64_t exclusive_owner_;
358 volatile int32_t num_pending_readers_;
360 AtomicInteger num_pending_writers_;
362 pthread_rwlock_t rwlock_;
363 volatile uint64_t exclusive_owner_; // Guarded by rwlock_.
365 DISALLOW_COPY_AND_ASSIGN(ReaderWriterMutex);
368 // ConditionVariables allow threads to queue and sleep. Threads may then be resumed individually
369 // (Signal) or all at once (Broadcast).
370 class ConditionVariable {
372 explicit ConditionVariable(const char* name, Mutex& mutex);
373 ~ConditionVariable();
375 void Broadcast(Thread* self);
376 void Signal(Thread* self);
377 // TODO: No thread safety analysis on Wait and TimedWait as they call mutex operations via their
378 // pointer copy, thereby defeating annotalysis.
379 void Wait(Thread* self) NO_THREAD_SAFETY_ANALYSIS;
380 void TimedWait(Thread* self, int64_t ms, int32_t ns) NO_THREAD_SAFETY_ANALYSIS;
381 // Variant of Wait that should be used with caution. Doesn't validate that no mutexes are held
383 // TODO: remove this.
384 void WaitHoldingLocks(Thread* self) NO_THREAD_SAFETY_ANALYSIS;
387 const char* const name_;
388 // The Mutex being used by waiters. It is an error to mix condition variables between different
392 // A counter that is modified by signals and broadcasts. This ensures that when a waiter gives up
393 // their Mutex and another thread takes it and signals, the waiting thread observes that sequence_
394 // changed and doesn't enter the wait. Modified while holding guard_, but is read by futex wait
395 // without guard_ held.
396 AtomicInteger sequence_;
397 // Number of threads that have come into to wait, not the length of the waiters on the futex as
398 // waiters may have been requeued onto guard_. Guarded by guard_.
399 volatile int32_t num_waiters_;
401 pthread_cond_t cond_;
403 DISALLOW_COPY_AND_ASSIGN(ConditionVariable);
406 // Scoped locker/unlocker for a regular Mutex that acquires mu upon construction and releases it
408 class SCOPED_LOCKABLE MutexLock {
410 explicit MutexLock(Thread* self, Mutex& mu) EXCLUSIVE_LOCK_FUNCTION(mu) : self_(self), mu_(mu) {
411 mu_.ExclusiveLock(self_);
414 ~MutexLock() UNLOCK_FUNCTION() {
415 mu_.ExclusiveUnlock(self_);
421 DISALLOW_COPY_AND_ASSIGN(MutexLock);
423 // Catch bug where variable name is omitted. "MutexLock (lock);" instead of "MutexLock mu(lock)".
424 #define MutexLock(x) COMPILE_ASSERT(0, mutex_lock_declaration_missing_variable_name)
426 // Scoped locker/unlocker for a ReaderWriterMutex that acquires read access to mu upon
427 // construction and releases it upon destruction.
428 class SCOPED_LOCKABLE ReaderMutexLock {
430 explicit ReaderMutexLock(Thread* self, ReaderWriterMutex& mu) EXCLUSIVE_LOCK_FUNCTION(mu) :
431 self_(self), mu_(mu) {
432 mu_.SharedLock(self_);
435 ~ReaderMutexLock() UNLOCK_FUNCTION() {
436 mu_.SharedUnlock(self_);
441 ReaderWriterMutex& mu_;
442 DISALLOW_COPY_AND_ASSIGN(ReaderMutexLock);
444 // Catch bug where variable name is omitted. "ReaderMutexLock (lock);" instead of
445 // "ReaderMutexLock mu(lock)".
446 #define ReaderMutexLock(x) COMPILE_ASSERT(0, reader_mutex_lock_declaration_missing_variable_name)
448 // Scoped locker/unlocker for a ReaderWriterMutex that acquires write access to mu upon
449 // construction and releases it upon destruction.
450 class SCOPED_LOCKABLE WriterMutexLock {
452 explicit WriterMutexLock(Thread* self, ReaderWriterMutex& mu) EXCLUSIVE_LOCK_FUNCTION(mu) :
453 self_(self), mu_(mu) {
454 mu_.ExclusiveLock(self_);
457 ~WriterMutexLock() UNLOCK_FUNCTION() {
458 mu_.ExclusiveUnlock(self_);
463 ReaderWriterMutex& mu_;
464 DISALLOW_COPY_AND_ASSIGN(WriterMutexLock);
466 // Catch bug where variable name is omitted. "WriterMutexLock (lock);" instead of
467 // "WriterMutexLock mu(lock)".
468 #define WriterMutexLock(x) COMPILE_ASSERT(0, writer_mutex_lock_declaration_missing_variable_name)
470 // Global mutexes corresponding to the levels above.
475 // The mutator_lock_ is used to allow mutators to execute in a shared (reader) mode or to block
476 // mutators by having an exclusive (writer) owner. In normal execution each mutator thread holds
477 // a share on the mutator_lock_. The garbage collector may also execute with shared access but
478 // at times requires exclusive access to the heap (not to be confused with the heap meta-data
479 // guarded by the heap_lock_ below). When the garbage collector requires exclusive access it asks
480 // the mutators to suspend themselves which also involves usage of the thread_suspend_count_lock_
481 // to cover weaknesses in using ReaderWriterMutexes with ConditionVariables. We use a condition
482 // variable to wait upon in the suspension logic as releasing and then re-acquiring a share on
483 // the mutator lock doesn't necessarily allow the exclusive user (e.g the garbage collector)
484 // chance to acquire the lock.
486 // Thread suspension:
487 // Shared users | Exclusive user
488 // (holding mutator lock and in kRunnable state) | .. running ..
489 // .. running .. | Request thread suspension by:
490 // .. running .. | - acquiring thread_suspend_count_lock_
491 // .. running .. | - incrementing Thread::suspend_count_ on
492 // .. running .. | all mutator threads
493 // .. running .. | - releasing thread_suspend_count_lock_
494 // .. running .. | Block trying to acquire exclusive mutator lock
495 // Poll Thread::suspend_count_ and enter full | .. blocked ..
496 // suspend code. | .. blocked ..
497 // Change state to kSuspended | .. blocked ..
498 // x: Release share on mutator_lock_ | Carry out exclusive access
499 // Acquire thread_suspend_count_lock_ | .. exclusive ..
500 // while Thread::suspend_count_ > 0 | .. exclusive ..
501 // - wait on Thread::resume_cond_ | .. exclusive ..
502 // (releases thread_suspend_count_lock_) | .. exclusive ..
503 // .. waiting .. | Release mutator_lock_
504 // .. waiting .. | Request thread resumption by:
505 // .. waiting .. | - acquiring thread_suspend_count_lock_
506 // .. waiting .. | - decrementing Thread::suspend_count_ on
507 // .. waiting .. | all mutator threads
508 // .. waiting .. | - notifying on Thread::resume_cond_
509 // - re-acquire thread_suspend_count_lock_ | - releasing thread_suspend_count_lock_
510 // Release thread_suspend_count_lock_ | .. running ..
511 // Acquire share on mutator_lock_ | .. running ..
512 // - This could block but the thread still | .. running ..
513 // has a state of kSuspended and so this | .. running ..
514 // isn't an issue. | .. running ..
515 // Acquire thread_suspend_count_lock_ | .. running ..
516 // - we poll here as we're transitioning into | .. running ..
517 // kRunnable and an individual thread suspend | .. running ..
518 // request (e.g for debugging) won't try | .. running ..
519 // to acquire the mutator lock (which would | .. running ..
520 // block as we hold the mutator lock). This | .. running ..
521 // poll ensures that if the suspender thought | .. running ..
522 // we were suspended by incrementing our | .. running ..
523 // Thread::suspend_count_ and then reading | .. running ..
524 // our state we go back to waiting on | .. running ..
525 // Thread::resume_cond_. | .. running ..
526 // can_go_runnable = Thread::suspend_count_ == 0 | .. running ..
527 // Release thread_suspend_count_lock_ | .. running ..
528 // if can_go_runnable | .. running ..
529 // Change state to kRunnable | .. running ..
530 // else | .. running ..
531 // Goto x | .. running ..
532 // .. running .. | .. running ..
533 static ReaderWriterMutex* mutator_lock_;
535 // Allow reader-writer mutual exclusion on the mark and live bitmaps of the heap.
536 static ReaderWriterMutex* heap_bitmap_lock_ ACQUIRED_AFTER(mutator_lock_);
538 // Guards shutdown of the runtime.
539 static Mutex* runtime_shutdown_lock_ ACQUIRED_AFTER(heap_bitmap_lock_);
541 // Guards background profiler global state.
542 static Mutex* profiler_lock_ ACQUIRED_AFTER(runtime_shutdown_lock_);
544 // Guards trace (ie traceview) requests.
545 static Mutex* trace_lock_ ACQUIRED_AFTER(profiler_lock_);
547 // The thread_list_lock_ guards ThreadList::list_. It is also commonly held to stop threads
548 // attaching and detaching.
549 static Mutex* thread_list_lock_ ACQUIRED_AFTER(trace_lock_);
551 // Guards breakpoints.
552 static Mutex* breakpoint_lock_ ACQUIRED_AFTER(thread_list_lock_);
554 // Guards lists of classes within the class linker.
555 static ReaderWriterMutex* classlinker_classes_lock_ ACQUIRED_AFTER(breakpoint_lock_);
557 // When declaring any Mutex add DEFAULT_MUTEX_ACQUIRED_AFTER to use annotalysis to check the code
558 // doesn't try to hold a higher level Mutex.
559 #define DEFAULT_MUTEX_ACQUIRED_AFTER ACQUIRED_AFTER(Locks::classlinker_classes_lock_)
561 static Mutex* allocated_monitor_ids_lock_ ACQUIRED_AFTER(classlinker_classes_lock_);
563 // Guard the allocation/deallocation of thread ids.
564 static Mutex* allocated_thread_ids_lock_ ACQUIRED_AFTER(allocated_monitor_ids_lock_);
566 // Guards modification of the LDT on x86.
567 static Mutex* modify_ldt_lock_ ACQUIRED_AFTER(allocated_thread_ids_lock_);
569 // Guards intern table.
570 static Mutex* intern_table_lock_ ACQUIRED_AFTER(modify_ldt_lock_);
572 // Have an exclusive aborting thread.
573 static Mutex* abort_lock_ ACQUIRED_AFTER(classlinker_classes_lock_);
575 // Allow mutual exclusion when manipulating Thread::suspend_count_.
576 // TODO: Does the trade-off of a per-thread lock make sense?
577 static Mutex* thread_suspend_count_lock_ ACQUIRED_AFTER(abort_lock_);
579 // One unexpected signal at a time lock.
580 static Mutex* unexpected_signal_lock_ ACQUIRED_AFTER(thread_suspend_count_lock_);
582 // Guards the maps in mem_map.
583 static Mutex* mem_maps_lock_ ACQUIRED_AFTER(unexpected_signal_lock_);
585 // Have an exclusive logging thread.
586 static Mutex* logging_lock_ ACQUIRED_AFTER(unexpected_signal_lock_);
591 #endif // ART_RUNTIME_BASE_MUTEX_H_