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