blob: fd1eb12420afe5b6d3d0452e917010c41bb197aa [file] [log] [blame]
Elliott Hughes8daa0922011-09-11 13:46:25 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "mutex.h"
18
19#include <errno.h>
Ian Rogersc604d732012-10-14 16:09:54 -070020#include <sys/time.h>
Elliott Hughes8daa0922011-09-11 13:46:25 -070021
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070022#include "atomic.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080023#include "base/logging.h"
Ian Rogers693ff612013-02-01 10:56:12 -080024#include "mutex-inl.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"
Ian Rogers04d7aa92013-03-16 14:29:17 -070027#include "thread-inl.h"
Elliott Hughesffb465f2012-03-01 18:46:05 -080028#include "utils.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070029
30namespace art {
31
Ian Rogers719d1a32014-03-06 12:13:39 -080032Mutex* Locks::abort_lock_ = nullptr;
Chao-ying Fu9e369312014-05-21 11:20:52 -070033Mutex* Locks::allocated_thread_ids_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080034Mutex* Locks::breakpoint_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080035ReaderWriterMutex* Locks::classlinker_classes_lock_ = nullptr;
36ReaderWriterMutex* Locks::heap_bitmap_lock_ = nullptr;
37Mutex* Locks::logging_lock_ = nullptr;
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -070038Mutex* Locks::mem_maps_lock_ = nullptr;
Chao-ying Fu9e369312014-05-21 11:20:52 -070039Mutex* Locks::modify_ldt_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080040ReaderWriterMutex* Locks::mutator_lock_ = nullptr;
41Mutex* Locks::runtime_shutdown_lock_ = nullptr;
42Mutex* Locks::thread_list_lock_ = nullptr;
43Mutex* Locks::thread_suspend_count_lock_ = nullptr;
44Mutex* Locks::trace_lock_ = nullptr;
45Mutex* Locks::profiler_lock_ = nullptr;
46Mutex* Locks::unexpected_signal_lock_ = nullptr;
47Mutex* Locks::intern_table_lock_ = nullptr;
48
49struct AllMutexData {
50 // A guard for all_mutexes_ that's not a mutex (Mutexes must CAS to acquire and busy wait).
51 Atomic<const BaseMutex*> all_mutexes_guard;
52 // All created mutexes guarded by all_mutexes_guard_.
53 std::set<BaseMutex*>* all_mutexes;
54 AllMutexData() : all_mutexes(NULL) {}
55};
56static struct AllMutexData gAllMutexData[kAllMutexDataSize];
57
Ian Rogersc604d732012-10-14 16:09:54 -070058#if ART_USE_FUTEXES
59static bool ComputeRelativeTimeSpec(timespec* result_ts, const timespec& lhs, const timespec& rhs) {
Brian Carlstromfb6996f2013-07-18 18:21:14 -070060 const int32_t one_sec = 1000 * 1000 * 1000; // one second in nanoseconds.
Ian Rogersc604d732012-10-14 16:09:54 -070061 result_ts->tv_sec = lhs.tv_sec - rhs.tv_sec;
62 result_ts->tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
63 if (result_ts->tv_nsec < 0) {
64 result_ts->tv_sec--;
65 result_ts->tv_nsec += one_sec;
66 } else if (result_ts->tv_nsec > one_sec) {
67 result_ts->tv_sec++;
68 result_ts->tv_nsec -= one_sec;
69 }
70 return result_ts->tv_sec < 0;
71}
72#endif
73
Ian Rogers56edc432013-01-18 16:51:51 -080074class ScopedAllMutexesLock {
75 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -070076 explicit ScopedAllMutexesLock(const BaseMutex* mutex) : mutex_(mutex) {
Ian Rogers3e5cf302014-05-20 16:40:37 -070077 while (!gAllMutexData->all_mutexes_guard.CompareExchangeWeakAcquire(0, mutex)) {
Ian Rogers56edc432013-01-18 16:51:51 -080078 NanoSleep(100);
79 }
80 }
81 ~ScopedAllMutexesLock() {
Ian Rogers3e5cf302014-05-20 16:40:37 -070082 while (!gAllMutexData->all_mutexes_guard.CompareExchangeWeakRelease(mutex_, 0)) {
Ian Rogers56edc432013-01-18 16:51:51 -080083 NanoSleep(100);
84 }
85 }
86 private:
87 const BaseMutex* const mutex_;
88};
Ian Rogers56edc432013-01-18 16:51:51 -080089
90BaseMutex::BaseMutex(const char* name, LockLevel level) : level_(level), name_(name) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070091 if (kLogLockContentions) {
92 ScopedAllMutexesLock mu(this);
Ian Rogersd9c4fc92013-10-01 19:45:43 -070093 std::set<BaseMutex*>** all_mutexes_ptr = &gAllMutexData->all_mutexes;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070094 if (*all_mutexes_ptr == NULL) {
95 // We leak the global set of all mutexes to avoid ordering issues in global variable
96 // construction/destruction.
97 *all_mutexes_ptr = new std::set<BaseMutex*>();
98 }
99 (*all_mutexes_ptr)->insert(this);
Ian Rogers56edc432013-01-18 16:51:51 -0800100 }
Ian Rogers56edc432013-01-18 16:51:51 -0800101}
102
103BaseMutex::~BaseMutex() {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700104 if (kLogLockContentions) {
105 ScopedAllMutexesLock mu(this);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700106 gAllMutexData->all_mutexes->erase(this);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700107 }
Ian Rogers56edc432013-01-18 16:51:51 -0800108}
109
110void BaseMutex::DumpAll(std::ostream& os) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700111 if (kLogLockContentions) {
112 os << "Mutex logging:\n";
113 ScopedAllMutexesLock mu(reinterpret_cast<const BaseMutex*>(-1));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700114 std::set<BaseMutex*>* all_mutexes = gAllMutexData->all_mutexes;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700115 if (all_mutexes == NULL) {
116 // No mutexes have been created yet during at startup.
117 return;
118 }
119 typedef std::set<BaseMutex*>::const_iterator It;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700120 os << "(Contended)\n";
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700121 for (It it = all_mutexes->begin(); it != all_mutexes->end(); ++it) {
122 BaseMutex* mutex = *it;
123 if (mutex->HasEverContended()) {
124 mutex->Dump(os);
125 os << "\n";
126 }
127 }
128 os << "(Never contented)\n";
129 for (It it = all_mutexes->begin(); it != all_mutexes->end(); ++it) {
130 BaseMutex* mutex = *it;
131 if (!mutex->HasEverContended()) {
132 mutex->Dump(os);
133 os << "\n";
134 }
135 }
Ian Rogers56edc432013-01-18 16:51:51 -0800136 }
Ian Rogers56edc432013-01-18 16:51:51 -0800137}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700138
Ian Rogers81d425b2012-09-27 16:03:43 -0700139void BaseMutex::CheckSafeToWait(Thread* self) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700140 if (self == NULL) {
141 CheckUnattachedThread(level_);
142 return;
143 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700144 if (kDebugLocking) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700145 CHECK(self->GetHeldMutex(level_) == this || level_ == kMonitorLock)
146 << "Waiting on unacquired mutex: " << name_;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700147 bool bad_mutexes_held = false;
Elliott Hughes0f827162013-02-26 12:12:58 -0800148 for (int i = kLockLevelCount - 1; i >= 0; --i) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700149 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700150 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogers25fd14b2012-09-05 10:56:38 -0700151 if (held_mutex != NULL) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800152 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
153 << "(level " << LockLevel(i) << ") while performing wait on "
154 << "\"" << name_ << "\" (level " << level_ << ")";
Ian Rogers25fd14b2012-09-05 10:56:38 -0700155 bad_mutexes_held = true;
156 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700157 }
158 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700159 CHECK(!bad_mutexes_held);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700160 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700161}
162
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700163inline void BaseMutex::ContentionLogData::AddToWaitTime(uint64_t value) {
164 if (kLogLockContentions) {
165 // Atomically add value to wait_time.
166 uint64_t new_val, old_val;
167 volatile int64_t* addr = reinterpret_cast<volatile int64_t*>(&wait_time);
168 volatile const int64_t* caddr = const_cast<volatile const int64_t*>(addr);
169 do {
170 old_val = static_cast<uint64_t>(QuasiAtomic::Read64(caddr));
171 new_val = old_val + value;
172 } while (!QuasiAtomic::Cas64(static_cast<int64_t>(old_val), static_cast<int64_t>(new_val), addr));
173 }
174}
175
Brian Carlstrom0de79852013-07-25 22:29:58 -0700176void BaseMutex::RecordContention(uint64_t blocked_tid,
177 uint64_t owner_tid,
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700178 uint64_t nano_time_blocked) {
179 if (kLogLockContentions) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700180 ContentionLogData* data = contention_log_data_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700181 ++(data->contention_count);
182 data->AddToWaitTime(nano_time_blocked);
183 ContentionLogEntry* log = data->contention_log;
184 // This code is intentionally racy as it is only used for diagnostics.
Ian Rogers3e5cf302014-05-20 16:40:37 -0700185 uint32_t slot = data->cur_content_log_entry.LoadRelaxed();
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700186 if (log[slot].blocked_tid == blocked_tid &&
187 log[slot].owner_tid == blocked_tid) {
188 ++log[slot].count;
189 } else {
190 uint32_t new_slot;
191 do {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700192 slot = data->cur_content_log_entry.LoadRelaxed();
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700193 new_slot = (slot + 1) % kContentionLogSize;
Ian Rogers3e5cf302014-05-20 16:40:37 -0700194 } while (!data->cur_content_log_entry.CompareExchangeWeakRelaxed(slot, new_slot));
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700195 log[new_slot].blocked_tid = blocked_tid;
196 log[new_slot].owner_tid = owner_tid;
Ian Rogers3e5cf302014-05-20 16:40:37 -0700197 log[new_slot].count.StoreRelaxed(1);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700198 }
Ian Rogers56edc432013-01-18 16:51:51 -0800199 }
Ian Rogers56edc432013-01-18 16:51:51 -0800200}
201
Ian Rogers56edc432013-01-18 16:51:51 -0800202void BaseMutex::DumpContention(std::ostream& os) const {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700203 if (kLogLockContentions) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700204 const ContentionLogData* data = contention_log_data_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700205 const ContentionLogEntry* log = data->contention_log;
206 uint64_t wait_time = data->wait_time;
Ian Rogers3e5cf302014-05-20 16:40:37 -0700207 uint32_t contention_count = data->contention_count.LoadRelaxed();
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700208 if (contention_count == 0) {
209 os << "never contended";
210 } else {
211 os << "contended " << contention_count
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700212 << " total wait of contender " << PrettyDuration(wait_time)
213 << " average " << PrettyDuration(wait_time / contention_count);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700214 SafeMap<uint64_t, size_t> most_common_blocker;
215 SafeMap<uint64_t, size_t> most_common_blocked;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700216 for (size_t i = 0; i < kContentionLogSize; ++i) {
217 uint64_t blocked_tid = log[i].blocked_tid;
218 uint64_t owner_tid = log[i].owner_tid;
Ian Rogers3e5cf302014-05-20 16:40:37 -0700219 uint32_t count = log[i].count.LoadRelaxed();
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700220 if (count > 0) {
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700221 auto it = most_common_blocked.find(blocked_tid);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700222 if (it != most_common_blocked.end()) {
223 most_common_blocked.Overwrite(blocked_tid, it->second + count);
224 } else {
225 most_common_blocked.Put(blocked_tid, count);
226 }
227 it = most_common_blocker.find(owner_tid);
228 if (it != most_common_blocker.end()) {
229 most_common_blocker.Overwrite(owner_tid, it->second + count);
230 } else {
231 most_common_blocker.Put(owner_tid, count);
232 }
Ian Rogers56edc432013-01-18 16:51:51 -0800233 }
234 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700235 uint64_t max_tid = 0;
236 size_t max_tid_count = 0;
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700237 for (const auto& pair : most_common_blocked) {
238 if (pair.second > max_tid_count) {
239 max_tid = pair.first;
240 max_tid_count = pair.second;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700241 }
Ian Rogers56edc432013-01-18 16:51:51 -0800242 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700243 if (max_tid != 0) {
244 os << " sample shows most blocked tid=" << max_tid;
Ian Rogers56edc432013-01-18 16:51:51 -0800245 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700246 max_tid = 0;
247 max_tid_count = 0;
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700248 for (const auto& pair : most_common_blocker) {
249 if (pair.second > max_tid_count) {
250 max_tid = pair.first;
251 max_tid_count = pair.second;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700252 }
253 }
254 if (max_tid != 0) {
255 os << " sample shows tid=" << max_tid << " owning during this time";
256 }
Ian Rogers56edc432013-01-18 16:51:51 -0800257 }
258 }
Ian Rogers56edc432013-01-18 16:51:51 -0800259}
260
261
Ian Rogers81d425b2012-09-27 16:03:43 -0700262Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700263 : BaseMutex(name, level), recursive_(recursive), recursion_count_(0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700264#if ART_USE_FUTEXES
265 state_ = 0;
Ian Rogers3e5cf302014-05-20 16:40:37 -0700266 DCHECK_EQ(0, num_contenders_.LoadRelaxed());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700267#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700268 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, nullptr));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700269#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700270 exclusive_owner_ = 0;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700271}
272
273Mutex::~Mutex() {
Ian Rogersc604d732012-10-14 16:09:54 -0700274#if ART_USE_FUTEXES
275 if (state_ != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700276 Runtime* runtime = Runtime::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700277 bool shutting_down = runtime == nullptr || runtime->IsShuttingDown(Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700278 LOG(shutting_down ? WARNING : FATAL) << "destroying mutex with owner: " << exclusive_owner_;
279 } else {
280 CHECK_EQ(exclusive_owner_, 0U) << "unexpectedly found an owner on unlocked mutex " << name_;
Ian Rogers3e5cf302014-05-20 16:40:37 -0700281 CHECK_EQ(num_contenders_.LoadRelaxed(), 0)
282 << "unexpectedly found a contender on mutex " << name_;
Ian Rogersc604d732012-10-14 16:09:54 -0700283 }
284#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700285 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
286 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800287 int rc = pthread_mutex_destroy(&mutex_);
288 if (rc != 0) {
289 errno = rc;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800290 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700291 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700292 Runtime* runtime = Runtime::Current();
Mathieu Chartier34e82932013-11-12 18:22:47 -0800293 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDownLocked();
Elliott Hughes6b355752012-01-13 16:49:08 -0800294 PLOG(shutting_down ? WARNING : FATAL) << "pthread_mutex_destroy failed for " << name_;
295 }
Ian Rogersc604d732012-10-14 16:09:54 -0700296#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700297}
298
Ian Rogers81d425b2012-09-27 16:03:43 -0700299void Mutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700300 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700301 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700302 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700303 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700304 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700305#if ART_USE_FUTEXES
306 bool done = false;
307 do {
308 int32_t cur_state = state_;
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700309 if (LIKELY(cur_state == 0)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700310 // Change state from 0 to 1.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800311 done = __sync_bool_compare_and_swap(&state_, 0 /* cur_state */, 1 /* new state */);
Ian Rogersc604d732012-10-14 16:09:54 -0700312 } else {
313 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700314 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersb122a4b2013-11-19 18:00:50 -0800315 num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -0700316 if (futex(&state_, FUTEX_WAIT, 1, NULL, NULL, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700317 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
318 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
319 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700320 PLOG(FATAL) << "futex wait failed for " << name_;
321 }
322 }
Ian Rogersb122a4b2013-11-19 18:00:50 -0800323 num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700324 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700325 } while (!done);
Hans Boehm30359612014-05-21 17:46:23 -0700326 // We assert that no memory fence is needed here, since
327 // __sync_bool_compare_and_swap includes it.
328 // TODO: Change state_ to be a art::Atomic and use an intention revealing CAS operation
329 // that exposes the ordering semantics.
Ian Rogersc604d732012-10-14 16:09:54 -0700330 DCHECK_EQ(state_, 1);
Ian Rogersc604d732012-10-14 16:09:54 -0700331#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700332 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700333#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700334 DCHECK_EQ(exclusive_owner_, 0U);
335 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700336 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700337 }
338 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700339 if (kDebugLocking) {
340 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
341 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700342 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700343 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700344}
345
Ian Rogers81d425b2012-09-27 16:03:43 -0700346bool Mutex::ExclusiveTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700347 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700348 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700349 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700350 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700351 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700352#if ART_USE_FUTEXES
353 bool done = false;
354 do {
355 int32_t cur_state = state_;
356 if (cur_state == 0) {
357 // Change state from 0 to 1.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800358 done = __sync_bool_compare_and_swap(&state_, 0 /* cur_state */, 1 /* new state */);
Ian Rogersc604d732012-10-14 16:09:54 -0700359 } else {
360 return false;
361 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700362 } while (!done);
Hans Boehm30359612014-05-21 17:46:23 -0700363 // We again assert no memory fence is needed.
Ian Rogersc604d732012-10-14 16:09:54 -0700364 DCHECK_EQ(state_, 1);
Ian Rogersc604d732012-10-14 16:09:54 -0700365#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700366 int result = pthread_mutex_trylock(&mutex_);
367 if (result == EBUSY) {
368 return false;
369 }
370 if (result != 0) {
371 errno = result;
372 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
373 }
Ian Rogersc604d732012-10-14 16:09:54 -0700374#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700375 DCHECK_EQ(exclusive_owner_, 0U);
376 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700377 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700378 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700379 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700380 if (kDebugLocking) {
381 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
382 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700383 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700384 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700385 return true;
386}
387
Ian Rogers81d425b2012-09-27 16:03:43 -0700388void Mutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700389 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700390 AssertHeld(self);
Ian Rogersc5f17732014-06-05 20:48:42 -0700391 DCHECK_NE(exclusive_owner_, 0U);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700392 recursion_count_--;
393 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700394 if (kDebugLocking) {
395 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
396 << name_ << " " << recursion_count_;
397 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700398 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700399#if ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700400 bool done = false;
401 do {
402 int32_t cur_state = state_;
403 if (LIKELY(cur_state == 1)) {
404 // The __sync_bool_compare_and_swap enforces the necessary memory ordering.
405 // We're no longer the owner.
406 exclusive_owner_ = 0;
407 // Change state to 0.
408 done = __sync_bool_compare_and_swap(&state_, cur_state, 0 /* new state */);
409 if (LIKELY(done)) { // Spurious fail?
410 // Wake a contender
411 if (UNLIKELY(num_contenders_.LoadRelaxed() > 0)) {
412 futex(&state_, FUTEX_WAKE, 1, NULL, NULL, 0);
413 }
414 }
415 } else {
416 // Logging acquires the logging lock, avoid infinite recursion in that case.
417 if (this != Locks::logging_lock_) {
418 LOG(FATAL) << "Unexpected state_ in unlock " << cur_state << " for " << name_;
419 } else {
420 LogMessageData data(__FILE__, __LINE__, INTERNAL_FATAL, -1);
421 LogMessage::LogLine(data, StringPrintf("Unexpected state_ %d in unlock for %s",
422 cur_state, name_).c_str());
423 _exit(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700424 }
425 }
Ian Rogersc5f17732014-06-05 20:48:42 -0700426 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700427#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700428 exclusive_owner_ = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700429 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700430#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700431 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700432}
433
Ian Rogers56edc432013-01-18 16:51:51 -0800434void Mutex::Dump(std::ostream& os) const {
435 os << (recursive_ ? "recursive " : "non-recursive ")
436 << name_
437 << " level=" << static_cast<int>(level_)
438 << " rec=" << recursion_count_
439 << " owner=" << GetExclusiveOwnerTid() << " ";
440 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700441}
442
443std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800444 mu.Dump(os);
445 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700446}
447
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700448ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level)
449 : BaseMutex(name, level)
Ian Rogers81d425b2012-09-27 16:03:43 -0700450#if ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700451 , state_(0), num_pending_readers_(0), num_pending_writers_(0)
Ian Rogers81d425b2012-09-27 16:03:43 -0700452#endif
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700453{ // NOLINT(whitespace/braces)
Ian Rogers81d425b2012-09-27 16:03:43 -0700454#if !ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700455 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, nullptr));
Ian Rogers81d425b2012-09-27 16:03:43 -0700456#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700457 exclusive_owner_ = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700458}
459
460ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700461#if ART_USE_FUTEXES
462 CHECK_EQ(state_, 0);
463 CHECK_EQ(exclusive_owner_, 0U);
464 CHECK_EQ(num_pending_readers_, 0);
Ian Rogers3e5cf302014-05-20 16:40:37 -0700465 CHECK_EQ(num_pending_writers_.LoadRelaxed(), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700466#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
468 // may still be using locks.
469 int rc = pthread_rwlock_destroy(&rwlock_);
470 if (rc != 0) {
471 errno = rc;
472 // TODO: should we just not log at all if shutting down? this could be the logging mutex!
Ian Rogers50b35e22012-10-04 10:09:15 -0700473 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700474 Runtime* runtime = Runtime::Current();
Mathieu Chartier34e82932013-11-12 18:22:47 -0800475 bool shutting_down = runtime == NULL || runtime->IsShuttingDownLocked();
Ian Rogers120f1c72012-09-28 17:17:10 -0700476 PLOG(shutting_down ? WARNING : FATAL) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800477 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700478#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700479}
480
Ian Rogers81d425b2012-09-27 16:03:43 -0700481void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700482 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700483 AssertNotExclusiveHeld(self);
484#if ART_USE_FUTEXES
485 bool done = false;
486 do {
487 int32_t cur_state = state_;
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700488 if (LIKELY(cur_state == 0)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700489 // Change state from 0 to -1.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800490 done = __sync_bool_compare_and_swap(&state_, 0 /* cur_state*/, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700491 } else {
492 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700493 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersb122a4b2013-11-19 18:00:50 -0800494 num_pending_writers_++;
Ian Rogers81d425b2012-09-27 16:03:43 -0700495 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700496 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
497 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
498 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700499 PLOG(FATAL) << "futex wait failed for " << name_;
500 }
501 }
Ian Rogersb122a4b2013-11-19 18:00:50 -0800502 num_pending_writers_--;
Ian Rogers81d425b2012-09-27 16:03:43 -0700503 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700504 } while (!done);
Ian Rogersab470162012-09-29 23:06:53 -0700505 DCHECK_EQ(state_, -1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700506#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700507 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700508#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700509 DCHECK_EQ(exclusive_owner_, 0U);
510 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700511 RegisterAsLocked(self);
512 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700513}
514
Ian Rogers81d425b2012-09-27 16:03:43 -0700515void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700516 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700517 AssertExclusiveHeld(self);
518 RegisterAsUnlocked(self);
Ian Rogersc5f17732014-06-05 20:48:42 -0700519 DCHECK_NE(exclusive_owner_, 0U);
Ian Rogers81d425b2012-09-27 16:03:43 -0700520#if ART_USE_FUTEXES
521 bool done = false;
522 do {
523 int32_t cur_state = state_;
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700524 if (LIKELY(cur_state == -1)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700525 // We're no longer the owner.
526 exclusive_owner_ = 0;
527 // Change state from -1 to 0.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800528 done = __sync_bool_compare_and_swap(&state_, -1 /* cur_state*/, 0 /* new state */);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700529 if (LIKELY(done)) { // cmpxchg may fail due to noise?
Ian Rogers81d425b2012-09-27 16:03:43 -0700530 // Wake any waiters.
Ian Rogers3e5cf302014-05-20 16:40:37 -0700531 if (UNLIKELY(num_pending_readers_ > 0 || num_pending_writers_.LoadRelaxed() > 0)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700532 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
533 }
534 }
535 } else {
536 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
537 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700538 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700539#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700540 exclusive_owner_ = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700541 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700542#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700543}
544
Ian Rogers66aee5c2012-08-15 17:17:47 -0700545#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700546bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700547 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700548#if ART_USE_FUTEXES
549 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700550 timespec end_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800551 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700552 do {
553 int32_t cur_state = state_;
554 if (cur_state == 0) {
555 // Change state from 0 to -1.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800556 done = __sync_bool_compare_and_swap(&state_, 0 /* cur_state */, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700557 } else {
558 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700559 timespec now_abs_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800560 InitTimeSpec(true, CLOCK_REALTIME, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700561 timespec rel_ts;
562 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
563 return false; // Timed out.
564 }
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700565 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersb122a4b2013-11-19 18:00:50 -0800566 num_pending_writers_++;
Ian Rogersc604d732012-10-14 16:09:54 -0700567 if (futex(&state_, FUTEX_WAIT, cur_state, &rel_ts, NULL, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700568 if (errno == ETIMEDOUT) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800569 num_pending_writers_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700570 return false; // Timed out.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700571 } else if ((errno != EAGAIN) && (errno != EINTR)) {
572 // EAGAIN and EINTR both indicate a spurious failure,
573 // recompute the relative time out from now and try again.
574 // We don't use TEMP_FAILURE_RETRY so we can recompute rel_ts;
Ian Rogers81d425b2012-09-27 16:03:43 -0700575 PLOG(FATAL) << "timed futex wait failed for " << name_;
576 }
577 }
Ian Rogersb122a4b2013-11-19 18:00:50 -0800578 num_pending_writers_--;
Ian Rogers81d425b2012-09-27 16:03:43 -0700579 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700580 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700581#else
Ian Rogersc604d732012-10-14 16:09:54 -0700582 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700583 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700584 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700585 if (result == ETIMEDOUT) {
586 return false;
587 }
588 if (result != 0) {
589 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700590 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700591 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700592#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700593 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700594 RegisterAsLocked(self);
595 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700596 return true;
597}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700598#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700599
Ian Rogers81d425b2012-09-27 16:03:43 -0700600bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700601 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700602#if ART_USE_FUTEXES
603 bool done = false;
604 do {
605 int32_t cur_state = state_;
606 if (cur_state >= 0) {
607 // Add as an extra reader.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800608 done = __sync_bool_compare_and_swap(&state_, cur_state, cur_state + 1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700609 } else {
610 // Owner holds it exclusively.
611 return false;
612 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700613 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700614#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700615 int result = pthread_rwlock_tryrdlock(&rwlock_);
616 if (result == EBUSY) {
617 return false;
618 }
619 if (result != 0) {
620 errno = result;
621 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
622 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700623#endif
624 RegisterAsLocked(self);
625 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700626 return true;
627}
628
Ian Rogers81d425b2012-09-27 16:03:43 -0700629bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Ian Rogers01ae5802012-09-28 16:14:01 -0700630 DCHECK(self == NULL || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700631 bool result;
632 if (UNLIKELY(self == NULL)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700633 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700634 } else {
635 result = (self->GetHeldMutex(level_) == this);
636 }
637 return result;
638}
639
Ian Rogers56edc432013-01-18 16:51:51 -0800640void ReaderWriterMutex::Dump(std::ostream& os) const {
641 os << name_
642 << " level=" << static_cast<int>(level_)
643 << " owner=" << GetExclusiveOwnerTid() << " ";
644 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700645}
646
647std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800648 mu.Dump(os);
649 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700650}
651
Ian Rogers23055dc2013-04-18 16:29:16 -0700652ConditionVariable::ConditionVariable(const char* name, Mutex& guard)
Ian Rogersc604d732012-10-14 16:09:54 -0700653 : name_(name), guard_(guard) {
654#if ART_USE_FUTEXES
Ian Rogers3e5cf302014-05-20 16:40:37 -0700655 DCHECK_EQ(0, sequence_.LoadRelaxed());
Ian Rogersc604d732012-10-14 16:09:54 -0700656 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700657#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000658 pthread_condattr_t cond_attrs;
Ian Rogersc5f17732014-06-05 20:48:42 -0700659 CHECK_MUTEX_CALL(pthread_condattr_init, (&cond_attrs));
Narayan Kamath51b71022014-03-04 11:57:09 +0000660#if !defined(__APPLE__)
661 // Apple doesn't have CLOCK_MONOTONIC or pthread_condattr_setclock.
662 CHECK_MUTEX_CALL(pthread_condattr_setclock(&cond_attrs, CLOCK_MONOTONIC));
663#endif
664 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, &cond_attrs));
Ian Rogersc604d732012-10-14 16:09:54 -0700665#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700666}
667
668ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800669#if ART_USE_FUTEXES
670 if (num_waiters_!= 0) {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800671 Runtime* runtime = Runtime::Current();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700672 bool shutting_down = runtime == nullptr || runtime->IsShuttingDown(Thread::Current());
Ian Rogersd45f2012012-11-28 11:46:23 -0800673 LOG(shutting_down ? WARNING : FATAL) << "ConditionVariable::~ConditionVariable for " << name_
674 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800675 }
676#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700677 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
678 // may still be using condition variables.
679 int rc = pthread_cond_destroy(&cond_);
680 if (rc != 0) {
681 errno = rc;
Ian Rogers50b35e22012-10-04 10:09:15 -0700682 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700683 Runtime* runtime = Runtime::Current();
Mathieu Chartier34e82932013-11-12 18:22:47 -0800684 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDownLocked();
Elliott Hughese62934d2012-04-09 11:24:29 -0700685 PLOG(shutting_down ? WARNING : FATAL) << "pthread_cond_destroy failed for " << name_;
686 }
Ian Rogersc604d732012-10-14 16:09:54 -0700687#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700688}
689
Ian Rogersc604d732012-10-14 16:09:54 -0700690void ConditionVariable::Broadcast(Thread* self) {
691 DCHECK(self == NULL || self == Thread::Current());
692 // TODO: enable below, there's a race in thread creation that causes false failures currently.
693 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700694 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700695#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800696 if (num_waiters_ > 0) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800697 sequence_++; // Indicate the broadcast occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700698 bool done = false;
699 do {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700700 int32_t cur_sequence = sequence_.LoadRelaxed();
Ian Rogersd45f2012012-11-28 11:46:23 -0800701 // Requeue waiters onto mutex. The waiter holds the contender count on the mutex high ensuring
702 // mutex unlocks will awaken the requeued waiter thread.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800703 done = futex(sequence_.Address(), FUTEX_CMP_REQUEUE, 0,
Ian Rogers5bd97c42012-11-27 02:38:26 -0800704 reinterpret_cast<const timespec*>(std::numeric_limits<int32_t>::max()),
Ian Rogersd45f2012012-11-28 11:46:23 -0800705 &guard_.state_, cur_sequence) != -1;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800706 if (!done) {
707 if (errno != EAGAIN) {
708 PLOG(FATAL) << "futex cmp requeue failed for " << name_;
709 }
Ian Rogers5bd97c42012-11-27 02:38:26 -0800710 }
Ian Rogersc604d732012-10-14 16:09:54 -0700711 } while (!done);
712 }
713#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700714 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700715#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700716}
717
Ian Rogersc604d732012-10-14 16:09:54 -0700718void ConditionVariable::Signal(Thread* self) {
719 DCHECK(self == NULL || self == Thread::Current());
720 guard_.AssertExclusiveHeld(self);
721#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800722 if (num_waiters_ > 0) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800723 sequence_++; // Indicate a signal occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700724 // Futex wake 1 waiter who will then come and in contend on mutex. It'd be nice to requeue them
725 // to avoid this, however, requeueing can only move all waiters.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800726 int num_woken = futex(sequence_.Address(), FUTEX_WAKE, 1, NULL, NULL, 0);
Ian Rogersd45f2012012-11-28 11:46:23 -0800727 // Check something was woken or else we changed sequence_ before they had chance to wait.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800728 CHECK((num_woken == 0) || (num_woken == 1));
Ian Rogersc604d732012-10-14 16:09:54 -0700729 }
730#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700731 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700732#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700733}
734
Ian Rogersc604d732012-10-14 16:09:54 -0700735void ConditionVariable::Wait(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700736 guard_.CheckSafeToWait(self);
737 WaitHoldingLocks(self);
738}
739
740void ConditionVariable::WaitHoldingLocks(Thread* self) {
Ian Rogersc604d732012-10-14 16:09:54 -0700741 DCHECK(self == NULL || self == Thread::Current());
742 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700743 unsigned int old_recursion_count = guard_.recursion_count_;
744#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700745 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800746 // Ensure the Mutex is contended so that requeued threads are awoken.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800747 guard_.num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -0700748 guard_.recursion_count_ = 1;
Ian Rogers3e5cf302014-05-20 16:40:37 -0700749 int32_t cur_sequence = sequence_.LoadRelaxed();
Ian Rogersc604d732012-10-14 16:09:54 -0700750 guard_.ExclusiveUnlock(self);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800751 if (futex(sequence_.Address(), FUTEX_WAIT, cur_sequence, NULL, NULL, 0) != 0) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800752 // Futex failed, check it is an expected error.
753 // EAGAIN == EWOULDBLK, so we let the caller try again.
754 // EINTR implies a signal was sent to this thread.
755 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700756 PLOG(FATAL) << "futex wait failed for " << name_;
757 }
758 }
759 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800760 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700761 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800762 // We awoke and so no longer require awakes from the guard_'s unlock.
Ian Rogers3e5cf302014-05-20 16:40:37 -0700763 CHECK_GE(guard_.num_contenders_.LoadRelaxed(), 0);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800764 guard_.num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700765#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700766 uint64_t old_owner = guard_.exclusive_owner_;
767 guard_.exclusive_owner_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700768 guard_.recursion_count_ = 0;
769 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
Ian Rogersc5f17732014-06-05 20:48:42 -0700770 guard_.exclusive_owner_ = old_owner;
Ian Rogersc604d732012-10-14 16:09:54 -0700771#endif
772 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700773}
774
Ian Rogersc604d732012-10-14 16:09:54 -0700775void ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
776 DCHECK(self == NULL || self == Thread::Current());
777 guard_.AssertExclusiveHeld(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700778 guard_.CheckSafeToWait(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700779 unsigned int old_recursion_count = guard_.recursion_count_;
780#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700781 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800782 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700783 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800784 // Ensure the Mutex is contended so that requeued threads are awoken.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800785 guard_.num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -0700786 guard_.recursion_count_ = 1;
Ian Rogers3e5cf302014-05-20 16:40:37 -0700787 int32_t cur_sequence = sequence_.LoadRelaxed();
Ian Rogersc604d732012-10-14 16:09:54 -0700788 guard_.ExclusiveUnlock(self);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800789 if (futex(sequence_.Address(), FUTEX_WAIT, cur_sequence, &rel_ts, NULL, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700790 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800791 // Timed out we're done.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700792 } else if ((errno == EAGAIN) || (errno == EINTR)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800793 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700794 } else {
795 PLOG(FATAL) << "timed futex wait failed for " << name_;
796 }
797 }
798 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800799 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700800 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800801 // We awoke and so no longer require awakes from the guard_'s unlock.
Ian Rogers3e5cf302014-05-20 16:40:37 -0700802 CHECK_GE(guard_.num_contenders_.LoadRelaxed(), 0);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800803 guard_.num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700804#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000805#if !defined(__APPLE__)
Ian Rogersc604d732012-10-14 16:09:54 -0700806 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700807#else
Ian Rogersc604d732012-10-14 16:09:54 -0700808 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700809#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700810 uint64_t old_owner = guard_.exclusive_owner_;
811 guard_.exclusive_owner_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700812 guard_.recursion_count_ = 0;
813 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700814 InitTimeSpec(true, clock, ms, ns, &ts);
Narayan Kamath51b71022014-03-04 11:57:09 +0000815 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &guard_.mutex_, &ts));
Elliott Hughes5f791332011-09-15 17:45:30 -0700816 if (rc != 0 && rc != ETIMEDOUT) {
817 errno = rc;
818 PLOG(FATAL) << "TimedWait failed for " << name_;
819 }
Ian Rogersc5f17732014-06-05 20:48:42 -0700820 guard_.exclusive_owner_ = old_owner;
Ian Rogersc604d732012-10-14 16:09:54 -0700821#endif
822 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700823}
824
Ian Rogers719d1a32014-03-06 12:13:39 -0800825void Locks::Init() {
826 if (logging_lock_ != nullptr) {
827 // Already initialized.
Nicolas Geoffray7f0a6d62014-05-26 14:01:46 +0100828 if (kRuntimeISA == kX86 || kRuntimeISA == kX86_64) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700829 DCHECK(modify_ldt_lock_ != nullptr);
830 } else {
831 DCHECK(modify_ldt_lock_ == nullptr);
832 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800833 DCHECK(abort_lock_ != nullptr);
Chao-ying Fu9e369312014-05-21 11:20:52 -0700834 DCHECK(allocated_thread_ids_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -0800835 DCHECK(breakpoint_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -0800836 DCHECK(classlinker_classes_lock_ != nullptr);
837 DCHECK(heap_bitmap_lock_ != nullptr);
838 DCHECK(logging_lock_ != nullptr);
839 DCHECK(mutator_lock_ != nullptr);
840 DCHECK(thread_list_lock_ != nullptr);
841 DCHECK(thread_suspend_count_lock_ != nullptr);
842 DCHECK(trace_lock_ != nullptr);
843 DCHECK(profiler_lock_ != nullptr);
844 DCHECK(unexpected_signal_lock_ != nullptr);
845 DCHECK(intern_table_lock_ != nullptr);
846 } else {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700847 // Create global locks in level order from highest lock level to lowest.
848 LockLevel current_lock_level = kMutatorLock;
849 DCHECK(mutator_lock_ == nullptr);
850 mutator_lock_ = new ReaderWriterMutex("mutator lock", current_lock_level);
Ian Rogers719d1a32014-03-06 12:13:39 -0800851
Chao-ying Fu9e369312014-05-21 11:20:52 -0700852 #define UPDATE_CURRENT_LOCK_LEVEL(new_level) \
853 DCHECK_LT(new_level, current_lock_level); \
854 current_lock_level = new_level;
855
856 UPDATE_CURRENT_LOCK_LEVEL(kHeapBitmapLock);
857 DCHECK(heap_bitmap_lock_ == nullptr);
858 heap_bitmap_lock_ = new ReaderWriterMutex("heap bitmap lock", current_lock_level);
859
860 UPDATE_CURRENT_LOCK_LEVEL(kRuntimeShutdownLock);
861 DCHECK(runtime_shutdown_lock_ == nullptr);
862 runtime_shutdown_lock_ = new Mutex("runtime shutdown lock", current_lock_level);
863
864 UPDATE_CURRENT_LOCK_LEVEL(kProfilerLock);
865 DCHECK(profiler_lock_ == nullptr);
866 profiler_lock_ = new Mutex("profiler lock", current_lock_level);
867
868 UPDATE_CURRENT_LOCK_LEVEL(kTraceLock);
869 DCHECK(trace_lock_ == nullptr);
870 trace_lock_ = new Mutex("trace lock", current_lock_level);
871
872 UPDATE_CURRENT_LOCK_LEVEL(kThreadListLock);
873 DCHECK(thread_list_lock_ == nullptr);
874 thread_list_lock_ = new Mutex("thread list lock", current_lock_level);
875
876 UPDATE_CURRENT_LOCK_LEVEL(kBreakpointLock);
Ian Rogers719d1a32014-03-06 12:13:39 -0800877 DCHECK(breakpoint_lock_ == nullptr);
Chao-ying Fu9e369312014-05-21 11:20:52 -0700878 breakpoint_lock_ = new Mutex("breakpoint lock", current_lock_level);
879
880 UPDATE_CURRENT_LOCK_LEVEL(kClassLinkerClassesLock);
Ian Rogers719d1a32014-03-06 12:13:39 -0800881 DCHECK(classlinker_classes_lock_ == nullptr);
882 classlinker_classes_lock_ = new ReaderWriterMutex("ClassLinker classes lock",
Chao-ying Fu9e369312014-05-21 11:20:52 -0700883 current_lock_level);
884
885 UPDATE_CURRENT_LOCK_LEVEL(kAllocatedThreadIdsLock);
886 DCHECK(allocated_thread_ids_lock_ == nullptr);
887 allocated_thread_ids_lock_ = new Mutex("allocated thread ids lock", current_lock_level);
888
Nicolas Geoffray7f0a6d62014-05-26 14:01:46 +0100889 if (kRuntimeISA == kX86 || kRuntimeISA == kX86_64) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700890 UPDATE_CURRENT_LOCK_LEVEL(kModifyLdtLock);
891 DCHECK(modify_ldt_lock_ == nullptr);
892 modify_ldt_lock_ = new Mutex("modify_ldt lock", current_lock_level);
893 }
894
895 UPDATE_CURRENT_LOCK_LEVEL(kInternTableLock);
Ian Rogers719d1a32014-03-06 12:13:39 -0800896 DCHECK(intern_table_lock_ == nullptr);
Chao-ying Fu9e369312014-05-21 11:20:52 -0700897 intern_table_lock_ = new Mutex("InternTable lock", current_lock_level);
898
899
900 UPDATE_CURRENT_LOCK_LEVEL(kAbortLock);
901 DCHECK(abort_lock_ == nullptr);
902 abort_lock_ = new Mutex("abort lock", current_lock_level, true);
903
904 UPDATE_CURRENT_LOCK_LEVEL(kThreadSuspendCountLock);
905 DCHECK(thread_suspend_count_lock_ == nullptr);
906 thread_suspend_count_lock_ = new Mutex("thread suspend count lock", current_lock_level);
907
908 UPDATE_CURRENT_LOCK_LEVEL(kUnexpectedSignalLock);
909 DCHECK(unexpected_signal_lock_ == nullptr);
910 unexpected_signal_lock_ = new Mutex("unexpected signal lock", current_lock_level, true);
911
Hiroshi Yamauchi3eed93d2014-06-04 11:43:59 -0700912 UPDATE_CURRENT_LOCK_LEVEL(kMemMapsLock);
913 DCHECK(mem_maps_lock_ == nullptr);
914 mem_maps_lock_ = new Mutex("mem maps lock", current_lock_level);
915
Chao-ying Fu9e369312014-05-21 11:20:52 -0700916 UPDATE_CURRENT_LOCK_LEVEL(kLoggingLock);
917 DCHECK(logging_lock_ == nullptr);
918 logging_lock_ = new Mutex("logging lock", current_lock_level, true);
919
920 #undef UPDATE_CURRENT_LOCK_LEVEL
Ian Rogers719d1a32014-03-06 12:13:39 -0800921 }
922}
923
924
Elliott Hughese62934d2012-04-09 11:24:29 -0700925} // namespace art