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