blob: d822eedb675252b8982948888f86e6b1d37a0048 [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"
Ian Rogers04d7aa92013-03-16 14:29:17 -070028#include "thread-inl.h"
Elliott Hughesffb465f2012-03-01 18:46:05 -080029#include "utils.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070030
31namespace art {
32
Brian Carlstrom6eb52882013-07-19 00:31:07 -070033#if defined(__APPLE__)
34
Brian Carlstromf3a26412012-08-24 11:06:02 -070035// This works on Mac OS 10.6 but hasn't been tested on older releases.
Elliott Hughesf1498432012-03-28 19:34:27 -070036struct __attribute__((__may_alias__)) darwin_pthread_mutex_t {
Brian Carlstrom6eb52882013-07-19 00:31:07 -070037 long padding0; // NOLINT(runtime/int) exact match to darwin type
Brian Carlstromf3a26412012-08-24 11:06:02 -070038 int padding1;
39 uint32_t padding2;
40 int16_t padding3;
41 int16_t padding4;
42 uint32_t padding5;
43 pthread_t darwin_pthread_mutex_owner;
Ian Rogers00f7d0e2012-07-19 15:28:27 -070044 // ...other stuff we don't care about.
45};
46
47struct __attribute__((__may_alias__)) darwin_pthread_rwlock_t {
Brian Carlstrom6eb52882013-07-19 00:31:07 -070048 long padding0; // NOLINT(runtime/int) exact match to darwin type
Brian Carlstromf3a26412012-08-24 11:06:02 -070049 pthread_mutex_t padding1;
50 int padding2;
51 pthread_cond_t padding3;
52 pthread_cond_t padding4;
53 int padding5;
54 int padding6;
55 pthread_t darwin_pthread_rwlock_owner;
Elliott Hughesf1498432012-03-28 19:34:27 -070056 // ...other stuff we don't care about.
57};
58
Brian Carlstrom6eb52882013-07-19 00:31:07 -070059#endif // __APPLE__
60
61#if defined(__GLIBC__)
62
Elliott Hughesf1498432012-03-28 19:34:27 -070063struct __attribute__((__may_alias__)) glibc_pthread_mutex_t {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070064 int32_t padding0[2];
Elliott Hughesf1498432012-03-28 19:34:27 -070065 int owner;
66 // ...other stuff we don't care about.
67};
68
Ian Rogers00f7d0e2012-07-19 15:28:27 -070069struct __attribute__((__may_alias__)) glibc_pthread_rwlock_t {
70#ifdef __LP64__
71 int32_t padding0[6];
72#else
73 int32_t padding0[7];
74#endif
75 int writer;
76 // ...other stuff we don't care about.
77};
78
Brian Carlstrom6eb52882013-07-19 00:31:07 -070079#endif // __GLIBC__
80
Ian Rogersc604d732012-10-14 16:09:54 -070081#if ART_USE_FUTEXES
82static bool ComputeRelativeTimeSpec(timespec* result_ts, const timespec& lhs, const timespec& rhs) {
Brian Carlstromfb6996f2013-07-18 18:21:14 -070083 const int32_t one_sec = 1000 * 1000 * 1000; // one second in nanoseconds.
Ian Rogersc604d732012-10-14 16:09:54 -070084 result_ts->tv_sec = lhs.tv_sec - rhs.tv_sec;
85 result_ts->tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
86 if (result_ts->tv_nsec < 0) {
87 result_ts->tv_sec--;
88 result_ts->tv_nsec += one_sec;
89 } else if (result_ts->tv_nsec > one_sec) {
90 result_ts->tv_sec++;
91 result_ts->tv_nsec -= one_sec;
92 }
93 return result_ts->tv_sec < 0;
94}
95#endif
96
Ian Rogers56edc432013-01-18 16:51:51 -080097#if CONTENTION_LOGGING
98// A guard for all_mutexes_ that's not a mutex (Mutexes must CAS to acquire and busy wait).
99static AtomicInteger all_mutexes_guard_;
100// All created mutexes guarded by all_mutexes_guard_.
101std::set<BaseMutex*>* all_mutexes_;
102
103class ScopedAllMutexesLock {
104 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700105 explicit ScopedAllMutexesLock(const BaseMutex* mutex) : mutex_(mutex) {
Ian Rogers56edc432013-01-18 16:51:51 -0800106 while (!all_mutexes_guard_.CompareAndSwap(0, reinterpret_cast<int32_t>(mutex))) {
107 NanoSleep(100);
108 }
109 }
110 ~ScopedAllMutexesLock() {
111 while (!all_mutexes_guard_.CompareAndSwap(reinterpret_cast<int32_t>(mutex_), 0)) {
112 NanoSleep(100);
113 }
114 }
115 private:
116 const BaseMutex* const mutex_;
117};
118#endif
119
120BaseMutex::BaseMutex(const char* name, LockLevel level) : level_(level), name_(name) {
121#if CONTENTION_LOGGING
122 ScopedAllMutexesLock mu(this);
123 if (all_mutexes_ == NULL) {
124 // We leak the global set of all mutexes to avoid ordering issues in global variable
125 // construction/destruction.
126 all_mutexes_ = new std::set<BaseMutex*>();
127 }
128 all_mutexes_->insert(this);
129#endif
130}
131
132BaseMutex::~BaseMutex() {
133#if CONTENTION_LOGGING
134 ScopedAllMutexesLock mu(this);
135 all_mutexes_->erase(this);
136#endif
137}
138
139void BaseMutex::DumpAll(std::ostream& os) {
140#if CONTENTION_LOGGING
141 os << "Mutex logging:\n";
142 ScopedAllMutexesLock mu(reinterpret_cast<const BaseMutex*>(-1));
143 typedef std::set<BaseMutex*>::const_iterator It;
144 for (It it = all_mutexes_->begin(); it != all_mutexes_->end(); ++it) {
145 BaseMutex* mutex = *it;
146 mutex->Dump(os);
147 os << "\n";
148 }
149#endif
150}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700151
Ian Rogers81d425b2012-09-27 16:03:43 -0700152void BaseMutex::CheckSafeToWait(Thread* self) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700153 if (self == NULL) {
154 CheckUnattachedThread(level_);
155 return;
156 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700157 if (kDebugLocking) {
158 CHECK(self->GetHeldMutex(level_) == this) << "Waiting on unacquired mutex: " << name_;
159 bool bad_mutexes_held = false;
Elliott Hughes0f827162013-02-26 12:12:58 -0800160 for (int i = kLockLevelCount - 1; i >= 0; --i) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700161 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700162 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700163 if (held_mutex != NULL) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800164 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
165 << "(level " << LockLevel(i) << ") while performing wait on "
166 << "\"" << name_ << "\" (level " << level_ << ")";
Ian Rogers25fd14b2012-09-05 10:56:38 -0700167 bad_mutexes_held = true;
168 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700169 }
170 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700171 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700172 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700173}
174
Brian Carlstrom0de79852013-07-25 22:29:58 -0700175void BaseMutex::RecordContention(uint64_t blocked_tid,
176 uint64_t owner_tid,
177 uint64_t milli_time_blocked) {
Ian Rogers56edc432013-01-18 16:51:51 -0800178#if CONTENTION_LOGGING
179 ++contention_count_;
180 wait_time_ += static_cast<uint32_t>(milli_time_blocked); // May overflow.
181 // This code is intentionally racy as it is only used for diagnostics.
182 uint32_t slot = cur_content_log_entry_;
183 if (contention_log_[slot].blocked_tid == blocked_tid &&
184 contention_log_[slot].owner_tid == blocked_tid) {
185 ++contention_log_[slot].count;
186 } else {
187 uint32_t new_slot;
188 do {
189 slot = cur_content_log_entry_;
190 new_slot = (slot + 1) % kContentionLogSize;
Brian Carlstromdf629502013-07-17 22:39:56 -0700191 } while (!cur_content_log_entry_.CompareAndSwap(slot, new_slot));
Ian Rogers56edc432013-01-18 16:51:51 -0800192 contention_log_[new_slot].blocked_tid = blocked_tid;
193 contention_log_[new_slot].owner_tid = owner_tid;
194 contention_log_[new_slot].count = 1;
195 }
196#endif
197}
198
Ian Rogers56edc432013-01-18 16:51:51 -0800199void BaseMutex::DumpContention(std::ostream& os) const {
200#if CONTENTION_LOGGING
201 uint32_t wait_time = wait_time_;
202 uint32_t contention_count = contention_count_;
203 if (contention_count == 0) {
204 os << "never contended";
205 } else {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700206 os << "contended " << contention_count
207 << " times, average wait of contender " << (wait_time / contention_count) << "ms";
Ian Rogers56edc432013-01-18 16:51:51 -0800208 SafeMap<uint64_t, size_t> most_common_blocker;
209 SafeMap<uint64_t, size_t> most_common_blocked;
210 typedef SafeMap<uint64_t, size_t>::const_iterator It;
211 for (size_t i = 0; i < kContentionLogSize; ++i) {
212 uint64_t blocked_tid = contention_log_[i].blocked_tid;
213 uint64_t owner_tid = contention_log_[i].owner_tid;
214 uint32_t count = contention_log_[i].count;
215 if (count > 0) {
216 It it = most_common_blocked.find(blocked_tid);
217 if (it != most_common_blocked.end()) {
218 most_common_blocked.Overwrite(blocked_tid, it->second + count);
219 } else {
220 most_common_blocked.Put(blocked_tid, count);
221 }
222 it = most_common_blocker.find(owner_tid);
223 if (it != most_common_blocker.end()) {
224 most_common_blocker.Overwrite(owner_tid, it->second + count);
225 } else {
226 most_common_blocker.Put(owner_tid, count);
227 }
228 }
229 }
230 uint64_t max_tid = 0;
231 size_t max_tid_count = 0;
232 for (It it = most_common_blocked.begin(); it != most_common_blocked.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 most blocked tid=" << max_tid;
240 }
241 max_tid = 0;
242 max_tid_count = 0;
243 for (It it = most_common_blocker.begin(); it != most_common_blocker.end(); ++it) {
244 if (it->second > max_tid_count) {
245 max_tid = it->first;
246 max_tid_count = it->second;
247 }
248 }
249 if (max_tid != 0) {
250 os << " sample shows tid=" << max_tid << " owning during this time";
251 }
252 }
253#endif
254}
255
256
Ian Rogers81d425b2012-09-27 16:03:43 -0700257Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700258 : BaseMutex(name, level), recursive_(recursive), recursion_count_(0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700259#if ART_USE_FUTEXES
260 state_ = 0;
261 exclusive_owner_ = 0;
262 num_contenders_ = 0;
263#elif defined(__BIONIC__) || defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700264 // Use recursive mutexes for bionic and Apple otherwise the
265 // non-recursive mutexes don't have TIDs to check lock ownership of.
Elliott Hughesbbd9d832011-11-07 14:40:00 -0800266 pthread_mutexattr_t attributes;
267 CHECK_MUTEX_CALL(pthread_mutexattr_init, (&attributes));
268 CHECK_MUTEX_CALL(pthread_mutexattr_settype, (&attributes, PTHREAD_MUTEX_RECURSIVE));
269 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, &attributes));
270 CHECK_MUTEX_CALL(pthread_mutexattr_destroy, (&attributes));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700271#else
272 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, NULL));
273#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700274}
275
276Mutex::~Mutex() {
Ian Rogersc604d732012-10-14 16:09:54 -0700277#if ART_USE_FUTEXES
278 if (state_ != 0) {
279 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
280 Runtime* runtime = Runtime::Current();
281 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
282 LOG(shutting_down ? WARNING : FATAL) << "destroying mutex with owner: " << exclusive_owner_;
283 } else {
284 CHECK_EQ(exclusive_owner_, 0U) << "unexpectedly found an owner on unlocked mutex " << name_;
285 CHECK_EQ(num_contenders_, 0) << "unexpectedly found a contender on mutex " << name_;
286 }
287#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700288 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
289 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800290 int rc = pthread_mutex_destroy(&mutex_);
291 if (rc != 0) {
292 errno = rc;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800293 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700294 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700295 Runtime* runtime = Runtime::Current();
296 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughes6b355752012-01-13 16:49:08 -0800297 PLOG(shutting_down ? WARNING : FATAL) << "pthread_mutex_destroy failed for " << name_;
298 }
Ian Rogersc604d732012-10-14 16:09:54 -0700299#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700300}
301
Ian Rogers81d425b2012-09-27 16:03:43 -0700302void Mutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700303 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700304 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700305 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700306 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700307 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700308#if ART_USE_FUTEXES
309 bool done = false;
310 do {
311 int32_t cur_state = state_;
312 if (cur_state == 0) {
313 // Change state from 0 to 1.
Ian Rogers693ff612013-02-01 10:56:12 -0800314 done = android_atomic_acquire_cas(0, 1, &state_) == 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700315 } else {
316 // Failed to acquire, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800317 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700318 android_atomic_inc(&num_contenders_);
319 if (futex(&state_, FUTEX_WAIT, 1, NULL, NULL, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700320 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
321 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
322 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700323 PLOG(FATAL) << "futex wait failed for " << name_;
324 }
325 }
326 android_atomic_dec(&num_contenders_);
327 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700328 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700329 DCHECK_EQ(state_, 1);
330 exclusive_owner_ = SafeGetTid(self);
331#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700332 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700333#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700334 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700335 }
336 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700337 if (kDebugLocking) {
338 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
339 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700340 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700341 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700342}
343
Ian Rogers81d425b2012-09-27 16:03:43 -0700344bool Mutex::ExclusiveTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700345 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700346 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700347 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700348 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700349 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700350#if ART_USE_FUTEXES
351 bool done = false;
352 do {
353 int32_t cur_state = state_;
354 if (cur_state == 0) {
355 // Change state from 0 to 1.
Ian Rogers693ff612013-02-01 10:56:12 -0800356 done = android_atomic_acquire_cas(0, 1, &state_) == 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700357 } else {
358 return false;
359 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700360 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700361 DCHECK_EQ(state_, 1);
362 exclusive_owner_ = SafeGetTid(self);
363#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700364 int result = pthread_mutex_trylock(&mutex_);
365 if (result == EBUSY) {
366 return false;
367 }
368 if (result != 0) {
369 errno = result;
370 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
371 }
Ian Rogersc604d732012-10-14 16:09:54 -0700372#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700373 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700374 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700375 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700376 if (kDebugLocking) {
377 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
378 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700379 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700380 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700381 return true;
382}
383
Ian Rogers81d425b2012-09-27 16:03:43 -0700384void Mutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700385 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700386 AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700387 recursion_count_--;
388 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700389 if (kDebugLocking) {
390 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
391 << name_ << " " << recursion_count_;
392 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700393 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700394#if ART_USE_FUTEXES
395 bool done = false;
396 do {
397 int32_t cur_state = state_;
398 if (cur_state == 1) {
399 // We're no longer the owner.
400 exclusive_owner_ = 0;
401 // Change state to 0.
Ian Rogers693ff612013-02-01 10:56:12 -0800402 done = android_atomic_release_cas(cur_state, 0, &state_) == 0;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700403 if (done) { // Spurious fail?
Ian Rogersc604d732012-10-14 16:09:54 -0700404 // Wake a contender
405 if (num_contenders_ > 0) {
406 futex(&state_, FUTEX_WAKE, 1, NULL, NULL, 0);
407 }
408 }
409 } else {
Ian Rogersc4ee12e2013-05-16 11:19:53 -0700410 // Logging acquires the logging lock, avoid infinite recursion in that case.
411 if (this != Locks::logging_lock_) {
412 LOG(FATAL) << "Unexpected state_ in unlock " << cur_state << " for " << name_;
413 } else {
414 LogMessageData data(__FILE__, __LINE__, INTERNAL_FATAL, -1);
415 LogMessage::LogLine(data, StringPrintf("Unexpected state_ %d in unlock for %s",
416 cur_state, name_).c_str());
417 _exit(1);
418 }
Ian Rogersc604d732012-10-14 16:09:54 -0700419 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700420 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700421#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700422 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700423#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700424 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700425}
426
Ian Rogers81d425b2012-09-27 16:03:43 -0700427bool Mutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700428 DCHECK(self == NULL || self == Thread::Current());
429 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
430 if (kDebugLocking) {
431 // Sanity debug check that if we think it is locked we have it in our held mutexes.
Brian Carlstrom9e419ca2012-11-27 11:31:49 -0800432 if (result && self != NULL && level_ != kMonitorLock && !gAborting) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700433 CHECK_EQ(self->GetHeldMutex(level_), this);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700434 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700435 }
436 return result;
Elliott Hughesf1498432012-03-28 19:34:27 -0700437}
438
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700439uint64_t Mutex::GetExclusiveOwnerTid() const {
Ian Rogersc604d732012-10-14 16:09:54 -0700440#if ART_USE_FUTEXES
441 return exclusive_owner_;
442#elif defined(__BIONIC__)
Elliott Hughesf1498432012-03-28 19:34:27 -0700443 return static_cast<uint64_t>((mutex_.value >> 16) & 0xffff);
Elliott Hughes3147a232011-10-12 15:55:07 -0700444#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700445 return reinterpret_cast<const glibc_pthread_mutex_t*>(&mutex_)->owner;
Elliott Hughescf044312012-01-23 18:48:51 -0800446#elif defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700447 const darwin_pthread_mutex_t* dpmutex = reinterpret_cast<const darwin_pthread_mutex_t*>(&mutex_);
448 pthread_t owner = dpmutex->darwin_pthread_mutex_owner;
Brian Carlstrombd93c302012-08-27 16:58:28 -0700449 // 0 for unowned, -1 for PTHREAD_MTX_TID_SWITCHING
450 // TODO: should we make darwin_pthread_mutex_owner volatile and recheck until not -1?
Brian Carlstromf3a26412012-08-24 11:06:02 -0700451 if ((owner == (pthread_t)0) || (owner == (pthread_t)-1)) {
452 return 0;
453 }
454 uint64_t tid;
455 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
456 return tid;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700457#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700458#error unsupported C library
Elliott Hughes8daa0922011-09-11 13:46:25 -0700459#endif
460}
461
Ian Rogers56edc432013-01-18 16:51:51 -0800462void Mutex::Dump(std::ostream& os) const {
463 os << (recursive_ ? "recursive " : "non-recursive ")
464 << name_
465 << " level=" << static_cast<int>(level_)
466 << " rec=" << recursion_count_
467 << " owner=" << GetExclusiveOwnerTid() << " ";
468 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700469}
470
471std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800472 mu.Dump(os);
473 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700474}
475
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700476ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level)
477 : BaseMutex(name, level)
Ian Rogers81d425b2012-09-27 16:03:43 -0700478#if ART_USE_FUTEXES
479 , state_(0), exclusive_owner_(0), num_pending_readers_(0), num_pending_writers_(0)
480#endif
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700481{ // NOLINT(whitespace/braces)
Ian Rogers81d425b2012-09-27 16:03:43 -0700482#if !ART_USE_FUTEXES
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700483 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, NULL));
Ian Rogers81d425b2012-09-27 16:03:43 -0700484#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700485}
486
487ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700488#if ART_USE_FUTEXES
489 CHECK_EQ(state_, 0);
490 CHECK_EQ(exclusive_owner_, 0U);
491 CHECK_EQ(num_pending_readers_, 0);
492 CHECK_EQ(num_pending_writers_, 0);
493#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700494 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
495 // may still be using locks.
496 int rc = pthread_rwlock_destroy(&rwlock_);
497 if (rc != 0) {
498 errno = rc;
499 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700500 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700501 Runtime* runtime = Runtime::Current();
502 bool shutting_down = runtime == NULL || runtime->IsShuttingDown();
503 PLOG(shutting_down ? WARNING : FATAL) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800504 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700505#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700506}
507
Ian Rogers81d425b2012-09-27 16:03:43 -0700508void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700509 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700510 AssertNotExclusiveHeld(self);
511#if ART_USE_FUTEXES
512 bool done = false;
513 do {
514 int32_t cur_state = state_;
515 if (cur_state == 0) {
516 // Change state from 0 to -1.
Ian Rogers693ff612013-02-01 10:56:12 -0800517 done = android_atomic_acquire_cas(0, -1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700518 } else {
519 // Failed to acquire, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800520 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700521 android_atomic_inc(&num_pending_writers_);
522 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700523 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
524 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
525 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700526 PLOG(FATAL) << "futex wait failed for " << name_;
527 }
528 }
529 android_atomic_dec(&num_pending_writers_);
530 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700531 } while (!done);
Ian Rogersab470162012-09-29 23:06:53 -0700532 DCHECK_EQ(state_, -1);
533 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700534#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700535 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700536#endif
537 RegisterAsLocked(self);
538 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700539}
540
Ian Rogers81d425b2012-09-27 16:03:43 -0700541void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700542 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700543 AssertExclusiveHeld(self);
544 RegisterAsUnlocked(self);
545#if ART_USE_FUTEXES
546 bool done = false;
547 do {
548 int32_t cur_state = state_;
549 if (cur_state == -1) {
550 // We're no longer the owner.
551 exclusive_owner_ = 0;
552 // Change state from -1 to 0.
Ian Rogers693ff612013-02-01 10:56:12 -0800553 done = android_atomic_release_cas(-1, 0, &state_) == 0;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700554 if (done) { // cmpxchg may fail due to noise?
Ian Rogers81d425b2012-09-27 16:03:43 -0700555 // Wake any waiters.
556 if (num_pending_readers_ > 0 || num_pending_writers_ > 0) {
557 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
558 }
559 }
560 } else {
561 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
562 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700563 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700564#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700565 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700566#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700567}
568
Ian Rogers66aee5c2012-08-15 17:17:47 -0700569#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700570bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700571 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700572#if ART_USE_FUTEXES
573 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700574 timespec end_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800575 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700576 do {
577 int32_t cur_state = state_;
578 if (cur_state == 0) {
579 // Change state from 0 to -1.
Ian Rogers693ff612013-02-01 10:56:12 -0800580 done = android_atomic_acquire_cas(0, -1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700581 } else {
582 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700583 timespec now_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800584 InitTimeSpec(true, CLOCK_REALTIME, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700585 timespec rel_ts;
586 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
587 return false; // Timed out.
588 }
Ian Rogers56edc432013-01-18 16:51:51 -0800589 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700590 android_atomic_inc(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700591 if (futex(&state_, FUTEX_WAIT, cur_state, &rel_ts, NULL, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700592 if (errno == ETIMEDOUT) {
593 android_atomic_dec(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700594 return false; // Timed out.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700595 } else if ((errno != EAGAIN) && (errno != EINTR)) {
596 // EAGAIN and EINTR both indicate a spurious failure,
597 // recompute the relative time out from now and try again.
598 // We don't use TEMP_FAILURE_RETRY so we can recompute rel_ts;
Ian Rogers81d425b2012-09-27 16:03:43 -0700599 PLOG(FATAL) << "timed futex wait failed for " << name_;
600 }
601 }
602 android_atomic_dec(&num_pending_writers_);
603 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700604 } while (!done);
Ian Rogers01ae5802012-09-28 16:14:01 -0700605 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700606#else
Ian Rogersc604d732012-10-14 16:09:54 -0700607 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700608 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700609 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700610 if (result == ETIMEDOUT) {
611 return false;
612 }
613 if (result != 0) {
614 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700615 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700616 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700617#endif
618 RegisterAsLocked(self);
619 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700620 return true;
621}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700622#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700623
Ian Rogers81d425b2012-09-27 16:03:43 -0700624bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700625 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700626#if ART_USE_FUTEXES
627 bool done = false;
628 do {
629 int32_t cur_state = state_;
630 if (cur_state >= 0) {
631 // Add as an extra reader.
Ian Rogers693ff612013-02-01 10:56:12 -0800632 done = android_atomic_acquire_cas(cur_state, cur_state + 1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700633 } else {
634 // Owner holds it exclusively.
635 return false;
636 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700637 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700638#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700639 int result = pthread_rwlock_tryrdlock(&rwlock_);
640 if (result == EBUSY) {
641 return false;
642 }
643 if (result != 0) {
644 errno = result;
645 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
646 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700647#endif
648 RegisterAsLocked(self);
649 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700650 return true;
651}
652
Ian Rogers81d425b2012-09-27 16:03:43 -0700653bool ReaderWriterMutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700654 DCHECK(self == NULL || self == Thread::Current());
655 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700656 if (kDebugLocking) {
657 // Sanity that if the pthread thinks we own the lock the Thread agrees.
Ian Rogers01ae5802012-09-28 16:14:01 -0700658 if (self != NULL && result) {
659 CHECK_EQ(self->GetHeldMutex(level_), this);
660 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700661 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700662 return result;
663}
664
Ian Rogers81d425b2012-09-27 16:03:43 -0700665bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700666 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700667 bool result;
668 if (UNLIKELY(self == NULL)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700669 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700670 } else {
671 result = (self->GetHeldMutex(level_) == this);
672 }
673 return result;
674}
675
676uint64_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700677#if ART_USE_FUTEXES
Ian Rogers56edc432013-01-18 16:51:51 -0800678 int32_t state = state_;
679 if (state == 0) {
680 return 0; // No owner.
681 } else if (state > 0) {
682 return -1; // Shared.
683 } else {
684 return exclusive_owner_;
685 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700686#else
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800687#if defined(__BIONIC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700688 return rwlock_.writerThreadId;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800689#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700690 return reinterpret_cast<const glibc_pthread_rwlock_t*>(&rwlock_)->writer;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800691#elif defined(__APPLE__)
Ian Rogers81d425b2012-09-27 16:03:43 -0700692 const darwin_pthread_rwlock_t*
693 dprwlock = reinterpret_cast<const darwin_pthread_rwlock_t*>(&rwlock_);
Brian Carlstromf3a26412012-08-24 11:06:02 -0700694 pthread_t owner = dprwlock->darwin_pthread_rwlock_owner;
695 if (owner == (pthread_t)0) {
696 return 0;
697 }
698 uint64_t tid;
699 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
700 return tid;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800701#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700702#error unsupported C library
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800703#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700704#endif
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800705}
706
Ian Rogers56edc432013-01-18 16:51:51 -0800707void ReaderWriterMutex::Dump(std::ostream& os) const {
708 os << name_
709 << " level=" << static_cast<int>(level_)
710 << " owner=" << GetExclusiveOwnerTid() << " ";
711 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700712}
713
714std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800715 mu.Dump(os);
716 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700717}
718
Ian Rogers23055dc2013-04-18 16:29:16 -0700719ConditionVariable::ConditionVariable(const char* name, Mutex& guard)
Ian Rogersc604d732012-10-14 16:09:54 -0700720 : name_(name), guard_(guard) {
721#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800722 sequence_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700723 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700724#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700725 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, NULL));
Ian Rogersc604d732012-10-14 16:09:54 -0700726#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700727}
728
729ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800730#if ART_USE_FUTEXES
731 if (num_waiters_!= 0) {
732 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
733 Runtime* runtime = Runtime::Current();
734 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Ian Rogersd45f2012012-11-28 11:46:23 -0800735 LOG(shutting_down ? WARNING : FATAL) << "ConditionVariable::~ConditionVariable for " << name_
736 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800737 }
738#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700739 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
740 // may still be using condition variables.
741 int rc = pthread_cond_destroy(&cond_);
742 if (rc != 0) {
743 errno = rc;
Ian Rogers50b35e22012-10-04 10:09:15 -0700744 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700745 Runtime* runtime = Runtime::Current();
746 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughese62934d2012-04-09 11:24:29 -0700747 PLOG(shutting_down ? WARNING : FATAL) << "pthread_cond_destroy failed for " << name_;
748 }
Ian Rogersc604d732012-10-14 16:09:54 -0700749#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700750}
751
Ian Rogersc604d732012-10-14 16:09:54 -0700752void ConditionVariable::Broadcast(Thread* self) {
753 DCHECK(self == NULL || self == Thread::Current());
754 // TODO: enable below, there's a race in thread creation that causes false failures currently.
755 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700756 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700757#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800758 if (num_waiters_ > 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700759 android_atomic_inc(&sequence_); // Indicate the broadcast occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700760 bool done = false;
761 do {
Ian Rogersd45f2012012-11-28 11:46:23 -0800762 int32_t cur_sequence = sequence_;
763 // Requeue waiters onto mutex. The waiter holds the contender count on the mutex high ensuring
764 // mutex unlocks will awaken the requeued waiter thread.
765 done = futex(&sequence_, FUTEX_CMP_REQUEUE, 0,
Ian Rogers5bd97c42012-11-27 02:38:26 -0800766 reinterpret_cast<const timespec*>(std::numeric_limits<int32_t>::max()),
Ian Rogersd45f2012012-11-28 11:46:23 -0800767 &guard_.state_, cur_sequence) != -1;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800768 if (!done) {
769 if (errno != EAGAIN) {
770 PLOG(FATAL) << "futex cmp requeue failed for " << name_;
771 }
Ian Rogers5bd97c42012-11-27 02:38:26 -0800772 }
Ian Rogersc604d732012-10-14 16:09:54 -0700773 } while (!done);
774 }
775#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700776 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700777#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700778}
779
Ian Rogersc604d732012-10-14 16:09:54 -0700780void ConditionVariable::Signal(Thread* self) {
781 DCHECK(self == NULL || self == Thread::Current());
782 guard_.AssertExclusiveHeld(self);
783#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800784 if (num_waiters_ > 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700785 android_atomic_inc(&sequence_); // Indicate a signal occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700786 // Futex wake 1 waiter who will then come and in contend on mutex. It'd be nice to requeue them
787 // to avoid this, however, requeueing can only move all waiters.
Ian Rogersd45f2012012-11-28 11:46:23 -0800788 int num_woken = futex(&sequence_, FUTEX_WAKE, 1, NULL, NULL, 0);
789 // Check something was woken or else we changed sequence_ before they had chance to wait.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800790 CHECK((num_woken == 0) || (num_woken == 1));
Ian Rogersc604d732012-10-14 16:09:54 -0700791 }
792#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700793 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700794#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700795}
796
Ian Rogersc604d732012-10-14 16:09:54 -0700797void ConditionVariable::Wait(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700798 guard_.CheckSafeToWait(self);
799 WaitHoldingLocks(self);
800}
801
802void ConditionVariable::WaitHoldingLocks(Thread* self) {
Ian Rogersc604d732012-10-14 16:09:54 -0700803 DCHECK(self == NULL || self == Thread::Current());
804 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700805 unsigned int old_recursion_count = guard_.recursion_count_;
806#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700807 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800808 // Ensure the Mutex is contended so that requeued threads are awoken.
809 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700810 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800811 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700812 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800813 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, NULL, NULL, 0) != 0) {
814 // Futex failed, check it is an expected error.
815 // EAGAIN == EWOULDBLK, so we let the caller try again.
816 // EINTR implies a signal was sent to this thread.
817 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700818 PLOG(FATAL) << "futex wait failed for " << name_;
819 }
820 }
821 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800822 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700823 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800824 // We awoke and so no longer require awakes from the guard_'s unlock.
825 CHECK_GE(guard_.num_contenders_, 0);
826 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700827#else
828 guard_.recursion_count_ = 0;
829 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
830#endif
831 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700832}
833
Ian Rogersc604d732012-10-14 16:09:54 -0700834void ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
835 DCHECK(self == NULL || self == Thread::Current());
836 guard_.AssertExclusiveHeld(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700837 guard_.CheckSafeToWait(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700838 unsigned int old_recursion_count = guard_.recursion_count_;
839#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700840 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800841 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700842 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800843 // Ensure the Mutex is contended so that requeued threads are awoken.
844 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700845 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800846 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700847 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800848 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, &rel_ts, NULL, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700849 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800850 // Timed out we're done.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700851 } else if ((errno == EAGAIN) || (errno == EINTR)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800852 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700853 } else {
854 PLOG(FATAL) << "timed futex wait failed for " << name_;
855 }
856 }
857 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800858 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700859 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800860 // We awoke and so no longer require awakes from the guard_'s unlock.
861 CHECK_GE(guard_.num_contenders_, 0);
862 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700863#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700864#ifdef HAVE_TIMEDWAIT_MONOTONIC
865#define TIMEDWAIT pthread_cond_timedwait_monotonic
Ian Rogersc604d732012-10-14 16:09:54 -0700866 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700867#else
868#define TIMEDWAIT pthread_cond_timedwait
Ian Rogersc604d732012-10-14 16:09:54 -0700869 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700870#endif
Ian Rogersc604d732012-10-14 16:09:54 -0700871 guard_.recursion_count_ = 0;
872 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700873 InitTimeSpec(true, clock, ms, ns, &ts);
874 int rc = TEMP_FAILURE_RETRY(TIMEDWAIT(&cond_, &guard_.mutex_, &ts));
Elliott Hughes5f791332011-09-15 17:45:30 -0700875 if (rc != 0 && rc != ETIMEDOUT) {
876 errno = rc;
877 PLOG(FATAL) << "TimedWait failed for " << name_;
878 }
Ian Rogersc604d732012-10-14 16:09:54 -0700879#endif
880 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700881}
882
Elliott Hughese62934d2012-04-09 11:24:29 -0700883} // namespace art