blob: b048bbb1ec57123bd78f85398068472b3eaaee09 [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
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070022#include "atomic.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080023#include "base/logging.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070024#include "cutils/atomic.h"
Ian Rogers693ff612013-02-01 10:56:12 -080025#include "cutils/atomic-inline.h"
26#include "mutex-inl.h"
Elliott Hughes6b355752012-01-13 16:49:08 -080027#include "runtime.h"
Ian Rogersc604d732012-10-14 16:09:54 -070028#include "scoped_thread_state_change.h"
Ian Rogers04d7aa92013-03-16 14:29:17 -070029#include "thread-inl.h"
Elliott Hughesffb465f2012-03-01 18:46:05 -080030#include "utils.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070031
32namespace art {
33
Ian Rogersc604d732012-10-14 16:09:54 -070034#if ART_USE_FUTEXES
35static bool ComputeRelativeTimeSpec(timespec* result_ts, const timespec& lhs, const timespec& rhs) {
Brian Carlstromfb6996f2013-07-18 18:21:14 -070036 const int32_t one_sec = 1000 * 1000 * 1000; // one second in nanoseconds.
Ian Rogersc604d732012-10-14 16:09:54 -070037 result_ts->tv_sec = lhs.tv_sec - rhs.tv_sec;
38 result_ts->tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
39 if (result_ts->tv_nsec < 0) {
40 result_ts->tv_sec--;
41 result_ts->tv_nsec += one_sec;
42 } else if (result_ts->tv_nsec > one_sec) {
43 result_ts->tv_sec++;
44 result_ts->tv_nsec -= one_sec;
45 }
46 return result_ts->tv_sec < 0;
47}
48#endif
49
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070050struct AllMutexData {
51 // A guard for all_mutexes_ that's not a mutex (Mutexes must CAS to acquire and busy wait).
52 AtomicInteger all_mutexes_guard;
53 // All created mutexes guarded by all_mutexes_guard_.
54 std::set<BaseMutex*>* all_mutexes;
55 AllMutexData() : all_mutexes(NULL) {}
56};
57static struct AllMutexData all_mutex_data[kAllMutexDataSize];
Ian Rogers56edc432013-01-18 16:51:51 -080058
59class ScopedAllMutexesLock {
60 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -070061 explicit ScopedAllMutexesLock(const BaseMutex* mutex) : mutex_(mutex) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070062 while (!all_mutex_data->all_mutexes_guard.compare_and_swap(0, reinterpret_cast<int32_t>(mutex))) {
Ian Rogers56edc432013-01-18 16:51:51 -080063 NanoSleep(100);
64 }
65 }
66 ~ScopedAllMutexesLock() {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070067 while (!all_mutex_data->all_mutexes_guard.compare_and_swap(reinterpret_cast<int32_t>(mutex_), 0)) {
Ian Rogers56edc432013-01-18 16:51:51 -080068 NanoSleep(100);
69 }
70 }
71 private:
72 const BaseMutex* const mutex_;
73};
Ian Rogers56edc432013-01-18 16:51:51 -080074
75BaseMutex::BaseMutex(const char* name, LockLevel level) : level_(level), name_(name) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070076 if (kLogLockContentions) {
77 ScopedAllMutexesLock mu(this);
78 std::set<BaseMutex*>** all_mutexes_ptr = &all_mutex_data->all_mutexes;
79 if (*all_mutexes_ptr == NULL) {
80 // We leak the global set of all mutexes to avoid ordering issues in global variable
81 // construction/destruction.
82 *all_mutexes_ptr = new std::set<BaseMutex*>();
83 }
84 (*all_mutexes_ptr)->insert(this);
Ian Rogers56edc432013-01-18 16:51:51 -080085 }
Ian Rogers56edc432013-01-18 16:51:51 -080086}
87
88BaseMutex::~BaseMutex() {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070089 if (kLogLockContentions) {
90 ScopedAllMutexesLock mu(this);
91 all_mutex_data->all_mutexes->erase(this);
92 }
Ian Rogers56edc432013-01-18 16:51:51 -080093}
94
95void BaseMutex::DumpAll(std::ostream& os) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070096 if (kLogLockContentions) {
97 os << "Mutex logging:\n";
98 ScopedAllMutexesLock mu(reinterpret_cast<const BaseMutex*>(-1));
99 std::set<BaseMutex*>* all_mutexes = all_mutex_data->all_mutexes;
100 if (all_mutexes == NULL) {
101 // No mutexes have been created yet during at startup.
102 return;
103 }
104 typedef std::set<BaseMutex*>::const_iterator It;
105 os << "(Contented)\n";
106 for (It it = all_mutexes->begin(); it != all_mutexes->end(); ++it) {
107 BaseMutex* mutex = *it;
108 if (mutex->HasEverContended()) {
109 mutex->Dump(os);
110 os << "\n";
111 }
112 }
113 os << "(Never contented)\n";
114 for (It it = all_mutexes->begin(); it != all_mutexes->end(); ++it) {
115 BaseMutex* mutex = *it;
116 if (!mutex->HasEverContended()) {
117 mutex->Dump(os);
118 os << "\n";
119 }
120 }
Ian Rogers56edc432013-01-18 16:51:51 -0800121 }
Ian Rogers56edc432013-01-18 16:51:51 -0800122}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700123
Ian Rogers81d425b2012-09-27 16:03:43 -0700124void BaseMutex::CheckSafeToWait(Thread* self) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700125 if (self == NULL) {
126 CheckUnattachedThread(level_);
127 return;
128 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700129 if (kDebugLocking) {
130 CHECK(self->GetHeldMutex(level_) == this) << "Waiting on unacquired mutex: " << name_;
131 bool bad_mutexes_held = false;
Elliott Hughes0f827162013-02-26 12:12:58 -0800132 for (int i = kLockLevelCount - 1; i >= 0; --i) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700133 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700134 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700135 if (held_mutex != NULL) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800136 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
137 << "(level " << LockLevel(i) << ") while performing wait on "
138 << "\"" << name_ << "\" (level " << level_ << ")";
Ian Rogers25fd14b2012-09-05 10:56:38 -0700139 bad_mutexes_held = true;
140 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700141 }
142 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700143 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700144 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700145}
146
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700147inline void BaseMutex::ContentionLogData::AddToWaitTime(uint64_t value) {
148 if (kLogLockContentions) {
149 // Atomically add value to wait_time.
150 uint64_t new_val, old_val;
151 volatile int64_t* addr = reinterpret_cast<volatile int64_t*>(&wait_time);
152 volatile const int64_t* caddr = const_cast<volatile const int64_t*>(addr);
153 do {
154 old_val = static_cast<uint64_t>(QuasiAtomic::Read64(caddr));
155 new_val = old_val + value;
156 } while (!QuasiAtomic::Cas64(static_cast<int64_t>(old_val), static_cast<int64_t>(new_val), addr));
157 }
158}
159
Brian Carlstrom0de79852013-07-25 22:29:58 -0700160void BaseMutex::RecordContention(uint64_t blocked_tid,
161 uint64_t owner_tid,
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700162 uint64_t nano_time_blocked) {
163 if (kLogLockContentions) {
164 ContentionLogData* data = contetion_log_data_;
165 ++(data->contention_count);
166 data->AddToWaitTime(nano_time_blocked);
167 ContentionLogEntry* log = data->contention_log;
168 // This code is intentionally racy as it is only used for diagnostics.
169 uint32_t slot = data->cur_content_log_entry;
170 if (log[slot].blocked_tid == blocked_tid &&
171 log[slot].owner_tid == blocked_tid) {
172 ++log[slot].count;
173 } else {
174 uint32_t new_slot;
175 do {
176 slot = data->cur_content_log_entry;
177 new_slot = (slot + 1) % kContentionLogSize;
178 } while (!data->cur_content_log_entry.compare_and_swap(slot, new_slot));
179 log[new_slot].blocked_tid = blocked_tid;
180 log[new_slot].owner_tid = owner_tid;
181 log[new_slot].count = 1;
182 }
Ian Rogers56edc432013-01-18 16:51:51 -0800183 }
Ian Rogers56edc432013-01-18 16:51:51 -0800184}
185
Ian Rogers56edc432013-01-18 16:51:51 -0800186void BaseMutex::DumpContention(std::ostream& os) const {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700187 if (kLogLockContentions) {
188 const ContentionLogData* data = contetion_log_data_;
189 const ContentionLogEntry* log = data->contention_log;
190 uint64_t wait_time = data->wait_time;
191 uint32_t contention_count = data->contention_count;
192 if (contention_count == 0) {
193 os << "never contended";
194 } else {
195 os << "contended " << contention_count
196 << " times, average wait of contender " << PrettyDuration(wait_time / contention_count);
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 = log[i].blocked_tid;
202 uint64_t owner_tid = log[i].owner_tid;
203 uint32_t count = 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 }
Ian Rogers56edc432013-01-18 16:51:51 -0800217 }
218 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700219 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 }
Ian Rogers56edc432013-01-18 16:51:51 -0800226 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700227 if (max_tid != 0) {
228 os << " sample shows most blocked tid=" << max_tid;
Ian Rogers56edc432013-01-18 16:51:51 -0800229 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700230 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 }
Ian Rogers56edc432013-01-18 16:51:51 -0800241 }
242 }
Ian Rogers56edc432013-01-18 16:51:51 -0800243}
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_;
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700301 if (LIKELY(cur_state == 0)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700302 // 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.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700306 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersc604d732012-10-14 16:09:54 -0700307 android_atomic_inc(&num_contenders_);
308 if (futex(&state_, FUTEX_WAIT, 1, NULL, NULL, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700309 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
310 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
311 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700312 PLOG(FATAL) << "futex wait failed for " << name_;
313 }
314 }
315 android_atomic_dec(&num_contenders_);
316 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700317 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700318 DCHECK_EQ(state_, 1);
319 exclusive_owner_ = SafeGetTid(self);
320#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700321 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700322#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700323 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700324 }
325 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700326 if (kDebugLocking) {
327 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
328 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700329 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700330 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700331}
332
Ian Rogers81d425b2012-09-27 16:03:43 -0700333bool Mutex::ExclusiveTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700334 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700335 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700336 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700337 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700338 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700339#if ART_USE_FUTEXES
340 bool done = false;
341 do {
342 int32_t cur_state = state_;
343 if (cur_state == 0) {
344 // Change state from 0 to 1.
Ian Rogers693ff612013-02-01 10:56:12 -0800345 done = android_atomic_acquire_cas(0, 1, &state_) == 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700346 } else {
347 return false;
348 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700349 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700350 DCHECK_EQ(state_, 1);
351 exclusive_owner_ = SafeGetTid(self);
352#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700353 int result = pthread_mutex_trylock(&mutex_);
354 if (result == EBUSY) {
355 return false;
356 }
357 if (result != 0) {
358 errno = result;
359 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
360 }
Ian Rogersc604d732012-10-14 16:09:54 -0700361#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700362 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700363 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700364 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700365 if (kDebugLocking) {
366 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
367 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700368 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700369 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700370 return true;
371}
372
Ian Rogers81d425b2012-09-27 16:03:43 -0700373void Mutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700374 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700375 AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700376 recursion_count_--;
377 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700378 if (kDebugLocking) {
379 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
380 << name_ << " " << recursion_count_;
381 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700382 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700383#if ART_USE_FUTEXES
384 bool done = false;
385 do {
386 int32_t cur_state = state_;
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700387 if (LIKELY(cur_state == 1)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700388 // We're no longer the owner.
389 exclusive_owner_ = 0;
390 // Change state to 0.
Ian Rogers693ff612013-02-01 10:56:12 -0800391 done = android_atomic_release_cas(cur_state, 0, &state_) == 0;
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700392 if (LIKELY(done)) { // Spurious fail?
Ian Rogersc604d732012-10-14 16:09:54 -0700393 // Wake a contender
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700394 if (UNLIKELY(num_contenders_ > 0)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700395 futex(&state_, FUTEX_WAKE, 1, NULL, NULL, 0);
396 }
397 }
398 } else {
Ian Rogersc4ee12e2013-05-16 11:19:53 -0700399 // Logging acquires the logging lock, avoid infinite recursion in that case.
400 if (this != Locks::logging_lock_) {
401 LOG(FATAL) << "Unexpected state_ in unlock " << cur_state << " for " << name_;
402 } else {
403 LogMessageData data(__FILE__, __LINE__, INTERNAL_FATAL, -1);
404 LogMessage::LogLine(data, StringPrintf("Unexpected state_ %d in unlock for %s",
405 cur_state, name_).c_str());
406 _exit(1);
407 }
Ian Rogersc604d732012-10-14 16:09:54 -0700408 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700409 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700410#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700411 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700412#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700413 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700414}
415
Ian Rogers56edc432013-01-18 16:51:51 -0800416void Mutex::Dump(std::ostream& os) const {
417 os << (recursive_ ? "recursive " : "non-recursive ")
418 << name_
419 << " level=" << static_cast<int>(level_)
420 << " rec=" << recursion_count_
421 << " owner=" << GetExclusiveOwnerTid() << " ";
422 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700423}
424
425std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800426 mu.Dump(os);
427 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700428}
429
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700430ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level)
431 : BaseMutex(name, level)
Ian Rogers81d425b2012-09-27 16:03:43 -0700432#if ART_USE_FUTEXES
433 , state_(0), exclusive_owner_(0), num_pending_readers_(0), num_pending_writers_(0)
434#endif
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700435{ // NOLINT(whitespace/braces)
Ian Rogers81d425b2012-09-27 16:03:43 -0700436#if !ART_USE_FUTEXES
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700437 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, NULL));
Ian Rogers81d425b2012-09-27 16:03:43 -0700438#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700439}
440
441ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700442#if ART_USE_FUTEXES
443 CHECK_EQ(state_, 0);
444 CHECK_EQ(exclusive_owner_, 0U);
445 CHECK_EQ(num_pending_readers_, 0);
446 CHECK_EQ(num_pending_writers_, 0);
447#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700448 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
449 // may still be using locks.
450 int rc = pthread_rwlock_destroy(&rwlock_);
451 if (rc != 0) {
452 errno = rc;
453 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700454 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700455 Runtime* runtime = Runtime::Current();
456 bool shutting_down = runtime == NULL || runtime->IsShuttingDown();
457 PLOG(shutting_down ? WARNING : FATAL) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800458 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700459#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700460}
461
Ian Rogers81d425b2012-09-27 16:03:43 -0700462void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700463 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700464 AssertNotExclusiveHeld(self);
465#if ART_USE_FUTEXES
466 bool done = false;
467 do {
468 int32_t cur_state = state_;
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700469 if (LIKELY(cur_state == 0)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700470 // Change state from 0 to -1.
Ian Rogers693ff612013-02-01 10:56:12 -0800471 done = android_atomic_acquire_cas(0, -1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700472 } else {
473 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700474 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogers81d425b2012-09-27 16:03:43 -0700475 android_atomic_inc(&num_pending_writers_);
476 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700477 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
478 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
479 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700480 PLOG(FATAL) << "futex wait failed for " << name_;
481 }
482 }
483 android_atomic_dec(&num_pending_writers_);
484 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700485 } while (!done);
Ian Rogersab470162012-09-29 23:06:53 -0700486 DCHECK_EQ(state_, -1);
487 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700488#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700489 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700490#endif
491 RegisterAsLocked(self);
492 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700493}
494
Ian Rogers81d425b2012-09-27 16:03:43 -0700495void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700496 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700497 AssertExclusiveHeld(self);
498 RegisterAsUnlocked(self);
499#if ART_USE_FUTEXES
500 bool done = false;
501 do {
502 int32_t cur_state = state_;
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700503 if (LIKELY(cur_state == -1)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700504 // We're no longer the owner.
505 exclusive_owner_ = 0;
506 // Change state from -1 to 0.
Ian Rogers693ff612013-02-01 10:56:12 -0800507 done = android_atomic_release_cas(-1, 0, &state_) == 0;
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700508 if (LIKELY(done)) { // cmpxchg may fail due to noise?
Ian Rogers81d425b2012-09-27 16:03:43 -0700509 // Wake any waiters.
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700510 if (UNLIKELY(num_pending_readers_ > 0 || num_pending_writers_ > 0)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700511 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
512 }
513 }
514 } else {
515 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
516 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700517 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700518#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700519 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700520#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700521}
522
Ian Rogers66aee5c2012-08-15 17:17:47 -0700523#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700524bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700525 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700526#if ART_USE_FUTEXES
527 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700528 timespec end_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800529 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700530 do {
531 int32_t cur_state = state_;
532 if (cur_state == 0) {
533 // Change state from 0 to -1.
Ian Rogers693ff612013-02-01 10:56:12 -0800534 done = android_atomic_acquire_cas(0, -1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700535 } else {
536 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700537 timespec now_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800538 InitTimeSpec(true, CLOCK_REALTIME, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700539 timespec rel_ts;
540 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
541 return false; // Timed out.
542 }
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700543 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogers81d425b2012-09-27 16:03:43 -0700544 android_atomic_inc(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700545 if (futex(&state_, FUTEX_WAIT, cur_state, &rel_ts, NULL, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700546 if (errno == ETIMEDOUT) {
547 android_atomic_dec(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700548 return false; // Timed out.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700549 } else if ((errno != EAGAIN) && (errno != EINTR)) {
550 // EAGAIN and EINTR both indicate a spurious failure,
551 // recompute the relative time out from now and try again.
552 // We don't use TEMP_FAILURE_RETRY so we can recompute rel_ts;
Ian Rogers81d425b2012-09-27 16:03:43 -0700553 PLOG(FATAL) << "timed futex wait failed for " << name_;
554 }
555 }
556 android_atomic_dec(&num_pending_writers_);
557 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700558 } while (!done);
Ian Rogers01ae5802012-09-28 16:14:01 -0700559 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700560#else
Ian Rogersc604d732012-10-14 16:09:54 -0700561 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700562 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700563 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700564 if (result == ETIMEDOUT) {
565 return false;
566 }
567 if (result != 0) {
568 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700569 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700570 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700571#endif
572 RegisterAsLocked(self);
573 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700574 return true;
575}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700576#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700577
Ian Rogers81d425b2012-09-27 16:03:43 -0700578bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700579 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700580#if ART_USE_FUTEXES
581 bool done = false;
582 do {
583 int32_t cur_state = state_;
584 if (cur_state >= 0) {
585 // Add as an extra reader.
Ian Rogers693ff612013-02-01 10:56:12 -0800586 done = android_atomic_acquire_cas(cur_state, cur_state + 1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700587 } else {
588 // Owner holds it exclusively.
589 return false;
590 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700591 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700592#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700593 int result = pthread_rwlock_tryrdlock(&rwlock_);
594 if (result == EBUSY) {
595 return false;
596 }
597 if (result != 0) {
598 errno = result;
599 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
600 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700601#endif
602 RegisterAsLocked(self);
603 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700604 return true;
605}
606
Ian Rogers81d425b2012-09-27 16:03:43 -0700607bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700608 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700609 bool result;
610 if (UNLIKELY(self == NULL)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700611 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700612 } else {
613 result = (self->GetHeldMutex(level_) == this);
614 }
615 return result;
616}
617
Ian Rogers56edc432013-01-18 16:51:51 -0800618void ReaderWriterMutex::Dump(std::ostream& os) const {
619 os << name_
620 << " level=" << static_cast<int>(level_)
621 << " owner=" << GetExclusiveOwnerTid() << " ";
622 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700623}
624
625std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800626 mu.Dump(os);
627 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700628}
629
Ian Rogers23055dc2013-04-18 16:29:16 -0700630ConditionVariable::ConditionVariable(const char* name, Mutex& guard)
Ian Rogersc604d732012-10-14 16:09:54 -0700631 : name_(name), guard_(guard) {
632#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800633 sequence_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700634 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700635#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700636 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, NULL));
Ian Rogersc604d732012-10-14 16:09:54 -0700637#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700638}
639
640ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800641#if ART_USE_FUTEXES
642 if (num_waiters_!= 0) {
643 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
644 Runtime* runtime = Runtime::Current();
645 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Ian Rogersd45f2012012-11-28 11:46:23 -0800646 LOG(shutting_down ? WARNING : FATAL) << "ConditionVariable::~ConditionVariable for " << name_
647 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800648 }
649#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700650 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
651 // may still be using condition variables.
652 int rc = pthread_cond_destroy(&cond_);
653 if (rc != 0) {
654 errno = rc;
Ian Rogers50b35e22012-10-04 10:09:15 -0700655 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700656 Runtime* runtime = Runtime::Current();
657 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughese62934d2012-04-09 11:24:29 -0700658 PLOG(shutting_down ? WARNING : FATAL) << "pthread_cond_destroy failed for " << name_;
659 }
Ian Rogersc604d732012-10-14 16:09:54 -0700660#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700661}
662
Ian Rogersc604d732012-10-14 16:09:54 -0700663void ConditionVariable::Broadcast(Thread* self) {
664 DCHECK(self == NULL || self == Thread::Current());
665 // TODO: enable below, there's a race in thread creation that causes false failures currently.
666 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700667 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700668#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800669 if (num_waiters_ > 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700670 android_atomic_inc(&sequence_); // Indicate the broadcast occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700671 bool done = false;
672 do {
Ian Rogersd45f2012012-11-28 11:46:23 -0800673 int32_t cur_sequence = sequence_;
674 // Requeue waiters onto mutex. The waiter holds the contender count on the mutex high ensuring
675 // mutex unlocks will awaken the requeued waiter thread.
676 done = futex(&sequence_, FUTEX_CMP_REQUEUE, 0,
Ian Rogers5bd97c42012-11-27 02:38:26 -0800677 reinterpret_cast<const timespec*>(std::numeric_limits<int32_t>::max()),
Ian Rogersd45f2012012-11-28 11:46:23 -0800678 &guard_.state_, cur_sequence) != -1;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800679 if (!done) {
680 if (errno != EAGAIN) {
681 PLOG(FATAL) << "futex cmp requeue failed for " << name_;
682 }
Ian Rogers5bd97c42012-11-27 02:38:26 -0800683 }
Ian Rogersc604d732012-10-14 16:09:54 -0700684 } while (!done);
685 }
686#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700687 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700688#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700689}
690
Ian Rogersc604d732012-10-14 16:09:54 -0700691void ConditionVariable::Signal(Thread* self) {
692 DCHECK(self == NULL || self == Thread::Current());
693 guard_.AssertExclusiveHeld(self);
694#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800695 if (num_waiters_ > 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700696 android_atomic_inc(&sequence_); // Indicate a signal occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700697 // Futex wake 1 waiter who will then come and in contend on mutex. It'd be nice to requeue them
698 // to avoid this, however, requeueing can only move all waiters.
Ian Rogersd45f2012012-11-28 11:46:23 -0800699 int num_woken = futex(&sequence_, FUTEX_WAKE, 1, NULL, NULL, 0);
700 // Check something was woken or else we changed sequence_ before they had chance to wait.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800701 CHECK((num_woken == 0) || (num_woken == 1));
Ian Rogersc604d732012-10-14 16:09:54 -0700702 }
703#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700704 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700705#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700706}
707
Ian Rogersc604d732012-10-14 16:09:54 -0700708void ConditionVariable::Wait(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700709 guard_.CheckSafeToWait(self);
710 WaitHoldingLocks(self);
711}
712
713void ConditionVariable::WaitHoldingLocks(Thread* self) {
Ian Rogersc604d732012-10-14 16:09:54 -0700714 DCHECK(self == NULL || self == Thread::Current());
715 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700716 unsigned int old_recursion_count = guard_.recursion_count_;
717#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700718 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800719 // Ensure the Mutex is contended so that requeued threads are awoken.
720 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700721 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800722 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700723 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800724 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, NULL, NULL, 0) != 0) {
725 // Futex failed, check it is an expected error.
726 // EAGAIN == EWOULDBLK, so we let the caller try again.
727 // EINTR implies a signal was sent to this thread.
728 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700729 PLOG(FATAL) << "futex wait failed for " << name_;
730 }
731 }
732 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800733 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700734 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800735 // We awoke and so no longer require awakes from the guard_'s unlock.
736 CHECK_GE(guard_.num_contenders_, 0);
737 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700738#else
739 guard_.recursion_count_ = 0;
740 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
741#endif
742 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700743}
744
Ian Rogersc604d732012-10-14 16:09:54 -0700745void ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
746 DCHECK(self == NULL || self == Thread::Current());
747 guard_.AssertExclusiveHeld(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700748 guard_.CheckSafeToWait(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700749 unsigned int old_recursion_count = guard_.recursion_count_;
750#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700751 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800752 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700753 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800754 // Ensure the Mutex is contended so that requeued threads are awoken.
755 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700756 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800757 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700758 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800759 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, &rel_ts, NULL, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700760 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800761 // Timed out we're done.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700762 } else if ((errno == EAGAIN) || (errno == EINTR)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800763 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700764 } else {
765 PLOG(FATAL) << "timed futex wait failed for " << name_;
766 }
767 }
768 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800769 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700770 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800771 // We awoke and so no longer require awakes from the guard_'s unlock.
772 CHECK_GE(guard_.num_contenders_, 0);
773 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700774#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700775#ifdef HAVE_TIMEDWAIT_MONOTONIC
776#define TIMEDWAIT pthread_cond_timedwait_monotonic
Ian Rogersc604d732012-10-14 16:09:54 -0700777 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700778#else
779#define TIMEDWAIT pthread_cond_timedwait
Ian Rogersc604d732012-10-14 16:09:54 -0700780 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700781#endif
Ian Rogersc604d732012-10-14 16:09:54 -0700782 guard_.recursion_count_ = 0;
783 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700784 InitTimeSpec(true, clock, ms, ns, &ts);
785 int rc = TEMP_FAILURE_RETRY(TIMEDWAIT(&cond_, &guard_.mutex_, &ts));
Elliott Hughes5f791332011-09-15 17:45:30 -0700786 if (rc != 0 && rc != ETIMEDOUT) {
787 errno = rc;
788 PLOG(FATAL) << "TimedWait failed for " << name_;
789 }
Ian Rogersc604d732012-10-14 16:09:54 -0700790#endif
791 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700792}
793
Elliott Hughese62934d2012-04-09 11:24:29 -0700794} // namespace art