blob: 96e04ef353a22c4a054733c8105f86d9f9739d6d [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
Ian Rogers81d425b2012-09-27 16:03:43 -070021#include "cutils/atomic.h"
22#include "cutils/atomic-inline.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070023#include "logging.h"
Elliott Hughes6b355752012-01-13 16:49:08 -080024#include "runtime.h"
Elliott Hughesffb465f2012-03-01 18:46:05 -080025#include "thread.h"
26#include "utils.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070027
Elliott Hughesb08e8a32012-04-02 10:51:41 -070028#if defined(__APPLE__)
29#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
30#endif
31
Elliott Hughes8d768a92011-09-14 16:35:25 -070032#define CHECK_MUTEX_CALL(call, args) CHECK_PTHREAD_CALL(call, args, name_)
33
Elliott Hughesf8349362012-06-18 15:00:06 -070034extern int pthread_mutex_lock(pthread_mutex_t* mutex) EXCLUSIVE_LOCK_FUNCTION(mutex);
35extern int pthread_mutex_unlock(pthread_mutex_t* mutex) UNLOCK_FUNCTION(1);
36extern int pthread_mutex_trylock(pthread_mutex_t* mutex) EXCLUSIVE_TRYLOCK_FUNCTION(0, mutex);
37
Ian Rogers81d425b2012-09-27 16:03:43 -070038#if ART_USE_FUTEXES
Ian Rogersacc46d62012-09-27 21:39:40 -070039#include "linux/futex.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070040#include "sys/syscall.h"
41#ifndef SYS_futex
42#define SYS_futex __NR_futex
43#endif
44int futex(volatile int *uaddr, int op, int val, const struct timespec *timeout, int *, int ) {
45 return syscall(SYS_futex, uaddr, op, val, timeout, NULL, NULL);
46}
47#endif // ART_USE_FUTEXES
48
Elliott Hughes8daa0922011-09-11 13:46:25 -070049namespace art {
50
Brian Carlstromf3a26412012-08-24 11:06:02 -070051// This works on Mac OS 10.6 but hasn't been tested on older releases.
Elliott Hughesf1498432012-03-28 19:34:27 -070052struct __attribute__((__may_alias__)) darwin_pthread_mutex_t {
Brian Carlstromf3a26412012-08-24 11:06:02 -070053 long padding0;
54 int padding1;
55 uint32_t padding2;
56 int16_t padding3;
57 int16_t padding4;
58 uint32_t padding5;
59 pthread_t darwin_pthread_mutex_owner;
Ian Rogers00f7d0e2012-07-19 15:28:27 -070060 // ...other stuff we don't care about.
61};
62
63struct __attribute__((__may_alias__)) darwin_pthread_rwlock_t {
Brian Carlstromf3a26412012-08-24 11:06:02 -070064 long padding0;
65 pthread_mutex_t padding1;
66 int padding2;
67 pthread_cond_t padding3;
68 pthread_cond_t padding4;
69 int padding5;
70 int padding6;
71 pthread_t darwin_pthread_rwlock_owner;
Elliott Hughesf1498432012-03-28 19:34:27 -070072 // ...other stuff we don't care about.
73};
74
75struct __attribute__((__may_alias__)) glibc_pthread_mutex_t {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070076 int32_t padding0[2];
Elliott Hughesf1498432012-03-28 19:34:27 -070077 int owner;
78 // ...other stuff we don't care about.
79};
80
Ian Rogers00f7d0e2012-07-19 15:28:27 -070081struct __attribute__((__may_alias__)) glibc_pthread_rwlock_t {
82#ifdef __LP64__
83 int32_t padding0[6];
84#else
85 int32_t padding0[7];
86#endif
87 int writer;
88 // ...other stuff we don't care about.
89};
90
Ian Rogers01ae5802012-09-28 16:14:01 -070091static uint64_t SafeGetTid(const Thread* self) {
92 if (self != NULL) {
93 return static_cast<uint64_t>(self->GetTid());
94 } else {
95 return static_cast<uint64_t>(GetTid());
96 }
97}
98
Ian Rogers81d425b2012-09-27 16:03:43 -070099BaseMutex::BaseMutex(const char* name, LockLevel level) : level_(level), name_(name) {}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700100
Ian Rogers120f1c72012-09-28 17:17:10 -0700101static void CheckUnattachedThread(LockLevel level) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700102 // The check below enumerates the cases where we expect not to be able to sanity check locks
Ian Rogers120f1c72012-09-28 17:17:10 -0700103 // on a thread. Lock checking is disabled to avoid deadlock when checking shutdown lock.
104 // TODO: tighten this check.
Ian Rogers25fd14b2012-09-05 10:56:38 -0700105 if (kDebugLocking) {
106 Runtime* runtime = Runtime::Current();
107 CHECK(runtime == NULL || !runtime->IsStarted() || runtime->IsShuttingDown() ||
Ian Rogers120f1c72012-09-28 17:17:10 -0700108 level == kDefaultMutexLevel || level == kRuntimeShutdownLock ||
109 level == kThreadListLock || level == kLoggingLock || level == kAbortLock);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700110 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800111}
112
Ian Rogers81d425b2012-09-27 16:03:43 -0700113void BaseMutex::RegisterAsLocked(Thread* self) {
114 if (UNLIKELY(self == NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700115 CheckUnattachedThread(level_);
116 return;
117 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700118 if (kDebugLocking) {
119 // Check if a bad Mutex of this level or lower is held.
120 bool bad_mutexes_held = false;
121 for (int i = level_; i >= 0; --i) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700122 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700123 if (UNLIKELY(held_mutex != NULL)) {
124 LOG(ERROR) << "Lock level violation: holding \"" << held_mutex->name_ << "\" (level " << i
125 << ") while locking \"" << name_ << "\" (level " << static_cast<int>(level_) << ")";
126 if (i > kAbortLock) {
127 // Only abort in the check below if this is more than abort level lock.
128 bad_mutexes_held = true;
129 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700130 }
131 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700132 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700133 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700134 // Don't record monitors as they are outside the scope of analysis. They may be inspected off of
135 // the monitor list.
136 if (level_ != kMonitorLock) {
137 self->SetHeldMutex(level_, this);
138 }
139}
140
Ian Rogers81d425b2012-09-27 16:03:43 -0700141void BaseMutex::RegisterAsUnlocked(Thread* self) {
142 if (UNLIKELY(self == NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700143 CheckUnattachedThread(level_);
144 return;
145 }
146 if (level_ != kMonitorLock) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700147 if (kDebugLocking) {
148 CHECK(self->GetHeldMutex(level_) == this) << "Unlocking on unacquired mutex: " << name_;
149 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700150 self->SetHeldMutex(level_, NULL);
151 }
152}
153
Ian Rogers81d425b2012-09-27 16:03:43 -0700154void BaseMutex::CheckSafeToWait(Thread* self) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700155 if (self == NULL) {
156 CheckUnattachedThread(level_);
157 return;
158 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700159 if (kDebugLocking) {
160 CHECK(self->GetHeldMutex(level_) == this) << "Waiting on unacquired mutex: " << name_;
161 bool bad_mutexes_held = false;
162 for (int i = kMaxMutexLevel; i >= 0; --i) {
163 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700164 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700165 if (held_mutex != NULL) {
166 LOG(ERROR) << "Holding " << held_mutex->name_ << " (level " << i
167 << ") while performing wait on: "
168 << name_ << " (level " << static_cast<int>(level_) << ")";
169 bad_mutexes_held = true;
170 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700171 }
172 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700173 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700174 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700175}
176
Ian Rogers81d425b2012-09-27 16:03:43 -0700177Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700178 : BaseMutex(name, level), recursive_(recursive), recursion_count_(0) {
Brian Carlstromf3a26412012-08-24 11:06:02 -0700179#if defined(__BIONIC__) || defined(__APPLE__)
180 // Use recursive mutexes for bionic and Apple otherwise the
181 // non-recursive mutexes don't have TIDs to check lock ownership of.
Elliott Hughesbbd9d832011-11-07 14:40:00 -0800182 pthread_mutexattr_t attributes;
183 CHECK_MUTEX_CALL(pthread_mutexattr_init, (&attributes));
184 CHECK_MUTEX_CALL(pthread_mutexattr_settype, (&attributes, PTHREAD_MUTEX_RECURSIVE));
185 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, &attributes));
186 CHECK_MUTEX_CALL(pthread_mutexattr_destroy, (&attributes));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700187#else
188 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, NULL));
189#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700190}
191
192Mutex::~Mutex() {
Elliott Hughese62934d2012-04-09 11:24:29 -0700193 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
194 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800195 int rc = pthread_mutex_destroy(&mutex_);
196 if (rc != 0) {
197 errno = rc;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800198 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700199 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700200 Runtime* runtime = Runtime::Current();
201 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughes6b355752012-01-13 16:49:08 -0800202 PLOG(shutting_down ? WARNING : FATAL) << "pthread_mutex_destroy failed for " << name_;
203 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700204}
205
Ian Rogers81d425b2012-09-27 16:03:43 -0700206void Mutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700207 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700208 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700209 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700210 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700211 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700212 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700213 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700214 }
215 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700216 if (kDebugLocking) {
217 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
218 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700219 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700220 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700221}
222
Ian Rogers81d425b2012-09-27 16:03:43 -0700223bool Mutex::ExclusiveTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700224 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700225 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700226 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700227 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700228 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700229 int result = pthread_mutex_trylock(&mutex_);
230 if (result == EBUSY) {
231 return false;
232 }
233 if (result != 0) {
234 errno = result;
235 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
236 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700237 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700238 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700239 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700240 if (kDebugLocking) {
241 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
242 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700243 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700244 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700245 return true;
246}
247
Ian Rogers81d425b2012-09-27 16:03:43 -0700248void Mutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700249 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700250 AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700251 recursion_count_--;
252 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700253 if (kDebugLocking) {
254 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
255 << name_ << " " << recursion_count_;
256 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700257 RegisterAsUnlocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700258 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
259 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700260}
261
Ian Rogers81d425b2012-09-27 16:03:43 -0700262bool Mutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700263 DCHECK(self == NULL || self == Thread::Current());
264 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
265 if (kDebugLocking) {
266 // Sanity debug check that if we think it is locked we have it in our held mutexes.
267 if (result && self != NULL && level_ != kMonitorLock) {
268 CHECK_EQ(self->GetHeldMutex(level_), this);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700269 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700270 }
271 return result;
Elliott Hughesf1498432012-03-28 19:34:27 -0700272}
273
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700274uint64_t Mutex::GetExclusiveOwnerTid() const {
Elliott Hughes3147a232011-10-12 15:55:07 -0700275#if defined(__BIONIC__)
Elliott Hughesf1498432012-03-28 19:34:27 -0700276 return static_cast<uint64_t>((mutex_.value >> 16) & 0xffff);
Elliott Hughes3147a232011-10-12 15:55:07 -0700277#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700278 return reinterpret_cast<const glibc_pthread_mutex_t*>(&mutex_)->owner;
Elliott Hughescf044312012-01-23 18:48:51 -0800279#elif defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700280 const darwin_pthread_mutex_t* dpmutex = reinterpret_cast<const darwin_pthread_mutex_t*>(&mutex_);
281 pthread_t owner = dpmutex->darwin_pthread_mutex_owner;
Brian Carlstrombd93c302012-08-27 16:58:28 -0700282 // 0 for unowned, -1 for PTHREAD_MTX_TID_SWITCHING
283 // TODO: should we make darwin_pthread_mutex_owner volatile and recheck until not -1?
Brian Carlstromf3a26412012-08-24 11:06:02 -0700284 if ((owner == (pthread_t)0) || (owner == (pthread_t)-1)) {
285 return 0;
286 }
287 uint64_t tid;
288 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
289 return tid;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700290#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700291#error unsupported C library
Elliott Hughes8daa0922011-09-11 13:46:25 -0700292#endif
293}
294
Ian Rogers01ae5802012-09-28 16:14:01 -0700295std::string Mutex::Dump() const {
296 return StringPrintf("%s %s level=%d count=%d owner=%llx",
297 recursive_ ? "recursive" : "non-recursive",
298 name_.c_str(),
299 static_cast<int>(level_),
300 recursion_count_,
301 GetExclusiveOwnerTid());
302}
303
304std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
305 return os << mu.Dump();
306}
307
Ian Rogers81d425b2012-09-27 16:03:43 -0700308ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level) :
309 BaseMutex(name, level)
310#if ART_USE_FUTEXES
311 , state_(0), exclusive_owner_(0), num_pending_readers_(0), num_pending_writers_(0)
312#endif
313{
314#if !ART_USE_FUTEXES
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700315 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, NULL));
Ian Rogers81d425b2012-09-27 16:03:43 -0700316#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700317}
318
319ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700320#if ART_USE_FUTEXES
321 CHECK_EQ(state_, 0);
322 CHECK_EQ(exclusive_owner_, 0U);
323 CHECK_EQ(num_pending_readers_, 0);
324 CHECK_EQ(num_pending_writers_, 0);
325#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700326 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
327 // may still be using locks.
328 int rc = pthread_rwlock_destroy(&rwlock_);
329 if (rc != 0) {
330 errno = rc;
331 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700332 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700333 Runtime* runtime = Runtime::Current();
334 bool shutting_down = runtime == NULL || runtime->IsShuttingDown();
335 PLOG(shutting_down ? WARNING : FATAL) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800336 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700337#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700338}
339
Ian Rogers81d425b2012-09-27 16:03:43 -0700340void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700341 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700342 AssertNotExclusiveHeld(self);
343#if ART_USE_FUTEXES
344 bool done = false;
345 do {
346 int32_t cur_state = state_;
347 if (cur_state == 0) {
348 // Change state from 0 to -1.
349 done = android_atomic_cmpxchg(0, -1, &state_) == 0;
350 } else {
351 // Failed to acquire, hang up.
352 android_atomic_inc(&num_pending_writers_);
353 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
354 if (errno != EAGAIN) {
355 PLOG(FATAL) << "futex wait failed for " << name_;
356 }
357 }
358 android_atomic_dec(&num_pending_writers_);
359 }
360 } while(!done);
Ian Rogersab470162012-09-29 23:06:53 -0700361 DCHECK_EQ(state_, -1);
362 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700363#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700364 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700365#endif
366 RegisterAsLocked(self);
367 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700368}
369
Ian Rogers81d425b2012-09-27 16:03:43 -0700370void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700371 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700372 AssertExclusiveHeld(self);
373 RegisterAsUnlocked(self);
374#if ART_USE_FUTEXES
375 bool done = false;
376 do {
377 int32_t cur_state = state_;
378 if (cur_state == -1) {
379 // We're no longer the owner.
380 exclusive_owner_ = 0;
381 // Change state from -1 to 0.
382 done = android_atomic_cmpxchg(-1, 0, &state_) == 0;
383 if (done) { // cmpxchg may fail due to noise?
384 // Wake any waiters.
385 if (num_pending_readers_ > 0 || num_pending_writers_ > 0) {
386 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
387 }
388 }
389 } else {
390 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
391 }
392 } while(!done);
393#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700394 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700395#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700396}
397
Ian Rogers66aee5c2012-08-15 17:17:47 -0700398#if HAVE_TIMED_RWLOCK
Ian Rogers81d425b2012-09-27 16:03:43 -0700399bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, const timespec& abs_timeout) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700400 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700401#if ART_USE_FUTEXES
402 bool done = false;
403 do {
404 int32_t cur_state = state_;
405 if (cur_state == 0) {
406 // Change state from 0 to -1.
407 done = android_atomic_cmpxchg(0, -1, &state_) == 0;
408 } else {
409 // Failed to acquire, hang up.
410 android_atomic_inc(&num_pending_writers_);
411 if (futex(&state_, FUTEX_WAIT, cur_state, &abs_timeout, NULL, 0) != 0) {
412 if (errno == ETIMEDOUT) {
413 android_atomic_dec(&num_pending_writers_);
414 return false;
415 } else if (errno != EAGAIN) {
416 PLOG(FATAL) << "timed futex wait failed for " << name_;
417 }
418 }
419 android_atomic_dec(&num_pending_writers_);
420 }
421 } while(!done);
Ian Rogers01ae5802012-09-28 16:14:01 -0700422 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700423#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700424 int result = pthread_rwlock_timedwrlock(&rwlock_, &abs_timeout);
425 if (result == ETIMEDOUT) {
426 return false;
427 }
428 if (result != 0) {
429 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700430 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700431 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700432#endif
433 RegisterAsLocked(self);
434 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700435 return true;
436}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700437#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700438
Ian Rogers81d425b2012-09-27 16:03:43 -0700439void ReaderWriterMutex::SharedLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700440 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700441#if ART_USE_FUTEXES
442 bool done = false;
443 do {
444 int32_t cur_state = state_;
445 if (cur_state >= 0) {
446 // Add as an extra reader.
447 done = android_atomic_cmpxchg(cur_state, cur_state + 1, &state_) == 0;
448 } else {
449 // Owner holds it exclusively, hang up.
450 android_atomic_inc(&num_pending_readers_);
451 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
452 if (errno != EAGAIN) {
453 PLOG(FATAL) << "futex wait failed for " << name_;
454 }
455 }
456 android_atomic_dec(&num_pending_readers_);
457 }
458 } while(!done);
459#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700460 CHECK_MUTEX_CALL(pthread_rwlock_rdlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700461#endif
462 RegisterAsLocked(self);
463 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464}
465
Ian Rogers81d425b2012-09-27 16:03:43 -0700466bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700467 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700468#if ART_USE_FUTEXES
469 bool done = false;
470 do {
471 int32_t cur_state = state_;
472 if (cur_state >= 0) {
473 // Add as an extra reader.
474 done = android_atomic_cmpxchg(cur_state, cur_state + 1, &state_) == 0;
475 } else {
476 // Owner holds it exclusively.
477 return false;
478 }
479 } while(!done);
480#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481 int result = pthread_rwlock_tryrdlock(&rwlock_);
482 if (result == EBUSY) {
483 return false;
484 }
485 if (result != 0) {
486 errno = result;
487 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
488 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700489#endif
490 RegisterAsLocked(self);
491 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700492 return true;
493}
494
Ian Rogers81d425b2012-09-27 16:03:43 -0700495void ReaderWriterMutex::SharedUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700496 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700497 AssertSharedHeld(self);
498 RegisterAsUnlocked(self);
499#if ART_USE_FUTEXES
500 bool done = false;
501 do {
502 int32_t cur_state = state_;
503 if (LIKELY(cur_state > 0)) {
504 // Reduce state by 1.
505 done = android_atomic_cmpxchg(cur_state, cur_state - 1, &state_) == 0;
506 if (done && (cur_state - 1) == 0) { // cmpxchg may fail due to noise?
507 if (num_pending_writers_ > 0 || num_pending_readers_ > 0) {
508 // Wake any exclusive waiters as there are now no readers.
509 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
510 }
511 }
512 } else {
513 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
514 }
515 } while(!done);
516#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700517 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700518#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700519}
520
Ian Rogers81d425b2012-09-27 16:03:43 -0700521bool ReaderWriterMutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700522 DCHECK(self == NULL || self == Thread::Current());
523 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700524 if (kDebugLocking) {
525 // Sanity that if the pthread thinks we own the lock the Thread agrees.
Ian Rogers01ae5802012-09-28 16:14:01 -0700526 if (self != NULL && result) {
527 CHECK_EQ(self->GetHeldMutex(level_), this);
528 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700529 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700530 return result;
531}
532
Ian Rogers81d425b2012-09-27 16:03:43 -0700533bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700534 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700535 bool result;
536 if (UNLIKELY(self == NULL)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700537 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700538 } else {
539 result = (self->GetHeldMutex(level_) == this);
540 }
541 return result;
542}
543
544uint64_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700545#if ART_USE_FUTEXES
546 return exclusive_owner_;
547#else
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800548#if defined(__BIONIC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700549 return rwlock_.writerThreadId;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800550#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700551 return reinterpret_cast<const glibc_pthread_rwlock_t*>(&rwlock_)->writer;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800552#elif defined(__APPLE__)
Ian Rogers81d425b2012-09-27 16:03:43 -0700553 const darwin_pthread_rwlock_t*
554 dprwlock = reinterpret_cast<const darwin_pthread_rwlock_t*>(&rwlock_);
Brian Carlstromf3a26412012-08-24 11:06:02 -0700555 pthread_t owner = dprwlock->darwin_pthread_rwlock_owner;
556 if (owner == (pthread_t)0) {
557 return 0;
558 }
559 uint64_t tid;
560 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
561 return tid;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800562#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700563#error unsupported C library
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800564#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700565#endif
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800566}
567
Ian Rogers01ae5802012-09-28 16:14:01 -0700568std::string ReaderWriterMutex::Dump() const {
569 return StringPrintf("%s level=%d owner=%llx",
570 name_.c_str(),
571 static_cast<int>(level_),
572 GetExclusiveOwnerTid());
573}
574
575std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
576 return os << mu.Dump();
577}
578
Elliott Hughes5f791332011-09-15 17:45:30 -0700579ConditionVariable::ConditionVariable(const std::string& name) : name_(name) {
580 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, NULL));
581}
582
583ConditionVariable::~ConditionVariable() {
Elliott Hughese62934d2012-04-09 11:24:29 -0700584 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
585 // may still be using condition variables.
586 int rc = pthread_cond_destroy(&cond_);
587 if (rc != 0) {
588 errno = rc;
Ian Rogers50b35e22012-10-04 10:09:15 -0700589 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700590 Runtime* runtime = Runtime::Current();
591 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughese62934d2012-04-09 11:24:29 -0700592 PLOG(shutting_down ? WARNING : FATAL) << "pthread_cond_destroy failed for " << name_;
593 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700594}
595
596void ConditionVariable::Broadcast() {
597 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
598}
599
600void ConditionVariable::Signal() {
601 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
602}
603
Ian Rogers81d425b2012-09-27 16:03:43 -0700604void ConditionVariable::Wait(Thread* self, Mutex& mutex) {
605 mutex.CheckSafeToWait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700606 unsigned int old_recursion_count = mutex.recursion_count_;
607 mutex.recursion_count_ = 0;
Elliott Hughesf1498432012-03-28 19:34:27 -0700608 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &mutex.mutex_));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700609 mutex.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700610}
611
Ian Rogers81d425b2012-09-27 16:03:43 -0700612void ConditionVariable::TimedWait(Thread* self, Mutex& mutex, const timespec& ts) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700613#ifdef HAVE_TIMEDWAIT_MONOTONIC
614#define TIMEDWAIT pthread_cond_timedwait_monotonic
615#else
616#define TIMEDWAIT pthread_cond_timedwait
617#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700618 mutex.CheckSafeToWait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700619 unsigned int old_recursion_count = mutex.recursion_count_;
620 mutex.recursion_count_ = 0;
Elliott Hughesf1498432012-03-28 19:34:27 -0700621 int rc = TIMEDWAIT(&cond_, &mutex.mutex_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700622 mutex.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700623 if (rc != 0 && rc != ETIMEDOUT) {
624 errno = rc;
625 PLOG(FATAL) << "TimedWait failed for " << name_;
626 }
627}
628
Elliott Hughese62934d2012-04-09 11:24:29 -0700629} // namespace art