blob: 85d75ab099af0c7141ecde271f234920681ce0f1 [file] [log] [blame]
Elliott Hughes8daa0922011-09-11 13:46:25 -07001/*
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_SRC_MUTEX_H_
18#define ART_SRC_MUTEX_H_
19
20#include <pthread.h>
Brian Carlstromcd74c4b2012-01-23 13:21:00 -080021#include <stdint.h>
Elliott Hughesffb465f2012-03-01 18:46:05 -080022
23#include <iosfwd>
Elliott Hughes8daa0922011-09-11 13:46:25 -070024#include <string>
25
Ian Rogers00f7d0e2012-07-19 15:28:27 -070026#include "globals.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070027#include "logging.h"
28#include "macros.h"
29
Ian Rogers66aee5c2012-08-15 17:17:47 -070030// Currently Darwin doesn't support locks with timeouts.
31#if !defined(__APPLE__)
32#define HAVE_TIMED_RWLOCK 1
33#else
34#define HAVE_TIMED_RWLOCK 0
35#endif
36
Elliott Hughes8daa0922011-09-11 13:46:25 -070037namespace art {
38
Ian Rogers25fd14b2012-09-05 10:56:38 -070039const bool kDebugLocking = kIsDebugBuild;
40
Ian Rogers00f7d0e2012-07-19 15:28:27 -070041class LOCKABLE Mutex;
42class LOCKABLE ReaderWriterMutex;
Elliott Hughesffb465f2012-03-01 18:46:05 -080043
Ian Rogers00f7d0e2012-07-19 15:28:27 -070044// MutexLevel is used to impose a lock hierarchy [1] where acquisition of a Mutex at a higher or
45// equal level to a lock a thread holds is invalid. The lock hierarchy achieves a cycle free
46// partial ordering and thereby cause deadlock situations to fail checks.
47//
48// [1] http://www.drdobbs.com/parallel/use-lock-hierarchies-to-avoid-deadlock/204801163
49enum MutexLevel {
50 kLoggingLock = 0,
51 kUnexpectedSignalLock = 1,
52 kThreadSuspendCountLock = 2,
53 kAbortLock = 3,
54 kDefaultMutexLevel = 4,
Ian Rogers15bf2d32012-08-28 17:33:04 -070055 kJdwpSerialLock = 5,
56 kAllocSpaceLock = 6,
57 kLoadLibraryLock = 7,
58 kClassLinkerClassesLock = 8,
59 kThreadListLock = 9,
60 kHeapBitmapLock = 10,
61 kMonitorLock = 11,
62 kMutatorLock = 12,
63 kZygoteCreationLock = 13,
Ian Rogers00f7d0e2012-07-19 15:28:27 -070064 kMaxMutexLevel = kMutatorLock,
65};
66std::ostream& operator<<(std::ostream& os, const MutexLevel& rhs);
67
68// Global mutexes corresponding to the levels above.
Ian Rogersb726dcb2012-09-05 08:57:23 -070069class Locks {
Elliott Hughes8daa0922011-09-11 13:46:25 -070070 public:
Ian Rogers00f7d0e2012-07-19 15:28:27 -070071 static void Init();
72
73 // The mutator_lock_ is used to allow mutators to execute in a shared (reader) mode or to block
74 // mutators by having an exclusive (writer) owner. In normal execution each mutator thread holds
75 // a share on the mutator_lock_. The garbage collector may also execute with shared access but
76 // at times requires exclusive access to the heap (not to be confused with the heap meta-data
77 // guarded by the heap_lock_ below). When the garbage collector requires exclusive access it asks
78 // the mutators to suspend themselves which also involves usage of the thread_suspend_count_lock_
79 // to cover weaknesses in using ReaderWriterMutexes with ConditionVariables. We use a condition
80 // variable to wait upon in the suspension logic as releasing and then re-acquiring a share on
81 // the mutator lock doesn't necessarily allow the exclusive user (e.g the garbage collector)
82 // chance to acquire the lock.
83 //
84 // Thread suspension:
85 // Shared users | Exclusive user
86 // (holding mutator lock and in kRunnable state) | .. running ..
87 // .. running .. | Request thread suspension by:
88 // .. running .. | - acquiring thread_suspend_count_lock_
89 // .. running .. | - incrementing Thread::suspend_count_ on
90 // .. running .. | all mutator threads
91 // .. running .. | - releasing thread_suspend_count_lock_
92 // .. running .. | Block trying to acquire exclusive mutator lock
93 // Poll Thread::suspend_count_ and enter full | .. blocked ..
94 // suspend code. | .. blocked ..
95 // Change state to kSuspended | .. blocked ..
96 // x: Release share on mutator_lock_ | Carry out exclusive access
97 // Acquire thread_suspend_count_lock_ | .. exclusive ..
98 // while Thread::suspend_count_ > 0 | .. exclusive ..
99 // - wait on Thread::resume_cond_ | .. exclusive ..
100 // (releases thread_suspend_count_lock_) | .. exclusive ..
101 // .. waiting .. | Release mutator_lock_
102 // .. waiting .. | Request thread resumption by:
103 // .. waiting .. | - acquiring thread_suspend_count_lock_
104 // .. waiting .. | - decrementing Thread::suspend_count_ on
105 // .. waiting .. | all mutator threads
106 // .. waiting .. | - notifying on Thread::resume_cond_
107 // - re-acquire thread_suspend_count_lock_ | - releasing thread_suspend_count_lock_
108 // Release thread_suspend_count_lock_ | .. running ..
109 // Acquire share on mutator_lock_ | .. running ..
110 // - This could block but the thread still | .. running ..
111 // has a state of kSuspended and so this | .. running ..
112 // isn't an issue. | .. running ..
113 // Acquire thread_suspend_count_lock_ | .. running ..
114 // - we poll here as we're transitioning into | .. running ..
115 // kRunnable and an individual thread suspend | .. running ..
116 // request (e.g for debugging) won't try | .. running ..
117 // to acquire the mutator lock (which would | .. running ..
118 // block as we hold the mutator lock). This | .. running ..
119 // poll ensures that if the suspender thought | .. running ..
120 // we were suspended by incrementing our | .. running ..
121 // Thread::suspend_count_ and then reading | .. running ..
122 // our state we go back to waiting on | .. running ..
123 // Thread::resume_cond_. | .. running ..
124 // can_go_runnable = Thread::suspend_count_ == 0 | .. running ..
125 // Release thread_suspend_count_lock_ | .. running ..
126 // if can_go_runnable | .. running ..
127 // Change state to kRunnable | .. running ..
128 // else | .. running ..
129 // Goto x | .. running ..
130 // .. running .. | .. running ..
131 static ReaderWriterMutex* mutator_lock_;
132
133 // Allow reader-writer mutual exclusion on the mark and live bitmaps of the heap.
134 static ReaderWriterMutex* heap_bitmap_lock_ ACQUIRED_AFTER(mutator_lock_);
135
136 // The thread_list_lock_ guards ThreadList::list_. It is also commonly held to stop threads
137 // attaching and detaching.
138 static Mutex* thread_list_lock_ ACQUIRED_AFTER(heap_bitmap_lock_);
139
140 // Guards lists of classes within the class linker.
141 static Mutex* classlinker_classes_lock_ ACQUIRED_AFTER(thread_list_lock_);
142
143 // When declaring any Mutex add DEFAULT_MUTEX_ACQUIRED_AFTER to use annotalysis to check the code
144 // doesn't try to hold a higher level Mutex.
145 #define DEFAULT_MUTEX_ACQUIRED_AFTER ACQUIRED_AFTER(classlinker_classes_lock_)
146
147 // Have an exclusive aborting thread.
148 static Mutex* abort_lock_ ACQUIRED_AFTER(classlinker_classes_lock_);
149
150 // Allow mutual exclusion when manipulating Thread::suspend_count_.
151 // TODO: Does the trade-off of a per-thread lock make sense?
152 static Mutex* thread_suspend_count_lock_ ACQUIRED_AFTER(abort_lock_);
153
154 // One unexpected signal at a time lock.
155 static Mutex* unexpected_signal_lock_ ACQUIRED_AFTER(thread_suspend_count_lock_);
156
157 // Have an exclusive logging thread.
158 static Mutex* logging_lock_ ACQUIRED_AFTER(unexpected_signal_lock_);
159};
160
161// Base class for all Mutex implementations
162class BaseMutex {
163 public:
164 const std::string& GetName() const {
165 return name_;
166 }
167
168 virtual bool IsMutex() const { return false; }
169 virtual bool IsReaderWriterMutex() const { return false; }
170
171 protected:
172 friend class ConditionVariable;
173
174 BaseMutex(const char* name, MutexLevel level);
175 virtual ~BaseMutex() {}
176 void RegisterAsLockedWithCurrentThread();
177 void RegisterAsUnlockedWithCurrentThread();
178 void CheckSafeToWait();
179
180 const MutexLevel level_; // Support for lock hierarchy.
181 const std::string name_;
182};
183
184// A Mutex is used to achieve mutual exclusion between threads. A Mutex can be used to gain
185// exclusive access to what it guards. A Mutex can be in one of two states:
186// - Free - not owned by any thread,
187// - Exclusive - owned by a single thread.
188//
189// The effect of locking and unlocking operations on the state is:
190// State | ExclusiveLock | ExclusiveUnlock
191// -------------------------------------------
192// Free | Exclusive | error
193// Exclusive | Block* | Free
194// * Mutex is not reentrant and so an attempt to ExclusiveLock on the same thread will result in
195// an error. Being non-reentrant simplifies Waiting on ConditionVariables.
196class LOCKABLE Mutex : public BaseMutex {
197 public:
198 explicit Mutex(const char* name, MutexLevel level = kDefaultMutexLevel, bool recursive = false);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700199 ~Mutex();
200
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700201 virtual bool IsMutex() const { return true; }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700202
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700203 // Block until mutex is free then acquire exclusive access.
204 void ExclusiveLock() EXCLUSIVE_LOCK_FUNCTION();
205 void Lock() EXCLUSIVE_LOCK_FUNCTION() { ExclusiveLock(); }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700206
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700207 // Returns true if acquires exclusive access, false otherwise.
208 bool ExclusiveTryLock() EXCLUSIVE_TRYLOCK_FUNCTION(true);
209 bool TryLock() EXCLUSIVE_TRYLOCK_FUNCTION(true) { return ExclusiveTryLock(); }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700210
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700211 // Release exclusive access.
212 void ExclusiveUnlock() UNLOCK_FUNCTION();
213 void Unlock() UNLOCK_FUNCTION() { ExclusiveUnlock(); }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700214
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700215 // Is the current thread the exclusive holder of the Mutex.
216 bool IsExclusiveHeld() const;
217
218 // Assert that the Mutex is exclusively held by the current thread.
219 void AssertExclusiveHeld() {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700220 if (kDebugLocking) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700221 CHECK(IsExclusiveHeld());
222 }
223 }
224 void AssertHeld() { AssertExclusiveHeld(); }
225
226 // Assert that the Mutex is not held by the current thread.
227 void AssertNotHeldExclusive() {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700228 if (kDebugLocking) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700229 CHECK(!IsExclusiveHeld());
230 }
231 }
232 void AssertNotHeld() { AssertNotHeldExclusive(); }
233
234 // Id associated with exclusive owner.
235 uint64_t GetExclusiveOwnerTid() const;
236
237 // Returns how many times this Mutex has been locked, it is better to use AssertHeld/NotHeld.
238 unsigned int GetDepth() const {
239 return recursion_count_;
240 }
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700241
242 private:
Elliott Hughes8daa0922011-09-11 13:46:25 -0700243 pthread_mutex_t mutex_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700244 const bool recursive_; // Can the lock be recursively held?
245 unsigned int recursion_count_;
Elliott Hughesf1498432012-03-28 19:34:27 -0700246 friend class ConditionVariable;
Elliott Hughes3efb8412012-03-16 16:09:38 -0700247 friend class MutexTester;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700248 DISALLOW_COPY_AND_ASSIGN(Mutex);
249};
250
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700251// A ReaderWriterMutex is used to achieve mutual exclusion between threads, similar to a Mutex.
252// Unlike a Mutex a ReaderWriterMutex can be used to gain exclusive (writer) or shared (reader)
253// access to what it guards. A flaw in relation to a Mutex is that it cannot be used with a
254// condition variable. A ReaderWriterMutex can be in one of three states:
255// - Free - not owned by any thread,
256// - Exclusive - owned by a single thread,
257// - Shared(n) - shared amongst n threads.
258//
259// The effect of locking and unlocking operations on the state is:
260//
261// State | ExclusiveLock | ExclusiveUnlock | SharedLock | SharedUnlock
262// ----------------------------------------------------------------------------
263// Free | Exclusive | error | SharedLock(1) | error
264// Exclusive | Block | Free | Block | error
265// Shared(n) | Block | error | SharedLock(n+1)* | Shared(n-1) or Free
266// * for large values of n the SharedLock may block.
267class LOCKABLE ReaderWriterMutex : public BaseMutex {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700268 public:
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700269 explicit ReaderWriterMutex(const char* name, MutexLevel level = kDefaultMutexLevel);
270 ~ReaderWriterMutex();
271
272 virtual bool IsReaderWriterMutex() const { return true; }
273
274 // Block until ReaderWriterMutex is free then acquire exclusive access.
275 void ExclusiveLock() EXCLUSIVE_LOCK_FUNCTION();
276 void WriterLock() EXCLUSIVE_LOCK_FUNCTION() { ExclusiveLock(); }
277
278 // Release exclusive access.
279 void ExclusiveUnlock() UNLOCK_FUNCTION();
280 void WriterUnlock() UNLOCK_FUNCTION() { ExclusiveUnlock(); }
281
282 // Block until ReaderWriterMutex is free and acquire exclusive access. Returns true on success
283 // or false if timeout is reached.
Ian Rogers66aee5c2012-08-15 17:17:47 -0700284#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700285 bool ExclusiveLockWithTimeout(const timespec& abs_timeout) EXCLUSIVE_TRYLOCK_FUNCTION(true);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700286#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700287
288 // Block until ReaderWriterMutex is shared or free then acquire a share on the access.
289 void SharedLock() SHARED_LOCK_FUNCTION();
290 void ReaderLock() SHARED_LOCK_FUNCTION() { SharedLock(); }
291
292 // Try to acquire share of ReaderWriterMutex.
293 bool SharedTryLock() EXCLUSIVE_TRYLOCK_FUNCTION(true);
294
295 // Release a share of the access.
296 void SharedUnlock() UNLOCK_FUNCTION();
297 void ReaderUnlock() UNLOCK_FUNCTION() { SharedUnlock(); }
298
299 // Is the current thread the exclusive holder of the ReaderWriterMutex.
300 bool IsExclusiveHeld() const;
301
302 // Assert the current thread has exclusive access to the ReaderWriterMutex.
303 void AssertExclusiveHeld() {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700304 if (kDebugLocking) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700305 CHECK(IsExclusiveHeld());
306 }
307 }
308 void AssertWriterHeld() { AssertExclusiveHeld(); }
309
310 // Assert the current thread doesn't have exclusive access to the ReaderWriterMutex.
311 void AssertNotExclusiveHeld() {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700312 if (kDebugLocking) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700313 CHECK(!IsExclusiveHeld());
314 }
315 }
316 void AssertNotWriterHeld() { AssertNotExclusiveHeld(); }
317
318 // Is the current thread a shared holder of the ReaderWriterMutex.
319 bool IsSharedHeld() const;
320
321 // Assert the current thread has shared access to the ReaderWriterMutex.
322 void AssertSharedHeld() {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700323 if (kDebugLocking) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700324 CHECK(IsSharedHeld());
325 }
326 }
327 void AssertReaderHeld() { AssertSharedHeld(); }
328
329 // Assert the current thread doesn't hold this ReaderWriterMutex either in shared or exclusive
330 // mode.
331 void AssertNotHeld() {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700332 if (kDebugLocking) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700333 CHECK(!IsSharedHeld());
334 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700335 }
336
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700337 // Id associated with exclusive owner.
338 uint64_t GetExclusiveOwnerTid() const;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700339 private:
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700340 pthread_rwlock_t rwlock_;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700341
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700342 friend class MutexTester;
343 DISALLOW_COPY_AND_ASSIGN(ReaderWriterMutex);
344};
345
346// ConditionVariables allow threads to queue and sleep. Threads may then be resumed individually
347// (Signal) or all at once (Broadcast).
Elliott Hughes5f791332011-09-15 17:45:30 -0700348class ConditionVariable {
349 public:
Elliott Hughesa51a3dd2011-10-17 15:19:26 -0700350 explicit ConditionVariable(const std::string& name);
Elliott Hughes5f791332011-09-15 17:45:30 -0700351 ~ConditionVariable();
352
353 void Broadcast();
354 void Signal();
355 void Wait(Mutex& mutex);
356 void TimedWait(Mutex& mutex, const timespec& ts);
357
358 private:
359 pthread_cond_t cond_;
360 std::string name_;
361 DISALLOW_COPY_AND_ASSIGN(ConditionVariable);
362};
363
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700364// Scoped locker/unlocker for a regular Mutex that acquires mu upon construction and releases it
365// upon destruction.
366class SCOPED_LOCKABLE MutexLock {
367 public:
368 explicit MutexLock(Mutex& mu) EXCLUSIVE_LOCK_FUNCTION(mu) : mu_(mu) {
369 mu_.ExclusiveLock();
370 }
371
372 ~MutexLock() UNLOCK_FUNCTION() {
373 mu_.ExclusiveUnlock();
374 }
375
376 private:
377 Mutex& mu_;
378 DISALLOW_COPY_AND_ASSIGN(MutexLock);
379};
380// Catch bug where variable name is omitted. "MutexLock (lock);" instead of "MutexLock mu(lock)".
381#define MutexLock(x) COMPILE_ASSERT(0, mutex_lock_declaration_missing_variable_name)
382
383// Scoped locker/unlocker for a ReaderWriterMutex that acquires read access to mu upon
384// construction and releases it upon destruction.
385class SCOPED_LOCKABLE ReaderMutexLock {
386 public:
387 explicit ReaderMutexLock(ReaderWriterMutex& mu) EXCLUSIVE_LOCK_FUNCTION(mu) : mu_(mu) {
388 mu_.SharedLock();
389 }
390
391 ~ReaderMutexLock() UNLOCK_FUNCTION() {
392 mu_.SharedUnlock();
393 }
394
395 private:
396 ReaderWriterMutex& mu_;
397 DISALLOW_COPY_AND_ASSIGN(ReaderMutexLock);
398};
399// Catch bug where variable name is omitted. "ReaderMutexLock (lock);" instead of
400// "ReaderMutexLock mu(lock)".
401#define ReaderMutexLock(x) COMPILE_ASSERT(0, reader_mutex_lock_declaration_missing_variable_name)
402
403// Scoped locker/unlocker for a ReaderWriterMutex that acquires write access to mu upon
404// construction and releases it upon destruction.
405class SCOPED_LOCKABLE WriterMutexLock {
406 public:
407 explicit WriterMutexLock(ReaderWriterMutex& mu) EXCLUSIVE_LOCK_FUNCTION(mu) : mu_(mu) {
408 mu_.ExclusiveLock();
409 }
410
411 ~WriterMutexLock() UNLOCK_FUNCTION() {
412 mu_.ExclusiveUnlock();
413 }
414
415 private:
416 ReaderWriterMutex& mu_;
417 DISALLOW_COPY_AND_ASSIGN(WriterMutexLock);
418};
419// Catch bug where variable name is omitted. "WriterMutexLock (lock);" instead of
420// "WriterMutexLock mu(lock)".
421#define WriterMutexLock(x) COMPILE_ASSERT(0, writer_mutex_lock_declaration_missing_variable_name)
422
423// Scoped unlocker/locker for a ReaderWriterMutex that releases read access to mu upon
424// construction and acquires it again upon destruction.
425class ReaderMutexUnlock {
426 public:
427 explicit ReaderMutexUnlock(ReaderWriterMutex& mu) UNLOCK_FUNCTION(mu) : mu_(mu) {
428 mu_.SharedUnlock();
429 }
430
431 ~ReaderMutexUnlock() SHARED_LOCK_FUNCTION(mu_) {
432 mu_.SharedLock();
433 }
434
435 private:
436 ReaderWriterMutex& mu_;
437 DISALLOW_COPY_AND_ASSIGN(ReaderMutexUnlock);
438};
439// Catch bug where variable name is omitted. "ReaderMutexUnlock (lock);" instead of
440// "ReaderMutexUnlock mu(lock)".
441#define ReaderMutexUnlock(x) \
442 COMPILE_ASSERT(0, reader_mutex_unlock_declaration_missing_variable_name)
443
Elliott Hughes8daa0922011-09-11 13:46:25 -0700444} // namespace art
445
446#endif // ART_SRC_MUTEX_H_