blob: 1c7d7449458e9966c5fd00391e342e1fc6020fe6 [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};
Ian Rogersd9c4fc92013-10-01 19:45:43 -070057static struct AllMutexData gAllMutexData[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) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070062 while (!gAllMutexData->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() {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070067 while (!gAllMutexData->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);
Ian Rogersd9c4fc92013-10-01 19:45:43 -070078 std::set<BaseMutex*>** all_mutexes_ptr = &gAllMutexData->all_mutexes;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070079 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);
Ian Rogersd9c4fc92013-10-01 19:45:43 -070091 gAllMutexData->all_mutexes->erase(this);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070092 }
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));
Ian Rogersd9c4fc92013-10-01 19:45:43 -070099 std::set<BaseMutex*>* all_mutexes = gAllMutexData->all_mutexes;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700100 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;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700105 os << "(Contended)\n";
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700106 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) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700130 CHECK(self->GetHeldMutex(level_) == this || level_ == kMonitorLock)
131 << "Waiting on unacquired mutex: " << name_;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700132 bool bad_mutexes_held = false;
Elliott Hughes0f827162013-02-26 12:12:58 -0800133 for (int i = kLockLevelCount - 1; i >= 0; --i) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700134 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700135 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700136 if (held_mutex != NULL) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800137 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
138 << "(level " << LockLevel(i) << ") while performing wait on "
139 << "\"" << name_ << "\" (level " << level_ << ")";
Ian Rogers25fd14b2012-09-05 10:56:38 -0700140 bad_mutexes_held = true;
141 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700142 }
143 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700144 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700145 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700146}
147
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700148inline void BaseMutex::ContentionLogData::AddToWaitTime(uint64_t value) {
149 if (kLogLockContentions) {
150 // Atomically add value to wait_time.
151 uint64_t new_val, old_val;
152 volatile int64_t* addr = reinterpret_cast<volatile int64_t*>(&wait_time);
153 volatile const int64_t* caddr = const_cast<volatile const int64_t*>(addr);
154 do {
155 old_val = static_cast<uint64_t>(QuasiAtomic::Read64(caddr));
156 new_val = old_val + value;
157 } while (!QuasiAtomic::Cas64(static_cast<int64_t>(old_val), static_cast<int64_t>(new_val), addr));
158 }
159}
160
Brian Carlstrom0de79852013-07-25 22:29:58 -0700161void BaseMutex::RecordContention(uint64_t blocked_tid,
162 uint64_t owner_tid,
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700163 uint64_t nano_time_blocked) {
164 if (kLogLockContentions) {
165 ContentionLogData* data = contetion_log_data_;
166 ++(data->contention_count);
167 data->AddToWaitTime(nano_time_blocked);
168 ContentionLogEntry* log = data->contention_log;
169 // This code is intentionally racy as it is only used for diagnostics.
170 uint32_t slot = data->cur_content_log_entry;
171 if (log[slot].blocked_tid == blocked_tid &&
172 log[slot].owner_tid == blocked_tid) {
173 ++log[slot].count;
174 } else {
175 uint32_t new_slot;
176 do {
177 slot = data->cur_content_log_entry;
178 new_slot = (slot + 1) % kContentionLogSize;
179 } while (!data->cur_content_log_entry.compare_and_swap(slot, new_slot));
180 log[new_slot].blocked_tid = blocked_tid;
181 log[new_slot].owner_tid = owner_tid;
182 log[new_slot].count = 1;
183 }
Ian Rogers56edc432013-01-18 16:51:51 -0800184 }
Ian Rogers56edc432013-01-18 16:51:51 -0800185}
186
Ian Rogers56edc432013-01-18 16:51:51 -0800187void BaseMutex::DumpContention(std::ostream& os) const {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700188 if (kLogLockContentions) {
189 const ContentionLogData* data = contetion_log_data_;
190 const ContentionLogEntry* log = data->contention_log;
191 uint64_t wait_time = data->wait_time;
192 uint32_t contention_count = data->contention_count;
193 if (contention_count == 0) {
194 os << "never contended";
195 } else {
196 os << "contended " << contention_count
197 << " times, average wait of contender " << PrettyDuration(wait_time / contention_count);
198 SafeMap<uint64_t, size_t> most_common_blocker;
199 SafeMap<uint64_t, size_t> most_common_blocked;
200 typedef SafeMap<uint64_t, size_t>::const_iterator It;
201 for (size_t i = 0; i < kContentionLogSize; ++i) {
202 uint64_t blocked_tid = log[i].blocked_tid;
203 uint64_t owner_tid = log[i].owner_tid;
204 uint32_t count = log[i].count;
205 if (count > 0) {
206 It it = most_common_blocked.find(blocked_tid);
207 if (it != most_common_blocked.end()) {
208 most_common_blocked.Overwrite(blocked_tid, it->second + count);
209 } else {
210 most_common_blocked.Put(blocked_tid, count);
211 }
212 it = most_common_blocker.find(owner_tid);
213 if (it != most_common_blocker.end()) {
214 most_common_blocker.Overwrite(owner_tid, it->second + count);
215 } else {
216 most_common_blocker.Put(owner_tid, count);
217 }
Ian Rogers56edc432013-01-18 16:51:51 -0800218 }
219 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700220 uint64_t max_tid = 0;
221 size_t max_tid_count = 0;
222 for (It it = most_common_blocked.begin(); it != most_common_blocked.end(); ++it) {
223 if (it->second > max_tid_count) {
224 max_tid = it->first;
225 max_tid_count = it->second;
226 }
Ian Rogers56edc432013-01-18 16:51:51 -0800227 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700228 if (max_tid != 0) {
229 os << " sample shows most blocked tid=" << max_tid;
Ian Rogers56edc432013-01-18 16:51:51 -0800230 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700231 max_tid = 0;
232 max_tid_count = 0;
233 for (It it = most_common_blocker.begin(); it != most_common_blocker.end(); ++it) {
234 if (it->second > max_tid_count) {
235 max_tid = it->first;
236 max_tid_count = it->second;
237 }
238 }
239 if (max_tid != 0) {
240 os << " sample shows tid=" << max_tid << " owning during this time";
241 }
Ian Rogers56edc432013-01-18 16:51:51 -0800242 }
243 }
Ian Rogers56edc432013-01-18 16:51:51 -0800244}
245
246
Ian Rogers81d425b2012-09-27 16:03:43 -0700247Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700248 : BaseMutex(name, level), recursive_(recursive), recursion_count_(0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700249#if ART_USE_FUTEXES
250 state_ = 0;
251 exclusive_owner_ = 0;
252 num_contenders_ = 0;
253#elif defined(__BIONIC__) || defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700254 // Use recursive mutexes for bionic and Apple otherwise the
255 // non-recursive mutexes don't have TIDs to check lock ownership of.
Elliott Hughesbbd9d832011-11-07 14:40:00 -0800256 pthread_mutexattr_t attributes;
257 CHECK_MUTEX_CALL(pthread_mutexattr_init, (&attributes));
258 CHECK_MUTEX_CALL(pthread_mutexattr_settype, (&attributes, PTHREAD_MUTEX_RECURSIVE));
259 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, &attributes));
260 CHECK_MUTEX_CALL(pthread_mutexattr_destroy, (&attributes));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700261#else
262 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, NULL));
263#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700264}
265
266Mutex::~Mutex() {
Ian Rogersc604d732012-10-14 16:09:54 -0700267#if ART_USE_FUTEXES
268 if (state_ != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700269 Runtime* runtime = Runtime::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700270 bool shutting_down = runtime == nullptr || runtime->IsShuttingDown(Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700271 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) {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800643 Runtime* runtime = Runtime::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700644 bool shutting_down = runtime == nullptr || runtime->IsShuttingDown(Thread::Current());
Ian Rogersd45f2012012-11-28 11:46:23 -0800645 LOG(shutting_down ? WARNING : FATAL) << "ConditionVariable::~ConditionVariable for " << name_
646 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800647 }
648#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700649 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
650 // may still be using condition variables.
651 int rc = pthread_cond_destroy(&cond_);
652 if (rc != 0) {
653 errno = rc;
Ian Rogers50b35e22012-10-04 10:09:15 -0700654 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700655 Runtime* runtime = Runtime::Current();
656 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughese62934d2012-04-09 11:24:29 -0700657 PLOG(shutting_down ? WARNING : FATAL) << "pthread_cond_destroy failed for " << name_;
658 }
Ian Rogersc604d732012-10-14 16:09:54 -0700659#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700660}
661
Ian Rogersc604d732012-10-14 16:09:54 -0700662void ConditionVariable::Broadcast(Thread* self) {
663 DCHECK(self == NULL || self == Thread::Current());
664 // TODO: enable below, there's a race in thread creation that causes false failures currently.
665 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700666 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700667#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800668 if (num_waiters_ > 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700669 android_atomic_inc(&sequence_); // Indicate the broadcast occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700670 bool done = false;
671 do {
Ian Rogersd45f2012012-11-28 11:46:23 -0800672 int32_t cur_sequence = sequence_;
673 // Requeue waiters onto mutex. The waiter holds the contender count on the mutex high ensuring
674 // mutex unlocks will awaken the requeued waiter thread.
675 done = futex(&sequence_, FUTEX_CMP_REQUEUE, 0,
Ian Rogers5bd97c42012-11-27 02:38:26 -0800676 reinterpret_cast<const timespec*>(std::numeric_limits<int32_t>::max()),
Ian Rogersd45f2012012-11-28 11:46:23 -0800677 &guard_.state_, cur_sequence) != -1;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800678 if (!done) {
679 if (errno != EAGAIN) {
680 PLOG(FATAL) << "futex cmp requeue failed for " << name_;
681 }
Ian Rogers5bd97c42012-11-27 02:38:26 -0800682 }
Ian Rogersc604d732012-10-14 16:09:54 -0700683 } while (!done);
684 }
685#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700686 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700687#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700688}
689
Ian Rogersc604d732012-10-14 16:09:54 -0700690void ConditionVariable::Signal(Thread* self) {
691 DCHECK(self == NULL || self == Thread::Current());
692 guard_.AssertExclusiveHeld(self);
693#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800694 if (num_waiters_ > 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700695 android_atomic_inc(&sequence_); // Indicate a signal occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700696 // Futex wake 1 waiter who will then come and in contend on mutex. It'd be nice to requeue them
697 // to avoid this, however, requeueing can only move all waiters.
Ian Rogersd45f2012012-11-28 11:46:23 -0800698 int num_woken = futex(&sequence_, FUTEX_WAKE, 1, NULL, NULL, 0);
699 // Check something was woken or else we changed sequence_ before they had chance to wait.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800700 CHECK((num_woken == 0) || (num_woken == 1));
Ian Rogersc604d732012-10-14 16:09:54 -0700701 }
702#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700703 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700704#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700705}
706
Ian Rogersc604d732012-10-14 16:09:54 -0700707void ConditionVariable::Wait(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700708 guard_.CheckSafeToWait(self);
709 WaitHoldingLocks(self);
710}
711
712void ConditionVariable::WaitHoldingLocks(Thread* self) {
Ian Rogersc604d732012-10-14 16:09:54 -0700713 DCHECK(self == NULL || self == Thread::Current());
714 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700715 unsigned int old_recursion_count = guard_.recursion_count_;
716#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700717 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800718 // Ensure the Mutex is contended so that requeued threads are awoken.
719 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700720 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800721 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700722 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800723 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, NULL, NULL, 0) != 0) {
724 // Futex failed, check it is an expected error.
725 // EAGAIN == EWOULDBLK, so we let the caller try again.
726 // EINTR implies a signal was sent to this thread.
727 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700728 PLOG(FATAL) << "futex wait failed for " << name_;
729 }
730 }
731 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800732 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700733 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800734 // We awoke and so no longer require awakes from the guard_'s unlock.
735 CHECK_GE(guard_.num_contenders_, 0);
736 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700737#else
738 guard_.recursion_count_ = 0;
739 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
740#endif
741 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700742}
743
Ian Rogersc604d732012-10-14 16:09:54 -0700744void ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
745 DCHECK(self == NULL || self == Thread::Current());
746 guard_.AssertExclusiveHeld(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700747 guard_.CheckSafeToWait(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700748 unsigned int old_recursion_count = guard_.recursion_count_;
749#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700750 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800751 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700752 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800753 // Ensure the Mutex is contended so that requeued threads are awoken.
754 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700755 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800756 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700757 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800758 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, &rel_ts, NULL, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700759 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800760 // Timed out we're done.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700761 } else if ((errno == EAGAIN) || (errno == EINTR)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800762 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700763 } else {
764 PLOG(FATAL) << "timed futex wait failed for " << name_;
765 }
766 }
767 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800768 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700769 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800770 // We awoke and so no longer require awakes from the guard_'s unlock.
771 CHECK_GE(guard_.num_contenders_, 0);
772 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700773#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700774#ifdef HAVE_TIMEDWAIT_MONOTONIC
775#define TIMEDWAIT pthread_cond_timedwait_monotonic
Ian Rogersc604d732012-10-14 16:09:54 -0700776 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700777#else
778#define TIMEDWAIT pthread_cond_timedwait
Ian Rogersc604d732012-10-14 16:09:54 -0700779 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700780#endif
Ian Rogersc604d732012-10-14 16:09:54 -0700781 guard_.recursion_count_ = 0;
782 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700783 InitTimeSpec(true, clock, ms, ns, &ts);
784 int rc = TEMP_FAILURE_RETRY(TIMEDWAIT(&cond_, &guard_.mutex_, &ts));
Elliott Hughes5f791332011-09-15 17:45:30 -0700785 if (rc != 0 && rc != ETIMEDOUT) {
786 errno = rc;
787 PLOG(FATAL) << "TimedWait failed for " << name_;
788 }
Ian Rogersc604d732012-10-14 16:09:54 -0700789#endif
790 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700791}
792
Elliott Hughese62934d2012-04-09 11:24:29 -0700793} // namespace art