blob: 1975f3bfd2a78492dc1bd8f0ef58bfec82229e5f [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"
Ian Rogers693ff612013-02-01 10:56:12 -080024#include "cutils/atomic-inline.h"
25#include "mutex-inl.h"
Elliott Hughes6b355752012-01-13 16:49:08 -080026#include "runtime.h"
Ian Rogersc604d732012-10-14 16:09:54 -070027#include "scoped_thread_state_change.h"
Elliott Hughesffb465f2012-03-01 18:46:05 -080028#include "thread.h"
29#include "utils.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070030
31namespace art {
32
Brian Carlstromf3a26412012-08-24 11:06:02 -070033// This works on Mac OS 10.6 but hasn't been tested on older releases.
Elliott Hughesf1498432012-03-28 19:34:27 -070034struct __attribute__((__may_alias__)) darwin_pthread_mutex_t {
Brian Carlstromf3a26412012-08-24 11:06:02 -070035 long padding0;
36 int padding1;
37 uint32_t padding2;
38 int16_t padding3;
39 int16_t padding4;
40 uint32_t padding5;
41 pthread_t darwin_pthread_mutex_owner;
Ian Rogers00f7d0e2012-07-19 15:28:27 -070042 // ...other stuff we don't care about.
43};
44
45struct __attribute__((__may_alias__)) darwin_pthread_rwlock_t {
Brian Carlstromf3a26412012-08-24 11:06:02 -070046 long padding0;
47 pthread_mutex_t padding1;
48 int padding2;
49 pthread_cond_t padding3;
50 pthread_cond_t padding4;
51 int padding5;
52 int padding6;
53 pthread_t darwin_pthread_rwlock_owner;
Elliott Hughesf1498432012-03-28 19:34:27 -070054 // ...other stuff we don't care about.
55};
56
57struct __attribute__((__may_alias__)) glibc_pthread_mutex_t {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070058 int32_t padding0[2];
Elliott Hughesf1498432012-03-28 19:34:27 -070059 int owner;
60 // ...other stuff we don't care about.
61};
62
Ian Rogers00f7d0e2012-07-19 15:28:27 -070063struct __attribute__((__may_alias__)) glibc_pthread_rwlock_t {
64#ifdef __LP64__
65 int32_t padding0[6];
66#else
67 int32_t padding0[7];
68#endif
69 int writer;
70 // ...other stuff we don't care about.
71};
72
Ian Rogersc604d732012-10-14 16:09:54 -070073#if ART_USE_FUTEXES
74static bool ComputeRelativeTimeSpec(timespec* result_ts, const timespec& lhs, const timespec& rhs) {
75 const long int one_sec = 1000 * 1000 * 1000; // one second in nanoseconds.
76 result_ts->tv_sec = lhs.tv_sec - rhs.tv_sec;
77 result_ts->tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
78 if (result_ts->tv_nsec < 0) {
79 result_ts->tv_sec--;
80 result_ts->tv_nsec += one_sec;
81 } else if (result_ts->tv_nsec > one_sec) {
82 result_ts->tv_sec++;
83 result_ts->tv_nsec -= one_sec;
84 }
85 return result_ts->tv_sec < 0;
86}
87#endif
88
Ian Rogers56edc432013-01-18 16:51:51 -080089#if CONTENTION_LOGGING
90// A guard for all_mutexes_ that's not a mutex (Mutexes must CAS to acquire and busy wait).
91static AtomicInteger all_mutexes_guard_;
92// All created mutexes guarded by all_mutexes_guard_.
93std::set<BaseMutex*>* all_mutexes_;
94
95class ScopedAllMutexesLock {
96 public:
97 ScopedAllMutexesLock(const BaseMutex* mutex) : mutex_(mutex) {
98 while (!all_mutexes_guard_.CompareAndSwap(0, reinterpret_cast<int32_t>(mutex))) {
99 NanoSleep(100);
100 }
101 }
102 ~ScopedAllMutexesLock() {
103 while (!all_mutexes_guard_.CompareAndSwap(reinterpret_cast<int32_t>(mutex_), 0)) {
104 NanoSleep(100);
105 }
106 }
107 private:
108 const BaseMutex* const mutex_;
109};
110#endif
111
112BaseMutex::BaseMutex(const char* name, LockLevel level) : level_(level), name_(name) {
113#if CONTENTION_LOGGING
114 ScopedAllMutexesLock mu(this);
115 if (all_mutexes_ == NULL) {
116 // We leak the global set of all mutexes to avoid ordering issues in global variable
117 // construction/destruction.
118 all_mutexes_ = new std::set<BaseMutex*>();
119 }
120 all_mutexes_->insert(this);
121#endif
122}
123
124BaseMutex::~BaseMutex() {
125#if CONTENTION_LOGGING
126 ScopedAllMutexesLock mu(this);
127 all_mutexes_->erase(this);
128#endif
129}
130
131void BaseMutex::DumpAll(std::ostream& os) {
132#if CONTENTION_LOGGING
133 os << "Mutex logging:\n";
134 ScopedAllMutexesLock mu(reinterpret_cast<const BaseMutex*>(-1));
135 typedef std::set<BaseMutex*>::const_iterator It;
136 for (It it = all_mutexes_->begin(); it != all_mutexes_->end(); ++it) {
137 BaseMutex* mutex = *it;
138 mutex->Dump(os);
139 os << "\n";
140 }
141#endif
142}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700143
Ian Rogers81d425b2012-09-27 16:03:43 -0700144void BaseMutex::CheckSafeToWait(Thread* self) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700145 if (self == NULL) {
146 CheckUnattachedThread(level_);
147 return;
148 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700149 if (kDebugLocking) {
150 CHECK(self->GetHeldMutex(level_) == this) << "Waiting on unacquired mutex: " << name_;
151 bool bad_mutexes_held = false;
Elliott Hughes0f827162013-02-26 12:12:58 -0800152 for (int i = kLockLevelCount - 1; i >= 0; --i) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700153 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700154 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700155 if (held_mutex != NULL) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800156 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
157 << "(level " << LockLevel(i) << ") while performing wait on "
158 << "\"" << name_ << "\" (level " << level_ << ")";
Ian Rogers25fd14b2012-09-05 10:56:38 -0700159 bad_mutexes_held = true;
160 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700161 }
162 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700163 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700164 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700165}
166
Ian Rogers56edc432013-01-18 16:51:51 -0800167void BaseMutex::RecordContention(uint64_t blocked_tid, uint64_t owner_tid, uint64_t milli_time_blocked) {
168#if CONTENTION_LOGGING
169 ++contention_count_;
170 wait_time_ += static_cast<uint32_t>(milli_time_blocked); // May overflow.
171 // This code is intentionally racy as it is only used for diagnostics.
172 uint32_t slot = cur_content_log_entry_;
173 if (contention_log_[slot].blocked_tid == blocked_tid &&
174 contention_log_[slot].owner_tid == blocked_tid) {
175 ++contention_log_[slot].count;
176 } else {
177 uint32_t new_slot;
178 do {
179 slot = cur_content_log_entry_;
180 new_slot = (slot + 1) % kContentionLogSize;
181 } while(!cur_content_log_entry_.CompareAndSwap(slot, new_slot));
182 contention_log_[new_slot].blocked_tid = blocked_tid;
183 contention_log_[new_slot].owner_tid = owner_tid;
184 contention_log_[new_slot].count = 1;
185 }
186#endif
187}
188
Ian Rogers56edc432013-01-18 16:51:51 -0800189void BaseMutex::DumpContention(std::ostream& os) const {
190#if CONTENTION_LOGGING
191 uint32_t wait_time = wait_time_;
192 uint32_t contention_count = contention_count_;
193 if (contention_count == 0) {
194 os << "never contended";
195 } else {
196 os << "contended " << contention_count << " times, average wait of contender " << (wait_time / contention_count) << "ms";
197 SafeMap<uint64_t, size_t> most_common_blocker;
198 SafeMap<uint64_t, size_t> most_common_blocked;
199 typedef SafeMap<uint64_t, size_t>::const_iterator It;
200 for (size_t i = 0; i < kContentionLogSize; ++i) {
201 uint64_t blocked_tid = contention_log_[i].blocked_tid;
202 uint64_t owner_tid = contention_log_[i].owner_tid;
203 uint32_t count = contention_log_[i].count;
204 if (count > 0) {
205 It it = most_common_blocked.find(blocked_tid);
206 if (it != most_common_blocked.end()) {
207 most_common_blocked.Overwrite(blocked_tid, it->second + count);
208 } else {
209 most_common_blocked.Put(blocked_tid, count);
210 }
211 it = most_common_blocker.find(owner_tid);
212 if (it != most_common_blocker.end()) {
213 most_common_blocker.Overwrite(owner_tid, it->second + count);
214 } else {
215 most_common_blocker.Put(owner_tid, count);
216 }
217 }
218 }
219 uint64_t max_tid = 0;
220 size_t max_tid_count = 0;
221 for (It it = most_common_blocked.begin(); it != most_common_blocked.end(); ++it) {
222 if (it->second > max_tid_count) {
223 max_tid = it->first;
224 max_tid_count = it->second;
225 }
226 }
227 if (max_tid != 0) {
228 os << " sample shows most blocked tid=" << max_tid;
229 }
230 max_tid = 0;
231 max_tid_count = 0;
232 for (It it = most_common_blocker.begin(); it != most_common_blocker.end(); ++it) {
233 if (it->second > max_tid_count) {
234 max_tid = it->first;
235 max_tid_count = it->second;
236 }
237 }
238 if (max_tid != 0) {
239 os << " sample shows tid=" << max_tid << " owning during this time";
240 }
241 }
242#endif
243}
244
245
Ian Rogers81d425b2012-09-27 16:03:43 -0700246Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700247 : BaseMutex(name, level), recursive_(recursive), recursion_count_(0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700248#if ART_USE_FUTEXES
249 state_ = 0;
250 exclusive_owner_ = 0;
251 num_contenders_ = 0;
252#elif defined(__BIONIC__) || defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700253 // Use recursive mutexes for bionic and Apple otherwise the
254 // non-recursive mutexes don't have TIDs to check lock ownership of.
Elliott Hughesbbd9d832011-11-07 14:40:00 -0800255 pthread_mutexattr_t attributes;
256 CHECK_MUTEX_CALL(pthread_mutexattr_init, (&attributes));
257 CHECK_MUTEX_CALL(pthread_mutexattr_settype, (&attributes, PTHREAD_MUTEX_RECURSIVE));
258 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, &attributes));
259 CHECK_MUTEX_CALL(pthread_mutexattr_destroy, (&attributes));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700260#else
261 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, NULL));
262#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700263}
264
265Mutex::~Mutex() {
Ian Rogersc604d732012-10-14 16:09:54 -0700266#if ART_USE_FUTEXES
267 if (state_ != 0) {
268 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
269 Runtime* runtime = Runtime::Current();
270 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
271 LOG(shutting_down ? WARNING : FATAL) << "destroying mutex with owner: " << exclusive_owner_;
272 } else {
273 CHECK_EQ(exclusive_owner_, 0U) << "unexpectedly found an owner on unlocked mutex " << name_;
274 CHECK_EQ(num_contenders_, 0) << "unexpectedly found a contender on mutex " << name_;
275 }
276#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700277 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
278 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800279 int rc = pthread_mutex_destroy(&mutex_);
280 if (rc != 0) {
281 errno = rc;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800282 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700283 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700284 Runtime* runtime = Runtime::Current();
285 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughes6b355752012-01-13 16:49:08 -0800286 PLOG(shutting_down ? WARNING : FATAL) << "pthread_mutex_destroy failed for " << name_;
287 }
Ian Rogersc604d732012-10-14 16:09:54 -0700288#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700289}
290
Ian Rogers81d425b2012-09-27 16:03:43 -0700291void Mutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700292 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700293 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700294 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700295 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700296 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700297#if ART_USE_FUTEXES
298 bool done = false;
299 do {
300 int32_t cur_state = state_;
301 if (cur_state == 0) {
302 // Change state from 0 to 1.
Ian Rogers693ff612013-02-01 10:56:12 -0800303 done = android_atomic_acquire_cas(0, 1, &state_) == 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700304 } else {
305 // Failed to acquire, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800306 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700307 android_atomic_inc(&num_contenders_);
308 if (futex(&state_, FUTEX_WAIT, 1, NULL, NULL, 0) != 0) {
309 if (errno != EAGAIN) {
310 PLOG(FATAL) << "futex wait failed for " << name_;
311 }
312 }
313 android_atomic_dec(&num_contenders_);
314 }
315 } while(!done);
316 DCHECK_EQ(state_, 1);
317 exclusive_owner_ = SafeGetTid(self);
318#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700319 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700320#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700321 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700322 }
323 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700324 if (kDebugLocking) {
325 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
326 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700327 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700328 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700329}
330
Ian Rogers81d425b2012-09-27 16:03:43 -0700331bool Mutex::ExclusiveTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700332 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700333 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700334 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700335 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700336 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700337#if ART_USE_FUTEXES
338 bool done = false;
339 do {
340 int32_t cur_state = state_;
341 if (cur_state == 0) {
342 // Change state from 0 to 1.
Ian Rogers693ff612013-02-01 10:56:12 -0800343 done = android_atomic_acquire_cas(0, 1, &state_) == 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700344 } else {
345 return false;
346 }
347 } while(!done);
348 DCHECK_EQ(state_, 1);
349 exclusive_owner_ = SafeGetTid(self);
350#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700351 int result = pthread_mutex_trylock(&mutex_);
352 if (result == EBUSY) {
353 return false;
354 }
355 if (result != 0) {
356 errno = result;
357 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
358 }
Ian Rogersc604d732012-10-14 16:09:54 -0700359#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700360 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700361 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700362 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700363 if (kDebugLocking) {
364 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
365 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700366 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700367 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700368 return true;
369}
370
Ian Rogers81d425b2012-09-27 16:03:43 -0700371void Mutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700372 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700373 AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700374 recursion_count_--;
375 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700376 if (kDebugLocking) {
377 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
378 << name_ << " " << recursion_count_;
379 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700380 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700381#if ART_USE_FUTEXES
382 bool done = false;
383 do {
384 int32_t cur_state = state_;
385 if (cur_state == 1) {
386 // We're no longer the owner.
387 exclusive_owner_ = 0;
388 // Change state to 0.
Ian Rogers693ff612013-02-01 10:56:12 -0800389 done = android_atomic_release_cas(cur_state, 0, &state_) == 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700390 if (done) { // Spurious fail?
391 // Wake a contender
392 if (num_contenders_ > 0) {
393 futex(&state_, FUTEX_WAKE, 1, NULL, NULL, 0);
394 }
395 }
396 } else {
397 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
398 }
399 } while(!done);
400#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700401 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700402#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700403 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700404}
405
Ian Rogers81d425b2012-09-27 16:03:43 -0700406bool Mutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700407 DCHECK(self == NULL || self == Thread::Current());
408 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
409 if (kDebugLocking) {
410 // Sanity debug check that if we think it is locked we have it in our held mutexes.
Brian Carlstrom9e419ca2012-11-27 11:31:49 -0800411 if (result && self != NULL && level_ != kMonitorLock && !gAborting) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700412 CHECK_EQ(self->GetHeldMutex(level_), this);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700413 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700414 }
415 return result;
Elliott Hughesf1498432012-03-28 19:34:27 -0700416}
417
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700418uint64_t Mutex::GetExclusiveOwnerTid() const {
Ian Rogersc604d732012-10-14 16:09:54 -0700419#if ART_USE_FUTEXES
420 return exclusive_owner_;
421#elif defined(__BIONIC__)
Elliott Hughesf1498432012-03-28 19:34:27 -0700422 return static_cast<uint64_t>((mutex_.value >> 16) & 0xffff);
Elliott Hughes3147a232011-10-12 15:55:07 -0700423#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700424 return reinterpret_cast<const glibc_pthread_mutex_t*>(&mutex_)->owner;
Elliott Hughescf044312012-01-23 18:48:51 -0800425#elif defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700426 const darwin_pthread_mutex_t* dpmutex = reinterpret_cast<const darwin_pthread_mutex_t*>(&mutex_);
427 pthread_t owner = dpmutex->darwin_pthread_mutex_owner;
Brian Carlstrombd93c302012-08-27 16:58:28 -0700428 // 0 for unowned, -1 for PTHREAD_MTX_TID_SWITCHING
429 // TODO: should we make darwin_pthread_mutex_owner volatile and recheck until not -1?
Brian Carlstromf3a26412012-08-24 11:06:02 -0700430 if ((owner == (pthread_t)0) || (owner == (pthread_t)-1)) {
431 return 0;
432 }
433 uint64_t tid;
434 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
435 return tid;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700436#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700437#error unsupported C library
Elliott Hughes8daa0922011-09-11 13:46:25 -0700438#endif
439}
440
Ian Rogers56edc432013-01-18 16:51:51 -0800441void Mutex::Dump(std::ostream& os) const {
442 os << (recursive_ ? "recursive " : "non-recursive ")
443 << name_
444 << " level=" << static_cast<int>(level_)
445 << " rec=" << recursion_count_
446 << " owner=" << GetExclusiveOwnerTid() << " ";
447 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700448}
449
450std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800451 mu.Dump(os);
452 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700453}
454
Ian Rogers81d425b2012-09-27 16:03:43 -0700455ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level) :
456 BaseMutex(name, level)
457#if ART_USE_FUTEXES
458 , state_(0), exclusive_owner_(0), num_pending_readers_(0), num_pending_writers_(0)
459#endif
460{
461#if !ART_USE_FUTEXES
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700462 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, NULL));
Ian Rogers81d425b2012-09-27 16:03:43 -0700463#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464}
465
466ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700467#if ART_USE_FUTEXES
468 CHECK_EQ(state_, 0);
469 CHECK_EQ(exclusive_owner_, 0U);
470 CHECK_EQ(num_pending_readers_, 0);
471 CHECK_EQ(num_pending_writers_, 0);
472#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700473 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
474 // may still be using locks.
475 int rc = pthread_rwlock_destroy(&rwlock_);
476 if (rc != 0) {
477 errno = rc;
478 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700479 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700480 Runtime* runtime = Runtime::Current();
481 bool shutting_down = runtime == NULL || runtime->IsShuttingDown();
482 PLOG(shutting_down ? WARNING : FATAL) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800483 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700484#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700485}
486
Ian Rogers81d425b2012-09-27 16:03:43 -0700487void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700488 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700489 AssertNotExclusiveHeld(self);
490#if ART_USE_FUTEXES
491 bool done = false;
492 do {
493 int32_t cur_state = state_;
494 if (cur_state == 0) {
495 // Change state from 0 to -1.
Ian Rogers693ff612013-02-01 10:56:12 -0800496 done = android_atomic_acquire_cas(0, -1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700497 } else {
498 // Failed to acquire, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800499 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700500 android_atomic_inc(&num_pending_writers_);
501 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
502 if (errno != EAGAIN) {
503 PLOG(FATAL) << "futex wait failed for " << name_;
504 }
505 }
506 android_atomic_dec(&num_pending_writers_);
507 }
508 } while(!done);
Ian Rogersab470162012-09-29 23:06:53 -0700509 DCHECK_EQ(state_, -1);
510 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700511#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700512 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700513#endif
514 RegisterAsLocked(self);
515 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700516}
517
Ian Rogers81d425b2012-09-27 16:03:43 -0700518void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700519 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700520 AssertExclusiveHeld(self);
521 RegisterAsUnlocked(self);
522#if ART_USE_FUTEXES
523 bool done = false;
524 do {
525 int32_t cur_state = state_;
526 if (cur_state == -1) {
527 // We're no longer the owner.
528 exclusive_owner_ = 0;
529 // Change state from -1 to 0.
Ian Rogers693ff612013-02-01 10:56:12 -0800530 done = android_atomic_release_cas(-1, 0, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700531 if (done) { // cmpxchg may fail due to noise?
532 // Wake any waiters.
533 if (num_pending_readers_ > 0 || num_pending_writers_ > 0) {
534 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
535 }
536 }
537 } else {
538 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
539 }
540 } while(!done);
541#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700542 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700543#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700544}
545
Ian Rogers66aee5c2012-08-15 17:17:47 -0700546#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700547bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700548 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700549#if ART_USE_FUTEXES
550 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700551 timespec end_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800552 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700553 do {
554 int32_t cur_state = state_;
555 if (cur_state == 0) {
556 // Change state from 0 to -1.
Ian Rogers693ff612013-02-01 10:56:12 -0800557 done = android_atomic_acquire_cas(0, -1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700558 } else {
559 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700560 timespec now_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800561 InitTimeSpec(true, CLOCK_REALTIME, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700562 timespec rel_ts;
563 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
564 return false; // Timed out.
565 }
Ian Rogers56edc432013-01-18 16:51:51 -0800566 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700567 android_atomic_inc(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700568 if (futex(&state_, FUTEX_WAIT, cur_state, &rel_ts, NULL, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700569 if (errno == ETIMEDOUT) {
570 android_atomic_dec(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700571 return false; // Timed out.
572 } else if (errno != EAGAIN && errno != EINTR) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700573 PLOG(FATAL) << "timed futex wait failed for " << name_;
574 }
575 }
576 android_atomic_dec(&num_pending_writers_);
577 }
578 } while(!done);
Ian Rogers01ae5802012-09-28 16:14:01 -0700579 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700580#else
Ian Rogersc604d732012-10-14 16:09:54 -0700581 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700582 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700583 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700584 if (result == ETIMEDOUT) {
585 return false;
586 }
587 if (result != 0) {
588 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700589 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700590 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700591#endif
592 RegisterAsLocked(self);
593 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700594 return true;
595}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700596#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700597
Ian Rogers81d425b2012-09-27 16:03:43 -0700598bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700599 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700600#if ART_USE_FUTEXES
601 bool done = false;
602 do {
603 int32_t cur_state = state_;
604 if (cur_state >= 0) {
605 // Add as an extra reader.
Ian Rogers693ff612013-02-01 10:56:12 -0800606 done = android_atomic_acquire_cas(cur_state, cur_state + 1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700607 } else {
608 // Owner holds it exclusively.
609 return false;
610 }
611 } while(!done);
612#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700613 int result = pthread_rwlock_tryrdlock(&rwlock_);
614 if (result == EBUSY) {
615 return false;
616 }
617 if (result != 0) {
618 errno = result;
619 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
620 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700621#endif
622 RegisterAsLocked(self);
623 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700624 return true;
625}
626
Ian Rogers81d425b2012-09-27 16:03:43 -0700627bool ReaderWriterMutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700628 DCHECK(self == NULL || self == Thread::Current());
629 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700630 if (kDebugLocking) {
631 // Sanity that if the pthread thinks we own the lock the Thread agrees.
Ian Rogers01ae5802012-09-28 16:14:01 -0700632 if (self != NULL && result) {
633 CHECK_EQ(self->GetHeldMutex(level_), this);
634 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700635 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700636 return result;
637}
638
Ian Rogers81d425b2012-09-27 16:03:43 -0700639bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700640 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700641 bool result;
642 if (UNLIKELY(self == NULL)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700643 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700644 } else {
645 result = (self->GetHeldMutex(level_) == this);
646 }
647 return result;
648}
649
650uint64_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700651#if ART_USE_FUTEXES
Ian Rogers56edc432013-01-18 16:51:51 -0800652 int32_t state = state_;
653 if (state == 0) {
654 return 0; // No owner.
655 } else if (state > 0) {
656 return -1; // Shared.
657 } else {
658 return exclusive_owner_;
659 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700660#else
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800661#if defined(__BIONIC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700662 return rwlock_.writerThreadId;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800663#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700664 return reinterpret_cast<const glibc_pthread_rwlock_t*>(&rwlock_)->writer;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800665#elif defined(__APPLE__)
Ian Rogers81d425b2012-09-27 16:03:43 -0700666 const darwin_pthread_rwlock_t*
667 dprwlock = reinterpret_cast<const darwin_pthread_rwlock_t*>(&rwlock_);
Brian Carlstromf3a26412012-08-24 11:06:02 -0700668 pthread_t owner = dprwlock->darwin_pthread_rwlock_owner;
669 if (owner == (pthread_t)0) {
670 return 0;
671 }
672 uint64_t tid;
673 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
674 return tid;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800675#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700676#error unsupported C library
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800677#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700678#endif
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800679}
680
Ian Rogers56edc432013-01-18 16:51:51 -0800681void ReaderWriterMutex::Dump(std::ostream& os) const {
682 os << name_
683 << " level=" << static_cast<int>(level_)
684 << " owner=" << GetExclusiveOwnerTid() << " ";
685 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700686}
687
688std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800689 mu.Dump(os);
690 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700691}
692
Ian Rogersc604d732012-10-14 16:09:54 -0700693ConditionVariable::ConditionVariable(const std::string& name, Mutex& guard)
694 : name_(name), guard_(guard) {
695#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800696 sequence_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700697 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700698#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700699 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, NULL));
Ian Rogersc604d732012-10-14 16:09:54 -0700700#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700701}
702
703ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800704#if ART_USE_FUTEXES
705 if (num_waiters_!= 0) {
706 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
707 Runtime* runtime = Runtime::Current();
708 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Ian Rogersd45f2012012-11-28 11:46:23 -0800709 LOG(shutting_down ? WARNING : FATAL) << "ConditionVariable::~ConditionVariable for " << name_
710 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800711 }
712#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700713 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
714 // may still be using condition variables.
715 int rc = pthread_cond_destroy(&cond_);
716 if (rc != 0) {
717 errno = rc;
Ian Rogers50b35e22012-10-04 10:09:15 -0700718 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700719 Runtime* runtime = Runtime::Current();
720 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughese62934d2012-04-09 11:24:29 -0700721 PLOG(shutting_down ? WARNING : FATAL) << "pthread_cond_destroy failed for " << name_;
722 }
Ian Rogersc604d732012-10-14 16:09:54 -0700723#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700724}
725
Ian Rogersc604d732012-10-14 16:09:54 -0700726void ConditionVariable::Broadcast(Thread* self) {
727 DCHECK(self == NULL || self == Thread::Current());
728 // TODO: enable below, there's a race in thread creation that causes false failures currently.
729 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700730 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700731#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800732 if (num_waiters_ > 0) {
733 android_atomic_inc(&sequence_); // Indicate the broadcast occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700734 bool done = false;
735 do {
Ian Rogersd45f2012012-11-28 11:46:23 -0800736 int32_t cur_sequence = sequence_;
737 // Requeue waiters onto mutex. The waiter holds the contender count on the mutex high ensuring
738 // mutex unlocks will awaken the requeued waiter thread.
739 done = futex(&sequence_, FUTEX_CMP_REQUEUE, 0,
Ian Rogers5bd97c42012-11-27 02:38:26 -0800740 reinterpret_cast<const timespec*>(std::numeric_limits<int32_t>::max()),
Ian Rogersd45f2012012-11-28 11:46:23 -0800741 &guard_.state_, cur_sequence) != -1;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800742 if (!done) {
743 if (errno != EAGAIN) {
744 PLOG(FATAL) << "futex cmp requeue failed for " << name_;
745 }
Ian Rogers5bd97c42012-11-27 02:38:26 -0800746 }
Ian Rogersc604d732012-10-14 16:09:54 -0700747 } while (!done);
748 }
749#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700750 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700751#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700752}
753
Ian Rogersc604d732012-10-14 16:09:54 -0700754void ConditionVariable::Signal(Thread* self) {
755 DCHECK(self == NULL || self == Thread::Current());
756 guard_.AssertExclusiveHeld(self);
757#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800758 if (num_waiters_ > 0) {
759 android_atomic_inc(&sequence_); // Indicate a signal occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700760 // Futex wake 1 waiter who will then come and in contend on mutex. It'd be nice to requeue them
761 // to avoid this, however, requeueing can only move all waiters.
Ian Rogersd45f2012012-11-28 11:46:23 -0800762 int num_woken = futex(&sequence_, FUTEX_WAKE, 1, NULL, NULL, 0);
763 // Check something was woken or else we changed sequence_ before they had chance to wait.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800764 CHECK((num_woken == 0) || (num_woken == 1));
Ian Rogersc604d732012-10-14 16:09:54 -0700765 }
766#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700767 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700768#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700769}
770
Ian Rogersc604d732012-10-14 16:09:54 -0700771void ConditionVariable::Wait(Thread* self) {
772 DCHECK(self == NULL || self == Thread::Current());
773 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700774 unsigned int old_recursion_count = guard_.recursion_count_;
775#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700776 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800777 // Ensure the Mutex is contended so that requeued threads are awoken.
778 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700779 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800780 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700781 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800782 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, NULL, NULL, 0) != 0) {
783 // Futex failed, check it is an expected error.
784 // EAGAIN == EWOULDBLK, so we let the caller try again.
785 // EINTR implies a signal was sent to this thread.
786 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700787 PLOG(FATAL) << "futex wait failed for " << name_;
788 }
789 }
790 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800791 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700792 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800793 // We awoke and so no longer require awakes from the guard_'s unlock.
794 CHECK_GE(guard_.num_contenders_, 0);
795 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700796#else
797 guard_.recursion_count_ = 0;
798 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
799#endif
800 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700801}
802
Ian Rogersc604d732012-10-14 16:09:54 -0700803void ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
804 DCHECK(self == NULL || self == Thread::Current());
805 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700806 unsigned int old_recursion_count = guard_.recursion_count_;
807#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700808 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800809 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700810 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800811 // Ensure the Mutex is contended so that requeued threads are awoken.
812 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700813 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800814 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700815 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800816 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, &rel_ts, NULL, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700817 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800818 // Timed out we're done.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800819 } else if ((errno == EINTR) || (errno == EAGAIN)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800820 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700821 } else {
822 PLOG(FATAL) << "timed futex wait failed for " << name_;
823 }
824 }
825 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800826 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700827 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800828 // We awoke and so no longer require awakes from the guard_'s unlock.
829 CHECK_GE(guard_.num_contenders_, 0);
830 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700831#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700832#ifdef HAVE_TIMEDWAIT_MONOTONIC
833#define TIMEDWAIT pthread_cond_timedwait_monotonic
Ian Rogersc604d732012-10-14 16:09:54 -0700834 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700835#else
836#define TIMEDWAIT pthread_cond_timedwait
Ian Rogersc604d732012-10-14 16:09:54 -0700837 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700838#endif
Ian Rogersc604d732012-10-14 16:09:54 -0700839 guard_.recursion_count_ = 0;
840 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700841 InitTimeSpec(true, clock, ms, ns, &ts);
842 int rc = TEMP_FAILURE_RETRY(TIMEDWAIT(&cond_, &guard_.mutex_, &ts));
Elliott Hughes5f791332011-09-15 17:45:30 -0700843 if (rc != 0 && rc != ETIMEDOUT) {
844 errno = rc;
845 PLOG(FATAL) << "TimedWait failed for " << name_;
846 }
Ian Rogersc604d732012-10-14 16:09:54 -0700847#endif
848 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700849}
850
Elliott Hughese62934d2012-04-09 11:24:29 -0700851} // namespace art