blob: e2ab51f2f90f3241488eaf086c4afef4b11d1fd0 [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"
24#include "cutils/atomic-inline.h"
Elliott Hughes6b355752012-01-13 16:49:08 -080025#include "runtime.h"
Ian Rogersc604d732012-10-14 16:09:54 -070026#include "scoped_thread_state_change.h"
Elliott Hughesffb465f2012-03-01 18:46:05 -080027#include "thread.h"
28#include "utils.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070029
Elliott Hughes8d768a92011-09-14 16:35:25 -070030#define CHECK_MUTEX_CALL(call, args) CHECK_PTHREAD_CALL(call, args, name_)
31
Elliott Hughesf8349362012-06-18 15:00:06 -070032extern int pthread_mutex_lock(pthread_mutex_t* mutex) EXCLUSIVE_LOCK_FUNCTION(mutex);
33extern int pthread_mutex_unlock(pthread_mutex_t* mutex) UNLOCK_FUNCTION(1);
34extern int pthread_mutex_trylock(pthread_mutex_t* mutex) EXCLUSIVE_TRYLOCK_FUNCTION(0, mutex);
35
Ian Rogers81d425b2012-09-27 16:03:43 -070036#if ART_USE_FUTEXES
Ian Rogersacc46d62012-09-27 21:39:40 -070037#include "linux/futex.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070038#include "sys/syscall.h"
39#ifndef SYS_futex
40#define SYS_futex __NR_futex
41#endif
Ian Rogersc604d732012-10-14 16:09:54 -070042int futex(volatile int *uaddr, int op, int val, const struct timespec *timeout, volatile int *uaddr2, int val3) {
43 return syscall(SYS_futex, uaddr, op, val, timeout, uaddr2, val3);
Ian Rogers81d425b2012-09-27 16:03:43 -070044}
45#endif // ART_USE_FUTEXES
46
Elliott Hughes8daa0922011-09-11 13:46:25 -070047namespace art {
48
Brian Carlstromf3a26412012-08-24 11:06:02 -070049// This works on Mac OS 10.6 but hasn't been tested on older releases.
Elliott Hughesf1498432012-03-28 19:34:27 -070050struct __attribute__((__may_alias__)) darwin_pthread_mutex_t {
Brian Carlstromf3a26412012-08-24 11:06:02 -070051 long padding0;
52 int padding1;
53 uint32_t padding2;
54 int16_t padding3;
55 int16_t padding4;
56 uint32_t padding5;
57 pthread_t darwin_pthread_mutex_owner;
Ian Rogers00f7d0e2012-07-19 15:28:27 -070058 // ...other stuff we don't care about.
59};
60
61struct __attribute__((__may_alias__)) darwin_pthread_rwlock_t {
Brian Carlstromf3a26412012-08-24 11:06:02 -070062 long padding0;
63 pthread_mutex_t padding1;
64 int padding2;
65 pthread_cond_t padding3;
66 pthread_cond_t padding4;
67 int padding5;
68 int padding6;
69 pthread_t darwin_pthread_rwlock_owner;
Elliott Hughesf1498432012-03-28 19:34:27 -070070 // ...other stuff we don't care about.
71};
72
73struct __attribute__((__may_alias__)) glibc_pthread_mutex_t {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070074 int32_t padding0[2];
Elliott Hughesf1498432012-03-28 19:34:27 -070075 int owner;
76 // ...other stuff we don't care about.
77};
78
Ian Rogers00f7d0e2012-07-19 15:28:27 -070079struct __attribute__((__may_alias__)) glibc_pthread_rwlock_t {
80#ifdef __LP64__
81 int32_t padding0[6];
82#else
83 int32_t padding0[7];
84#endif
85 int writer;
86 // ...other stuff we don't care about.
87};
88
Ian Rogers01ae5802012-09-28 16:14:01 -070089static uint64_t SafeGetTid(const Thread* self) {
90 if (self != NULL) {
91 return static_cast<uint64_t>(self->GetTid());
92 } else {
93 return static_cast<uint64_t>(GetTid());
94 }
95}
96
Ian Rogersc604d732012-10-14 16:09:54 -070097#if ART_USE_FUTEXES
98static bool ComputeRelativeTimeSpec(timespec* result_ts, const timespec& lhs, const timespec& rhs) {
99 const long int one_sec = 1000 * 1000 * 1000; // one second in nanoseconds.
100 result_ts->tv_sec = lhs.tv_sec - rhs.tv_sec;
101 result_ts->tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
102 if (result_ts->tv_nsec < 0) {
103 result_ts->tv_sec--;
104 result_ts->tv_nsec += one_sec;
105 } else if (result_ts->tv_nsec > one_sec) {
106 result_ts->tv_sec++;
107 result_ts->tv_nsec -= one_sec;
108 }
109 return result_ts->tv_sec < 0;
110}
111#endif
112
Ian Rogers56edc432013-01-18 16:51:51 -0800113#if CONTENTION_LOGGING
114// A guard for all_mutexes_ that's not a mutex (Mutexes must CAS to acquire and busy wait).
115static AtomicInteger all_mutexes_guard_;
116// All created mutexes guarded by all_mutexes_guard_.
117std::set<BaseMutex*>* all_mutexes_;
118
119class ScopedAllMutexesLock {
120 public:
121 ScopedAllMutexesLock(const BaseMutex* mutex) : mutex_(mutex) {
122 while (!all_mutexes_guard_.CompareAndSwap(0, reinterpret_cast<int32_t>(mutex))) {
123 NanoSleep(100);
124 }
125 }
126 ~ScopedAllMutexesLock() {
127 while (!all_mutexes_guard_.CompareAndSwap(reinterpret_cast<int32_t>(mutex_), 0)) {
128 NanoSleep(100);
129 }
130 }
131 private:
132 const BaseMutex* const mutex_;
133};
134#endif
135
136BaseMutex::BaseMutex(const char* name, LockLevel level) : level_(level), name_(name) {
137#if CONTENTION_LOGGING
138 ScopedAllMutexesLock mu(this);
139 if (all_mutexes_ == NULL) {
140 // We leak the global set of all mutexes to avoid ordering issues in global variable
141 // construction/destruction.
142 all_mutexes_ = new std::set<BaseMutex*>();
143 }
144 all_mutexes_->insert(this);
145#endif
146}
147
148BaseMutex::~BaseMutex() {
149#if CONTENTION_LOGGING
150 ScopedAllMutexesLock mu(this);
151 all_mutexes_->erase(this);
152#endif
153}
154
155void BaseMutex::DumpAll(std::ostream& os) {
156#if CONTENTION_LOGGING
157 os << "Mutex logging:\n";
158 ScopedAllMutexesLock mu(reinterpret_cast<const BaseMutex*>(-1));
159 typedef std::set<BaseMutex*>::const_iterator It;
160 for (It it = all_mutexes_->begin(); it != all_mutexes_->end(); ++it) {
161 BaseMutex* mutex = *it;
162 mutex->Dump(os);
163 os << "\n";
164 }
165#endif
166}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700167
Ian Rogers120f1c72012-09-28 17:17:10 -0700168static void CheckUnattachedThread(LockLevel level) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700169 // The check below enumerates the cases where we expect not to be able to sanity check locks
Ian Rogers120f1c72012-09-28 17:17:10 -0700170 // on a thread. Lock checking is disabled to avoid deadlock when checking shutdown lock.
171 // TODO: tighten this check.
Ian Rogers25fd14b2012-09-05 10:56:38 -0700172 if (kDebugLocking) {
173 Runtime* runtime = Runtime::Current();
174 CHECK(runtime == NULL || !runtime->IsStarted() || runtime->IsShuttingDown() ||
Ian Rogers120f1c72012-09-28 17:17:10 -0700175 level == kDefaultMutexLevel || level == kRuntimeShutdownLock ||
176 level == kThreadListLock || level == kLoggingLock || level == kAbortLock);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700177 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800178}
179
Ian Rogers81d425b2012-09-27 16:03:43 -0700180void BaseMutex::RegisterAsLocked(Thread* self) {
181 if (UNLIKELY(self == NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700182 CheckUnattachedThread(level_);
183 return;
184 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700185 if (kDebugLocking) {
186 // Check if a bad Mutex of this level or lower is held.
187 bool bad_mutexes_held = false;
188 for (int i = level_; i >= 0; --i) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700189 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700190 if (UNLIKELY(held_mutex != NULL)) {
191 LOG(ERROR) << "Lock level violation: holding \"" << held_mutex->name_ << "\" (level " << i
192 << ") while locking \"" << name_ << "\" (level " << static_cast<int>(level_) << ")";
193 if (i > kAbortLock) {
194 // Only abort in the check below if this is more than abort level lock.
195 bad_mutexes_held = true;
196 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700197 }
198 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700199 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700200 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700201 // Don't record monitors as they are outside the scope of analysis. They may be inspected off of
202 // the monitor list.
203 if (level_ != kMonitorLock) {
204 self->SetHeldMutex(level_, this);
205 }
206}
207
Ian Rogers81d425b2012-09-27 16:03:43 -0700208void BaseMutex::RegisterAsUnlocked(Thread* self) {
209 if (UNLIKELY(self == NULL)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700210 CheckUnattachedThread(level_);
211 return;
212 }
213 if (level_ != kMonitorLock) {
Brian Carlstrom760c9432012-11-29 16:46:27 -0800214 if (kDebugLocking && !gAborting) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700215 CHECK(self->GetHeldMutex(level_) == this) << "Unlocking on unacquired mutex: " << name_;
216 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700217 self->SetHeldMutex(level_, NULL);
218 }
219}
220
Ian Rogers81d425b2012-09-27 16:03:43 -0700221void BaseMutex::CheckSafeToWait(Thread* self) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700222 if (self == NULL) {
223 CheckUnattachedThread(level_);
224 return;
225 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700226 if (kDebugLocking) {
227 CHECK(self->GetHeldMutex(level_) == this) << "Waiting on unacquired mutex: " << name_;
228 bool bad_mutexes_held = false;
229 for (int i = kMaxMutexLevel; i >= 0; --i) {
230 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700231 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700232 if (held_mutex != NULL) {
233 LOG(ERROR) << "Holding " << held_mutex->name_ << " (level " << i
234 << ") while performing wait on: "
235 << name_ << " (level " << static_cast<int>(level_) << ")";
236 bad_mutexes_held = true;
237 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700238 }
239 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700240 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700241 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700242}
243
Ian Rogers56edc432013-01-18 16:51:51 -0800244void BaseMutex::RecordContention(uint64_t blocked_tid, uint64_t owner_tid, uint64_t milli_time_blocked) {
245#if CONTENTION_LOGGING
246 ++contention_count_;
247 wait_time_ += static_cast<uint32_t>(milli_time_blocked); // May overflow.
248 // This code is intentionally racy as it is only used for diagnostics.
249 uint32_t slot = cur_content_log_entry_;
250 if (contention_log_[slot].blocked_tid == blocked_tid &&
251 contention_log_[slot].owner_tid == blocked_tid) {
252 ++contention_log_[slot].count;
253 } else {
254 uint32_t new_slot;
255 do {
256 slot = cur_content_log_entry_;
257 new_slot = (slot + 1) % kContentionLogSize;
258 } while(!cur_content_log_entry_.CompareAndSwap(slot, new_slot));
259 contention_log_[new_slot].blocked_tid = blocked_tid;
260 contention_log_[new_slot].owner_tid = owner_tid;
261 contention_log_[new_slot].count = 1;
262 }
263#endif
264}
265
266class ScopedContentionRecorder {
267 public:
268 ScopedContentionRecorder(BaseMutex* mutex, uint64_t blocked_tid, uint64_t owner_tid) :
269 mutex_(mutex), blocked_tid_(blocked_tid), owner_tid_(owner_tid),
270 start_milli_time_(MilliTime()) {
271 }
272
273 ~ScopedContentionRecorder() {
274 uint64_t end_milli_time = MilliTime();
275 mutex_->RecordContention(blocked_tid_, owner_tid_, end_milli_time - start_milli_time_);
276 }
277
278 private:
279 BaseMutex* const mutex_;
280 uint64_t blocked_tid_;
281 uint64_t owner_tid_;
282 const uint64_t start_milli_time_;
283};
284
285void BaseMutex::DumpContention(std::ostream& os) const {
286#if CONTENTION_LOGGING
287 uint32_t wait_time = wait_time_;
288 uint32_t contention_count = contention_count_;
289 if (contention_count == 0) {
290 os << "never contended";
291 } else {
292 os << "contended " << contention_count << " times, average wait of contender " << (wait_time / contention_count) << "ms";
293 SafeMap<uint64_t, size_t> most_common_blocker;
294 SafeMap<uint64_t, size_t> most_common_blocked;
295 typedef SafeMap<uint64_t, size_t>::const_iterator It;
296 for (size_t i = 0; i < kContentionLogSize; ++i) {
297 uint64_t blocked_tid = contention_log_[i].blocked_tid;
298 uint64_t owner_tid = contention_log_[i].owner_tid;
299 uint32_t count = contention_log_[i].count;
300 if (count > 0) {
301 It it = most_common_blocked.find(blocked_tid);
302 if (it != most_common_blocked.end()) {
303 most_common_blocked.Overwrite(blocked_tid, it->second + count);
304 } else {
305 most_common_blocked.Put(blocked_tid, count);
306 }
307 it = most_common_blocker.find(owner_tid);
308 if (it != most_common_blocker.end()) {
309 most_common_blocker.Overwrite(owner_tid, it->second + count);
310 } else {
311 most_common_blocker.Put(owner_tid, count);
312 }
313 }
314 }
315 uint64_t max_tid = 0;
316 size_t max_tid_count = 0;
317 for (It it = most_common_blocked.begin(); it != most_common_blocked.end(); ++it) {
318 if (it->second > max_tid_count) {
319 max_tid = it->first;
320 max_tid_count = it->second;
321 }
322 }
323 if (max_tid != 0) {
324 os << " sample shows most blocked tid=" << max_tid;
325 }
326 max_tid = 0;
327 max_tid_count = 0;
328 for (It it = most_common_blocker.begin(); it != most_common_blocker.end(); ++it) {
329 if (it->second > max_tid_count) {
330 max_tid = it->first;
331 max_tid_count = it->second;
332 }
333 }
334 if (max_tid != 0) {
335 os << " sample shows tid=" << max_tid << " owning during this time";
336 }
337 }
338#endif
339}
340
341
Ian Rogers81d425b2012-09-27 16:03:43 -0700342Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700343 : BaseMutex(name, level), recursive_(recursive), recursion_count_(0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700344#if ART_USE_FUTEXES
345 state_ = 0;
346 exclusive_owner_ = 0;
347 num_contenders_ = 0;
348#elif defined(__BIONIC__) || defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700349 // Use recursive mutexes for bionic and Apple otherwise the
350 // non-recursive mutexes don't have TIDs to check lock ownership of.
Elliott Hughesbbd9d832011-11-07 14:40:00 -0800351 pthread_mutexattr_t attributes;
352 CHECK_MUTEX_CALL(pthread_mutexattr_init, (&attributes));
353 CHECK_MUTEX_CALL(pthread_mutexattr_settype, (&attributes, PTHREAD_MUTEX_RECURSIVE));
354 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, &attributes));
355 CHECK_MUTEX_CALL(pthread_mutexattr_destroy, (&attributes));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700356#else
357 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, NULL));
358#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700359}
360
361Mutex::~Mutex() {
Ian Rogersc604d732012-10-14 16:09:54 -0700362#if ART_USE_FUTEXES
363 if (state_ != 0) {
364 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
365 Runtime* runtime = Runtime::Current();
366 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
367 LOG(shutting_down ? WARNING : FATAL) << "destroying mutex with owner: " << exclusive_owner_;
368 } else {
369 CHECK_EQ(exclusive_owner_, 0U) << "unexpectedly found an owner on unlocked mutex " << name_;
370 CHECK_EQ(num_contenders_, 0) << "unexpectedly found a contender on mutex " << name_;
371 }
372#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700373 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
374 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800375 int rc = pthread_mutex_destroy(&mutex_);
376 if (rc != 0) {
377 errno = rc;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800378 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700379 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700380 Runtime* runtime = Runtime::Current();
381 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughes6b355752012-01-13 16:49:08 -0800382 PLOG(shutting_down ? WARNING : FATAL) << "pthread_mutex_destroy failed for " << name_;
383 }
Ian Rogersc604d732012-10-14 16:09:54 -0700384#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700385}
386
Ian Rogers81d425b2012-09-27 16:03:43 -0700387void Mutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700388 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700389 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700390 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700391 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700392 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700393#if ART_USE_FUTEXES
394 bool done = false;
395 do {
396 int32_t cur_state = state_;
397 if (cur_state == 0) {
398 // Change state from 0 to 1.
399 done = android_atomic_cmpxchg(0, 1, &state_) == 0;
400 } else {
401 // Failed to acquire, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800402 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700403 android_atomic_inc(&num_contenders_);
404 if (futex(&state_, FUTEX_WAIT, 1, NULL, NULL, 0) != 0) {
405 if (errno != EAGAIN) {
406 PLOG(FATAL) << "futex wait failed for " << name_;
407 }
408 }
409 android_atomic_dec(&num_contenders_);
410 }
411 } while(!done);
412 DCHECK_EQ(state_, 1);
413 exclusive_owner_ = SafeGetTid(self);
414#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700415 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700416#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700417 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700418 }
419 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700420 if (kDebugLocking) {
421 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
422 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700423 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700424 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700425}
426
Ian Rogers81d425b2012-09-27 16:03:43 -0700427bool Mutex::ExclusiveTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700428 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700429 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700430 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700431 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700432 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700433#if ART_USE_FUTEXES
434 bool done = false;
435 do {
436 int32_t cur_state = state_;
437 if (cur_state == 0) {
438 // Change state from 0 to 1.
439 done = android_atomic_cmpxchg(0, 1, &state_) == 0;
440 } else {
441 return false;
442 }
443 } while(!done);
444 DCHECK_EQ(state_, 1);
445 exclusive_owner_ = SafeGetTid(self);
446#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700447 int result = pthread_mutex_trylock(&mutex_);
448 if (result == EBUSY) {
449 return false;
450 }
451 if (result != 0) {
452 errno = result;
453 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
454 }
Ian Rogersc604d732012-10-14 16:09:54 -0700455#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700456 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700457 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700458 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700459 if (kDebugLocking) {
460 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
461 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700462 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700463 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700464 return true;
465}
466
Ian Rogers81d425b2012-09-27 16:03:43 -0700467void Mutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700468 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700469 AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700470 recursion_count_--;
471 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700472 if (kDebugLocking) {
473 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
474 << name_ << " " << recursion_count_;
475 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700476 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700477#if ART_USE_FUTEXES
478 bool done = false;
479 do {
480 int32_t cur_state = state_;
481 if (cur_state == 1) {
482 // We're no longer the owner.
483 exclusive_owner_ = 0;
484 // Change state to 0.
485 done = android_atomic_cmpxchg(cur_state, 0, &state_) == 0;
486 if (done) { // Spurious fail?
487 // Wake a contender
488 if (num_contenders_ > 0) {
489 futex(&state_, FUTEX_WAKE, 1, NULL, NULL, 0);
490 }
491 }
492 } else {
493 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
494 }
495 } while(!done);
496#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700497 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700498#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700499 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700500}
501
Ian Rogers81d425b2012-09-27 16:03:43 -0700502bool Mutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700503 DCHECK(self == NULL || self == Thread::Current());
504 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
505 if (kDebugLocking) {
506 // Sanity debug check that if we think it is locked we have it in our held mutexes.
Brian Carlstrom9e419ca2012-11-27 11:31:49 -0800507 if (result && self != NULL && level_ != kMonitorLock && !gAborting) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700508 CHECK_EQ(self->GetHeldMutex(level_), this);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700509 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700510 }
511 return result;
Elliott Hughesf1498432012-03-28 19:34:27 -0700512}
513
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700514uint64_t Mutex::GetExclusiveOwnerTid() const {
Ian Rogersc604d732012-10-14 16:09:54 -0700515#if ART_USE_FUTEXES
516 return exclusive_owner_;
517#elif defined(__BIONIC__)
Elliott Hughesf1498432012-03-28 19:34:27 -0700518 return static_cast<uint64_t>((mutex_.value >> 16) & 0xffff);
Elliott Hughes3147a232011-10-12 15:55:07 -0700519#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700520 return reinterpret_cast<const glibc_pthread_mutex_t*>(&mutex_)->owner;
Elliott Hughescf044312012-01-23 18:48:51 -0800521#elif defined(__APPLE__)
Brian Carlstromf3a26412012-08-24 11:06:02 -0700522 const darwin_pthread_mutex_t* dpmutex = reinterpret_cast<const darwin_pthread_mutex_t*>(&mutex_);
523 pthread_t owner = dpmutex->darwin_pthread_mutex_owner;
Brian Carlstrombd93c302012-08-27 16:58:28 -0700524 // 0 for unowned, -1 for PTHREAD_MTX_TID_SWITCHING
525 // TODO: should we make darwin_pthread_mutex_owner volatile and recheck until not -1?
Brian Carlstromf3a26412012-08-24 11:06:02 -0700526 if ((owner == (pthread_t)0) || (owner == (pthread_t)-1)) {
527 return 0;
528 }
529 uint64_t tid;
530 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
531 return tid;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700532#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700533#error unsupported C library
Elliott Hughes8daa0922011-09-11 13:46:25 -0700534#endif
535}
536
Ian Rogers56edc432013-01-18 16:51:51 -0800537void Mutex::Dump(std::ostream& os) const {
538 os << (recursive_ ? "recursive " : "non-recursive ")
539 << name_
540 << " level=" << static_cast<int>(level_)
541 << " rec=" << recursion_count_
542 << " owner=" << GetExclusiveOwnerTid() << " ";
543 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700544}
545
546std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800547 mu.Dump(os);
548 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700549}
550
Ian Rogers81d425b2012-09-27 16:03:43 -0700551ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level) :
552 BaseMutex(name, level)
553#if ART_USE_FUTEXES
554 , state_(0), exclusive_owner_(0), num_pending_readers_(0), num_pending_writers_(0)
555#endif
556{
557#if !ART_USE_FUTEXES
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700558 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, NULL));
Ian Rogers81d425b2012-09-27 16:03:43 -0700559#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700560}
561
562ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700563#if ART_USE_FUTEXES
564 CHECK_EQ(state_, 0);
565 CHECK_EQ(exclusive_owner_, 0U);
566 CHECK_EQ(num_pending_readers_, 0);
567 CHECK_EQ(num_pending_writers_, 0);
568#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700569 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
570 // may still be using locks.
571 int rc = pthread_rwlock_destroy(&rwlock_);
572 if (rc != 0) {
573 errno = rc;
574 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700575 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700576 Runtime* runtime = Runtime::Current();
577 bool shutting_down = runtime == NULL || runtime->IsShuttingDown();
578 PLOG(shutting_down ? WARNING : FATAL) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800579 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700580#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700581}
582
Ian Rogers81d425b2012-09-27 16:03:43 -0700583void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700584 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700585 AssertNotExclusiveHeld(self);
586#if ART_USE_FUTEXES
587 bool done = false;
588 do {
589 int32_t cur_state = state_;
590 if (cur_state == 0) {
591 // Change state from 0 to -1.
592 done = android_atomic_cmpxchg(0, -1, &state_) == 0;
593 } else {
594 // Failed to acquire, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800595 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700596 android_atomic_inc(&num_pending_writers_);
597 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
598 if (errno != EAGAIN) {
599 PLOG(FATAL) << "futex wait failed for " << name_;
600 }
601 }
602 android_atomic_dec(&num_pending_writers_);
603 }
604 } while(!done);
Ian Rogersab470162012-09-29 23:06:53 -0700605 DCHECK_EQ(state_, -1);
606 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700607#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700608 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700609#endif
610 RegisterAsLocked(self);
611 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700612}
613
Ian Rogers81d425b2012-09-27 16:03:43 -0700614void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700615 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700616 AssertExclusiveHeld(self);
617 RegisterAsUnlocked(self);
618#if ART_USE_FUTEXES
619 bool done = false;
620 do {
621 int32_t cur_state = state_;
622 if (cur_state == -1) {
623 // We're no longer the owner.
624 exclusive_owner_ = 0;
625 // Change state from -1 to 0.
626 done = android_atomic_cmpxchg(-1, 0, &state_) == 0;
627 if (done) { // cmpxchg may fail due to noise?
628 // Wake any waiters.
629 if (num_pending_readers_ > 0 || num_pending_writers_ > 0) {
630 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
631 }
632 }
633 } else {
634 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
635 }
636 } while(!done);
637#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700638 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700639#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700640}
641
Ian Rogers66aee5c2012-08-15 17:17:47 -0700642#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700643bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700644 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700645#if ART_USE_FUTEXES
646 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700647 timespec end_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800648 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700649 do {
650 int32_t cur_state = state_;
651 if (cur_state == 0) {
652 // Change state from 0 to -1.
653 done = android_atomic_cmpxchg(0, -1, &state_) == 0;
654 } else {
655 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700656 timespec now_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800657 InitTimeSpec(true, CLOCK_REALTIME, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700658 timespec rel_ts;
659 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
660 return false; // Timed out.
661 }
Ian Rogers56edc432013-01-18 16:51:51 -0800662 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700663 android_atomic_inc(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700664 if (futex(&state_, FUTEX_WAIT, cur_state, &rel_ts, NULL, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700665 if (errno == ETIMEDOUT) {
666 android_atomic_dec(&num_pending_writers_);
Ian Rogersc604d732012-10-14 16:09:54 -0700667 return false; // Timed out.
668 } else if (errno != EAGAIN && errno != EINTR) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700669 PLOG(FATAL) << "timed futex wait failed for " << name_;
670 }
671 }
672 android_atomic_dec(&num_pending_writers_);
673 }
674 } while(!done);
Ian Rogers01ae5802012-09-28 16:14:01 -0700675 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700676#else
Ian Rogersc604d732012-10-14 16:09:54 -0700677 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700678 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700679 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700680 if (result == ETIMEDOUT) {
681 return false;
682 }
683 if (result != 0) {
684 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700685 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700686 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700687#endif
688 RegisterAsLocked(self);
689 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700690 return true;
691}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700692#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700693
Ian Rogers81d425b2012-09-27 16:03:43 -0700694void ReaderWriterMutex::SharedLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700695 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700696#if ART_USE_FUTEXES
697 bool done = false;
698 do {
699 int32_t cur_state = state_;
700 if (cur_state >= 0) {
701 // Add as an extra reader.
702 done = android_atomic_cmpxchg(cur_state, cur_state + 1, &state_) == 0;
703 } else {
704 // Owner holds it exclusively, hang up.
Ian Rogers56edc432013-01-18 16:51:51 -0800705 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogers81d425b2012-09-27 16:03:43 -0700706 android_atomic_inc(&num_pending_readers_);
707 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
708 if (errno != EAGAIN) {
709 PLOG(FATAL) << "futex wait failed for " << name_;
710 }
711 }
712 android_atomic_dec(&num_pending_readers_);
713 }
714 } while(!done);
715#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700716 CHECK_MUTEX_CALL(pthread_rwlock_rdlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700717#endif
718 RegisterAsLocked(self);
719 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700720}
721
Ian Rogers81d425b2012-09-27 16:03:43 -0700722bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700723 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700724#if ART_USE_FUTEXES
725 bool done = false;
726 do {
727 int32_t cur_state = state_;
728 if (cur_state >= 0) {
729 // Add as an extra reader.
730 done = android_atomic_cmpxchg(cur_state, cur_state + 1, &state_) == 0;
731 } else {
732 // Owner holds it exclusively.
733 return false;
734 }
735 } while(!done);
736#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700737 int result = pthread_rwlock_tryrdlock(&rwlock_);
738 if (result == EBUSY) {
739 return false;
740 }
741 if (result != 0) {
742 errno = result;
743 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
744 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700745#endif
746 RegisterAsLocked(self);
747 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700748 return true;
749}
750
Ian Rogers81d425b2012-09-27 16:03:43 -0700751void ReaderWriterMutex::SharedUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700752 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700753 AssertSharedHeld(self);
754 RegisterAsUnlocked(self);
755#if ART_USE_FUTEXES
756 bool done = false;
757 do {
758 int32_t cur_state = state_;
759 if (LIKELY(cur_state > 0)) {
760 // Reduce state by 1.
761 done = android_atomic_cmpxchg(cur_state, cur_state - 1, &state_) == 0;
762 if (done && (cur_state - 1) == 0) { // cmpxchg may fail due to noise?
763 if (num_pending_writers_ > 0 || num_pending_readers_ > 0) {
764 // Wake any exclusive waiters as there are now no readers.
765 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
766 }
767 }
768 } else {
769 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
770 }
771 } while(!done);
772#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700773 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700774#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700775}
776
Ian Rogers81d425b2012-09-27 16:03:43 -0700777bool ReaderWriterMutex::IsExclusiveHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700778 DCHECK(self == NULL || self == Thread::Current());
779 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700780 if (kDebugLocking) {
781 // Sanity that if the pthread thinks we own the lock the Thread agrees.
Ian Rogers01ae5802012-09-28 16:14:01 -0700782 if (self != NULL && result) {
783 CHECK_EQ(self->GetHeldMutex(level_), this);
784 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700785 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700786 return result;
787}
788
Ian Rogers81d425b2012-09-27 16:03:43 -0700789bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700790 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700791 bool result;
792 if (UNLIKELY(self == NULL)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700793 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700794 } else {
795 result = (self->GetHeldMutex(level_) == this);
796 }
797 return result;
798}
799
800uint64_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700801#if ART_USE_FUTEXES
Ian Rogers56edc432013-01-18 16:51:51 -0800802 int32_t state = state_;
803 if (state == 0) {
804 return 0; // No owner.
805 } else if (state > 0) {
806 return -1; // Shared.
807 } else {
808 return exclusive_owner_;
809 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700810#else
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800811#if defined(__BIONIC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700812 return rwlock_.writerThreadId;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800813#elif defined(__GLIBC__)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700814 return reinterpret_cast<const glibc_pthread_rwlock_t*>(&rwlock_)->writer;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800815#elif defined(__APPLE__)
Ian Rogers81d425b2012-09-27 16:03:43 -0700816 const darwin_pthread_rwlock_t*
817 dprwlock = reinterpret_cast<const darwin_pthread_rwlock_t*>(&rwlock_);
Brian Carlstromf3a26412012-08-24 11:06:02 -0700818 pthread_t owner = dprwlock->darwin_pthread_rwlock_owner;
819 if (owner == (pthread_t)0) {
820 return 0;
821 }
822 uint64_t tid;
823 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
824 return tid;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800825#else
Elliott Hughesf1498432012-03-28 19:34:27 -0700826#error unsupported C library
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800827#endif
Ian Rogers81d425b2012-09-27 16:03:43 -0700828#endif
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800829}
830
Ian Rogers56edc432013-01-18 16:51:51 -0800831void ReaderWriterMutex::Dump(std::ostream& os) const {
832 os << name_
833 << " level=" << static_cast<int>(level_)
834 << " owner=" << GetExclusiveOwnerTid() << " ";
835 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700836}
837
838std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800839 mu.Dump(os);
840 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700841}
842
Ian Rogersc604d732012-10-14 16:09:54 -0700843ConditionVariable::ConditionVariable(const std::string& name, Mutex& guard)
844 : name_(name), guard_(guard) {
845#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800846 sequence_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700847 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700848#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700849 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, NULL));
Ian Rogersc604d732012-10-14 16:09:54 -0700850#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700851}
852
853ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800854#if ART_USE_FUTEXES
855 if (num_waiters_!= 0) {
856 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
857 Runtime* runtime = Runtime::Current();
858 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Ian Rogersd45f2012012-11-28 11:46:23 -0800859 LOG(shutting_down ? WARNING : FATAL) << "ConditionVariable::~ConditionVariable for " << name_
860 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800861 }
862#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700863 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
864 // may still be using condition variables.
865 int rc = pthread_cond_destroy(&cond_);
866 if (rc != 0) {
867 errno = rc;
Ian Rogers50b35e22012-10-04 10:09:15 -0700868 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700869 Runtime* runtime = Runtime::Current();
870 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
Elliott Hughese62934d2012-04-09 11:24:29 -0700871 PLOG(shutting_down ? WARNING : FATAL) << "pthread_cond_destroy failed for " << name_;
872 }
Ian Rogersc604d732012-10-14 16:09:54 -0700873#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700874}
875
Ian Rogersc604d732012-10-14 16:09:54 -0700876void ConditionVariable::Broadcast(Thread* self) {
877 DCHECK(self == NULL || self == Thread::Current());
878 // TODO: enable below, there's a race in thread creation that causes false failures currently.
879 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700880 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700881#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800882 if (num_waiters_ > 0) {
883 android_atomic_inc(&sequence_); // Indicate the broadcast occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700884 bool done = false;
885 do {
Ian Rogersd45f2012012-11-28 11:46:23 -0800886 int32_t cur_sequence = sequence_;
887 // Requeue waiters onto mutex. The waiter holds the contender count on the mutex high ensuring
888 // mutex unlocks will awaken the requeued waiter thread.
889 done = futex(&sequence_, FUTEX_CMP_REQUEUE, 0,
Ian Rogers5bd97c42012-11-27 02:38:26 -0800890 reinterpret_cast<const timespec*>(std::numeric_limits<int32_t>::max()),
Ian Rogersd45f2012012-11-28 11:46:23 -0800891 &guard_.state_, cur_sequence) != -1;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800892 if (!done) {
893 if (errno != EAGAIN) {
894 PLOG(FATAL) << "futex cmp requeue failed for " << name_;
895 }
Ian Rogers5bd97c42012-11-27 02:38:26 -0800896 }
Ian Rogersc604d732012-10-14 16:09:54 -0700897 } while (!done);
898 }
899#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700900 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700901#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700902}
903
Ian Rogersc604d732012-10-14 16:09:54 -0700904void ConditionVariable::Signal(Thread* self) {
905 DCHECK(self == NULL || self == Thread::Current());
906 guard_.AssertExclusiveHeld(self);
907#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800908 if (num_waiters_ > 0) {
909 android_atomic_inc(&sequence_); // Indicate a signal occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700910 // Futex wake 1 waiter who will then come and in contend on mutex. It'd be nice to requeue them
911 // to avoid this, however, requeueing can only move all waiters.
Ian Rogersd45f2012012-11-28 11:46:23 -0800912 int num_woken = futex(&sequence_, FUTEX_WAKE, 1, NULL, NULL, 0);
913 // Check something was woken or else we changed sequence_ before they had chance to wait.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800914 CHECK((num_woken == 0) || (num_woken == 1));
Ian Rogersc604d732012-10-14 16:09:54 -0700915 }
916#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700917 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700918#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700919}
920
Ian Rogersc604d732012-10-14 16:09:54 -0700921void ConditionVariable::Wait(Thread* self) {
922 DCHECK(self == NULL || self == Thread::Current());
923 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700924 unsigned int old_recursion_count = guard_.recursion_count_;
925#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700926 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800927 // Ensure the Mutex is contended so that requeued threads are awoken.
928 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700929 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800930 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700931 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800932 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, NULL, NULL, 0) != 0) {
933 // Futex failed, check it is an expected error.
934 // EAGAIN == EWOULDBLK, so we let the caller try again.
935 // EINTR implies a signal was sent to this thread.
936 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700937 PLOG(FATAL) << "futex wait failed for " << name_;
938 }
939 }
940 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800941 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700942 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800943 // We awoke and so no longer require awakes from the guard_'s unlock.
944 CHECK_GE(guard_.num_contenders_, 0);
945 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700946#else
947 guard_.recursion_count_ = 0;
948 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
949#endif
950 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700951}
952
Ian Rogersc604d732012-10-14 16:09:54 -0700953void ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
954 DCHECK(self == NULL || self == Thread::Current());
955 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700956 unsigned int old_recursion_count = guard_.recursion_count_;
957#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700958 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800959 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700960 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800961 // Ensure the Mutex is contended so that requeued threads are awoken.
962 android_atomic_inc(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700963 guard_.recursion_count_ = 1;
Ian Rogersd45f2012012-11-28 11:46:23 -0800964 int32_t cur_sequence = sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700965 guard_.ExclusiveUnlock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800966 if (futex(&sequence_, FUTEX_WAIT, cur_sequence, &rel_ts, NULL, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700967 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800968 // Timed out we're done.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800969 } else if ((errno == EINTR) || (errno == EAGAIN)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800970 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700971 } else {
972 PLOG(FATAL) << "timed futex wait failed for " << name_;
973 }
974 }
975 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800976 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700977 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800978 // We awoke and so no longer require awakes from the guard_'s unlock.
979 CHECK_GE(guard_.num_contenders_, 0);
980 android_atomic_dec(&guard_.num_contenders_);
Ian Rogersc604d732012-10-14 16:09:54 -0700981#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700982#ifdef HAVE_TIMEDWAIT_MONOTONIC
983#define TIMEDWAIT pthread_cond_timedwait_monotonic
Ian Rogersc604d732012-10-14 16:09:54 -0700984 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700985#else
986#define TIMEDWAIT pthread_cond_timedwait
Ian Rogersc604d732012-10-14 16:09:54 -0700987 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700988#endif
Ian Rogersc604d732012-10-14 16:09:54 -0700989 guard_.recursion_count_ = 0;
990 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700991 InitTimeSpec(true, clock, ms, ns, &ts);
992 int rc = TEMP_FAILURE_RETRY(TIMEDWAIT(&cond_, &guard_.mutex_, &ts));
Elliott Hughes5f791332011-09-15 17:45:30 -0700993 if (rc != 0 && rc != ETIMEDOUT) {
994 errno = rc;
995 PLOG(FATAL) << "TimedWait failed for " << name_;
996 }
Ian Rogersc604d732012-10-14 16:09:54 -0700997#endif
998 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700999}
1000
Elliott Hughese62934d2012-04-09 11:24:29 -07001001} // namespace art