blob: dc33fbea97e81e8a41136662bfa390cae6baff83 [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#include "mutex.h"
18
19#include <errno.h>
20
Elliott Hughes8daa0922011-09-11 13:46:25 -070021#include "logging.h"
Elliott Hughes6b355752012-01-13 16:49:08 -080022#include "runtime.h"
Elliott Hughesffb465f2012-03-01 18:46:05 -080023#include "thread.h"
24#include "utils.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070025
Elliott Hughesb08e8a32012-04-02 10:51:41 -070026#if defined(__APPLE__)
27#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
28#endif
29
Elliott Hughes8d768a92011-09-14 16:35:25 -070030#define CHECK_MUTEX_CALL(call, args) CHECK_PTHREAD_CALL(call, args, name_)
31
Elliott Hughesf8349362012-06-18 15:00:06 -070032extern int pthread_mutex_lock(pthread_mutex_t* mutex) EXCLUSIVE_LOCK_FUNCTION(mutex);
33extern int pthread_mutex_unlock(pthread_mutex_t* mutex) UNLOCK_FUNCTION(1);
34extern int pthread_mutex_trylock(pthread_mutex_t* mutex) EXCLUSIVE_TRYLOCK_FUNCTION(0, mutex);
35
Elliott Hughes8daa0922011-09-11 13:46:25 -070036namespace art {
37
Elliott Hughesf1498432012-03-28 19:34:27 -070038// This works on Mac OS 10.7, but hasn't been tested on older releases.
39struct __attribute__((__may_alias__)) darwin_pthread_mutex_t {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070040 uint32_t padding0[4];
41 intptr_t padding1;
42 uintptr_t owner_tid;
43 // ...other stuff we don't care about.
44};
45
46struct __attribute__((__may_alias__)) darwin_pthread_rwlock_t {
47 int32_t padding0[4];
48 intptr_t padding1[2];
49 uintptr_t rw_owner_tid;
Elliott Hughesf1498432012-03-28 19:34:27 -070050 // ...other stuff we don't care about.
51};
52
53struct __attribute__((__may_alias__)) glibc_pthread_mutex_t {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070054 int32_t padding0[2];
Elliott Hughesf1498432012-03-28 19:34:27 -070055 int owner;
56 // ...other stuff we don't care about.
57};
58
Ian Rogers00f7d0e2012-07-19 15:28:27 -070059struct __attribute__((__may_alias__)) glibc_pthread_rwlock_t {
60#ifdef __LP64__
61 int32_t padding0[6];
62#else
63 int32_t padding0[7];
64#endif
65 int writer;
66 // ...other stuff we don't care about.
67};
68
69ReaderWriterMutex* GlobalSynchronization::mutator_lock_ = NULL;
70Mutex* GlobalSynchronization::thread_list_lock_ = NULL;
71Mutex* GlobalSynchronization::classlinker_classes_lock_ = NULL;
72ReaderWriterMutex* GlobalSynchronization::heap_bitmap_lock_ = NULL;
73Mutex* GlobalSynchronization::abort_lock_ = NULL;
74Mutex* GlobalSynchronization::logging_lock_ = NULL;
75Mutex* GlobalSynchronization::unexpected_signal_lock_ = NULL;
76Mutex* GlobalSynchronization::thread_suspend_count_lock_ = NULL;
77
78void GlobalSynchronization::Init() {
79 if (logging_lock_ != NULL) {
80 // Already initialized.
81 DCHECK(mutator_lock_ != NULL);
82 DCHECK(thread_list_lock_ != NULL);
83 DCHECK(classlinker_classes_lock_ != NULL);
84 DCHECK(heap_bitmap_lock_ != NULL);
85 DCHECK(abort_lock_ != NULL);
86 DCHECK(logging_lock_ != NULL);
87 DCHECK(unexpected_signal_lock_ != NULL);
88 DCHECK(thread_suspend_count_lock_ != NULL);
89 } else {
90 logging_lock_ = new Mutex("logging lock", kLoggingLock, true);
91 abort_lock_ = new Mutex("abort lock", kAbortLock, true);
92 DCHECK(mutator_lock_ == NULL);
93 mutator_lock_ = new ReaderWriterMutex("mutator lock", kMutatorLock);
94 DCHECK(thread_list_lock_ == NULL);
95 thread_list_lock_ = new Mutex("thread list lock", kThreadListLock);
96 DCHECK(classlinker_classes_lock_ == NULL);
97 classlinker_classes_lock_ = new Mutex("ClassLinker classes lock", kClassLinkerClassesLock);
98 DCHECK(heap_bitmap_lock_ == NULL);
99 heap_bitmap_lock_ = new ReaderWriterMutex("heap bitmap lock", kHeapBitmapLock);
100 DCHECK(unexpected_signal_lock_ == NULL);
101 unexpected_signal_lock_ = new Mutex("unexpected signal lock", kUnexpectedSignalLock, true);
102 DCHECK(thread_suspend_count_lock_ == NULL);
103 thread_suspend_count_lock_ = new Mutex("thread suspend count lock", kThreadSuspendCountLock);
Elliott Hughes67d92002012-03-26 15:08:51 -0700104 }
Elliott Hughesa4060e52012-03-02 16:51:35 -0800105}
106
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700107BaseMutex::BaseMutex(const char* name, MutexLevel level) : level_(level), name_(name) {}
108
109static void CheckUnattachedThread(MutexLevel level) {
110 // The check below enumerates the cases where we expect not to be able to sanity check locks
111 // on a thread. TODO: tighten this check.
112 Runtime* runtime = Runtime::Current();
113 CHECK(runtime == NULL || !runtime->IsStarted() || runtime->IsShuttingDown() ||
114 level == kDefaultMutexLevel || level == kThreadListLock ||
115 level == kLoggingLock || level == kAbortLock);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800116}
117
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700118void BaseMutex::RegisterAsLockedWithCurrentThread() {
119 Thread* self = Thread::Current();
120 if (self == NULL) {
121 CheckUnattachedThread(level_);
122 return;
123 }
124 // Check if a bad Mutex of this level or lower is held.
125 bool bad_mutexes_held = false;
126 for (int i = level_; i >= 0; --i) {
127 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<MutexLevel>(i));
128 if (UNLIKELY(held_mutex != NULL)) {
129 LOG(ERROR) << "Lock level violation: holding \"" << held_mutex->name_ << "\" (level " << i
130 << ") while locking \"" << name_ << "\" (level " << static_cast<int>(level_) << ")";
131 if (i > kAbortLock) {
132 // Only abort in the check below if this is more than abort level lock.
133 bad_mutexes_held = true;
134 }
135 }
136 }
137 CHECK(!bad_mutexes_held);
138 // Don't record monitors as they are outside the scope of analysis. They may be inspected off of
139 // the monitor list.
140 if (level_ != kMonitorLock) {
141 self->SetHeldMutex(level_, this);
142 }
143}
144
145void BaseMutex::RegisterAsUnlockedWithCurrentThread() {
146 Thread* self = Thread::Current();
147 if (self == NULL) {
148 CheckUnattachedThread(level_);
149 return;
150 }
151 if (level_ != kMonitorLock) {
152 CHECK(self->GetHeldMutex(level_) == this) << "Unlocking on unacquired mutex: " << name_;
153 self->SetHeldMutex(level_, NULL);
154 }
155}
156
157void BaseMutex::CheckSafeToWait() {
158 Thread* self = Thread::Current();
159 if (self == NULL) {
160 CheckUnattachedThread(level_);
161 return;
162 }
163 CHECK(self->GetHeldMutex(level_) == this) << "Waiting on unacquired mutex: " << name_;
164 bool bad_mutexes_held = false;
165 for (int i = kMaxMutexLevel; i >= 0; --i) {
166 if (i != level_) {
167 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<MutexLevel>(i));
168 if (held_mutex != NULL) {
169 LOG(ERROR) << "Holding " << held_mutex->name_ << " (level " << i
170 << ") while performing wait on: "
171 << name_ << " (level " << static_cast<int>(level_) << ")";
172 bad_mutexes_held = true;
173 }
174 }
175 }
176 CHECK(!bad_mutexes_held);
177}
178
179Mutex::Mutex(const char* name, MutexLevel level, bool recursive)
180 : BaseMutex(name, level), recursive_(recursive), recursion_count_(0) {
181#if defined(__BIONIC__)
182 // Use recursive mutexes as Bionic's non-recursive mutexes don't have TIDs to check lock
183 // ownership of.
Elliott Hughesbbd9d832011-11-07 14:40:00 -0800184 pthread_mutexattr_t attributes;
185 CHECK_MUTEX_CALL(pthread_mutexattr_init, (&attributes));
186 CHECK_MUTEX_CALL(pthread_mutexattr_settype, (&attributes, PTHREAD_MUTEX_RECURSIVE));
187 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, &attributes));
188 CHECK_MUTEX_CALL(pthread_mutexattr_destroy, (&attributes));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700189#else
190 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, NULL));
191#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700192}
193
194Mutex::~Mutex() {
Elliott Hughese62934d2012-04-09 11:24:29 -0700195 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
196 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800197 int rc = pthread_mutex_destroy(&mutex_);
198 if (rc != 0) {
199 errno = rc;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800200 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Elliott Hughes6b355752012-01-13 16:49:08 -0800201 bool shutting_down = Runtime::Current()->IsShuttingDown();
202 PLOG(shutting_down ? WARNING : FATAL) << "pthread_mutex_destroy failed for " << name_;
203 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700204}
205
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700206void Mutex::ExclusiveLock() {
207 bool is_held = IsExclusiveHeld();
208 CHECK(recursive_ || !is_held)
209 << "Error attempt to recursively lock non-recursive lock \"" << name_ << "\"";
210 if (!is_held) {
211 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
212 RegisterAsLockedWithCurrentThread();
213 }
214 recursion_count_++;
215 DCHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
216 << name_ << " " << recursion_count_;
Ian Rogers105245c2012-01-27 11:42:43 -0800217 AssertHeld();
Elliott Hughes8daa0922011-09-11 13:46:25 -0700218}
219
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700220bool Mutex::ExclusiveTryLock() {
221 bool is_held = IsExclusiveHeld();
222 CHECK(recursive_ || !is_held)
223 << "Error attempt to recursively lock non-recursive lock \"" << name_ << "\"";
224 if (!is_held) {
225 int result = pthread_mutex_trylock(&mutex_);
226 if (result == EBUSY) {
227 return false;
228 }
229 if (result != 0) {
230 errno = result;
231 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
232 }
233 RegisterAsLockedWithCurrentThread();
Elliott Hughes8daa0922011-09-11 13:46:25 -0700234 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700235 recursion_count_++;
Ian Rogers105245c2012-01-27 11:42:43 -0800236 AssertHeld();
Elliott Hughes8daa0922011-09-11 13:46:25 -0700237 return true;
238}
239
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700240void Mutex::ExclusiveUnlock() {
Ian Rogers105245c2012-01-27 11:42:43 -0800241 AssertHeld();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700242 recursion_count_--;
243 if (!recursive_ || recursion_count_ == 0) {
244 DCHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
245 << name_ << " " << recursion_count_;
246 RegisterAsUnlockedWithCurrentThread();
247 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
248 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700249}
250
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700251bool Mutex::IsExclusiveHeld() const {
252 Thread* self = Thread::Current();
253 bool result;
254 if (self == NULL || level_ == kMonitorLock) { // Handle unattached threads and monitors.
255 result = (GetExclusiveOwnerTid() == static_cast<uint64_t>(GetTid()));
256 } else {
257 result = (self->GetHeldMutex(level_) == this);
258 // Sanity debug check that if we think it is locked, so does the pthread.
259 DCHECK(result == (GetExclusiveOwnerTid() == static_cast<uint64_t>(GetTid())));
260 }
261 return result;
Elliott Hughesf1498432012-03-28 19:34:27 -0700262}
263
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700264uint64_t Mutex::GetExclusiveOwnerTid() const {
Elliott Hughes3147a232011-10-12 15:55:07 -0700265#if defined(__BIONIC__)
Elliott Hughesf1498432012-03-28 19:34:27 -0700266 return static_cast<uint64_t>((mutex_.value >> 16) & 0xffff);
Elliott Hughes3147a232011-10-12 15:55:07 -0700267#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700268 return reinterpret_cast<const glibc_pthread_mutex_t*>(&mutex_)->owner;
Elliott Hughescf044312012-01-23 18:48:51 -0800269#elif defined(__APPLE__)
Ian Rogersa5acfd32012-08-15 11:50:10 -0700270 return reinterpret_cast<const darwin_pthread_mutex_t*>(&mutex_)->owner_tid;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700271#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700272#error unsupported C library
Elliott Hughes8daa0922011-09-11 13:46:25 -0700273#endif
274}
275
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700276ReaderWriterMutex::ReaderWriterMutex(const char* name, MutexLevel level) : BaseMutex(name, level) {
277 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, NULL));
278}
279
280ReaderWriterMutex::~ReaderWriterMutex() {
281 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
282 // may still be using locks.
283 int rc = pthread_rwlock_destroy(&rwlock_);
284 if (rc != 0) {
285 errno = rc;
286 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
287 bool shutting_down = Runtime::Current()->IsShuttingDown();
288 PLOG(shutting_down ? WARNING : FATAL) << "pthread_mutex_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800289 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700290}
291
292void ReaderWriterMutex::ExclusiveLock() {
293 AssertNotExclusiveHeld();
294 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
295 RegisterAsLockedWithCurrentThread();
296 AssertExclusiveHeld();
297}
298
299void ReaderWriterMutex::ExclusiveUnlock() {
300 AssertExclusiveHeld();
301 RegisterAsUnlockedWithCurrentThread();
302 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
303}
304
305bool ReaderWriterMutex::ExclusiveLockWithTimeout(const timespec& abs_timeout) {
Ian Rogersa5acfd32012-08-15 11:50:10 -0700306 // Check that timeouts are supported. Currently Darwin doesn't support timeouts, if we are
307 // running on Darwin the timeout won't be respected.
308#if defined(_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS - 200112) >= 0L
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700309 int result = pthread_rwlock_timedwrlock(&rwlock_, &abs_timeout);
310 if (result == ETIMEDOUT) {
311 return false;
312 }
313 if (result != 0) {
314 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700315 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700316 }
317 RegisterAsLockedWithCurrentThread();
318 AssertSharedHeld();
319 return true;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700320#else
321 UNUSED(abs_timeout);
322 ExclusiveLock();
323 return true;
324#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700325}
326
327void ReaderWriterMutex::SharedLock() {
328 CHECK_MUTEX_CALL(pthread_rwlock_rdlock, (&rwlock_));
329 RegisterAsLockedWithCurrentThread();
330 AssertSharedHeld();
331}
332
333bool ReaderWriterMutex::SharedTryLock() {
334 int result = pthread_rwlock_tryrdlock(&rwlock_);
335 if (result == EBUSY) {
336 return false;
337 }
338 if (result != 0) {
339 errno = result;
340 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
341 }
342 RegisterAsLockedWithCurrentThread();
343 AssertSharedHeld();
344 return true;
345}
346
347void ReaderWriterMutex::SharedUnlock() {
348 AssertSharedHeld();
349 RegisterAsUnlockedWithCurrentThread();
350 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
351}
352
353bool ReaderWriterMutex::IsExclusiveHeld() const {
354 bool result = (GetExclusiveOwnerTid() == static_cast<uint64_t>(GetTid()));
355 // Sanity that if the pthread thinks we own the lock the Thread agrees.
356 Thread* self = Thread::Current();
357 DCHECK((self == NULL) || !result || (self->GetHeldMutex(level_) == this));
358 return result;
359}
360
361bool ReaderWriterMutex::IsSharedHeld() const {
362 Thread* self = Thread::Current();
363 bool result;
364 if (UNLIKELY(self == NULL)) { // Handle unattached threads.
365 result = IsExclusiveHeld(); // TODO: a better best effort here.
366 } else {
367 result = (self->GetHeldMutex(level_) == this);
368 }
369 return result;
370}
371
372uint64_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800373#if defined(__BIONIC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700374 return rwlock_.writerThreadId;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800375#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700376 return reinterpret_cast<const glibc_pthread_rwlock_t*>(&rwlock_)->writer;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800377#elif defined(__APPLE__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700378 return reinterpret_cast<const darwin_pthread_rwlock_t*>(&rwlock_)->rw_owner_tid;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800379#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700380#error unsupported C library
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800381#endif
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800382}
383
Elliott Hughes5f791332011-09-15 17:45:30 -0700384ConditionVariable::ConditionVariable(const std::string& name) : name_(name) {
385 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, NULL));
386}
387
388ConditionVariable::~ConditionVariable() {
Elliott Hughese62934d2012-04-09 11:24:29 -0700389 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
390 // may still be using condition variables.
391 int rc = pthread_cond_destroy(&cond_);
392 if (rc != 0) {
393 errno = rc;
394 bool shutting_down = Runtime::Current()->IsShuttingDown();
395 PLOG(shutting_down ? WARNING : FATAL) << "pthread_cond_destroy failed for " << name_;
396 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700397}
398
399void ConditionVariable::Broadcast() {
400 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
401}
402
403void ConditionVariable::Signal() {
404 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
405}
406
407void ConditionVariable::Wait(Mutex& mutex) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700408 mutex.CheckSafeToWait();
409 unsigned int old_recursion_count = mutex.recursion_count_;
410 mutex.recursion_count_ = 0;
Elliott Hughesf1498432012-03-28 19:34:27 -0700411 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &mutex.mutex_));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700412 mutex.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700413}
414
415void ConditionVariable::TimedWait(Mutex& mutex, const timespec& ts) {
416#ifdef HAVE_TIMEDWAIT_MONOTONIC
417#define TIMEDWAIT pthread_cond_timedwait_monotonic
418#else
419#define TIMEDWAIT pthread_cond_timedwait
420#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700421 mutex.CheckSafeToWait();
422 unsigned int old_recursion_count = mutex.recursion_count_;
423 mutex.recursion_count_ = 0;
Elliott Hughesf1498432012-03-28 19:34:27 -0700424 int rc = TIMEDWAIT(&cond_, &mutex.mutex_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700425 mutex.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700426 if (rc != 0 && rc != ETIMEDOUT) {
427 errno = rc;
428 PLOG(FATAL) << "TimedWait failed for " << name_;
429 }
430}
431
Elliott Hughese62934d2012-04-09 11:24:29 -0700432} // namespace art