blob: fa7a617cd60ddf28abfcdfb7c81234ad3a407c2e [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::RegisterAsLocked(Thread* self) {
145 if (UNLIKELY(self == NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700146 CheckUnattachedThread(level_);
147 return;
148 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700149 if (kDebugLocking) {
150 // Check if a bad Mutex of this level or lower is held.
151 bool bad_mutexes_held = false;
152 for (int i = level_; i >= 0; --i) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700153 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700154 if (UNLIKELY(held_mutex != NULL)) {
155 LOG(ERROR) << "Lock level violation: holding \"" << held_mutex->name_ << "\" (level " << i
156 << ") while locking \"" << name_ << "\" (level " << static_cast<int>(level_) << ")";
157 if (i > kAbortLock) {
158 // Only abort in the check below if this is more than abort level lock.
159 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 // Don't record monitors as they are outside the scope of analysis. They may be inspected off of
166 // the monitor list.
167 if (level_ != kMonitorLock) {
168 self->SetHeldMutex(level_, this);
169 }
170}
171
Ian Rogers81d425b2012-09-27 16:03:43 -0700172void BaseMutex::CheckSafeToWait(Thread* self) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700173 if (self == NULL) {
174 CheckUnattachedThread(level_);
175 return;
176 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700177 if (kDebugLocking) {
178 CHECK(self->GetHeldMutex(level_) == this) << "Waiting on unacquired mutex: " << name_;
179 bool bad_mutexes_held = false;
180 for (int i = kMaxMutexLevel; i >= 0; --i) {
181 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700182 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700183 if (held_mutex != NULL) {
184 LOG(ERROR) << "Holding " << held_mutex->name_ << " (level " << i
185 << ") while performing wait on: "
186 << name_ << " (level " << static_cast<int>(level_) << ")";
187 bad_mutexes_held = true;
188 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700189 }
190 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700191 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700192 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700193}
194
Ian Rogers56edc432013-01-18 16:51:51 -0800195void BaseMutex::RecordContention(uint64_t blocked_tid, uint64_t owner_tid, uint64_t milli_time_blocked) {
196#if CONTENTION_LOGGING
197 ++contention_count_;
198 wait_time_ += static_cast<uint32_t>(milli_time_blocked); // May overflow.
199 // This code is intentionally racy as it is only used for diagnostics.
200 uint32_t slot = cur_content_log_entry_;
201 if (contention_log_[slot].blocked_tid == blocked_tid &&
202 contention_log_[slot].owner_tid == blocked_tid) {
203 ++contention_log_[slot].count;
204 } else {
205 uint32_t new_slot;
206 do {
207 slot = cur_content_log_entry_;
208 new_slot = (slot + 1) % kContentionLogSize;
209 } while(!cur_content_log_entry_.CompareAndSwap(slot, new_slot));
210 contention_log_[new_slot].blocked_tid = blocked_tid;
211 contention_log_[new_slot].owner_tid = owner_tid;
212 contention_log_[new_slot].count = 1;
213 }
214#endif
215}
216
Ian Rogers56edc432013-01-18 16:51:51 -0800217void BaseMutex::DumpContention(std::ostream& os) const {
218#if CONTENTION_LOGGING
219 uint32_t wait_time = wait_time_;
220 uint32_t contention_count = contention_count_;
221 if (contention_count == 0) {
222 os << "never contended";
223 } else {
224 os << "contended " << contention_count << " times, average wait of contender " << (wait_time / contention_count) << "ms";
225 SafeMap<uint64_t, size_t> most_common_blocker;
226 SafeMap<uint64_t, size_t> most_common_blocked;
227 typedef SafeMap<uint64_t, size_t>::const_iterator It;
228 for (size_t i = 0; i < kContentionLogSize; ++i) {
229 uint64_t blocked_tid = contention_log_[i].blocked_tid;
230 uint64_t owner_tid = contention_log_[i].owner_tid;
231 uint32_t count = contention_log_[i].count;
232 if (count > 0) {
233 It it = most_common_blocked.find(blocked_tid);
234 if (it != most_common_blocked.end()) {
235 most_common_blocked.Overwrite(blocked_tid, it->second + count);
236 } else {
237 most_common_blocked.Put(blocked_tid, count);
238 }
239 it = most_common_blocker.find(owner_tid);
240 if (it != most_common_blocker.end()) {
241 most_common_blocker.Overwrite(owner_tid, it->second + count);
242 } else {
243 most_common_blocker.Put(owner_tid, count);
244 }
245 }
246 }
247 uint64_t max_tid = 0;
248 size_t max_tid_count = 0;
249 for (It it = most_common_blocked.begin(); it != most_common_blocked.end(); ++it) {
250 if (it->second > max_tid_count) {
251 max_tid = it->first;
252 max_tid_count = it->second;
253 }
254 }
255 if (max_tid != 0) {
256 os << " sample shows most blocked tid=" << max_tid;
257 }
258 max_tid = 0;
259 max_tid_count = 0;
260 for (It it = most_common_blocker.begin(); it != most_common_blocker.end(); ++it) {
261 if (it->second > max_tid_count) {
262 max_tid = it->first;
263 max_tid_count = it->second;
264 }
265 }
266 if (max_tid != 0) {
267 os << " sample shows tid=" << max_tid << " owning during this time";
268 }
269 }
270#endif
271}
272
273
Ian Rogers81d425b2012-09-27 16:03:43 -0700274Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700275 : BaseMutex(name, level), recursive_(recursive), recursion_count_(0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700276#if ART_USE_FUTEXES
277 state_ = 0;
278 exclusive_owner_ = 0;
279 num_contenders_ = 0;
280#elif defined(__BIONIC__) || defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700281 // Use recursive mutexes for bionic and Apple otherwise the
282 // non-recursive mutexes don't have TIDs to check lock ownership of.
Elliott Hughesbbd9d832011-11-07 14:40:00 -0800283 pthread_mutexattr_t attributes;
284 CHECK_MUTEX_CALL(pthread_mutexattr_init, (&attributes));
285 CHECK_MUTEX_CALL(pthread_mutexattr_settype, (&attributes, PTHREAD_MUTEX_RECURSIVE));
286 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, &attributes));
287 CHECK_MUTEX_CALL(pthread_mutexattr_destroy, (&attributes));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700288#else
289 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, NULL));
290#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700291}
292
293Mutex::~Mutex() {
Ian Rogersc604d732012-10-14 16:09:54 -0700294#if ART_USE_FUTEXES
295 if (state_ != 0) {
296 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
297 Runtime* runtime = Runtime::Current();
298 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
299 LOG(shutting_down ? WARNING : FATAL) << "destroying mutex with owner: " << exclusive_owner_;
300 } else {
301 CHECK_EQ(exclusive_owner_, 0U) << "unexpectedly found an owner on unlocked mutex " << name_;
302 CHECK_EQ(num_contenders_, 0) << "unexpectedly found a contender on mutex " << name_;
303 }
304#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700305 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
306 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800307 int rc = pthread_mutex_destroy(&mutex_);
308 if (rc != 0) {
309 errno = rc;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800310 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700311 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700312 Runtime* runtime = Runtime::Current();
313 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughes6b355752012-01-13 16:49:08 -0800314 PLOG(shutting_down ? WARNING : FATAL) << "pthread_mutex_destroy failed for " << name_;
315 }
Ian Rogersc604d732012-10-14 16:09:54 -0700316#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700317}
318
Ian Rogers81d425b2012-09-27 16:03:43 -0700319void Mutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700320 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700321 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700322 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700323 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700324 if (!recursive_ || !IsExclusiveHeld(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 == 0) {
330 // Change state from 0 to 1.
Ian Rogers693ff612013-02-01 10:56:12 -0800331 done = android_atomic_acquire_cas(0, 1, &state_) == 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700332 } else {
333 // Failed to acquire, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800334 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700335 android_atomic_inc(&num_contenders_);
336 if (futex(&state_, FUTEX_WAIT, 1, NULL, NULL, 0) != 0) {
337 if (errno != EAGAIN) {
338 PLOG(FATAL) << "futex wait failed for " << name_;
339 }
340 }
341 android_atomic_dec(&num_contenders_);
342 }
343 } while(!done);
344 DCHECK_EQ(state_, 1);
345 exclusive_owner_ = SafeGetTid(self);
346#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700347 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700348#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700349 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700350 }
351 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700352 if (kDebugLocking) {
353 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
354 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700355 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700356 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700357}
358
Ian Rogers81d425b2012-09-27 16:03:43 -0700359bool Mutex::ExclusiveTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700360 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700361 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700362 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700363 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700364 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700365#if ART_USE_FUTEXES
366 bool done = false;
367 do {
368 int32_t cur_state = state_;
369 if (cur_state == 0) {
370 // Change state from 0 to 1.
Ian Rogers693ff612013-02-01 10:56:12 -0800371 done = android_atomic_acquire_cas(0, 1, &state_) == 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700372 } else {
373 return false;
374 }
375 } while(!done);
376 DCHECK_EQ(state_, 1);
377 exclusive_owner_ = SafeGetTid(self);
378#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700379 int result = pthread_mutex_trylock(&mutex_);
380 if (result == EBUSY) {
381 return false;
382 }
383 if (result != 0) {
384 errno = result;
385 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
386 }
Ian Rogersc604d732012-10-14 16:09:54 -0700387#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700388 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700389 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700390 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700391 if (kDebugLocking) {
392 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
393 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700394 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700395 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700396 return true;
397}
398
Ian Rogers81d425b2012-09-27 16:03:43 -0700399void Mutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700400 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700401 AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700402 recursion_count_--;
403 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700404 if (kDebugLocking) {
405 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
406 << name_ << " " << recursion_count_;
407 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700408 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700409#if ART_USE_FUTEXES
410 bool done = false;
411 do {
412 int32_t cur_state = state_;
413 if (cur_state == 1) {
414 // We're no longer the owner.
415 exclusive_owner_ = 0;
416 // Change state to 0.
Ian Rogers693ff612013-02-01 10:56:12 -0800417 done = android_atomic_release_cas(cur_state, 0, &state_) == 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700418 if (done) { // Spurious fail?
419 // Wake a contender
420 if (num_contenders_ > 0) {
421 futex(&state_, FUTEX_WAKE, 1, NULL, NULL, 0);
422 }
423 }
424 } else {
425 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
426 }
427 } while(!done);
428#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700429 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700430#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700431 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700432}
433
Ian Rogers81d425b2012-09-27 16:03:43 -0700434bool Mutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700435 DCHECK(self == NULL || self == Thread::Current());
436 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
437 if (kDebugLocking) {
438 // Sanity debug check that if we think it is locked we have it in our held mutexes.
Brian Carlstrom9e419ca2012-11-27 11:31:49 -0800439 if (result && self != NULL && level_ != kMonitorLock && !gAborting) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700440 CHECK_EQ(self->GetHeldMutex(level_), this);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700441 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700442 }
443 return result;
Elliott Hughesf1498432012-03-28 19:34:27 -0700444}
445
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700446uint64_t Mutex::GetExclusiveOwnerTid() const {
Ian Rogersc604d732012-10-14 16:09:54 -0700447#if ART_USE_FUTEXES
448 return exclusive_owner_;
449#elif defined(__BIONIC__)
Elliott Hughesf1498432012-03-28 19:34:27 -0700450 return static_cast<uint64_t>((mutex_.value >> 16) & 0xffff);
Elliott Hughes3147a232011-10-12 15:55:07 -0700451#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700452 return reinterpret_cast<const glibc_pthread_mutex_t*>(&mutex_)->owner;
Elliott Hughescf044312012-01-23 18:48:51 -0800453#elif defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700454 const darwin_pthread_mutex_t* dpmutex = reinterpret_cast<const darwin_pthread_mutex_t*>(&mutex_);
455 pthread_t owner = dpmutex->darwin_pthread_mutex_owner;
Brian Carlstrombd93c302012-08-27 16:58:28 -0700456 // 0 for unowned, -1 for PTHREAD_MTX_TID_SWITCHING
457 // TODO: should we make darwin_pthread_mutex_owner volatile and recheck until not -1?
Brian Carlstromf3a26412012-08-24 11:06:02 -0700458 if ((owner == (pthread_t)0) || (owner == (pthread_t)-1)) {
459 return 0;
460 }
461 uint64_t tid;
462 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
463 return tid;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700464#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700465#error unsupported C library
Elliott Hughes8daa0922011-09-11 13:46:25 -0700466#endif
467}
468
Ian Rogers56edc432013-01-18 16:51:51 -0800469void Mutex::Dump(std::ostream& os) const {
470 os << (recursive_ ? "recursive " : "non-recursive ")
471 << name_
472 << " level=" << static_cast<int>(level_)
473 << " rec=" << recursion_count_
474 << " owner=" << GetExclusiveOwnerTid() << " ";
475 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700476}
477
478std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800479 mu.Dump(os);
480 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700481}
482
Ian Rogers81d425b2012-09-27 16:03:43 -0700483ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level) :
484 BaseMutex(name, level)
485#if ART_USE_FUTEXES
486 , state_(0), exclusive_owner_(0), num_pending_readers_(0), num_pending_writers_(0)
487#endif
488{
489#if !ART_USE_FUTEXES
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700490 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, NULL));
Ian Rogers81d425b2012-09-27 16:03:43 -0700491#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700492}
493
494ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700495#if ART_USE_FUTEXES
496 CHECK_EQ(state_, 0);
497 CHECK_EQ(exclusive_owner_, 0U);
498 CHECK_EQ(num_pending_readers_, 0);
499 CHECK_EQ(num_pending_writers_, 0);
500#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700501 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
502 // may still be using locks.
503 int rc = pthread_rwlock_destroy(&rwlock_);
504 if (rc != 0) {
505 errno = rc;
506 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700507 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700508 Runtime* runtime = Runtime::Current();
509 bool shutting_down = runtime == NULL || runtime->IsShuttingDown();
510 PLOG(shutting_down ? WARNING : FATAL) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800511 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700512#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700513}
514
Ian Rogers81d425b2012-09-27 16:03:43 -0700515void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700516 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700517 AssertNotExclusiveHeld(self);
518#if ART_USE_FUTEXES
519 bool done = false;
520 do {
521 int32_t cur_state = state_;
522 if (cur_state == 0) {
523 // Change state from 0 to -1.
Ian Rogers693ff612013-02-01 10:56:12 -0800524 done = android_atomic_acquire_cas(0, -1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700525 } else {
526 // Failed to acquire, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800527 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700528 android_atomic_inc(&num_pending_writers_);
529 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
530 if (errno != EAGAIN) {
531 PLOG(FATAL) << "futex wait failed for " << name_;
532 }
533 }
534 android_atomic_dec(&num_pending_writers_);
535 }
536 } while(!done);
Ian Rogersab470162012-09-29 23:06:53 -0700537 DCHECK_EQ(state_, -1);
538 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700539#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700540 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700541#endif
542 RegisterAsLocked(self);
543 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700544}
545
Ian Rogers81d425b2012-09-27 16:03:43 -0700546void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700547 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700548 AssertExclusiveHeld(self);
549 RegisterAsUnlocked(self);
550#if ART_USE_FUTEXES
551 bool done = false;
552 do {
553 int32_t cur_state = state_;
554 if (cur_state == -1) {
555 // We're no longer the owner.
556 exclusive_owner_ = 0;
557 // Change state from -1 to 0.
Ian Rogers693ff612013-02-01 10:56:12 -0800558 done = android_atomic_release_cas(-1, 0, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700559 if (done) { // cmpxchg may fail due to noise?
560 // Wake any waiters.
561 if (num_pending_readers_ > 0 || num_pending_writers_ > 0) {
562 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
563 }
564 }
565 } else {
566 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
567 }
568 } while(!done);
569#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700570 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700571#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700572}
573
Ian Rogers66aee5c2012-08-15 17:17:47 -0700574#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700575bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700576 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700577#if ART_USE_FUTEXES
578 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700579 timespec end_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800580 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700581 do {
582 int32_t cur_state = state_;
583 if (cur_state == 0) {
584 // Change state from 0 to -1.
Ian Rogers693ff612013-02-01 10:56:12 -0800585 done = android_atomic_acquire_cas(0, -1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700586 } else {
587 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700588 timespec now_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800589 InitTimeSpec(true, CLOCK_REALTIME, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700590 timespec rel_ts;
591 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
592 return false; // Timed out.
593 }
Ian Rogers56edc432013-01-18 16:51:51 -0800594 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700595 android_atomic_inc(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700596 if (futex(&state_, FUTEX_WAIT, cur_state, &rel_ts, NULL, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700597 if (errno == ETIMEDOUT) {
598 android_atomic_dec(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700599 return false; // Timed out.
600 } else if (errno != EAGAIN && errno != EINTR) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700601 PLOG(FATAL) << "timed futex wait failed for " << name_;
602 }
603 }
604 android_atomic_dec(&num_pending_writers_);
605 }
606 } while(!done);
Ian Rogers01ae5802012-09-28 16:14:01 -0700607 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700608#else
Ian Rogersc604d732012-10-14 16:09:54 -0700609 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700610 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700611 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700612 if (result == ETIMEDOUT) {
613 return false;
614 }
615 if (result != 0) {
616 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700617 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700618 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700619#endif
620 RegisterAsLocked(self);
621 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700622 return true;
623}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700624#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700625
Ian Rogers81d425b2012-09-27 16:03:43 -0700626bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700627 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700628#if ART_USE_FUTEXES
629 bool done = false;
630 do {
631 int32_t cur_state = state_;
632 if (cur_state >= 0) {
633 // Add as an extra reader.
Ian Rogers693ff612013-02-01 10:56:12 -0800634 done = android_atomic_acquire_cas(cur_state, cur_state + 1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700635 } else {
636 // Owner holds it exclusively.
637 return false;
638 }
639 } while(!done);
640#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700641 int result = pthread_rwlock_tryrdlock(&rwlock_);
642 if (result == EBUSY) {
643 return false;
644 }
645 if (result != 0) {
646 errno = result;
647 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
648 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700649#endif
650 RegisterAsLocked(self);
651 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700652 return true;
653}
654
Ian Rogers81d425b2012-09-27 16:03:43 -0700655bool ReaderWriterMutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700656 DCHECK(self == NULL || self == Thread::Current());
657 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700658 if (kDebugLocking) {
659 // Sanity that if the pthread thinks we own the lock the Thread agrees.
Ian Rogers01ae5802012-09-28 16:14:01 -0700660 if (self != NULL && result) {
661 CHECK_EQ(self->GetHeldMutex(level_), this);
662 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700663 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700664 return result;
665}
666
Ian Rogers81d425b2012-09-27 16:03:43 -0700667bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700668 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700669 bool result;
670 if (UNLIKELY(self == NULL)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700671 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700672 } else {
673 result = (self->GetHeldMutex(level_) == this);
674 }
675 return result;
676}
677
678uint64_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700679#if ART_USE_FUTEXES
Ian Rogers56edc432013-01-18 16:51:51 -0800680 int32_t state = state_;
681 if (state == 0) {
682 return 0; // No owner.
683 } else if (state > 0) {
684 return -1; // Shared.
685 } else {
686 return exclusive_owner_;
687 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700688#else
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800689#if defined(__BIONIC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700690 return rwlock_.writerThreadId;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800691#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700692 return reinterpret_cast<const glibc_pthread_rwlock_t*>(&rwlock_)->writer;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800693#elif defined(__APPLE__)
Ian Rogers81d425b2012-09-27 16:03:43 -0700694 const darwin_pthread_rwlock_t*
695 dprwlock = reinterpret_cast<const darwin_pthread_rwlock_t*>(&rwlock_);
Brian Carlstromf3a26412012-08-24 11:06:02 -0700696 pthread_t owner = dprwlock->darwin_pthread_rwlock_owner;
697 if (owner == (pthread_t)0) {
698 return 0;
699 }
700 uint64_t tid;
701 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
702 return tid;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800703#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700704#error unsupported C library
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800705#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700706#endif
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800707}
708
Ian Rogers56edc432013-01-18 16:51:51 -0800709void ReaderWriterMutex::Dump(std::ostream& os) const {
710 os << name_
711 << " level=" << static_cast<int>(level_)
712 << " owner=" << GetExclusiveOwnerTid() << " ";
713 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700714}
715
716std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800717 mu.Dump(os);
718 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700719}
720
Ian Rogersc604d732012-10-14 16:09:54 -0700721ConditionVariable::ConditionVariable(const std::string& name, Mutex& guard)
722 : name_(name), guard_(guard) {
723#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800724 sequence_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700725 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700726#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700727 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, NULL));
Ian Rogersc604d732012-10-14 16:09:54 -0700728#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700729}
730
731ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800732#if ART_USE_FUTEXES
733 if (num_waiters_!= 0) {
734 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
735 Runtime* runtime = Runtime::Current();
736 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Ian Rogersd45f2012012-11-28 11:46:23 -0800737 LOG(shutting_down ? WARNING : FATAL) << "ConditionVariable::~ConditionVariable for " << name_
738 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800739 }
740#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700741 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
742 // may still be using condition variables.
743 int rc = pthread_cond_destroy(&cond_);
744 if (rc != 0) {
745 errno = rc;
Ian Rogers50b35e22012-10-04 10:09:15 -0700746 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700747 Runtime* runtime = Runtime::Current();
748 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughese62934d2012-04-09 11:24:29 -0700749 PLOG(shutting_down ? WARNING : FATAL) << "pthread_cond_destroy failed for " << name_;
750 }
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::Broadcast(Thread* self) {
755 DCHECK(self == NULL || self == Thread::Current());
756 // TODO: enable below, there's a race in thread creation that causes false failures currently.
757 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700758 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700759#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800760 if (num_waiters_ > 0) {
761 android_atomic_inc(&sequence_); // Indicate the broadcast occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700762 bool done = false;
763 do {
Ian Rogersd45f2012012-11-28 11:46:23 -0800764 int32_t cur_sequence = sequence_;
765 // Requeue waiters onto mutex. The waiter holds the contender count on the mutex high ensuring
766 // mutex unlocks will awaken the requeued waiter thread.
767 done = futex(&sequence_, FUTEX_CMP_REQUEUE, 0,
Ian Rogers5bd97c42012-11-27 02:38:26 -0800768 reinterpret_cast<const timespec*>(std::numeric_limits<int32_t>::max()),
Ian Rogersd45f2012012-11-28 11:46:23 -0800769 &guard_.state_, cur_sequence) != -1;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800770 if (!done) {
771 if (errno != EAGAIN) {
772 PLOG(FATAL) << "futex cmp requeue failed for " << name_;
773 }
Ian Rogers5bd97c42012-11-27 02:38:26 -0800774 }
Ian Rogersc604d732012-10-14 16:09:54 -0700775 } while (!done);
776 }
777#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700778 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700779#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700780}
781
Ian Rogersc604d732012-10-14 16:09:54 -0700782void ConditionVariable::Signal(Thread* self) {
783 DCHECK(self == NULL || self == Thread::Current());
784 guard_.AssertExclusiveHeld(self);
785#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800786 if (num_waiters_ > 0) {
787 android_atomic_inc(&sequence_); // Indicate a signal occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700788 // Futex wake 1 waiter who will then come and in contend on mutex. It'd be nice to requeue them
789 // to avoid this, however, requeueing can only move all waiters.
Ian Rogersd45f2012012-11-28 11:46:23 -0800790 int num_woken = futex(&sequence_, FUTEX_WAKE, 1, NULL, NULL, 0);
791 // Check something was woken or else we changed sequence_ before they had chance to wait.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800792 CHECK((num_woken == 0) || (num_woken == 1));
Ian Rogersc604d732012-10-14 16:09:54 -0700793 }
794#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700795 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700796#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700797}
798
Ian Rogersc604d732012-10-14 16:09:54 -0700799void ConditionVariable::Wait(Thread* self) {
800 DCHECK(self == NULL || self == Thread::Current());
801 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700802 unsigned int old_recursion_count = guard_.recursion_count_;
803#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700804 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800805 // Ensure the Mutex is contended so that requeued threads are awoken.
806 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700807 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800808 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700809 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800810 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, NULL, NULL, 0) != 0) {
811 // Futex failed, check it is an expected error.
812 // EAGAIN == EWOULDBLK, so we let the caller try again.
813 // EINTR implies a signal was sent to this thread.
814 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700815 PLOG(FATAL) << "futex wait failed for " << name_;
816 }
817 }
818 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800819 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700820 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800821 // We awoke and so no longer require awakes from the guard_'s unlock.
822 CHECK_GE(guard_.num_contenders_, 0);
823 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700824#else
825 guard_.recursion_count_ = 0;
826 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
827#endif
828 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700829}
830
Ian Rogersc604d732012-10-14 16:09:54 -0700831void ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
832 DCHECK(self == NULL || self == Thread::Current());
833 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700834 unsigned int old_recursion_count = guard_.recursion_count_;
835#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700836 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800837 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700838 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800839 // Ensure the Mutex is contended so that requeued threads are awoken.
840 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700841 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800842 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700843 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800844 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, &rel_ts, NULL, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700845 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800846 // Timed out we're done.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800847 } else if ((errno == EINTR) || (errno == EAGAIN)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800848 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700849 } else {
850 PLOG(FATAL) << "timed futex wait failed for " << name_;
851 }
852 }
853 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800854 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700855 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800856 // We awoke and so no longer require awakes from the guard_'s unlock.
857 CHECK_GE(guard_.num_contenders_, 0);
858 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700859#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700860#ifdef HAVE_TIMEDWAIT_MONOTONIC
861#define TIMEDWAIT pthread_cond_timedwait_monotonic
Ian Rogersc604d732012-10-14 16:09:54 -0700862 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700863#else
864#define TIMEDWAIT pthread_cond_timedwait
Ian Rogersc604d732012-10-14 16:09:54 -0700865 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700866#endif
Ian Rogersc604d732012-10-14 16:09:54 -0700867 guard_.recursion_count_ = 0;
868 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700869 InitTimeSpec(true, clock, ms, ns, &ts);
870 int rc = TEMP_FAILURE_RETRY(TIMEDWAIT(&cond_, &guard_.mutex_, &ts));
Elliott Hughes5f791332011-09-15 17:45:30 -0700871 if (rc != 0 && rc != ETIMEDOUT) {
872 errno = rc;
873 PLOG(FATAL) << "TimedWait failed for " << name_;
874 }
Ian Rogersc604d732012-10-14 16:09:54 -0700875#endif
876 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700877}
878
Elliott Hughese62934d2012-04-09 11:24:29 -0700879} // namespace art