blob: a5d890abc05f9ffa9c6e85505f6e90538095ac78 [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>
Ian Rogersc604d732012-10-14 16:09:54 -070020#include <sys/time.h>
Elliott Hughes8daa0922011-09-11 13:46:25 -070021
Elliott Hughes07ed66b2012-12-12 18:34:25 -080022#include "base/logging.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070023#include "cutils/atomic.h"
24#include "cutils/atomic-inline.h"
Elliott Hughes6b355752012-01-13 16:49:08 -080025#include "runtime.h"
Ian Rogersc604d732012-10-14 16:09:54 -070026#include "scoped_thread_state_change.h"
Elliott Hughesffb465f2012-03-01 18:46:05 -080027#include "thread.h"
28#include "utils.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070029
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
Ian Rogers81d425b2012-09-27 16:03:43 -070036#if ART_USE_FUTEXES
Ian Rogersacc46d62012-09-27 21:39:40 -070037#include "linux/futex.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070038#include "sys/syscall.h"
39#ifndef SYS_futex
40#define SYS_futex __NR_futex
41#endif
Ian Rogersc604d732012-10-14 16:09:54 -070042int futex(volatile int *uaddr, int op, int val, const struct timespec *timeout, volatile int *uaddr2, int val3) {
43 return syscall(SYS_futex, uaddr, op, val, timeout, uaddr2, val3);
Ian Rogers81d425b2012-09-27 16:03:43 -070044}
45#endif // ART_USE_FUTEXES
46
Elliott Hughes8daa0922011-09-11 13:46:25 -070047namespace art {
48
Brian Carlstromf3a26412012-08-24 11:06:02 -070049// This works on Mac OS 10.6 but hasn't been tested on older releases.
Elliott Hughesf1498432012-03-28 19:34:27 -070050struct __attribute__((__may_alias__)) darwin_pthread_mutex_t {
Brian Carlstromf3a26412012-08-24 11:06:02 -070051 long padding0;
52 int padding1;
53 uint32_t padding2;
54 int16_t padding3;
55 int16_t padding4;
56 uint32_t padding5;
57 pthread_t darwin_pthread_mutex_owner;
Ian Rogers00f7d0e2012-07-19 15:28:27 -070058 // ...other stuff we don't care about.
59};
60
61struct __attribute__((__may_alias__)) darwin_pthread_rwlock_t {
Brian Carlstromf3a26412012-08-24 11:06:02 -070062 long padding0;
63 pthread_mutex_t padding1;
64 int padding2;
65 pthread_cond_t padding3;
66 pthread_cond_t padding4;
67 int padding5;
68 int padding6;
69 pthread_t darwin_pthread_rwlock_owner;
Elliott Hughesf1498432012-03-28 19:34:27 -070070 // ...other stuff we don't care about.
71};
72
73struct __attribute__((__may_alias__)) glibc_pthread_mutex_t {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070074 int32_t padding0[2];
Elliott Hughesf1498432012-03-28 19:34:27 -070075 int owner;
76 // ...other stuff we don't care about.
77};
78
Ian Rogers00f7d0e2012-07-19 15:28:27 -070079struct __attribute__((__may_alias__)) glibc_pthread_rwlock_t {
80#ifdef __LP64__
81 int32_t padding0[6];
82#else
83 int32_t padding0[7];
84#endif
85 int writer;
86 // ...other stuff we don't care about.
87};
88
Ian Rogers01ae5802012-09-28 16:14:01 -070089static uint64_t SafeGetTid(const Thread* self) {
90 if (self != NULL) {
91 return static_cast<uint64_t>(self->GetTid());
92 } else {
93 return static_cast<uint64_t>(GetTid());
94 }
95}
96
Ian Rogersc604d732012-10-14 16:09:54 -070097#if ART_USE_FUTEXES
98static bool ComputeRelativeTimeSpec(timespec* result_ts, const timespec& lhs, const timespec& rhs) {
99 const long int one_sec = 1000 * 1000 * 1000; // one second in nanoseconds.
100 result_ts->tv_sec = lhs.tv_sec - rhs.tv_sec;
101 result_ts->tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
102 if (result_ts->tv_nsec < 0) {
103 result_ts->tv_sec--;
104 result_ts->tv_nsec += one_sec;
105 } else if (result_ts->tv_nsec > one_sec) {
106 result_ts->tv_sec++;
107 result_ts->tv_nsec -= one_sec;
108 }
109 return result_ts->tv_sec < 0;
110}
111#endif
112
Ian Rogers81d425b2012-09-27 16:03:43 -0700113BaseMutex::BaseMutex(const char* name, LockLevel level) : level_(level), name_(name) {}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700114
Ian Rogers120f1c72012-09-28 17:17:10 -0700115static void CheckUnattachedThread(LockLevel level) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700116 // The check below enumerates the cases where we expect not to be able to sanity check locks
Ian Rogers120f1c72012-09-28 17:17:10 -0700117 // on a thread. Lock checking is disabled to avoid deadlock when checking shutdown lock.
118 // TODO: tighten this check.
Ian Rogers25fd14b2012-09-05 10:56:38 -0700119 if (kDebugLocking) {
120 Runtime* runtime = Runtime::Current();
121 CHECK(runtime == NULL || !runtime->IsStarted() || runtime->IsShuttingDown() ||
Ian Rogers120f1c72012-09-28 17:17:10 -0700122 level == kDefaultMutexLevel || level == kRuntimeShutdownLock ||
123 level == kThreadListLock || level == kLoggingLock || level == kAbortLock);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700124 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800125}
126
Ian Rogers81d425b2012-09-27 16:03:43 -0700127void BaseMutex::RegisterAsLocked(Thread* self) {
128 if (UNLIKELY(self == NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700129 CheckUnattachedThread(level_);
130 return;
131 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700132 if (kDebugLocking) {
133 // Check if a bad Mutex of this level or lower is held.
134 bool bad_mutexes_held = false;
135 for (int i = level_; i >= 0; --i) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700136 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700137 if (UNLIKELY(held_mutex != NULL)) {
138 LOG(ERROR) << "Lock level violation: holding \"" << held_mutex->name_ << "\" (level " << i
139 << ") while locking \"" << name_ << "\" (level " << static_cast<int>(level_) << ")";
140 if (i > kAbortLock) {
141 // Only abort in the check below if this is more than abort level lock.
142 bad_mutexes_held = true;
143 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700144 }
145 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700146 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700147 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700148 // Don't record monitors as they are outside the scope of analysis. They may be inspected off of
149 // the monitor list.
150 if (level_ != kMonitorLock) {
151 self->SetHeldMutex(level_, this);
152 }
153}
154
Ian Rogers81d425b2012-09-27 16:03:43 -0700155void BaseMutex::RegisterAsUnlocked(Thread* self) {
156 if (UNLIKELY(self == NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700157 CheckUnattachedThread(level_);
158 return;
159 }
160 if (level_ != kMonitorLock) {
Brian Carlstrom760c9432012-11-29 16:46:27 -0800161 if (kDebugLocking && !gAborting) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700162 CHECK(self->GetHeldMutex(level_) == this) << "Unlocking on unacquired mutex: " << name_;
163 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700164 self->SetHeldMutex(level_, NULL);
165 }
166}
167
Ian Rogers81d425b2012-09-27 16:03:43 -0700168void BaseMutex::CheckSafeToWait(Thread* self) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700169 if (self == NULL) {
170 CheckUnattachedThread(level_);
171 return;
172 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700173 if (kDebugLocking) {
174 CHECK(self->GetHeldMutex(level_) == this) << "Waiting on unacquired mutex: " << name_;
175 bool bad_mutexes_held = false;
176 for (int i = kMaxMutexLevel; i >= 0; --i) {
177 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700178 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700179 if (held_mutex != NULL) {
180 LOG(ERROR) << "Holding " << held_mutex->name_ << " (level " << i
181 << ") while performing wait on: "
182 << name_ << " (level " << static_cast<int>(level_) << ")";
183 bad_mutexes_held = true;
184 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700185 }
186 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700187 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700188 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700189}
190
Ian Rogers81d425b2012-09-27 16:03:43 -0700191Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700192 : BaseMutex(name, level), recursive_(recursive), recursion_count_(0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700193#if ART_USE_FUTEXES
194 state_ = 0;
195 exclusive_owner_ = 0;
196 num_contenders_ = 0;
197#elif defined(__BIONIC__) || defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700198 // Use recursive mutexes for bionic and Apple otherwise the
199 // non-recursive mutexes don't have TIDs to check lock ownership of.
Elliott Hughesbbd9d832011-11-07 14:40:00 -0800200 pthread_mutexattr_t attributes;
201 CHECK_MUTEX_CALL(pthread_mutexattr_init, (&attributes));
202 CHECK_MUTEX_CALL(pthread_mutexattr_settype, (&attributes, PTHREAD_MUTEX_RECURSIVE));
203 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, &attributes));
204 CHECK_MUTEX_CALL(pthread_mutexattr_destroy, (&attributes));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700205#else
206 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, NULL));
207#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700208}
209
210Mutex::~Mutex() {
Ian Rogersc604d732012-10-14 16:09:54 -0700211#if ART_USE_FUTEXES
212 if (state_ != 0) {
213 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
214 Runtime* runtime = Runtime::Current();
215 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
216 LOG(shutting_down ? WARNING : FATAL) << "destroying mutex with owner: " << exclusive_owner_;
217 } else {
218 CHECK_EQ(exclusive_owner_, 0U) << "unexpectedly found an owner on unlocked mutex " << name_;
219 CHECK_EQ(num_contenders_, 0) << "unexpectedly found a contender on mutex " << name_;
220 }
221#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700222 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
223 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800224 int rc = pthread_mutex_destroy(&mutex_);
225 if (rc != 0) {
226 errno = rc;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800227 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700228 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700229 Runtime* runtime = Runtime::Current();
230 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughes6b355752012-01-13 16:49:08 -0800231 PLOG(shutting_down ? WARNING : FATAL) << "pthread_mutex_destroy failed for " << name_;
232 }
Ian Rogersc604d732012-10-14 16:09:54 -0700233#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700234}
235
Ian Rogers81d425b2012-09-27 16:03:43 -0700236void Mutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700237 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700238 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700239 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700240 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700241 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700242#if ART_USE_FUTEXES
243 bool done = false;
244 do {
245 int32_t cur_state = state_;
246 if (cur_state == 0) {
247 // Change state from 0 to 1.
248 done = android_atomic_cmpxchg(0, 1, &state_) == 0;
249 } else {
250 // Failed to acquire, hang up.
251 android_atomic_inc(&num_contenders_);
252 if (futex(&state_, FUTEX_WAIT, 1, NULL, NULL, 0) != 0) {
253 if (errno != EAGAIN) {
254 PLOG(FATAL) << "futex wait failed for " << name_;
255 }
256 }
257 android_atomic_dec(&num_contenders_);
258 }
259 } while(!done);
260 DCHECK_EQ(state_, 1);
261 exclusive_owner_ = SafeGetTid(self);
262#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700263 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700264#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700265 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700266 }
267 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700268 if (kDebugLocking) {
269 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
270 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700271 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700272 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700273}
274
Ian Rogers81d425b2012-09-27 16:03:43 -0700275bool Mutex::ExclusiveTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700276 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700277 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700278 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700279 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700280 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700281#if ART_USE_FUTEXES
282 bool done = false;
283 do {
284 int32_t cur_state = state_;
285 if (cur_state == 0) {
286 // Change state from 0 to 1.
287 done = android_atomic_cmpxchg(0, 1, &state_) == 0;
288 } else {
289 return false;
290 }
291 } while(!done);
292 DCHECK_EQ(state_, 1);
293 exclusive_owner_ = SafeGetTid(self);
294#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700295 int result = pthread_mutex_trylock(&mutex_);
296 if (result == EBUSY) {
297 return false;
298 }
299 if (result != 0) {
300 errno = result;
301 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
302 }
Ian Rogersc604d732012-10-14 16:09:54 -0700303#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700304 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700305 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700306 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700307 if (kDebugLocking) {
308 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
309 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700310 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700311 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700312 return true;
313}
314
Ian Rogers81d425b2012-09-27 16:03:43 -0700315void Mutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700316 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700317 AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700318 recursion_count_--;
319 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700320 if (kDebugLocking) {
321 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
322 << name_ << " " << recursion_count_;
323 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700324 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700325#if ART_USE_FUTEXES
326 bool done = false;
327 do {
328 int32_t cur_state = state_;
329 if (cur_state == 1) {
330 // We're no longer the owner.
331 exclusive_owner_ = 0;
332 // Change state to 0.
333 done = android_atomic_cmpxchg(cur_state, 0, &state_) == 0;
334 if (done) { // Spurious fail?
335 // Wake a contender
336 if (num_contenders_ > 0) {
337 futex(&state_, FUTEX_WAKE, 1, NULL, NULL, 0);
338 }
339 }
340 } else {
341 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
342 }
343 } while(!done);
344#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700345 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700346#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700347 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700348}
349
Ian Rogers81d425b2012-09-27 16:03:43 -0700350bool Mutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700351 DCHECK(self == NULL || self == Thread::Current());
352 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
353 if (kDebugLocking) {
354 // Sanity debug check that if we think it is locked we have it in our held mutexes.
Brian Carlstrom9e419ca2012-11-27 11:31:49 -0800355 if (result && self != NULL && level_ != kMonitorLock && !gAborting) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700356 CHECK_EQ(self->GetHeldMutex(level_), this);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700357 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700358 }
359 return result;
Elliott Hughesf1498432012-03-28 19:34:27 -0700360}
361
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700362uint64_t Mutex::GetExclusiveOwnerTid() const {
Ian Rogersc604d732012-10-14 16:09:54 -0700363#if ART_USE_FUTEXES
364 return exclusive_owner_;
365#elif defined(__BIONIC__)
Elliott Hughesf1498432012-03-28 19:34:27 -0700366 return static_cast<uint64_t>((mutex_.value >> 16) & 0xffff);
Elliott Hughes3147a232011-10-12 15:55:07 -0700367#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700368 return reinterpret_cast<const glibc_pthread_mutex_t*>(&mutex_)->owner;
Elliott Hughescf044312012-01-23 18:48:51 -0800369#elif defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700370 const darwin_pthread_mutex_t* dpmutex = reinterpret_cast<const darwin_pthread_mutex_t*>(&mutex_);
371 pthread_t owner = dpmutex->darwin_pthread_mutex_owner;
Brian Carlstrombd93c302012-08-27 16:58:28 -0700372 // 0 for unowned, -1 for PTHREAD_MTX_TID_SWITCHING
373 // TODO: should we make darwin_pthread_mutex_owner volatile and recheck until not -1?
Brian Carlstromf3a26412012-08-24 11:06:02 -0700374 if ((owner == (pthread_t)0) || (owner == (pthread_t)-1)) {
375 return 0;
376 }
377 uint64_t tid;
378 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
379 return tid;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700380#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700381#error unsupported C library
Elliott Hughes8daa0922011-09-11 13:46:25 -0700382#endif
383}
384
Ian Rogers01ae5802012-09-28 16:14:01 -0700385std::string Mutex::Dump() const {
386 return StringPrintf("%s %s level=%d count=%d owner=%llx",
387 recursive_ ? "recursive" : "non-recursive",
388 name_.c_str(),
389 static_cast<int>(level_),
390 recursion_count_,
391 GetExclusiveOwnerTid());
392}
393
394std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
395 return os << mu.Dump();
396}
397
Ian Rogers81d425b2012-09-27 16:03:43 -0700398ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level) :
399 BaseMutex(name, level)
400#if ART_USE_FUTEXES
401 , state_(0), exclusive_owner_(0), num_pending_readers_(0), num_pending_writers_(0)
402#endif
403{
404#if !ART_USE_FUTEXES
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700405 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, NULL));
Ian Rogers81d425b2012-09-27 16:03:43 -0700406#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700407}
408
409ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700410#if ART_USE_FUTEXES
411 CHECK_EQ(state_, 0);
412 CHECK_EQ(exclusive_owner_, 0U);
413 CHECK_EQ(num_pending_readers_, 0);
414 CHECK_EQ(num_pending_writers_, 0);
415#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700416 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
417 // may still be using locks.
418 int rc = pthread_rwlock_destroy(&rwlock_);
419 if (rc != 0) {
420 errno = rc;
421 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700422 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700423 Runtime* runtime = Runtime::Current();
424 bool shutting_down = runtime == NULL || runtime->IsShuttingDown();
425 PLOG(shutting_down ? WARNING : FATAL) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800426 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700427#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700428}
429
Ian Rogers81d425b2012-09-27 16:03:43 -0700430void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700431 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700432 AssertNotExclusiveHeld(self);
433#if ART_USE_FUTEXES
434 bool done = false;
435 do {
436 int32_t cur_state = state_;
437 if (cur_state == 0) {
438 // Change state from 0 to -1.
439 done = android_atomic_cmpxchg(0, -1, &state_) == 0;
440 } else {
441 // Failed to acquire, hang up.
442 android_atomic_inc(&num_pending_writers_);
443 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
444 if (errno != EAGAIN) {
445 PLOG(FATAL) << "futex wait failed for " << name_;
446 }
447 }
448 android_atomic_dec(&num_pending_writers_);
449 }
450 } while(!done);
Ian Rogersab470162012-09-29 23:06:53 -0700451 DCHECK_EQ(state_, -1);
452 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700453#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700454 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700455#endif
456 RegisterAsLocked(self);
457 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700458}
459
Ian Rogers81d425b2012-09-27 16:03:43 -0700460void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700461 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700462 AssertExclusiveHeld(self);
463 RegisterAsUnlocked(self);
464#if ART_USE_FUTEXES
465 bool done = false;
466 do {
467 int32_t cur_state = state_;
468 if (cur_state == -1) {
469 // We're no longer the owner.
470 exclusive_owner_ = 0;
471 // Change state from -1 to 0.
472 done = android_atomic_cmpxchg(-1, 0, &state_) == 0;
473 if (done) { // cmpxchg may fail due to noise?
474 // Wake any waiters.
475 if (num_pending_readers_ > 0 || num_pending_writers_ > 0) {
476 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
477 }
478 }
479 } else {
480 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
481 }
482 } while(!done);
483#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700484 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700485#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700486}
487
Ian Rogers66aee5c2012-08-15 17:17:47 -0700488#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700489bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700490 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700491#if ART_USE_FUTEXES
492 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700493 timespec end_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800494 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700495 do {
496 int32_t cur_state = state_;
497 if (cur_state == 0) {
498 // Change state from 0 to -1.
499 done = android_atomic_cmpxchg(0, -1, &state_) == 0;
500 } else {
501 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700502 timespec now_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800503 InitTimeSpec(true, CLOCK_REALTIME, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700504 timespec rel_ts;
505 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
506 return false; // Timed out.
507 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700508 android_atomic_inc(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700509 if (futex(&state_, FUTEX_WAIT, cur_state, &rel_ts, NULL, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700510 if (errno == ETIMEDOUT) {
511 android_atomic_dec(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700512 return false; // Timed out.
513 } else if (errno != EAGAIN && errno != EINTR) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700514 PLOG(FATAL) << "timed futex wait failed for " << name_;
515 }
516 }
517 android_atomic_dec(&num_pending_writers_);
518 }
519 } while(!done);
Ian Rogers01ae5802012-09-28 16:14:01 -0700520 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700521#else
Ian Rogersc604d732012-10-14 16:09:54 -0700522 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700523 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700524 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700525 if (result == ETIMEDOUT) {
526 return false;
527 }
528 if (result != 0) {
529 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700530 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700531 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700532#endif
533 RegisterAsLocked(self);
534 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700535 return true;
536}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700537#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700538
Ian Rogers81d425b2012-09-27 16:03:43 -0700539void ReaderWriterMutex::SharedLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700540 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700541#if ART_USE_FUTEXES
542 bool done = false;
543 do {
544 int32_t cur_state = state_;
545 if (cur_state >= 0) {
546 // Add as an extra reader.
547 done = android_atomic_cmpxchg(cur_state, cur_state + 1, &state_) == 0;
548 } else {
549 // Owner holds it exclusively, hang up.
550 android_atomic_inc(&num_pending_readers_);
551 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
552 if (errno != EAGAIN) {
553 PLOG(FATAL) << "futex wait failed for " << name_;
554 }
555 }
556 android_atomic_dec(&num_pending_readers_);
557 }
558 } while(!done);
559#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700560 CHECK_MUTEX_CALL(pthread_rwlock_rdlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700561#endif
562 RegisterAsLocked(self);
563 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700564}
565
Ian Rogers81d425b2012-09-27 16:03:43 -0700566bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700567 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700568#if ART_USE_FUTEXES
569 bool done = false;
570 do {
571 int32_t cur_state = state_;
572 if (cur_state >= 0) {
573 // Add as an extra reader.
574 done = android_atomic_cmpxchg(cur_state, cur_state + 1, &state_) == 0;
575 } else {
576 // Owner holds it exclusively.
577 return false;
578 }
579 } while(!done);
580#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700581 int result = pthread_rwlock_tryrdlock(&rwlock_);
582 if (result == EBUSY) {
583 return false;
584 }
585 if (result != 0) {
586 errno = result;
587 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
588 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700589#endif
590 RegisterAsLocked(self);
591 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700592 return true;
593}
594
Ian Rogers81d425b2012-09-27 16:03:43 -0700595void ReaderWriterMutex::SharedUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700596 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700597 AssertSharedHeld(self);
598 RegisterAsUnlocked(self);
599#if ART_USE_FUTEXES
600 bool done = false;
601 do {
602 int32_t cur_state = state_;
603 if (LIKELY(cur_state > 0)) {
604 // Reduce state by 1.
605 done = android_atomic_cmpxchg(cur_state, cur_state - 1, &state_) == 0;
606 if (done && (cur_state - 1) == 0) { // cmpxchg may fail due to noise?
607 if (num_pending_writers_ > 0 || num_pending_readers_ > 0) {
608 // Wake any exclusive waiters as there are now no readers.
609 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
610 }
611 }
612 } else {
613 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
614 }
615 } while(!done);
616#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700617 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700618#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700619}
620
Ian Rogers81d425b2012-09-27 16:03:43 -0700621bool ReaderWriterMutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700622 DCHECK(self == NULL || self == Thread::Current());
623 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700624 if (kDebugLocking) {
625 // Sanity that if the pthread thinks we own the lock the Thread agrees.
Ian Rogers01ae5802012-09-28 16:14:01 -0700626 if (self != NULL && result) {
627 CHECK_EQ(self->GetHeldMutex(level_), this);
628 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700629 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700630 return result;
631}
632
Ian Rogers81d425b2012-09-27 16:03:43 -0700633bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700634 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700635 bool result;
636 if (UNLIKELY(self == NULL)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700637 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700638 } else {
639 result = (self->GetHeldMutex(level_) == this);
640 }
641 return result;
642}
643
644uint64_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700645#if ART_USE_FUTEXES
646 return exclusive_owner_;
647#else
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800648#if defined(__BIONIC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700649 return rwlock_.writerThreadId;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800650#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700651 return reinterpret_cast<const glibc_pthread_rwlock_t*>(&rwlock_)->writer;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800652#elif defined(__APPLE__)
Ian Rogers81d425b2012-09-27 16:03:43 -0700653 const darwin_pthread_rwlock_t*
654 dprwlock = reinterpret_cast<const darwin_pthread_rwlock_t*>(&rwlock_);
Brian Carlstromf3a26412012-08-24 11:06:02 -0700655 pthread_t owner = dprwlock->darwin_pthread_rwlock_owner;
656 if (owner == (pthread_t)0) {
657 return 0;
658 }
659 uint64_t tid;
660 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
661 return tid;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800662#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700663#error unsupported C library
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800664#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700665#endif
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800666}
667
Ian Rogers01ae5802012-09-28 16:14:01 -0700668std::string ReaderWriterMutex::Dump() const {
669 return StringPrintf("%s level=%d owner=%llx",
670 name_.c_str(),
671 static_cast<int>(level_),
672 GetExclusiveOwnerTid());
673}
674
675std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
676 return os << mu.Dump();
677}
678
Ian Rogersc604d732012-10-14 16:09:54 -0700679ConditionVariable::ConditionVariable(const std::string& name, Mutex& guard)
680 : name_(name), guard_(guard) {
681#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800682 sequence_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700683 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700684#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700685 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, NULL));
Ian Rogersc604d732012-10-14 16:09:54 -0700686#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700687}
688
689ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800690#if ART_USE_FUTEXES
691 if (num_waiters_!= 0) {
692 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
693 Runtime* runtime = Runtime::Current();
694 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Ian Rogersd45f2012012-11-28 11:46:23 -0800695 LOG(shutting_down ? WARNING : FATAL) << "ConditionVariable::~ConditionVariable for " << name_
696 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800697 }
698#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700699 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
700 // may still be using condition variables.
701 int rc = pthread_cond_destroy(&cond_);
702 if (rc != 0) {
703 errno = rc;
Ian Rogers50b35e22012-10-04 10:09:15 -0700704 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700705 Runtime* runtime = Runtime::Current();
706 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughese62934d2012-04-09 11:24:29 -0700707 PLOG(shutting_down ? WARNING : FATAL) << "pthread_cond_destroy failed for " << name_;
708 }
Ian Rogersc604d732012-10-14 16:09:54 -0700709#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700710}
711
Ian Rogersc604d732012-10-14 16:09:54 -0700712void ConditionVariable::Broadcast(Thread* self) {
713 DCHECK(self == NULL || self == Thread::Current());
714 // TODO: enable below, there's a race in thread creation that causes false failures currently.
715 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700716 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700717#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800718 if (num_waiters_ > 0) {
719 android_atomic_inc(&sequence_); // Indicate the broadcast occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700720 bool done = false;
721 do {
Ian Rogersd45f2012012-11-28 11:46:23 -0800722 int32_t cur_sequence = sequence_;
723 // Requeue waiters onto mutex. The waiter holds the contender count on the mutex high ensuring
724 // mutex unlocks will awaken the requeued waiter thread.
725 done = futex(&sequence_, FUTEX_CMP_REQUEUE, 0,
Ian Rogers5bd97c42012-11-27 02:38:26 -0800726 reinterpret_cast<const timespec*>(std::numeric_limits<int32_t>::max()),
Ian Rogersd45f2012012-11-28 11:46:23 -0800727 &guard_.state_, cur_sequence) != -1;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800728 if (!done) {
729 if (errno != EAGAIN) {
730 PLOG(FATAL) << "futex cmp requeue failed for " << name_;
731 }
Ian Rogers5bd97c42012-11-27 02:38:26 -0800732 }
Ian Rogersc604d732012-10-14 16:09:54 -0700733 } while (!done);
734 }
735#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700736 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700737#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700738}
739
Ian Rogersc604d732012-10-14 16:09:54 -0700740void ConditionVariable::Signal(Thread* self) {
741 DCHECK(self == NULL || self == Thread::Current());
742 guard_.AssertExclusiveHeld(self);
743#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800744 if (num_waiters_ > 0) {
745 android_atomic_inc(&sequence_); // Indicate a signal occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700746 // Futex wake 1 waiter who will then come and in contend on mutex. It'd be nice to requeue them
747 // to avoid this, however, requeueing can only move all waiters.
Ian Rogersd45f2012012-11-28 11:46:23 -0800748 int num_woken = futex(&sequence_, FUTEX_WAKE, 1, NULL, NULL, 0);
749 // Check something was woken or else we changed sequence_ before they had chance to wait.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800750 CHECK((num_woken == 0) || (num_woken == 1));
Ian Rogersc604d732012-10-14 16:09:54 -0700751 }
752#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700753 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700754#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700755}
756
Ian Rogersc604d732012-10-14 16:09:54 -0700757void ConditionVariable::Wait(Thread* self) {
758 DCHECK(self == NULL || self == Thread::Current());
759 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700760 unsigned int old_recursion_count = guard_.recursion_count_;
761#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700762 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800763 // Ensure the Mutex is contended so that requeued threads are awoken.
764 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700765 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800766 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700767 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800768 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, NULL, NULL, 0) != 0) {
769 // Futex failed, check it is an expected error.
770 // EAGAIN == EWOULDBLK, so we let the caller try again.
771 // EINTR implies a signal was sent to this thread.
772 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700773 PLOG(FATAL) << "futex wait failed for " << name_;
774 }
775 }
776 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800777 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700778 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800779 // We awoke and so no longer require awakes from the guard_'s unlock.
780 CHECK_GE(guard_.num_contenders_, 0);
781 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700782#else
783 guard_.recursion_count_ = 0;
784 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
785#endif
786 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700787}
788
Ian Rogersc604d732012-10-14 16:09:54 -0700789void ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
790 DCHECK(self == NULL || self == Thread::Current());
791 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700792 unsigned int old_recursion_count = guard_.recursion_count_;
793#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700794 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800795 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700796 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800797 // Ensure the Mutex is contended so that requeued threads are awoken.
798 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700799 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800800 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700801 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800802 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, &rel_ts, NULL, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700803 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800804 // Timed out we're done.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800805 } else if ((errno == EINTR) || (errno == EAGAIN)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800806 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700807 } else {
808 PLOG(FATAL) << "timed futex wait failed for " << name_;
809 }
810 }
811 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800812 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700813 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800814 // We awoke and so no longer require awakes from the guard_'s unlock.
815 CHECK_GE(guard_.num_contenders_, 0);
816 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700817#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700818#ifdef HAVE_TIMEDWAIT_MONOTONIC
819#define TIMEDWAIT pthread_cond_timedwait_monotonic
Ian Rogersc604d732012-10-14 16:09:54 -0700820 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700821#else
822#define TIMEDWAIT pthread_cond_timedwait
Ian Rogersc604d732012-10-14 16:09:54 -0700823 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700824#endif
Ian Rogersc604d732012-10-14 16:09:54 -0700825 guard_.recursion_count_ = 0;
826 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700827 InitTimeSpec(true, clock, ms, ns, &ts);
828 int rc = TEMP_FAILURE_RETRY(TIMEDWAIT(&cond_, &guard_.mutex_, &ts));
Elliott Hughes5f791332011-09-15 17:45:30 -0700829 if (rc != 0 && rc != ETIMEDOUT) {
830 errno = rc;
831 PLOG(FATAL) << "TimedWait failed for " << name_;
832 }
Ian Rogersc604d732012-10-14 16:09:54 -0700833#endif
834 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700835}
836
Elliott Hughese62934d2012-04-09 11:24:29 -0700837} // namespace art