blob: d09a6a27f67e60a4b81a85da8678c23aecd7d496 [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"
Elliott Hughes6b355752012-01-13 16:49:08 -080024#include "runtime.h"
Ian Rogersc604d732012-10-14 16:09:54 -070025#include "scoped_thread_state_change.h"
Elliott Hughesffb465f2012-03-01 18:46:05 -080026#include "thread.h"
27#include "utils.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070028
Elliott Hughes8d768a92011-09-14 16:35:25 -070029#define CHECK_MUTEX_CALL(call, args) CHECK_PTHREAD_CALL(call, args, name_)
30
Elliott Hughesf8349362012-06-18 15:00:06 -070031extern int pthread_mutex_lock(pthread_mutex_t* mutex) EXCLUSIVE_LOCK_FUNCTION(mutex);
32extern int pthread_mutex_unlock(pthread_mutex_t* mutex) UNLOCK_FUNCTION(1);
33extern int pthread_mutex_trylock(pthread_mutex_t* mutex) EXCLUSIVE_TRYLOCK_FUNCTION(0, mutex);
34
Ian Rogers81d425b2012-09-27 16:03:43 -070035#if ART_USE_FUTEXES
Ian Rogersacc46d62012-09-27 21:39:40 -070036#include "linux/futex.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070037#include "sys/syscall.h"
38#ifndef SYS_futex
39#define SYS_futex __NR_futex
40#endif
Ian Rogersc604d732012-10-14 16:09:54 -070041int futex(volatile int *uaddr, int op, int val, const struct timespec *timeout, volatile int *uaddr2, int val3) {
42 return syscall(SYS_futex, uaddr, op, val, timeout, uaddr2, val3);
Ian Rogers81d425b2012-09-27 16:03:43 -070043}
44#endif // ART_USE_FUTEXES
45
Elliott Hughes8daa0922011-09-11 13:46:25 -070046namespace art {
47
Brian Carlstromf3a26412012-08-24 11:06:02 -070048// This works on Mac OS 10.6 but hasn't been tested on older releases.
Elliott Hughesf1498432012-03-28 19:34:27 -070049struct __attribute__((__may_alias__)) darwin_pthread_mutex_t {
Brian Carlstromf3a26412012-08-24 11:06:02 -070050 long padding0;
51 int padding1;
52 uint32_t padding2;
53 int16_t padding3;
54 int16_t padding4;
55 uint32_t padding5;
56 pthread_t darwin_pthread_mutex_owner;
Ian Rogers00f7d0e2012-07-19 15:28:27 -070057 // ...other stuff we don't care about.
58};
59
60struct __attribute__((__may_alias__)) darwin_pthread_rwlock_t {
Brian Carlstromf3a26412012-08-24 11:06:02 -070061 long padding0;
62 pthread_mutex_t padding1;
63 int padding2;
64 pthread_cond_t padding3;
65 pthread_cond_t padding4;
66 int padding5;
67 int padding6;
68 pthread_t darwin_pthread_rwlock_owner;
Elliott Hughesf1498432012-03-28 19:34:27 -070069 // ...other stuff we don't care about.
70};
71
72struct __attribute__((__may_alias__)) glibc_pthread_mutex_t {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070073 int32_t padding0[2];
Elliott Hughesf1498432012-03-28 19:34:27 -070074 int owner;
75 // ...other stuff we don't care about.
76};
77
Ian Rogers00f7d0e2012-07-19 15:28:27 -070078struct __attribute__((__may_alias__)) glibc_pthread_rwlock_t {
79#ifdef __LP64__
80 int32_t padding0[6];
81#else
82 int32_t padding0[7];
83#endif
84 int writer;
85 // ...other stuff we don't care about.
86};
87
Ian Rogers01ae5802012-09-28 16:14:01 -070088static uint64_t SafeGetTid(const Thread* self) {
89 if (self != NULL) {
90 return static_cast<uint64_t>(self->GetTid());
91 } else {
92 return static_cast<uint64_t>(GetTid());
93 }
94}
95
Ian Rogersc604d732012-10-14 16:09:54 -070096#if ART_USE_FUTEXES
97static bool ComputeRelativeTimeSpec(timespec* result_ts, const timespec& lhs, const timespec& rhs) {
98 const long int one_sec = 1000 * 1000 * 1000; // one second in nanoseconds.
99 result_ts->tv_sec = lhs.tv_sec - rhs.tv_sec;
100 result_ts->tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
101 if (result_ts->tv_nsec < 0) {
102 result_ts->tv_sec--;
103 result_ts->tv_nsec += one_sec;
104 } else if (result_ts->tv_nsec > one_sec) {
105 result_ts->tv_sec++;
106 result_ts->tv_nsec -= one_sec;
107 }
108 return result_ts->tv_sec < 0;
109}
110#endif
111
Ian Rogers56edc432013-01-18 16:51:51 -0800112#if CONTENTION_LOGGING
113// A guard for all_mutexes_ that's not a mutex (Mutexes must CAS to acquire and busy wait).
114static AtomicInteger all_mutexes_guard_;
115// All created mutexes guarded by all_mutexes_guard_.
116std::set<BaseMutex*>* all_mutexes_;
117
118class ScopedAllMutexesLock {
119 public:
120 ScopedAllMutexesLock(const BaseMutex* mutex) : mutex_(mutex) {
121 while (!all_mutexes_guard_.CompareAndSwap(0, reinterpret_cast<int32_t>(mutex))) {
122 NanoSleep(100);
123 }
124 }
125 ~ScopedAllMutexesLock() {
126 while (!all_mutexes_guard_.CompareAndSwap(reinterpret_cast<int32_t>(mutex_), 0)) {
127 NanoSleep(100);
128 }
129 }
130 private:
131 const BaseMutex* const mutex_;
132};
133#endif
134
135BaseMutex::BaseMutex(const char* name, LockLevel level) : level_(level), name_(name) {
136#if CONTENTION_LOGGING
137 ScopedAllMutexesLock mu(this);
138 if (all_mutexes_ == NULL) {
139 // We leak the global set of all mutexes to avoid ordering issues in global variable
140 // construction/destruction.
141 all_mutexes_ = new std::set<BaseMutex*>();
142 }
143 all_mutexes_->insert(this);
144#endif
145}
146
147BaseMutex::~BaseMutex() {
148#if CONTENTION_LOGGING
149 ScopedAllMutexesLock mu(this);
150 all_mutexes_->erase(this);
151#endif
152}
153
154void BaseMutex::DumpAll(std::ostream& os) {
155#if CONTENTION_LOGGING
156 os << "Mutex logging:\n";
157 ScopedAllMutexesLock mu(reinterpret_cast<const BaseMutex*>(-1));
158 typedef std::set<BaseMutex*>::const_iterator It;
159 for (It it = all_mutexes_->begin(); it != all_mutexes_->end(); ++it) {
160 BaseMutex* mutex = *it;
161 mutex->Dump(os);
162 os << "\n";
163 }
164#endif
165}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700166
Ian Rogers120f1c72012-09-28 17:17:10 -0700167static void CheckUnattachedThread(LockLevel level) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700168 // The check below enumerates the cases where we expect not to be able to sanity check locks
Ian Rogers120f1c72012-09-28 17:17:10 -0700169 // on a thread. Lock checking is disabled to avoid deadlock when checking shutdown lock.
170 // TODO: tighten this check.
Ian Rogers25fd14b2012-09-05 10:56:38 -0700171 if (kDebugLocking) {
172 Runtime* runtime = Runtime::Current();
173 CHECK(runtime == NULL || !runtime->IsStarted() || runtime->IsShuttingDown() ||
Ian Rogers120f1c72012-09-28 17:17:10 -0700174 level == kDefaultMutexLevel || level == kRuntimeShutdownLock ||
175 level == kThreadListLock || level == kLoggingLock || level == kAbortLock);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700176 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800177}
178
Ian Rogers81d425b2012-09-27 16:03:43 -0700179void BaseMutex::RegisterAsLocked(Thread* self) {
180 if (UNLIKELY(self == NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700181 CheckUnattachedThread(level_);
182 return;
183 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700184 if (kDebugLocking) {
185 // Check if a bad Mutex of this level or lower is held.
186 bool bad_mutexes_held = false;
187 for (int i = level_; i >= 0; --i) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700188 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700189 if (UNLIKELY(held_mutex != NULL)) {
190 LOG(ERROR) << "Lock level violation: holding \"" << held_mutex->name_ << "\" (level " << i
191 << ") while locking \"" << name_ << "\" (level " << static_cast<int>(level_) << ")";
192 if (i > kAbortLock) {
193 // Only abort in the check below if this is more than abort level lock.
194 bad_mutexes_held = true;
195 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700196 }
197 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700198 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700199 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700200 // Don't record monitors as they are outside the scope of analysis. They may be inspected off of
201 // the monitor list.
202 if (level_ != kMonitorLock) {
203 self->SetHeldMutex(level_, this);
204 }
205}
206
Ian Rogers81d425b2012-09-27 16:03:43 -0700207void BaseMutex::RegisterAsUnlocked(Thread* self) {
208 if (UNLIKELY(self == NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700209 CheckUnattachedThread(level_);
210 return;
211 }
212 if (level_ != kMonitorLock) {
Brian Carlstrom760c9432012-11-29 16:46:27 -0800213 if (kDebugLocking && !gAborting) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700214 CHECK(self->GetHeldMutex(level_) == this) << "Unlocking on unacquired mutex: " << name_;
215 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700216 self->SetHeldMutex(level_, NULL);
217 }
218}
219
Ian Rogers81d425b2012-09-27 16:03:43 -0700220void BaseMutex::CheckSafeToWait(Thread* self) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700221 if (self == NULL) {
222 CheckUnattachedThread(level_);
223 return;
224 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700225 if (kDebugLocking) {
226 CHECK(self->GetHeldMutex(level_) == this) << "Waiting on unacquired mutex: " << name_;
227 bool bad_mutexes_held = false;
228 for (int i = kMaxMutexLevel; i >= 0; --i) {
229 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700230 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700231 if (held_mutex != NULL) {
232 LOG(ERROR) << "Holding " << held_mutex->name_ << " (level " << i
233 << ") while performing wait on: "
234 << name_ << " (level " << static_cast<int>(level_) << ")";
235 bad_mutexes_held = true;
236 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700237 }
238 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700239 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700240 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700241}
242
Ian Rogers56edc432013-01-18 16:51:51 -0800243void BaseMutex::RecordContention(uint64_t blocked_tid, uint64_t owner_tid, uint64_t milli_time_blocked) {
244#if CONTENTION_LOGGING
245 ++contention_count_;
246 wait_time_ += static_cast<uint32_t>(milli_time_blocked); // May overflow.
247 // This code is intentionally racy as it is only used for diagnostics.
248 uint32_t slot = cur_content_log_entry_;
249 if (contention_log_[slot].blocked_tid == blocked_tid &&
250 contention_log_[slot].owner_tid == blocked_tid) {
251 ++contention_log_[slot].count;
252 } else {
253 uint32_t new_slot;
254 do {
255 slot = cur_content_log_entry_;
256 new_slot = (slot + 1) % kContentionLogSize;
257 } while(!cur_content_log_entry_.CompareAndSwap(slot, new_slot));
258 contention_log_[new_slot].blocked_tid = blocked_tid;
259 contention_log_[new_slot].owner_tid = owner_tid;
260 contention_log_[new_slot].count = 1;
261 }
262#endif
263}
264
265class ScopedContentionRecorder {
266 public:
267 ScopedContentionRecorder(BaseMutex* mutex, uint64_t blocked_tid, uint64_t owner_tid) :
268 mutex_(mutex), blocked_tid_(blocked_tid), owner_tid_(owner_tid),
269 start_milli_time_(MilliTime()) {
270 }
271
272 ~ScopedContentionRecorder() {
273 uint64_t end_milli_time = MilliTime();
274 mutex_->RecordContention(blocked_tid_, owner_tid_, end_milli_time - start_milli_time_);
275 }
276
277 private:
278 BaseMutex* const mutex_;
279 uint64_t blocked_tid_;
280 uint64_t owner_tid_;
281 const uint64_t start_milli_time_;
282};
283
284void BaseMutex::DumpContention(std::ostream& os) const {
285#if CONTENTION_LOGGING
286 uint32_t wait_time = wait_time_;
287 uint32_t contention_count = contention_count_;
288 if (contention_count == 0) {
289 os << "never contended";
290 } else {
291 os << "contended " << contention_count << " times, average wait of contender " << (wait_time / contention_count) << "ms";
292 SafeMap<uint64_t, size_t> most_common_blocker;
293 SafeMap<uint64_t, size_t> most_common_blocked;
294 typedef SafeMap<uint64_t, size_t>::const_iterator It;
295 for (size_t i = 0; i < kContentionLogSize; ++i) {
296 uint64_t blocked_tid = contention_log_[i].blocked_tid;
297 uint64_t owner_tid = contention_log_[i].owner_tid;
298 uint32_t count = contention_log_[i].count;
299 if (count > 0) {
300 It it = most_common_blocked.find(blocked_tid);
301 if (it != most_common_blocked.end()) {
302 most_common_blocked.Overwrite(blocked_tid, it->second + count);
303 } else {
304 most_common_blocked.Put(blocked_tid, count);
305 }
306 it = most_common_blocker.find(owner_tid);
307 if (it != most_common_blocker.end()) {
308 most_common_blocker.Overwrite(owner_tid, it->second + count);
309 } else {
310 most_common_blocker.Put(owner_tid, count);
311 }
312 }
313 }
314 uint64_t max_tid = 0;
315 size_t max_tid_count = 0;
316 for (It it = most_common_blocked.begin(); it != most_common_blocked.end(); ++it) {
317 if (it->second > max_tid_count) {
318 max_tid = it->first;
319 max_tid_count = it->second;
320 }
321 }
322 if (max_tid != 0) {
323 os << " sample shows most blocked tid=" << max_tid;
324 }
325 max_tid = 0;
326 max_tid_count = 0;
327 for (It it = most_common_blocker.begin(); it != most_common_blocker.end(); ++it) {
328 if (it->second > max_tid_count) {
329 max_tid = it->first;
330 max_tid_count = it->second;
331 }
332 }
333 if (max_tid != 0) {
334 os << " sample shows tid=" << max_tid << " owning during this time";
335 }
336 }
337#endif
338}
339
340
Ian Rogers81d425b2012-09-27 16:03:43 -0700341Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700342 : BaseMutex(name, level), recursive_(recursive), recursion_count_(0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700343#if ART_USE_FUTEXES
344 state_ = 0;
345 exclusive_owner_ = 0;
346 num_contenders_ = 0;
347#elif defined(__BIONIC__) || defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700348 // Use recursive mutexes for bionic and Apple otherwise the
349 // non-recursive mutexes don't have TIDs to check lock ownership of.
Elliott Hughesbbd9d832011-11-07 14:40:00 -0800350 pthread_mutexattr_t attributes;
351 CHECK_MUTEX_CALL(pthread_mutexattr_init, (&attributes));
352 CHECK_MUTEX_CALL(pthread_mutexattr_settype, (&attributes, PTHREAD_MUTEX_RECURSIVE));
353 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, &attributes));
354 CHECK_MUTEX_CALL(pthread_mutexattr_destroy, (&attributes));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700355#else
356 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, NULL));
357#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700358}
359
360Mutex::~Mutex() {
Ian Rogersc604d732012-10-14 16:09:54 -0700361#if ART_USE_FUTEXES
362 if (state_ != 0) {
363 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
364 Runtime* runtime = Runtime::Current();
365 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
366 LOG(shutting_down ? WARNING : FATAL) << "destroying mutex with owner: " << exclusive_owner_;
367 } else {
368 CHECK_EQ(exclusive_owner_, 0U) << "unexpectedly found an owner on unlocked mutex " << name_;
369 CHECK_EQ(num_contenders_, 0) << "unexpectedly found a contender on mutex " << name_;
370 }
371#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700372 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
373 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800374 int rc = pthread_mutex_destroy(&mutex_);
375 if (rc != 0) {
376 errno = rc;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800377 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700378 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700379 Runtime* runtime = Runtime::Current();
380 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughes6b355752012-01-13 16:49:08 -0800381 PLOG(shutting_down ? WARNING : FATAL) << "pthread_mutex_destroy failed for " << name_;
382 }
Ian Rogersc604d732012-10-14 16:09:54 -0700383#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700384}
385
Ian Rogers81d425b2012-09-27 16:03:43 -0700386void Mutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700387 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700388 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700389 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700390 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700391 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700392#if ART_USE_FUTEXES
393 bool done = false;
394 do {
395 int32_t cur_state = state_;
396 if (cur_state == 0) {
397 // Change state from 0 to 1.
398 done = android_atomic_cmpxchg(0, 1, &state_) == 0;
399 } else {
400 // Failed to acquire, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800401 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700402 android_atomic_inc(&num_contenders_);
403 if (futex(&state_, FUTEX_WAIT, 1, NULL, NULL, 0) != 0) {
404 if (errno != EAGAIN) {
405 PLOG(FATAL) << "futex wait failed for " << name_;
406 }
407 }
408 android_atomic_dec(&num_contenders_);
409 }
410 } while(!done);
411 DCHECK_EQ(state_, 1);
412 exclusive_owner_ = SafeGetTid(self);
413#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700414 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700415#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700416 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700417 }
418 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700419 if (kDebugLocking) {
420 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
421 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700422 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700423 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700424}
425
Ian Rogers81d425b2012-09-27 16:03:43 -0700426bool Mutex::ExclusiveTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700427 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700428 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700429 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700430 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700431 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700432#if ART_USE_FUTEXES
433 bool done = false;
434 do {
435 int32_t cur_state = state_;
436 if (cur_state == 0) {
437 // Change state from 0 to 1.
438 done = android_atomic_cmpxchg(0, 1, &state_) == 0;
439 } else {
440 return false;
441 }
442 } while(!done);
443 DCHECK_EQ(state_, 1);
444 exclusive_owner_ = SafeGetTid(self);
445#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700446 int result = pthread_mutex_trylock(&mutex_);
447 if (result == EBUSY) {
448 return false;
449 }
450 if (result != 0) {
451 errno = result;
452 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
453 }
Ian Rogersc604d732012-10-14 16:09:54 -0700454#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700455 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700456 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700457 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700458 if (kDebugLocking) {
459 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
460 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700461 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700462 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700463 return true;
464}
465
Ian Rogers81d425b2012-09-27 16:03:43 -0700466void Mutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700467 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700468 AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469 recursion_count_--;
470 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700471 if (kDebugLocking) {
472 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
473 << name_ << " " << recursion_count_;
474 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700475 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700476#if ART_USE_FUTEXES
477 bool done = false;
478 do {
479 int32_t cur_state = state_;
480 if (cur_state == 1) {
481 // We're no longer the owner.
482 exclusive_owner_ = 0;
483 // Change state to 0.
484 done = android_atomic_cmpxchg(cur_state, 0, &state_) == 0;
485 if (done) { // Spurious fail?
486 // Wake a contender
487 if (num_contenders_ > 0) {
488 futex(&state_, FUTEX_WAKE, 1, NULL, NULL, 0);
489 }
490 }
491 } else {
492 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
493 }
494 } while(!done);
495#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700496 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700497#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700498 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700499}
500
Ian Rogers81d425b2012-09-27 16:03:43 -0700501bool Mutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700502 DCHECK(self == NULL || self == Thread::Current());
503 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
504 if (kDebugLocking) {
505 // Sanity debug check that if we think it is locked we have it in our held mutexes.
Brian Carlstrom9e419ca2012-11-27 11:31:49 -0800506 if (result && self != NULL && level_ != kMonitorLock && !gAborting) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700507 CHECK_EQ(self->GetHeldMutex(level_), this);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700508 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700509 }
510 return result;
Elliott Hughesf1498432012-03-28 19:34:27 -0700511}
512
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700513uint64_t Mutex::GetExclusiveOwnerTid() const {
Ian Rogersc604d732012-10-14 16:09:54 -0700514#if ART_USE_FUTEXES
515 return exclusive_owner_;
516#elif defined(__BIONIC__)
Elliott Hughesf1498432012-03-28 19:34:27 -0700517 return static_cast<uint64_t>((mutex_.value >> 16) & 0xffff);
Elliott Hughes3147a232011-10-12 15:55:07 -0700518#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700519 return reinterpret_cast<const glibc_pthread_mutex_t*>(&mutex_)->owner;
Elliott Hughescf044312012-01-23 18:48:51 -0800520#elif defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700521 const darwin_pthread_mutex_t* dpmutex = reinterpret_cast<const darwin_pthread_mutex_t*>(&mutex_);
522 pthread_t owner = dpmutex->darwin_pthread_mutex_owner;
Brian Carlstrombd93c302012-08-27 16:58:28 -0700523 // 0 for unowned, -1 for PTHREAD_MTX_TID_SWITCHING
524 // TODO: should we make darwin_pthread_mutex_owner volatile and recheck until not -1?
Brian Carlstromf3a26412012-08-24 11:06:02 -0700525 if ((owner == (pthread_t)0) || (owner == (pthread_t)-1)) {
526 return 0;
527 }
528 uint64_t tid;
529 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
530 return tid;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700531#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700532#error unsupported C library
Elliott Hughes8daa0922011-09-11 13:46:25 -0700533#endif
534}
535
Ian Rogers56edc432013-01-18 16:51:51 -0800536void Mutex::Dump(std::ostream& os) const {
537 os << (recursive_ ? "recursive " : "non-recursive ")
538 << name_
539 << " level=" << static_cast<int>(level_)
540 << " rec=" << recursion_count_
541 << " owner=" << GetExclusiveOwnerTid() << " ";
542 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700543}
544
545std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800546 mu.Dump(os);
547 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700548}
549
Ian Rogers81d425b2012-09-27 16:03:43 -0700550ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level) :
551 BaseMutex(name, level)
552#if ART_USE_FUTEXES
553 , state_(0), exclusive_owner_(0), num_pending_readers_(0), num_pending_writers_(0)
554#endif
555{
556#if !ART_USE_FUTEXES
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700557 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, NULL));
Ian Rogers81d425b2012-09-27 16:03:43 -0700558#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700559}
560
561ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700562#if ART_USE_FUTEXES
563 CHECK_EQ(state_, 0);
564 CHECK_EQ(exclusive_owner_, 0U);
565 CHECK_EQ(num_pending_readers_, 0);
566 CHECK_EQ(num_pending_writers_, 0);
567#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700568 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
569 // may still be using locks.
570 int rc = pthread_rwlock_destroy(&rwlock_);
571 if (rc != 0) {
572 errno = rc;
573 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700574 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700575 Runtime* runtime = Runtime::Current();
576 bool shutting_down = runtime == NULL || runtime->IsShuttingDown();
577 PLOG(shutting_down ? WARNING : FATAL) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800578 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700579#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700580}
581
Ian Rogers81d425b2012-09-27 16:03:43 -0700582void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700583 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700584 AssertNotExclusiveHeld(self);
585#if ART_USE_FUTEXES
586 bool done = false;
587 do {
588 int32_t cur_state = state_;
589 if (cur_state == 0) {
590 // Change state from 0 to -1.
591 done = android_atomic_cmpxchg(0, -1, &state_) == 0;
592 } else {
593 // Failed to acquire, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800594 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700595 android_atomic_inc(&num_pending_writers_);
596 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
597 if (errno != EAGAIN) {
598 PLOG(FATAL) << "futex wait failed for " << name_;
599 }
600 }
601 android_atomic_dec(&num_pending_writers_);
602 }
603 } while(!done);
Ian Rogersab470162012-09-29 23:06:53 -0700604 DCHECK_EQ(state_, -1);
605 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700606#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700607 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700608#endif
609 RegisterAsLocked(self);
610 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700611}
612
Ian Rogers81d425b2012-09-27 16:03:43 -0700613void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700614 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700615 AssertExclusiveHeld(self);
616 RegisterAsUnlocked(self);
617#if ART_USE_FUTEXES
618 bool done = false;
619 do {
620 int32_t cur_state = state_;
621 if (cur_state == -1) {
622 // We're no longer the owner.
623 exclusive_owner_ = 0;
624 // Change state from -1 to 0.
625 done = android_atomic_cmpxchg(-1, 0, &state_) == 0;
626 if (done) { // cmpxchg may fail due to noise?
627 // Wake any waiters.
628 if (num_pending_readers_ > 0 || num_pending_writers_ > 0) {
629 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
630 }
631 }
632 } else {
633 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
634 }
635 } while(!done);
636#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700637 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700638#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700639}
640
Ian Rogers66aee5c2012-08-15 17:17:47 -0700641#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700642bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700643 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700644#if ART_USE_FUTEXES
645 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700646 timespec end_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800647 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700648 do {
649 int32_t cur_state = state_;
650 if (cur_state == 0) {
651 // Change state from 0 to -1.
652 done = android_atomic_cmpxchg(0, -1, &state_) == 0;
653 } else {
654 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700655 timespec now_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800656 InitTimeSpec(true, CLOCK_REALTIME, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700657 timespec rel_ts;
658 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
659 return false; // Timed out.
660 }
Ian Rogers56edc432013-01-18 16:51:51 -0800661 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700662 android_atomic_inc(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700663 if (futex(&state_, FUTEX_WAIT, cur_state, &rel_ts, NULL, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700664 if (errno == ETIMEDOUT) {
665 android_atomic_dec(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700666 return false; // Timed out.
667 } else if (errno != EAGAIN && errno != EINTR) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700668 PLOG(FATAL) << "timed futex wait failed for " << name_;
669 }
670 }
671 android_atomic_dec(&num_pending_writers_);
672 }
673 } while(!done);
Ian Rogers01ae5802012-09-28 16:14:01 -0700674 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700675#else
Ian Rogersc604d732012-10-14 16:09:54 -0700676 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700677 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700678 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700679 if (result == ETIMEDOUT) {
680 return false;
681 }
682 if (result != 0) {
683 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700684 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700685 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700686#endif
687 RegisterAsLocked(self);
688 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700689 return true;
690}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700691#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700692
Ian Rogers81d425b2012-09-27 16:03:43 -0700693void ReaderWriterMutex::SharedLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700694 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700695#if ART_USE_FUTEXES
696 bool done = false;
697 do {
698 int32_t cur_state = state_;
699 if (cur_state >= 0) {
700 // Add as an extra reader.
701 done = android_atomic_cmpxchg(cur_state, cur_state + 1, &state_) == 0;
702 } else {
703 // Owner holds it exclusively, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800704 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700705 android_atomic_inc(&num_pending_readers_);
706 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
707 if (errno != EAGAIN) {
708 PLOG(FATAL) << "futex wait failed for " << name_;
709 }
710 }
711 android_atomic_dec(&num_pending_readers_);
712 }
713 } while(!done);
714#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700715 CHECK_MUTEX_CALL(pthread_rwlock_rdlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700716#endif
717 RegisterAsLocked(self);
718 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700719}
720
Ian Rogers81d425b2012-09-27 16:03:43 -0700721bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700722 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700723#if ART_USE_FUTEXES
724 bool done = false;
725 do {
726 int32_t cur_state = state_;
727 if (cur_state >= 0) {
728 // Add as an extra reader.
729 done = android_atomic_cmpxchg(cur_state, cur_state + 1, &state_) == 0;
730 } else {
731 // Owner holds it exclusively.
732 return false;
733 }
734 } while(!done);
735#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700736 int result = pthread_rwlock_tryrdlock(&rwlock_);
737 if (result == EBUSY) {
738 return false;
739 }
740 if (result != 0) {
741 errno = result;
742 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
743 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700744#endif
745 RegisterAsLocked(self);
746 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700747 return true;
748}
749
Ian Rogers81d425b2012-09-27 16:03:43 -0700750void ReaderWriterMutex::SharedUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700751 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700752 AssertSharedHeld(self);
753 RegisterAsUnlocked(self);
754#if ART_USE_FUTEXES
755 bool done = false;
756 do {
757 int32_t cur_state = state_;
758 if (LIKELY(cur_state > 0)) {
759 // Reduce state by 1.
760 done = android_atomic_cmpxchg(cur_state, cur_state - 1, &state_) == 0;
761 if (done && (cur_state - 1) == 0) { // cmpxchg may fail due to noise?
762 if (num_pending_writers_ > 0 || num_pending_readers_ > 0) {
763 // Wake any exclusive waiters as there are now no readers.
764 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
765 }
766 }
767 } else {
768 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
769 }
770 } while(!done);
771#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700772 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700773#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700774}
775
Ian Rogers81d425b2012-09-27 16:03:43 -0700776bool ReaderWriterMutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700777 DCHECK(self == NULL || self == Thread::Current());
778 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700779 if (kDebugLocking) {
780 // Sanity that if the pthread thinks we own the lock the Thread agrees.
Ian Rogers01ae5802012-09-28 16:14:01 -0700781 if (self != NULL && result) {
782 CHECK_EQ(self->GetHeldMutex(level_), this);
783 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700784 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700785 return result;
786}
787
Ian Rogers81d425b2012-09-27 16:03:43 -0700788bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700789 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700790 bool result;
791 if (UNLIKELY(self == NULL)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700792 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700793 } else {
794 result = (self->GetHeldMutex(level_) == this);
795 }
796 return result;
797}
798
799uint64_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700800#if ART_USE_FUTEXES
Ian Rogers56edc432013-01-18 16:51:51 -0800801 int32_t state = state_;
802 if (state == 0) {
803 return 0; // No owner.
804 } else if (state > 0) {
805 return -1; // Shared.
806 } else {
807 return exclusive_owner_;
808 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700809#else
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800810#if defined(__BIONIC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700811 return rwlock_.writerThreadId;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800812#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700813 return reinterpret_cast<const glibc_pthread_rwlock_t*>(&rwlock_)->writer;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800814#elif defined(__APPLE__)
Ian Rogers81d425b2012-09-27 16:03:43 -0700815 const darwin_pthread_rwlock_t*
816 dprwlock = reinterpret_cast<const darwin_pthread_rwlock_t*>(&rwlock_);
Brian Carlstromf3a26412012-08-24 11:06:02 -0700817 pthread_t owner = dprwlock->darwin_pthread_rwlock_owner;
818 if (owner == (pthread_t)0) {
819 return 0;
820 }
821 uint64_t tid;
822 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
823 return tid;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800824#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700825#error unsupported C library
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800826#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700827#endif
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800828}
829
Ian Rogers56edc432013-01-18 16:51:51 -0800830void ReaderWriterMutex::Dump(std::ostream& os) const {
831 os << name_
832 << " level=" << static_cast<int>(level_)
833 << " owner=" << GetExclusiveOwnerTid() << " ";
834 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700835}
836
837std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800838 mu.Dump(os);
839 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700840}
841
Ian Rogersc604d732012-10-14 16:09:54 -0700842ConditionVariable::ConditionVariable(const std::string& name, Mutex& guard)
843 : name_(name), guard_(guard) {
844#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800845 sequence_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700846 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700847#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700848 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, NULL));
Ian Rogersc604d732012-10-14 16:09:54 -0700849#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700850}
851
852ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800853#if ART_USE_FUTEXES
854 if (num_waiters_!= 0) {
855 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
856 Runtime* runtime = Runtime::Current();
857 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Ian Rogersd45f2012012-11-28 11:46:23 -0800858 LOG(shutting_down ? WARNING : FATAL) << "ConditionVariable::~ConditionVariable for " << name_
859 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800860 }
861#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700862 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
863 // may still be using condition variables.
864 int rc = pthread_cond_destroy(&cond_);
865 if (rc != 0) {
866 errno = rc;
Ian Rogers50b35e22012-10-04 10:09:15 -0700867 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700868 Runtime* runtime = Runtime::Current();
869 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughese62934d2012-04-09 11:24:29 -0700870 PLOG(shutting_down ? WARNING : FATAL) << "pthread_cond_destroy failed for " << name_;
871 }
Ian Rogersc604d732012-10-14 16:09:54 -0700872#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700873}
874
Ian Rogersc604d732012-10-14 16:09:54 -0700875void ConditionVariable::Broadcast(Thread* self) {
876 DCHECK(self == NULL || self == Thread::Current());
877 // TODO: enable below, there's a race in thread creation that causes false failures currently.
878 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700879 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700880#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800881 if (num_waiters_ > 0) {
882 android_atomic_inc(&sequence_); // Indicate the broadcast occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700883 bool done = false;
884 do {
Ian Rogersd45f2012012-11-28 11:46:23 -0800885 int32_t cur_sequence = sequence_;
886 // Requeue waiters onto mutex. The waiter holds the contender count on the mutex high ensuring
887 // mutex unlocks will awaken the requeued waiter thread.
888 done = futex(&sequence_, FUTEX_CMP_REQUEUE, 0,
Ian Rogers5bd97c42012-11-27 02:38:26 -0800889 reinterpret_cast<const timespec*>(std::numeric_limits<int32_t>::max()),
Ian Rogersd45f2012012-11-28 11:46:23 -0800890 &guard_.state_, cur_sequence) != -1;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800891 if (!done) {
892 if (errno != EAGAIN) {
893 PLOG(FATAL) << "futex cmp requeue failed for " << name_;
894 }
Ian Rogers5bd97c42012-11-27 02:38:26 -0800895 }
Ian Rogersc604d732012-10-14 16:09:54 -0700896 } while (!done);
897 }
898#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700899 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700900#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700901}
902
Ian Rogersc604d732012-10-14 16:09:54 -0700903void ConditionVariable::Signal(Thread* self) {
904 DCHECK(self == NULL || self == Thread::Current());
905 guard_.AssertExclusiveHeld(self);
906#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800907 if (num_waiters_ > 0) {
908 android_atomic_inc(&sequence_); // Indicate a signal occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700909 // Futex wake 1 waiter who will then come and in contend on mutex. It'd be nice to requeue them
910 // to avoid this, however, requeueing can only move all waiters.
Ian Rogersd45f2012012-11-28 11:46:23 -0800911 int num_woken = futex(&sequence_, FUTEX_WAKE, 1, NULL, NULL, 0);
912 // Check something was woken or else we changed sequence_ before they had chance to wait.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800913 CHECK((num_woken == 0) || (num_woken == 1));
Ian Rogersc604d732012-10-14 16:09:54 -0700914 }
915#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700916 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700917#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700918}
919
Ian Rogersc604d732012-10-14 16:09:54 -0700920void ConditionVariable::Wait(Thread* self) {
921 DCHECK(self == NULL || self == Thread::Current());
922 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700923 unsigned int old_recursion_count = guard_.recursion_count_;
924#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700925 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800926 // Ensure the Mutex is contended so that requeued threads are awoken.
927 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700928 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800929 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700930 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800931 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, NULL, NULL, 0) != 0) {
932 // Futex failed, check it is an expected error.
933 // EAGAIN == EWOULDBLK, so we let the caller try again.
934 // EINTR implies a signal was sent to this thread.
935 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700936 PLOG(FATAL) << "futex wait failed for " << name_;
937 }
938 }
939 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800940 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700941 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800942 // We awoke and so no longer require awakes from the guard_'s unlock.
943 CHECK_GE(guard_.num_contenders_, 0);
944 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700945#else
946 guard_.recursion_count_ = 0;
947 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
948#endif
949 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700950}
951
Ian Rogersc604d732012-10-14 16:09:54 -0700952void ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
953 DCHECK(self == NULL || self == Thread::Current());
954 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700955 unsigned int old_recursion_count = guard_.recursion_count_;
956#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700957 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800958 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700959 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800960 // Ensure the Mutex is contended so that requeued threads are awoken.
961 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700962 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800963 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700964 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800965 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, &rel_ts, NULL, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700966 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800967 // Timed out we're done.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800968 } else if ((errno == EINTR) || (errno == EAGAIN)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800969 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700970 } else {
971 PLOG(FATAL) << "timed futex wait failed for " << name_;
972 }
973 }
974 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800975 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700976 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800977 // We awoke and so no longer require awakes from the guard_'s unlock.
978 CHECK_GE(guard_.num_contenders_, 0);
979 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700980#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700981#ifdef HAVE_TIMEDWAIT_MONOTONIC
982#define TIMEDWAIT pthread_cond_timedwait_monotonic
Ian Rogersc604d732012-10-14 16:09:54 -0700983 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700984#else
985#define TIMEDWAIT pthread_cond_timedwait
Ian Rogersc604d732012-10-14 16:09:54 -0700986 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700987#endif
Ian Rogersc604d732012-10-14 16:09:54 -0700988 guard_.recursion_count_ = 0;
989 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700990 InitTimeSpec(true, clock, ms, ns, &ts);
991 int rc = TEMP_FAILURE_RETRY(TIMEDWAIT(&cond_, &guard_.mutex_, &ts));
Elliott Hughes5f791332011-09-15 17:45:30 -0700992 if (rc != 0 && rc != ETIMEDOUT) {
993 errno = rc;
994 PLOG(FATAL) << "TimedWait failed for " << name_;
995 }
Ian Rogersc604d732012-10-14 16:09:54 -0700996#endif
997 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700998}
999
Elliott Hughese62934d2012-04-09 11:24:29 -07001000} // namespace art