blob: 3265a133cf59496fbd8f4f065b8208864f1c8eb0 [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
Ian Rogers56edc432013-01-18 16:51:51 -0800175void BaseMutex::RecordContention(uint64_t blocked_tid, uint64_t owner_tid, uint64_t milli_time_blocked) {
176#if CONTENTION_LOGGING
177 ++contention_count_;
178 wait_time_ += static_cast<uint32_t>(milli_time_blocked); // May overflow.
179 // This code is intentionally racy as it is only used for diagnostics.
180 uint32_t slot = cur_content_log_entry_;
181 if (contention_log_[slot].blocked_tid == blocked_tid &&
182 contention_log_[slot].owner_tid == blocked_tid) {
183 ++contention_log_[slot].count;
184 } else {
185 uint32_t new_slot;
186 do {
187 slot = cur_content_log_entry_;
188 new_slot = (slot + 1) % kContentionLogSize;
Brian Carlstromdf629502013-07-17 22:39:56 -0700189 } while (!cur_content_log_entry_.CompareAndSwap(slot, new_slot));
Ian Rogers56edc432013-01-18 16:51:51 -0800190 contention_log_[new_slot].blocked_tid = blocked_tid;
191 contention_log_[new_slot].owner_tid = owner_tid;
192 contention_log_[new_slot].count = 1;
193 }
194#endif
195}
196
Ian Rogers56edc432013-01-18 16:51:51 -0800197void BaseMutex::DumpContention(std::ostream& os) const {
198#if CONTENTION_LOGGING
199 uint32_t wait_time = wait_time_;
200 uint32_t contention_count = contention_count_;
201 if (contention_count == 0) {
202 os << "never contended";
203 } else {
204 os << "contended " << contention_count << " times, average wait of contender " << (wait_time / contention_count) << "ms";
205 SafeMap<uint64_t, size_t> most_common_blocker;
206 SafeMap<uint64_t, size_t> most_common_blocked;
207 typedef SafeMap<uint64_t, size_t>::const_iterator It;
208 for (size_t i = 0; i < kContentionLogSize; ++i) {
209 uint64_t blocked_tid = contention_log_[i].blocked_tid;
210 uint64_t owner_tid = contention_log_[i].owner_tid;
211 uint32_t count = contention_log_[i].count;
212 if (count > 0) {
213 It it = most_common_blocked.find(blocked_tid);
214 if (it != most_common_blocked.end()) {
215 most_common_blocked.Overwrite(blocked_tid, it->second + count);
216 } else {
217 most_common_blocked.Put(blocked_tid, count);
218 }
219 it = most_common_blocker.find(owner_tid);
220 if (it != most_common_blocker.end()) {
221 most_common_blocker.Overwrite(owner_tid, it->second + count);
222 } else {
223 most_common_blocker.Put(owner_tid, count);
224 }
225 }
226 }
227 uint64_t max_tid = 0;
228 size_t max_tid_count = 0;
229 for (It it = most_common_blocked.begin(); it != most_common_blocked.end(); ++it) {
230 if (it->second > max_tid_count) {
231 max_tid = it->first;
232 max_tid_count = it->second;
233 }
234 }
235 if (max_tid != 0) {
236 os << " sample shows most blocked tid=" << max_tid;
237 }
238 max_tid = 0;
239 max_tid_count = 0;
240 for (It it = most_common_blocker.begin(); it != most_common_blocker.end(); ++it) {
241 if (it->second > max_tid_count) {
242 max_tid = it->first;
243 max_tid_count = it->second;
244 }
245 }
246 if (max_tid != 0) {
247 os << " sample shows tid=" << max_tid << " owning during this time";
248 }
249 }
250#endif
251}
252
253
Ian Rogers81d425b2012-09-27 16:03:43 -0700254Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700255 : BaseMutex(name, level), recursive_(recursive), recursion_count_(0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700256#if ART_USE_FUTEXES
257 state_ = 0;
258 exclusive_owner_ = 0;
259 num_contenders_ = 0;
260#elif defined(__BIONIC__) || defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700261 // Use recursive mutexes for bionic and Apple otherwise the
262 // non-recursive mutexes don't have TIDs to check lock ownership of.
Elliott Hughesbbd9d832011-11-07 14:40:00 -0800263 pthread_mutexattr_t attributes;
264 CHECK_MUTEX_CALL(pthread_mutexattr_init, (&attributes));
265 CHECK_MUTEX_CALL(pthread_mutexattr_settype, (&attributes, PTHREAD_MUTEX_RECURSIVE));
266 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, &attributes));
267 CHECK_MUTEX_CALL(pthread_mutexattr_destroy, (&attributes));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700268#else
269 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, NULL));
270#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700271}
272
273Mutex::~Mutex() {
Ian Rogersc604d732012-10-14 16:09:54 -0700274#if ART_USE_FUTEXES
275 if (state_ != 0) {
276 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
277 Runtime* runtime = Runtime::Current();
278 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
279 LOG(shutting_down ? WARNING : FATAL) << "destroying mutex with owner: " << exclusive_owner_;
280 } else {
281 CHECK_EQ(exclusive_owner_, 0U) << "unexpectedly found an owner on unlocked mutex " << name_;
282 CHECK_EQ(num_contenders_, 0) << "unexpectedly found a contender on mutex " << name_;
283 }
284#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700285 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
286 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800287 int rc = pthread_mutex_destroy(&mutex_);
288 if (rc != 0) {
289 errno = rc;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800290 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700291 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700292 Runtime* runtime = Runtime::Current();
293 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughes6b355752012-01-13 16:49:08 -0800294 PLOG(shutting_down ? WARNING : FATAL) << "pthread_mutex_destroy failed for " << name_;
295 }
Ian Rogersc604d732012-10-14 16:09:54 -0700296#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700297}
298
Ian Rogers81d425b2012-09-27 16:03:43 -0700299void Mutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700300 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700301 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700302 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700303 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700304 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700305#if ART_USE_FUTEXES
306 bool done = false;
307 do {
308 int32_t cur_state = state_;
309 if (cur_state == 0) {
310 // Change state from 0 to 1.
Ian Rogers693ff612013-02-01 10:56:12 -0800311 done = android_atomic_acquire_cas(0, 1, &state_) == 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700312 } else {
313 // Failed to acquire, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800314 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700315 android_atomic_inc(&num_contenders_);
316 if (futex(&state_, FUTEX_WAIT, 1, NULL, NULL, 0) != 0) {
317 if (errno != EAGAIN) {
318 PLOG(FATAL) << "futex wait failed for " << name_;
319 }
320 }
321 android_atomic_dec(&num_contenders_);
322 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700323 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700324 DCHECK_EQ(state_, 1);
325 exclusive_owner_ = SafeGetTid(self);
326#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700327 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700328#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700329 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700330 }
331 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700332 if (kDebugLocking) {
333 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
334 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700335 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700336 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700337}
338
Ian Rogers81d425b2012-09-27 16:03:43 -0700339bool Mutex::ExclusiveTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700340 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700341 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700342 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700343 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700344 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700345#if ART_USE_FUTEXES
346 bool done = false;
347 do {
348 int32_t cur_state = state_;
349 if (cur_state == 0) {
350 // Change state from 0 to 1.
Ian Rogers693ff612013-02-01 10:56:12 -0800351 done = android_atomic_acquire_cas(0, 1, &state_) == 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700352 } else {
353 return false;
354 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700355 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700356 DCHECK_EQ(state_, 1);
357 exclusive_owner_ = SafeGetTid(self);
358#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700359 int result = pthread_mutex_trylock(&mutex_);
360 if (result == EBUSY) {
361 return false;
362 }
363 if (result != 0) {
364 errno = result;
365 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
366 }
Ian Rogersc604d732012-10-14 16:09:54 -0700367#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700368 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700369 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700370 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700371 if (kDebugLocking) {
372 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
373 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700374 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700375 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700376 return true;
377}
378
Ian Rogers81d425b2012-09-27 16:03:43 -0700379void Mutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700380 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700381 AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700382 recursion_count_--;
383 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700384 if (kDebugLocking) {
385 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
386 << name_ << " " << recursion_count_;
387 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700388 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700389#if ART_USE_FUTEXES
390 bool done = false;
391 do {
392 int32_t cur_state = state_;
393 if (cur_state == 1) {
394 // We're no longer the owner.
395 exclusive_owner_ = 0;
396 // Change state to 0.
Ian Rogers693ff612013-02-01 10:56:12 -0800397 done = android_atomic_release_cas(cur_state, 0, &state_) == 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700398 if (done) { // Spurious fail?
399 // Wake a contender
400 if (num_contenders_ > 0) {
401 futex(&state_, FUTEX_WAKE, 1, NULL, NULL, 0);
402 }
403 }
404 } else {
Ian Rogersc4ee12e2013-05-16 11:19:53 -0700405 // Logging acquires the logging lock, avoid infinite recursion in that case.
406 if (this != Locks::logging_lock_) {
407 LOG(FATAL) << "Unexpected state_ in unlock " << cur_state << " for " << name_;
408 } else {
409 LogMessageData data(__FILE__, __LINE__, INTERNAL_FATAL, -1);
410 LogMessage::LogLine(data, StringPrintf("Unexpected state_ %d in unlock for %s",
411 cur_state, name_).c_str());
412 _exit(1);
413 }
Ian Rogersc604d732012-10-14 16:09:54 -0700414 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700415 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700416#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700417 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700418#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700419 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700420}
421
Ian Rogers81d425b2012-09-27 16:03:43 -0700422bool Mutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700423 DCHECK(self == NULL || self == Thread::Current());
424 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
425 if (kDebugLocking) {
426 // Sanity debug check that if we think it is locked we have it in our held mutexes.
Brian Carlstrom9e419ca2012-11-27 11:31:49 -0800427 if (result && self != NULL && level_ != kMonitorLock && !gAborting) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700428 CHECK_EQ(self->GetHeldMutex(level_), this);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700429 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700430 }
431 return result;
Elliott Hughesf1498432012-03-28 19:34:27 -0700432}
433
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700434uint64_t Mutex::GetExclusiveOwnerTid() const {
Ian Rogersc604d732012-10-14 16:09:54 -0700435#if ART_USE_FUTEXES
436 return exclusive_owner_;
437#elif defined(__BIONIC__)
Elliott Hughesf1498432012-03-28 19:34:27 -0700438 return static_cast<uint64_t>((mutex_.value >> 16) & 0xffff);
Elliott Hughes3147a232011-10-12 15:55:07 -0700439#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700440 return reinterpret_cast<const glibc_pthread_mutex_t*>(&mutex_)->owner;
Elliott Hughescf044312012-01-23 18:48:51 -0800441#elif defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700442 const darwin_pthread_mutex_t* dpmutex = reinterpret_cast<const darwin_pthread_mutex_t*>(&mutex_);
443 pthread_t owner = dpmutex->darwin_pthread_mutex_owner;
Brian Carlstrombd93c302012-08-27 16:58:28 -0700444 // 0 for unowned, -1 for PTHREAD_MTX_TID_SWITCHING
445 // TODO: should we make darwin_pthread_mutex_owner volatile and recheck until not -1?
Brian Carlstromf3a26412012-08-24 11:06:02 -0700446 if ((owner == (pthread_t)0) || (owner == (pthread_t)-1)) {
447 return 0;
448 }
449 uint64_t tid;
450 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
451 return tid;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700452#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700453#error unsupported C library
Elliott Hughes8daa0922011-09-11 13:46:25 -0700454#endif
455}
456
Ian Rogers56edc432013-01-18 16:51:51 -0800457void Mutex::Dump(std::ostream& os) const {
458 os << (recursive_ ? "recursive " : "non-recursive ")
459 << name_
460 << " level=" << static_cast<int>(level_)
461 << " rec=" << recursion_count_
462 << " owner=" << GetExclusiveOwnerTid() << " ";
463 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700464}
465
466std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800467 mu.Dump(os);
468 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700469}
470
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700471ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level)
472 : BaseMutex(name, level)
Ian Rogers81d425b2012-09-27 16:03:43 -0700473#if ART_USE_FUTEXES
474 , state_(0), exclusive_owner_(0), num_pending_readers_(0), num_pending_writers_(0)
475#endif
Brian Carlstrom2ce745c2013-07-17 17:44:30 -0700476{ // NOLINT(whitespace/braces)
Ian Rogers81d425b2012-09-27 16:03:43 -0700477#if !ART_USE_FUTEXES
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700478 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, NULL));
Ian Rogers81d425b2012-09-27 16:03:43 -0700479#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700480}
481
482ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700483#if ART_USE_FUTEXES
484 CHECK_EQ(state_, 0);
485 CHECK_EQ(exclusive_owner_, 0U);
486 CHECK_EQ(num_pending_readers_, 0);
487 CHECK_EQ(num_pending_writers_, 0);
488#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700489 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
490 // may still be using locks.
491 int rc = pthread_rwlock_destroy(&rwlock_);
492 if (rc != 0) {
493 errno = rc;
494 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700495 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700496 Runtime* runtime = Runtime::Current();
497 bool shutting_down = runtime == NULL || runtime->IsShuttingDown();
498 PLOG(shutting_down ? WARNING : FATAL) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800499 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700500#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700501}
502
Ian Rogers81d425b2012-09-27 16:03:43 -0700503void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700504 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700505 AssertNotExclusiveHeld(self);
506#if ART_USE_FUTEXES
507 bool done = false;
508 do {
509 int32_t cur_state = state_;
510 if (cur_state == 0) {
511 // Change state from 0 to -1.
Ian Rogers693ff612013-02-01 10:56:12 -0800512 done = android_atomic_acquire_cas(0, -1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700513 } else {
514 // Failed to acquire, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800515 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700516 android_atomic_inc(&num_pending_writers_);
517 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
518 if (errno != EAGAIN) {
519 PLOG(FATAL) << "futex wait failed for " << name_;
520 }
521 }
522 android_atomic_dec(&num_pending_writers_);
523 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700524 } while (!done);
Ian Rogersab470162012-09-29 23:06:53 -0700525 DCHECK_EQ(state_, -1);
526 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700527#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700528 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700529#endif
530 RegisterAsLocked(self);
531 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700532}
533
Ian Rogers81d425b2012-09-27 16:03:43 -0700534void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700535 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700536 AssertExclusiveHeld(self);
537 RegisterAsUnlocked(self);
538#if ART_USE_FUTEXES
539 bool done = false;
540 do {
541 int32_t cur_state = state_;
542 if (cur_state == -1) {
543 // We're no longer the owner.
544 exclusive_owner_ = 0;
545 // Change state from -1 to 0.
Ian Rogers693ff612013-02-01 10:56:12 -0800546 done = android_atomic_release_cas(-1, 0, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700547 if (done) { // cmpxchg may fail due to noise?
548 // Wake any waiters.
549 if (num_pending_readers_ > 0 || num_pending_writers_ > 0) {
550 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
551 }
552 }
553 } else {
554 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
555 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700556 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700557#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700558 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700559#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700560}
561
Ian Rogers66aee5c2012-08-15 17:17:47 -0700562#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700563bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700564 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700565#if ART_USE_FUTEXES
566 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700567 timespec end_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800568 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700569 do {
570 int32_t cur_state = state_;
571 if (cur_state == 0) {
572 // Change state from 0 to -1.
Ian Rogers693ff612013-02-01 10:56:12 -0800573 done = android_atomic_acquire_cas(0, -1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700574 } else {
575 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700576 timespec now_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800577 InitTimeSpec(true, CLOCK_REALTIME, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700578 timespec rel_ts;
579 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
580 return false; // Timed out.
581 }
Ian Rogers56edc432013-01-18 16:51:51 -0800582 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700583 android_atomic_inc(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700584 if (futex(&state_, FUTEX_WAIT, cur_state, &rel_ts, NULL, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700585 if (errno == ETIMEDOUT) {
586 android_atomic_dec(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700587 return false; // Timed out.
588 } else if (errno != EAGAIN && errno != EINTR) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700589 PLOG(FATAL) << "timed futex wait failed for " << name_;
590 }
591 }
592 android_atomic_dec(&num_pending_writers_);
593 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700594 } while (!done);
Ian Rogers01ae5802012-09-28 16:14:01 -0700595 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700596#else
Ian Rogersc604d732012-10-14 16:09:54 -0700597 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700598 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700599 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700600 if (result == ETIMEDOUT) {
601 return false;
602 }
603 if (result != 0) {
604 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700605 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700606 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700607#endif
608 RegisterAsLocked(self);
609 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700610 return true;
611}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700612#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700613
Ian Rogers81d425b2012-09-27 16:03:43 -0700614bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700615 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700616#if ART_USE_FUTEXES
617 bool done = false;
618 do {
619 int32_t cur_state = state_;
620 if (cur_state >= 0) {
621 // Add as an extra reader.
Ian Rogers693ff612013-02-01 10:56:12 -0800622 done = android_atomic_acquire_cas(cur_state, cur_state + 1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700623 } else {
624 // Owner holds it exclusively.
625 return false;
626 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700627 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700628#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700629 int result = pthread_rwlock_tryrdlock(&rwlock_);
630 if (result == EBUSY) {
631 return false;
632 }
633 if (result != 0) {
634 errno = result;
635 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
636 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700637#endif
638 RegisterAsLocked(self);
639 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700640 return true;
641}
642
Ian Rogers81d425b2012-09-27 16:03:43 -0700643bool ReaderWriterMutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700644 DCHECK(self == NULL || self == Thread::Current());
645 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700646 if (kDebugLocking) {
647 // Sanity that if the pthread thinks we own the lock the Thread agrees.
Ian Rogers01ae5802012-09-28 16:14:01 -0700648 if (self != NULL && result) {
649 CHECK_EQ(self->GetHeldMutex(level_), this);
650 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700651 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700652 return result;
653}
654
Ian Rogers81d425b2012-09-27 16:03:43 -0700655bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700656 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700657 bool result;
658 if (UNLIKELY(self == NULL)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700659 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700660 } else {
661 result = (self->GetHeldMutex(level_) == this);
662 }
663 return result;
664}
665
666uint64_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700667#if ART_USE_FUTEXES
Ian Rogers56edc432013-01-18 16:51:51 -0800668 int32_t state = state_;
669 if (state == 0) {
670 return 0; // No owner.
671 } else if (state > 0) {
672 return -1; // Shared.
673 } else {
674 return exclusive_owner_;
675 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700676#else
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800677#if defined(__BIONIC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700678 return rwlock_.writerThreadId;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800679#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700680 return reinterpret_cast<const glibc_pthread_rwlock_t*>(&rwlock_)->writer;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800681#elif defined(__APPLE__)
Ian Rogers81d425b2012-09-27 16:03:43 -0700682 const darwin_pthread_rwlock_t*
683 dprwlock = reinterpret_cast<const darwin_pthread_rwlock_t*>(&rwlock_);
Brian Carlstromf3a26412012-08-24 11:06:02 -0700684 pthread_t owner = dprwlock->darwin_pthread_rwlock_owner;
685 if (owner == (pthread_t)0) {
686 return 0;
687 }
688 uint64_t tid;
689 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
690 return tid;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800691#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700692#error unsupported C library
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800693#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700694#endif
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800695}
696
Ian Rogers56edc432013-01-18 16:51:51 -0800697void ReaderWriterMutex::Dump(std::ostream& os) const {
698 os << name_
699 << " level=" << static_cast<int>(level_)
700 << " owner=" << GetExclusiveOwnerTid() << " ";
701 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700702}
703
704std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800705 mu.Dump(os);
706 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700707}
708
Ian Rogers23055dc2013-04-18 16:29:16 -0700709ConditionVariable::ConditionVariable(const char* name, Mutex& guard)
Ian Rogersc604d732012-10-14 16:09:54 -0700710 : name_(name), guard_(guard) {
711#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800712 sequence_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700713 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700714#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700715 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, NULL));
Ian Rogersc604d732012-10-14 16:09:54 -0700716#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700717}
718
719ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800720#if ART_USE_FUTEXES
721 if (num_waiters_!= 0) {
722 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
723 Runtime* runtime = Runtime::Current();
724 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Ian Rogersd45f2012012-11-28 11:46:23 -0800725 LOG(shutting_down ? WARNING : FATAL) << "ConditionVariable::~ConditionVariable for " << name_
726 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800727 }
728#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700729 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
730 // may still be using condition variables.
731 int rc = pthread_cond_destroy(&cond_);
732 if (rc != 0) {
733 errno = rc;
Ian Rogers50b35e22012-10-04 10:09:15 -0700734 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700735 Runtime* runtime = Runtime::Current();
736 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughese62934d2012-04-09 11:24:29 -0700737 PLOG(shutting_down ? WARNING : FATAL) << "pthread_cond_destroy failed for " << name_;
738 }
Ian Rogersc604d732012-10-14 16:09:54 -0700739#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700740}
741
Ian Rogersc604d732012-10-14 16:09:54 -0700742void ConditionVariable::Broadcast(Thread* self) {
743 DCHECK(self == NULL || self == Thread::Current());
744 // TODO: enable below, there's a race in thread creation that causes false failures currently.
745 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700746 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700747#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800748 if (num_waiters_ > 0) {
749 android_atomic_inc(&sequence_); // Indicate the broadcast occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700750 bool done = false;
751 do {
Ian Rogersd45f2012012-11-28 11:46:23 -0800752 int32_t cur_sequence = sequence_;
753 // Requeue waiters onto mutex. The waiter holds the contender count on the mutex high ensuring
754 // mutex unlocks will awaken the requeued waiter thread.
755 done = futex(&sequence_, FUTEX_CMP_REQUEUE, 0,
Ian Rogers5bd97c42012-11-27 02:38:26 -0800756 reinterpret_cast<const timespec*>(std::numeric_limits<int32_t>::max()),
Ian Rogersd45f2012012-11-28 11:46:23 -0800757 &guard_.state_, cur_sequence) != -1;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800758 if (!done) {
759 if (errno != EAGAIN) {
760 PLOG(FATAL) << "futex cmp requeue failed for " << name_;
761 }
Ian Rogers5bd97c42012-11-27 02:38:26 -0800762 }
Ian Rogersc604d732012-10-14 16:09:54 -0700763 } while (!done);
764 }
765#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700766 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700767#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700768}
769
Ian Rogersc604d732012-10-14 16:09:54 -0700770void ConditionVariable::Signal(Thread* self) {
771 DCHECK(self == NULL || self == Thread::Current());
772 guard_.AssertExclusiveHeld(self);
773#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800774 if (num_waiters_ > 0) {
775 android_atomic_inc(&sequence_); // Indicate a signal occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700776 // Futex wake 1 waiter who will then come and in contend on mutex. It'd be nice to requeue them
777 // to avoid this, however, requeueing can only move all waiters.
Ian Rogersd45f2012012-11-28 11:46:23 -0800778 int num_woken = futex(&sequence_, FUTEX_WAKE, 1, NULL, NULL, 0);
779 // Check something was woken or else we changed sequence_ before they had chance to wait.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800780 CHECK((num_woken == 0) || (num_woken == 1));
Ian Rogersc604d732012-10-14 16:09:54 -0700781 }
782#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700783 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700784#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700785}
786
Ian Rogersc604d732012-10-14 16:09:54 -0700787void ConditionVariable::Wait(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700788 guard_.CheckSafeToWait(self);
789 WaitHoldingLocks(self);
790}
791
792void ConditionVariable::WaitHoldingLocks(Thread* self) {
Ian Rogersc604d732012-10-14 16:09:54 -0700793 DCHECK(self == NULL || self == Thread::Current());
794 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700795 unsigned int old_recursion_count = guard_.recursion_count_;
796#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700797 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800798 // Ensure the Mutex is contended so that requeued threads are awoken.
799 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700800 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800801 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700802 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800803 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, NULL, NULL, 0) != 0) {
804 // Futex failed, check it is an expected error.
805 // EAGAIN == EWOULDBLK, so we let the caller try again.
806 // EINTR implies a signal was sent to this thread.
807 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700808 PLOG(FATAL) << "futex wait failed for " << name_;
809 }
810 }
811 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800812 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700813 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800814 // We awoke and so no longer require awakes from the guard_'s unlock.
815 CHECK_GE(guard_.num_contenders_, 0);
816 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700817#else
818 guard_.recursion_count_ = 0;
819 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
820#endif
821 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700822}
823
Ian Rogersc604d732012-10-14 16:09:54 -0700824void ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
825 DCHECK(self == NULL || self == Thread::Current());
826 guard_.AssertExclusiveHeld(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700827 guard_.CheckSafeToWait(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700828 unsigned int old_recursion_count = guard_.recursion_count_;
829#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700830 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800831 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700832 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800833 // Ensure the Mutex is contended so that requeued threads are awoken.
834 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700835 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800836 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700837 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800838 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, &rel_ts, NULL, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700839 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800840 // Timed out we're done.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800841 } else if ((errno == EINTR) || (errno == EAGAIN)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800842 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700843 } else {
844 PLOG(FATAL) << "timed futex wait failed for " << name_;
845 }
846 }
847 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800848 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700849 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800850 // We awoke and so no longer require awakes from the guard_'s unlock.
851 CHECK_GE(guard_.num_contenders_, 0);
852 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700853#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700854#ifdef HAVE_TIMEDWAIT_MONOTONIC
855#define TIMEDWAIT pthread_cond_timedwait_monotonic
Ian Rogersc604d732012-10-14 16:09:54 -0700856 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700857#else
858#define TIMEDWAIT pthread_cond_timedwait
Ian Rogersc604d732012-10-14 16:09:54 -0700859 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700860#endif
Ian Rogersc604d732012-10-14 16:09:54 -0700861 guard_.recursion_count_ = 0;
862 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700863 InitTimeSpec(true, clock, ms, ns, &ts);
864 int rc = TEMP_FAILURE_RETRY(TIMEDWAIT(&cond_, &guard_.mutex_, &ts));
Elliott Hughes5f791332011-09-15 17:45:30 -0700865 if (rc != 0 && rc != ETIMEDOUT) {
866 errno = rc;
867 PLOG(FATAL) << "TimedWait failed for " << name_;
868 }
Ian Rogersc604d732012-10-14 16:09:54 -0700869#endif
870 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700871}
872
Elliott Hughese62934d2012-04-09 11:24:29 -0700873} // namespace art