blob: 30079786d765406dcf65dda06eede0983a49a66a [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
Brian Carlstrom6eb52882013-07-19 00:31:07 -070034#if defined(__APPLE__)
35
Brian Carlstromf3a26412012-08-24 11:06:02 -070036// This works on Mac OS 10.6 but hasn't been tested on older releases.
Elliott Hughesf1498432012-03-28 19:34:27 -070037struct __attribute__((__may_alias__)) darwin_pthread_mutex_t {
Brian Carlstrom6eb52882013-07-19 00:31:07 -070038 long padding0; // NOLINT(runtime/int) exact match to darwin type
Brian Carlstromf3a26412012-08-24 11:06:02 -070039 int padding1;
40 uint32_t padding2;
41 int16_t padding3;
42 int16_t padding4;
43 uint32_t padding5;
44 pthread_t darwin_pthread_mutex_owner;
Ian Rogers00f7d0e2012-07-19 15:28:27 -070045 // ...other stuff we don't care about.
46};
47
48struct __attribute__((__may_alias__)) darwin_pthread_rwlock_t {
Brian Carlstrom6eb52882013-07-19 00:31:07 -070049 long padding0; // NOLINT(runtime/int) exact match to darwin type
Brian Carlstromf3a26412012-08-24 11:06:02 -070050 pthread_mutex_t padding1;
51 int padding2;
52 pthread_cond_t padding3;
53 pthread_cond_t padding4;
54 int padding5;
55 int padding6;
56 pthread_t darwin_pthread_rwlock_owner;
Elliott Hughesf1498432012-03-28 19:34:27 -070057 // ...other stuff we don't care about.
58};
59
Brian Carlstrom6eb52882013-07-19 00:31:07 -070060#endif // __APPLE__
61
62#if defined(__GLIBC__)
63
Elliott Hughesf1498432012-03-28 19:34:27 -070064struct __attribute__((__may_alias__)) glibc_pthread_mutex_t {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070065 int32_t padding0[2];
Elliott Hughesf1498432012-03-28 19:34:27 -070066 int owner;
67 // ...other stuff we don't care about.
68};
69
Ian Rogers00f7d0e2012-07-19 15:28:27 -070070struct __attribute__((__may_alias__)) glibc_pthread_rwlock_t {
71#ifdef __LP64__
72 int32_t padding0[6];
73#else
74 int32_t padding0[7];
75#endif
76 int writer;
77 // ...other stuff we don't care about.
78};
79
Brian Carlstrom6eb52882013-07-19 00:31:07 -070080#endif // __GLIBC__
81
Ian Rogersc604d732012-10-14 16:09:54 -070082#if ART_USE_FUTEXES
83static bool ComputeRelativeTimeSpec(timespec* result_ts, const timespec& lhs, const timespec& rhs) {
Brian Carlstromfb6996f2013-07-18 18:21:14 -070084 const int32_t one_sec = 1000 * 1000 * 1000; // one second in nanoseconds.
Ian Rogersc604d732012-10-14 16:09:54 -070085 result_ts->tv_sec = lhs.tv_sec - rhs.tv_sec;
86 result_ts->tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
87 if (result_ts->tv_nsec < 0) {
88 result_ts->tv_sec--;
89 result_ts->tv_nsec += one_sec;
90 } else if (result_ts->tv_nsec > one_sec) {
91 result_ts->tv_sec++;
92 result_ts->tv_nsec -= one_sec;
93 }
94 return result_ts->tv_sec < 0;
95}
96#endif
97
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070098struct AllMutexData {
99 // A guard for all_mutexes_ that's not a mutex (Mutexes must CAS to acquire and busy wait).
100 AtomicInteger all_mutexes_guard;
101 // All created mutexes guarded by all_mutexes_guard_.
102 std::set<BaseMutex*>* all_mutexes;
103 AllMutexData() : all_mutexes(NULL) {}
104};
105static struct AllMutexData all_mutex_data[kAllMutexDataSize];
Ian Rogers56edc432013-01-18 16:51:51 -0800106
107class ScopedAllMutexesLock {
108 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700109 explicit ScopedAllMutexesLock(const BaseMutex* mutex) : mutex_(mutex) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700110 while (!all_mutex_data->all_mutexes_guard.compare_and_swap(0, reinterpret_cast<int32_t>(mutex))) {
Ian Rogers56edc432013-01-18 16:51:51 -0800111 NanoSleep(100);
112 }
113 }
114 ~ScopedAllMutexesLock() {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700115 while (!all_mutex_data->all_mutexes_guard.compare_and_swap(reinterpret_cast<int32_t>(mutex_), 0)) {
Ian Rogers56edc432013-01-18 16:51:51 -0800116 NanoSleep(100);
117 }
118 }
119 private:
120 const BaseMutex* const mutex_;
121};
Ian Rogers56edc432013-01-18 16:51:51 -0800122
123BaseMutex::BaseMutex(const char* name, LockLevel level) : level_(level), name_(name) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700124 if (kLogLockContentions) {
125 ScopedAllMutexesLock mu(this);
126 std::set<BaseMutex*>** all_mutexes_ptr = &all_mutex_data->all_mutexes;
127 if (*all_mutexes_ptr == NULL) {
128 // We leak the global set of all mutexes to avoid ordering issues in global variable
129 // construction/destruction.
130 *all_mutexes_ptr = new std::set<BaseMutex*>();
131 }
132 (*all_mutexes_ptr)->insert(this);
Ian Rogers56edc432013-01-18 16:51:51 -0800133 }
Ian Rogers56edc432013-01-18 16:51:51 -0800134}
135
136BaseMutex::~BaseMutex() {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700137 if (kLogLockContentions) {
138 ScopedAllMutexesLock mu(this);
139 all_mutex_data->all_mutexes->erase(this);
140 }
Ian Rogers56edc432013-01-18 16:51:51 -0800141}
142
143void BaseMutex::DumpAll(std::ostream& os) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700144 if (kLogLockContentions) {
145 os << "Mutex logging:\n";
146 ScopedAllMutexesLock mu(reinterpret_cast<const BaseMutex*>(-1));
147 std::set<BaseMutex*>* all_mutexes = all_mutex_data->all_mutexes;
148 if (all_mutexes == NULL) {
149 // No mutexes have been created yet during at startup.
150 return;
151 }
152 typedef std::set<BaseMutex*>::const_iterator It;
153 os << "(Contented)\n";
154 for (It it = all_mutexes->begin(); it != all_mutexes->end(); ++it) {
155 BaseMutex* mutex = *it;
156 if (mutex->HasEverContended()) {
157 mutex->Dump(os);
158 os << "\n";
159 }
160 }
161 os << "(Never contented)\n";
162 for (It it = all_mutexes->begin(); it != all_mutexes->end(); ++it) {
163 BaseMutex* mutex = *it;
164 if (!mutex->HasEverContended()) {
165 mutex->Dump(os);
166 os << "\n";
167 }
168 }
Ian Rogers56edc432013-01-18 16:51:51 -0800169 }
Ian Rogers56edc432013-01-18 16:51:51 -0800170}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700171
Ian Rogers81d425b2012-09-27 16:03:43 -0700172void BaseMutex::CheckSafeToWait(Thread* self) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700173 if (self == NULL) {
174 CheckUnattachedThread(level_);
175 return;
176 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700177 if (kDebugLocking) {
178 CHECK(self->GetHeldMutex(level_) == this) << "Waiting on unacquired mutex: " << name_;
179 bool bad_mutexes_held = false;
Elliott Hughes0f827162013-02-26 12:12:58 -0800180 for (int i = kLockLevelCount - 1; i >= 0; --i) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700181 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700182 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700183 if (held_mutex != NULL) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800184 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
185 << "(level " << LockLevel(i) << ") while performing wait on "
186 << "\"" << name_ << "\" (level " << level_ << ")";
Ian Rogers25fd14b2012-09-05 10:56:38 -0700187 bad_mutexes_held = true;
188 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700189 }
190 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700191 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700192 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700193}
194
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700195inline void BaseMutex::ContentionLogData::AddToWaitTime(uint64_t value) {
196 if (kLogLockContentions) {
197 // Atomically add value to wait_time.
198 uint64_t new_val, old_val;
199 volatile int64_t* addr = reinterpret_cast<volatile int64_t*>(&wait_time);
200 volatile const int64_t* caddr = const_cast<volatile const int64_t*>(addr);
201 do {
202 old_val = static_cast<uint64_t>(QuasiAtomic::Read64(caddr));
203 new_val = old_val + value;
204 } while (!QuasiAtomic::Cas64(static_cast<int64_t>(old_val), static_cast<int64_t>(new_val), addr));
205 }
206}
207
Brian Carlstrom0de79852013-07-25 22:29:58 -0700208void BaseMutex::RecordContention(uint64_t blocked_tid,
209 uint64_t owner_tid,
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700210 uint64_t nano_time_blocked) {
211 if (kLogLockContentions) {
212 ContentionLogData* data = contetion_log_data_;
213 ++(data->contention_count);
214 data->AddToWaitTime(nano_time_blocked);
215 ContentionLogEntry* log = data->contention_log;
216 // This code is intentionally racy as it is only used for diagnostics.
217 uint32_t slot = data->cur_content_log_entry;
218 if (log[slot].blocked_tid == blocked_tid &&
219 log[slot].owner_tid == blocked_tid) {
220 ++log[slot].count;
221 } else {
222 uint32_t new_slot;
223 do {
224 slot = data->cur_content_log_entry;
225 new_slot = (slot + 1) % kContentionLogSize;
226 } while (!data->cur_content_log_entry.compare_and_swap(slot, new_slot));
227 log[new_slot].blocked_tid = blocked_tid;
228 log[new_slot].owner_tid = owner_tid;
229 log[new_slot].count = 1;
230 }
Ian Rogers56edc432013-01-18 16:51:51 -0800231 }
Ian Rogers56edc432013-01-18 16:51:51 -0800232}
233
Ian Rogers56edc432013-01-18 16:51:51 -0800234void BaseMutex::DumpContention(std::ostream& os) const {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700235 if (kLogLockContentions) {
236 const ContentionLogData* data = contetion_log_data_;
237 const ContentionLogEntry* log = data->contention_log;
238 uint64_t wait_time = data->wait_time;
239 uint32_t contention_count = data->contention_count;
240 if (contention_count == 0) {
241 os << "never contended";
242 } else {
243 os << "contended " << contention_count
244 << " times, average wait of contender " << PrettyDuration(wait_time / contention_count);
245 SafeMap<uint64_t, size_t> most_common_blocker;
246 SafeMap<uint64_t, size_t> most_common_blocked;
247 typedef SafeMap<uint64_t, size_t>::const_iterator It;
248 for (size_t i = 0; i < kContentionLogSize; ++i) {
249 uint64_t blocked_tid = log[i].blocked_tid;
250 uint64_t owner_tid = log[i].owner_tid;
251 uint32_t count = log[i].count;
252 if (count > 0) {
253 It it = most_common_blocked.find(blocked_tid);
254 if (it != most_common_blocked.end()) {
255 most_common_blocked.Overwrite(blocked_tid, it->second + count);
256 } else {
257 most_common_blocked.Put(blocked_tid, count);
258 }
259 it = most_common_blocker.find(owner_tid);
260 if (it != most_common_blocker.end()) {
261 most_common_blocker.Overwrite(owner_tid, it->second + count);
262 } else {
263 most_common_blocker.Put(owner_tid, count);
264 }
Ian Rogers56edc432013-01-18 16:51:51 -0800265 }
266 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700267 uint64_t max_tid = 0;
268 size_t max_tid_count = 0;
269 for (It it = most_common_blocked.begin(); it != most_common_blocked.end(); ++it) {
270 if (it->second > max_tid_count) {
271 max_tid = it->first;
272 max_tid_count = it->second;
273 }
Ian Rogers56edc432013-01-18 16:51:51 -0800274 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700275 if (max_tid != 0) {
276 os << " sample shows most blocked tid=" << max_tid;
Ian Rogers56edc432013-01-18 16:51:51 -0800277 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700278 max_tid = 0;
279 max_tid_count = 0;
280 for (It it = most_common_blocker.begin(); it != most_common_blocker.end(); ++it) {
281 if (it->second > max_tid_count) {
282 max_tid = it->first;
283 max_tid_count = it->second;
284 }
285 }
286 if (max_tid != 0) {
287 os << " sample shows tid=" << max_tid << " owning during this time";
288 }
Ian Rogers56edc432013-01-18 16:51:51 -0800289 }
290 }
Ian Rogers56edc432013-01-18 16:51:51 -0800291}
292
293
Ian Rogers81d425b2012-09-27 16:03:43 -0700294Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700295 : BaseMutex(name, level), recursive_(recursive), recursion_count_(0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700296#if ART_USE_FUTEXES
297 state_ = 0;
298 exclusive_owner_ = 0;
299 num_contenders_ = 0;
300#elif defined(__BIONIC__) || defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700301 // Use recursive mutexes for bionic and Apple otherwise the
302 // non-recursive mutexes don't have TIDs to check lock ownership of.
Elliott Hughesbbd9d832011-11-07 14:40:00 -0800303 pthread_mutexattr_t attributes;
304 CHECK_MUTEX_CALL(pthread_mutexattr_init, (&attributes));
305 CHECK_MUTEX_CALL(pthread_mutexattr_settype, (&attributes, PTHREAD_MUTEX_RECURSIVE));
306 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, &attributes));
307 CHECK_MUTEX_CALL(pthread_mutexattr_destroy, (&attributes));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700308#else
309 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, NULL));
310#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700311}
312
313Mutex::~Mutex() {
Ian Rogersc604d732012-10-14 16:09:54 -0700314#if ART_USE_FUTEXES
315 if (state_ != 0) {
316 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
317 Runtime* runtime = Runtime::Current();
318 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
319 LOG(shutting_down ? WARNING : FATAL) << "destroying mutex with owner: " << exclusive_owner_;
320 } else {
321 CHECK_EQ(exclusive_owner_, 0U) << "unexpectedly found an owner on unlocked mutex " << name_;
322 CHECK_EQ(num_contenders_, 0) << "unexpectedly found a contender on mutex " << name_;
323 }
324#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700325 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
326 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800327 int rc = pthread_mutex_destroy(&mutex_);
328 if (rc != 0) {
329 errno = rc;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800330 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700331 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700332 Runtime* runtime = Runtime::Current();
333 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughes6b355752012-01-13 16:49:08 -0800334 PLOG(shutting_down ? WARNING : FATAL) << "pthread_mutex_destroy failed for " << name_;
335 }
Ian Rogersc604d732012-10-14 16:09:54 -0700336#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700337}
338
Ian Rogers81d425b2012-09-27 16:03:43 -0700339void Mutex::ExclusiveLock(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 // Failed to acquire, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800354 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700355 android_atomic_inc(&num_contenders_);
356 if (futex(&state_, FUTEX_WAIT, 1, NULL, NULL, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700357 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
358 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
359 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700360 PLOG(FATAL) << "futex wait failed for " << name_;
361 }
362 }
363 android_atomic_dec(&num_contenders_);
364 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700365 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700366 DCHECK_EQ(state_, 1);
367 exclusive_owner_ = SafeGetTid(self);
368#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700369 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700370#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700371 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700372 }
373 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700374 if (kDebugLocking) {
375 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
376 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700377 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700378 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700379}
380
Ian Rogers81d425b2012-09-27 16:03:43 -0700381bool Mutex::ExclusiveTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700382 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700383 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700384 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700385 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700386 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700387#if ART_USE_FUTEXES
388 bool done = false;
389 do {
390 int32_t cur_state = state_;
391 if (cur_state == 0) {
392 // Change state from 0 to 1.
Ian Rogers693ff612013-02-01 10:56:12 -0800393 done = android_atomic_acquire_cas(0, 1, &state_) == 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700394 } else {
395 return false;
396 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700397 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700398 DCHECK_EQ(state_, 1);
399 exclusive_owner_ = SafeGetTid(self);
400#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700401 int result = pthread_mutex_trylock(&mutex_);
402 if (result == EBUSY) {
403 return false;
404 }
405 if (result != 0) {
406 errno = result;
407 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
408 }
Ian Rogersc604d732012-10-14 16:09:54 -0700409#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700410 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700411 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700412 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700413 if (kDebugLocking) {
414 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
415 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700416 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700417 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700418 return true;
419}
420
Ian Rogers81d425b2012-09-27 16:03:43 -0700421void Mutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700422 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700423 AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700424 recursion_count_--;
425 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700426 if (kDebugLocking) {
427 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
428 << name_ << " " << recursion_count_;
429 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700430 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700431#if ART_USE_FUTEXES
432 bool done = false;
433 do {
434 int32_t cur_state = state_;
435 if (cur_state == 1) {
436 // We're no longer the owner.
437 exclusive_owner_ = 0;
438 // Change state to 0.
Ian Rogers693ff612013-02-01 10:56:12 -0800439 done = android_atomic_release_cas(cur_state, 0, &state_) == 0;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700440 if (done) { // Spurious fail?
Ian Rogersc604d732012-10-14 16:09:54 -0700441 // Wake a contender
442 if (num_contenders_ > 0) {
443 futex(&state_, FUTEX_WAKE, 1, NULL, NULL, 0);
444 }
445 }
446 } else {
Ian Rogersc4ee12e2013-05-16 11:19:53 -0700447 // Logging acquires the logging lock, avoid infinite recursion in that case.
448 if (this != Locks::logging_lock_) {
449 LOG(FATAL) << "Unexpected state_ in unlock " << cur_state << " for " << name_;
450 } else {
451 LogMessageData data(__FILE__, __LINE__, INTERNAL_FATAL, -1);
452 LogMessage::LogLine(data, StringPrintf("Unexpected state_ %d in unlock for %s",
453 cur_state, name_).c_str());
454 _exit(1);
455 }
Ian Rogersc604d732012-10-14 16:09:54 -0700456 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700457 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700458#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700459 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700460#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700461 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700462}
463
Ian Rogers81d425b2012-09-27 16:03:43 -0700464bool Mutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700465 DCHECK(self == NULL || self == Thread::Current());
466 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
467 if (kDebugLocking) {
468 // Sanity debug check that if we think it is locked we have it in our held mutexes.
Brian Carlstrom9e419ca2012-11-27 11:31:49 -0800469 if (result && self != NULL && level_ != kMonitorLock && !gAborting) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700470 CHECK_EQ(self->GetHeldMutex(level_), this);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700471 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700472 }
473 return result;
Elliott Hughesf1498432012-03-28 19:34:27 -0700474}
475
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700476uint64_t Mutex::GetExclusiveOwnerTid() const {
Ian Rogersc604d732012-10-14 16:09:54 -0700477#if ART_USE_FUTEXES
478 return exclusive_owner_;
479#elif defined(__BIONIC__)
Elliott Hughesf1498432012-03-28 19:34:27 -0700480 return static_cast<uint64_t>((mutex_.value >> 16) & 0xffff);
Elliott Hughes3147a232011-10-12 15:55:07 -0700481#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700482 return reinterpret_cast<const glibc_pthread_mutex_t*>(&mutex_)->owner;
Elliott Hughescf044312012-01-23 18:48:51 -0800483#elif defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700484 const darwin_pthread_mutex_t* dpmutex = reinterpret_cast<const darwin_pthread_mutex_t*>(&mutex_);
485 pthread_t owner = dpmutex->darwin_pthread_mutex_owner;
Brian Carlstrombd93c302012-08-27 16:58:28 -0700486 // 0 for unowned, -1 for PTHREAD_MTX_TID_SWITCHING
487 // TODO: should we make darwin_pthread_mutex_owner volatile and recheck until not -1?
Brian Carlstromf3a26412012-08-24 11:06:02 -0700488 if ((owner == (pthread_t)0) || (owner == (pthread_t)-1)) {
489 return 0;
490 }
491 uint64_t tid;
492 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
493 return tid;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700494#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700495#error unsupported C library
Elliott Hughes8daa0922011-09-11 13:46:25 -0700496#endif
497}
498
Ian Rogers56edc432013-01-18 16:51:51 -0800499void Mutex::Dump(std::ostream& os) const {
500 os << (recursive_ ? "recursive " : "non-recursive ")
501 << name_
502 << " level=" << static_cast<int>(level_)
503 << " rec=" << recursion_count_
504 << " owner=" << GetExclusiveOwnerTid() << " ";
505 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700506}
507
508std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800509 mu.Dump(os);
510 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700511}
512
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700513ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level)
514 : BaseMutex(name, level)
Ian Rogers81d425b2012-09-27 16:03:43 -0700515#if ART_USE_FUTEXES
516 , state_(0), exclusive_owner_(0), num_pending_readers_(0), num_pending_writers_(0)
517#endif
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700518{ // NOLINT(whitespace/braces)
Ian Rogers81d425b2012-09-27 16:03:43 -0700519#if !ART_USE_FUTEXES
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700520 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, NULL));
Ian Rogers81d425b2012-09-27 16:03:43 -0700521#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700522}
523
524ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700525#if ART_USE_FUTEXES
526 CHECK_EQ(state_, 0);
527 CHECK_EQ(exclusive_owner_, 0U);
528 CHECK_EQ(num_pending_readers_, 0);
529 CHECK_EQ(num_pending_writers_, 0);
530#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700531 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
532 // may still be using locks.
533 int rc = pthread_rwlock_destroy(&rwlock_);
534 if (rc != 0) {
535 errno = rc;
536 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700537 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700538 Runtime* runtime = Runtime::Current();
539 bool shutting_down = runtime == NULL || runtime->IsShuttingDown();
540 PLOG(shutting_down ? WARNING : FATAL) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800541 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700542#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700543}
544
Ian Rogers81d425b2012-09-27 16:03:43 -0700545void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700546 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700547 AssertNotExclusiveHeld(self);
548#if ART_USE_FUTEXES
549 bool done = false;
550 do {
551 int32_t cur_state = state_;
552 if (cur_state == 0) {
553 // Change state from 0 to -1.
Ian Rogers693ff612013-02-01 10:56:12 -0800554 done = android_atomic_acquire_cas(0, -1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700555 } else {
556 // Failed to acquire, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800557 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700558 android_atomic_inc(&num_pending_writers_);
559 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700560 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
561 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
562 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700563 PLOG(FATAL) << "futex wait failed for " << name_;
564 }
565 }
566 android_atomic_dec(&num_pending_writers_);
567 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700568 } while (!done);
Ian Rogersab470162012-09-29 23:06:53 -0700569 DCHECK_EQ(state_, -1);
570 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700571#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700572 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700573#endif
574 RegisterAsLocked(self);
575 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700576}
577
Ian Rogers81d425b2012-09-27 16:03:43 -0700578void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700579 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700580 AssertExclusiveHeld(self);
581 RegisterAsUnlocked(self);
582#if ART_USE_FUTEXES
583 bool done = false;
584 do {
585 int32_t cur_state = state_;
586 if (cur_state == -1) {
587 // We're no longer the owner.
588 exclusive_owner_ = 0;
589 // Change state from -1 to 0.
Ian Rogers693ff612013-02-01 10:56:12 -0800590 done = android_atomic_release_cas(-1, 0, &state_) == 0;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700591 if (done) { // cmpxchg may fail due to noise?
Ian Rogers81d425b2012-09-27 16:03:43 -0700592 // Wake any waiters.
593 if (num_pending_readers_ > 0 || num_pending_writers_ > 0) {
594 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
595 }
596 }
597 } else {
598 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
599 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700600 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700601#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700602 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700603#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700604}
605
Ian Rogers66aee5c2012-08-15 17:17:47 -0700606#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700607bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700608 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700609#if ART_USE_FUTEXES
610 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700611 timespec end_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800612 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700613 do {
614 int32_t cur_state = state_;
615 if (cur_state == 0) {
616 // Change state from 0 to -1.
Ian Rogers693ff612013-02-01 10:56:12 -0800617 done = android_atomic_acquire_cas(0, -1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700618 } else {
619 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700620 timespec now_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800621 InitTimeSpec(true, CLOCK_REALTIME, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700622 timespec rel_ts;
623 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
624 return false; // Timed out.
625 }
Ian Rogers56edc432013-01-18 16:51:51 -0800626 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700627 android_atomic_inc(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700628 if (futex(&state_, FUTEX_WAIT, cur_state, &rel_ts, NULL, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700629 if (errno == ETIMEDOUT) {
630 android_atomic_dec(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700631 return false; // Timed out.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700632 } else if ((errno != EAGAIN) && (errno != EINTR)) {
633 // EAGAIN and EINTR both indicate a spurious failure,
634 // recompute the relative time out from now and try again.
635 // We don't use TEMP_FAILURE_RETRY so we can recompute rel_ts;
Ian Rogers81d425b2012-09-27 16:03:43 -0700636 PLOG(FATAL) << "timed futex wait failed for " << name_;
637 }
638 }
639 android_atomic_dec(&num_pending_writers_);
640 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700641 } while (!done);
Ian Rogers01ae5802012-09-28 16:14:01 -0700642 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700643#else
Ian Rogersc604d732012-10-14 16:09:54 -0700644 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700645 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700646 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700647 if (result == ETIMEDOUT) {
648 return false;
649 }
650 if (result != 0) {
651 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700652 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700653 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700654#endif
655 RegisterAsLocked(self);
656 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700657 return true;
658}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700659#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700660
Ian Rogers81d425b2012-09-27 16:03:43 -0700661bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700662 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700663#if ART_USE_FUTEXES
664 bool done = false;
665 do {
666 int32_t cur_state = state_;
667 if (cur_state >= 0) {
668 // Add as an extra reader.
Ian Rogers693ff612013-02-01 10:56:12 -0800669 done = android_atomic_acquire_cas(cur_state, cur_state + 1, &state_) == 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700670 } else {
671 // Owner holds it exclusively.
672 return false;
673 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700674 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700675#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700676 int result = pthread_rwlock_tryrdlock(&rwlock_);
677 if (result == EBUSY) {
678 return false;
679 }
680 if (result != 0) {
681 errno = result;
682 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
683 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700684#endif
685 RegisterAsLocked(self);
686 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700687 return true;
688}
689
Ian Rogers81d425b2012-09-27 16:03:43 -0700690bool ReaderWriterMutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700691 DCHECK(self == NULL || self == Thread::Current());
692 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700693 if (kDebugLocking) {
694 // Sanity that if the pthread thinks we own the lock the Thread agrees.
Ian Rogers01ae5802012-09-28 16:14:01 -0700695 if (self != NULL && result) {
696 CHECK_EQ(self->GetHeldMutex(level_), this);
697 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700698 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700699 return result;
700}
701
Ian Rogers81d425b2012-09-27 16:03:43 -0700702bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700703 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700704 bool result;
705 if (UNLIKELY(self == NULL)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700706 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700707 } else {
708 result = (self->GetHeldMutex(level_) == this);
709 }
710 return result;
711}
712
713uint64_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700714#if ART_USE_FUTEXES
Ian Rogers56edc432013-01-18 16:51:51 -0800715 int32_t state = state_;
716 if (state == 0) {
717 return 0; // No owner.
718 } else if (state > 0) {
719 return -1; // Shared.
720 } else {
721 return exclusive_owner_;
722 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700723#else
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800724#if defined(__BIONIC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700725 return rwlock_.writerThreadId;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800726#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700727 return reinterpret_cast<const glibc_pthread_rwlock_t*>(&rwlock_)->writer;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800728#elif defined(__APPLE__)
Ian Rogers81d425b2012-09-27 16:03:43 -0700729 const darwin_pthread_rwlock_t*
730 dprwlock = reinterpret_cast<const darwin_pthread_rwlock_t*>(&rwlock_);
Brian Carlstromf3a26412012-08-24 11:06:02 -0700731 pthread_t owner = dprwlock->darwin_pthread_rwlock_owner;
732 if (owner == (pthread_t)0) {
733 return 0;
734 }
735 uint64_t tid;
736 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
737 return tid;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800738#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700739#error unsupported C library
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800740#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700741#endif
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800742}
743
Ian Rogers56edc432013-01-18 16:51:51 -0800744void ReaderWriterMutex::Dump(std::ostream& os) const {
745 os << name_
746 << " level=" << static_cast<int>(level_)
747 << " owner=" << GetExclusiveOwnerTid() << " ";
748 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700749}
750
751std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800752 mu.Dump(os);
753 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700754}
755
Ian Rogers23055dc2013-04-18 16:29:16 -0700756ConditionVariable::ConditionVariable(const char* name, Mutex& guard)
Ian Rogersc604d732012-10-14 16:09:54 -0700757 : name_(name), guard_(guard) {
758#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800759 sequence_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700760 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700761#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700762 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, NULL));
Ian Rogersc604d732012-10-14 16:09:54 -0700763#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700764}
765
766ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800767#if ART_USE_FUTEXES
768 if (num_waiters_!= 0) {
769 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
770 Runtime* runtime = Runtime::Current();
771 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Ian Rogersd45f2012012-11-28 11:46:23 -0800772 LOG(shutting_down ? WARNING : FATAL) << "ConditionVariable::~ConditionVariable for " << name_
773 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800774 }
775#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700776 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
777 // may still be using condition variables.
778 int rc = pthread_cond_destroy(&cond_);
779 if (rc != 0) {
780 errno = rc;
Ian Rogers50b35e22012-10-04 10:09:15 -0700781 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700782 Runtime* runtime = Runtime::Current();
783 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughese62934d2012-04-09 11:24:29 -0700784 PLOG(shutting_down ? WARNING : FATAL) << "pthread_cond_destroy failed for " << name_;
785 }
Ian Rogersc604d732012-10-14 16:09:54 -0700786#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700787}
788
Ian Rogersc604d732012-10-14 16:09:54 -0700789void ConditionVariable::Broadcast(Thread* self) {
790 DCHECK(self == NULL || self == Thread::Current());
791 // TODO: enable below, there's a race in thread creation that causes false failures currently.
792 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700793 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700794#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800795 if (num_waiters_ > 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700796 android_atomic_inc(&sequence_); // Indicate the broadcast occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700797 bool done = false;
798 do {
Ian Rogersd45f2012012-11-28 11:46:23 -0800799 int32_t cur_sequence = sequence_;
800 // Requeue waiters onto mutex. The waiter holds the contender count on the mutex high ensuring
801 // mutex unlocks will awaken the requeued waiter thread.
802 done = futex(&sequence_, FUTEX_CMP_REQUEUE, 0,
Ian Rogers5bd97c42012-11-27 02:38:26 -0800803 reinterpret_cast<const timespec*>(std::numeric_limits<int32_t>::max()),
Ian Rogersd45f2012012-11-28 11:46:23 -0800804 &guard_.state_, cur_sequence) != -1;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800805 if (!done) {
806 if (errno != EAGAIN) {
807 PLOG(FATAL) << "futex cmp requeue failed for " << name_;
808 }
Ian Rogers5bd97c42012-11-27 02:38:26 -0800809 }
Ian Rogersc604d732012-10-14 16:09:54 -0700810 } while (!done);
811 }
812#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700813 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700814#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700815}
816
Ian Rogersc604d732012-10-14 16:09:54 -0700817void ConditionVariable::Signal(Thread* self) {
818 DCHECK(self == NULL || self == Thread::Current());
819 guard_.AssertExclusiveHeld(self);
820#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800821 if (num_waiters_ > 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700822 android_atomic_inc(&sequence_); // Indicate a signal occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700823 // Futex wake 1 waiter who will then come and in contend on mutex. It'd be nice to requeue them
824 // to avoid this, however, requeueing can only move all waiters.
Ian Rogersd45f2012012-11-28 11:46:23 -0800825 int num_woken = futex(&sequence_, FUTEX_WAKE, 1, NULL, NULL, 0);
826 // Check something was woken or else we changed sequence_ before they had chance to wait.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800827 CHECK((num_woken == 0) || (num_woken == 1));
Ian Rogersc604d732012-10-14 16:09:54 -0700828 }
829#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700830 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700831#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700832}
833
Ian Rogersc604d732012-10-14 16:09:54 -0700834void ConditionVariable::Wait(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700835 guard_.CheckSafeToWait(self);
836 WaitHoldingLocks(self);
837}
838
839void ConditionVariable::WaitHoldingLocks(Thread* self) {
Ian Rogersc604d732012-10-14 16:09:54 -0700840 DCHECK(self == NULL || self == Thread::Current());
841 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700842 unsigned int old_recursion_count = guard_.recursion_count_;
843#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700844 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800845 // Ensure the Mutex is contended so that requeued threads are awoken.
846 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700847 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800848 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700849 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800850 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, NULL, NULL, 0) != 0) {
851 // Futex failed, check it is an expected error.
852 // EAGAIN == EWOULDBLK, so we let the caller try again.
853 // EINTR implies a signal was sent to this thread.
854 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700855 PLOG(FATAL) << "futex wait failed for " << name_;
856 }
857 }
858 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800859 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700860 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800861 // We awoke and so no longer require awakes from the guard_'s unlock.
862 CHECK_GE(guard_.num_contenders_, 0);
863 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700864#else
865 guard_.recursion_count_ = 0;
866 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
867#endif
868 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700869}
870
Ian Rogersc604d732012-10-14 16:09:54 -0700871void ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
872 DCHECK(self == NULL || self == Thread::Current());
873 guard_.AssertExclusiveHeld(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700874 guard_.CheckSafeToWait(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700875 unsigned int old_recursion_count = guard_.recursion_count_;
876#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700877 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800878 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700879 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800880 // Ensure the Mutex is contended so that requeued threads are awoken.
881 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700882 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800883 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700884 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800885 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, &rel_ts, NULL, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700886 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800887 // Timed out we're done.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700888 } else if ((errno == EAGAIN) || (errno == EINTR)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800889 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700890 } else {
891 PLOG(FATAL) << "timed futex wait failed for " << name_;
892 }
893 }
894 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800895 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700896 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800897 // We awoke and so no longer require awakes from the guard_'s unlock.
898 CHECK_GE(guard_.num_contenders_, 0);
899 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700900#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700901#ifdef HAVE_TIMEDWAIT_MONOTONIC
902#define TIMEDWAIT pthread_cond_timedwait_monotonic
Ian Rogersc604d732012-10-14 16:09:54 -0700903 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700904#else
905#define TIMEDWAIT pthread_cond_timedwait
Ian Rogersc604d732012-10-14 16:09:54 -0700906 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700907#endif
Ian Rogersc604d732012-10-14 16:09:54 -0700908 guard_.recursion_count_ = 0;
909 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700910 InitTimeSpec(true, clock, ms, ns, &ts);
911 int rc = TEMP_FAILURE_RETRY(TIMEDWAIT(&cond_, &guard_.mutex_, &ts));
Elliott Hughes5f791332011-09-15 17:45:30 -0700912 if (rc != 0 && rc != ETIMEDOUT) {
913 errno = rc;
914 PLOG(FATAL) << "TimedWait failed for " << name_;
915 }
Ian Rogersc604d732012-10-14 16:09:54 -0700916#endif
917 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700918}
919
Elliott Hughese62934d2012-04-09 11:24:29 -0700920} // namespace art