blob: b0394a52550d3f665769dc30be457bad079f4bf6 [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
Andreas Gampe46ee31b2016-12-14 10:11:49 -080022#include "android-base/stringprintf.h"
23
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070024#include "atomic.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080025#include "base/logging.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010026#include "base/time_utils.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080027#include "base/systrace.h"
Ian Rogerscf7f1912014-10-22 22:06:39 -070028#include "base/value_object.h"
Ian Rogers693ff612013-02-01 10:56:12 -080029#include "mutex-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070030#include "scoped_thread_state_change-inl.h"
Ian Rogers04d7aa92013-03-16 14:29:17 -070031#include "thread-inl.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070032
33namespace art {
34
Andreas Gampe46ee31b2016-12-14 10:11:49 -080035using android::base::StringPrintf;
36
David Sehrf42eb2c2016-10-19 13:20:45 -070037static Atomic<Locks::ClientCallback*> safe_to_call_abort_callback(nullptr);
38
Ian Rogers719d1a32014-03-06 12:13:39 -080039Mutex* Locks::abort_lock_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -070040Mutex* Locks::alloc_tracker_lock_ = nullptr;
Andreas Gampe74240812014-04-17 10:35:09 -070041Mutex* Locks::allocated_monitor_ids_lock_ = nullptr;
Chao-ying Fu9e369312014-05-21 11:20:52 -070042Mutex* Locks::allocated_thread_ids_lock_ = nullptr;
Sebastien Hertzed2be172014-08-19 15:33:43 +020043ReaderWriterMutex* Locks::breakpoint_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080044ReaderWriterMutex* Locks::classlinker_classes_lock_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -070045Mutex* Locks::deoptimization_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080046ReaderWriterMutex* Locks::heap_bitmap_lock_ = nullptr;
Mathieu Chartier9ef78b52014-09-25 17:03:12 -070047Mutex* Locks::instrument_entrypoints_lock_ = nullptr;
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -070048Mutex* Locks::intern_table_lock_ = nullptr;
Andreas Gampec8089542017-01-16 12:41:12 -080049Mutex* Locks::jni_function_table_lock_ = nullptr;
Ian Rogers68d8b422014-07-17 11:09:10 -070050Mutex* Locks::jni_libraries_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080051Mutex* Locks::logging_lock_ = nullptr;
Chao-ying Fu9e369312014-05-21 11:20:52 -070052Mutex* Locks::modify_ldt_lock_ = nullptr;
Yu Lieac44242015-06-29 10:50:03 +080053MutatorMutex* Locks::mutator_lock_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -070054Mutex* Locks::profiler_lock_ = nullptr;
Nicolas Geoffray340dafa2016-11-18 16:03:10 +000055ReaderWriterMutex* Locks::verifier_deps_lock_ = nullptr;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070056ReaderWriterMutex* Locks::oat_file_manager_lock_ = nullptr;
Richard Uhlera206c742016-05-24 15:04:22 -070057Mutex* Locks::host_dlopen_handles_lock_ = nullptr;
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -070058Mutex* Locks::reference_processor_lock_ = nullptr;
59Mutex* Locks::reference_queue_cleared_references_lock_ = nullptr;
60Mutex* Locks::reference_queue_finalizer_references_lock_ = nullptr;
61Mutex* Locks::reference_queue_phantom_references_lock_ = nullptr;
62Mutex* Locks::reference_queue_soft_references_lock_ = nullptr;
63Mutex* Locks::reference_queue_weak_references_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080064Mutex* Locks::runtime_shutdown_lock_ = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -070065Mutex* Locks::cha_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080066Mutex* Locks::thread_list_lock_ = nullptr;
Mathieu Chartier91e56692015-03-03 13:51:04 -080067ConditionVariable* Locks::thread_exit_cond_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080068Mutex* Locks::thread_suspend_count_lock_ = nullptr;
69Mutex* Locks::trace_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080070Mutex* Locks::unexpected_signal_lock_ = nullptr;
Andreas Gampe5bdb6552015-07-22 23:44:55 -070071Uninterruptible Roles::uninterruptible_;
Andreas Gampe05a364c2016-10-14 13:27:12 -070072ReaderWriterMutex* Locks::jni_globals_lock_ = nullptr;
73Mutex* Locks::jni_weak_globals_lock_ = nullptr;
Andreas Gampecc1b5352016-12-01 16:58:38 -080074ReaderWriterMutex* Locks::dex_lock_ = nullptr;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -080075std::vector<BaseMutex*> Locks::expected_mutexes_on_weak_ref_access_;
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -080076Atomic<const BaseMutex*> Locks::expected_mutexes_on_weak_ref_access_guard_;
Ian Rogers719d1a32014-03-06 12:13:39 -080077
78struct AllMutexData {
79 // A guard for all_mutexes_ that's not a mutex (Mutexes must CAS to acquire and busy wait).
80 Atomic<const BaseMutex*> all_mutexes_guard;
81 // All created mutexes guarded by all_mutexes_guard_.
82 std::set<BaseMutex*>* all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -070083 AllMutexData() : all_mutexes(nullptr) {}
Ian Rogers719d1a32014-03-06 12:13:39 -080084};
85static struct AllMutexData gAllMutexData[kAllMutexDataSize];
86
Ian Rogersc604d732012-10-14 16:09:54 -070087#if ART_USE_FUTEXES
88static bool ComputeRelativeTimeSpec(timespec* result_ts, const timespec& lhs, const timespec& rhs) {
Brian Carlstromfb6996f2013-07-18 18:21:14 -070089 const int32_t one_sec = 1000 * 1000 * 1000; // one second in nanoseconds.
Ian Rogersc604d732012-10-14 16:09:54 -070090 result_ts->tv_sec = lhs.tv_sec - rhs.tv_sec;
91 result_ts->tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
92 if (result_ts->tv_nsec < 0) {
93 result_ts->tv_sec--;
94 result_ts->tv_nsec += one_sec;
95 } else if (result_ts->tv_nsec > one_sec) {
96 result_ts->tv_sec++;
97 result_ts->tv_nsec -= one_sec;
98 }
99 return result_ts->tv_sec < 0;
100}
101#endif
102
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700103class ScopedAllMutexesLock FINAL {
Ian Rogers56edc432013-01-18 16:51:51 -0800104 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700105 explicit ScopedAllMutexesLock(const BaseMutex* mutex) : mutex_(mutex) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700106 while (!gAllMutexData->all_mutexes_guard.CompareExchangeWeakAcquire(0, mutex)) {
Ian Rogers56edc432013-01-18 16:51:51 -0800107 NanoSleep(100);
108 }
109 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700110
Ian Rogers56edc432013-01-18 16:51:51 -0800111 ~ScopedAllMutexesLock() {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700112 while (!gAllMutexData->all_mutexes_guard.CompareExchangeWeakRelease(mutex_, 0)) {
Ian Rogers56edc432013-01-18 16:51:51 -0800113 NanoSleep(100);
114 }
115 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700116
Ian Rogers56edc432013-01-18 16:51:51 -0800117 private:
118 const BaseMutex* const mutex_;
119};
Ian Rogers56edc432013-01-18 16:51:51 -0800120
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -0800121class Locks::ScopedExpectedMutexesOnWeakRefAccessLock FINAL {
122 public:
123 explicit ScopedExpectedMutexesOnWeakRefAccessLock(const BaseMutex* mutex) : mutex_(mutex) {
124 while (!Locks::expected_mutexes_on_weak_ref_access_guard_.CompareExchangeWeakAcquire(0,
125 mutex)) {
126 NanoSleep(100);
127 }
128 }
129
130 ~ScopedExpectedMutexesOnWeakRefAccessLock() {
131 while (!Locks::expected_mutexes_on_weak_ref_access_guard_.CompareExchangeWeakRelease(mutex_,
132 0)) {
133 NanoSleep(100);
134 }
135 }
136
137 private:
138 const BaseMutex* const mutex_;
139};
140
Ian Rogerscf7f1912014-10-22 22:06:39 -0700141// Scoped class that generates events at the beginning and end of lock contention.
142class ScopedContentionRecorder FINAL : public ValueObject {
143 public:
144 ScopedContentionRecorder(BaseMutex* mutex, uint64_t blocked_tid, uint64_t owner_tid)
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700145 : mutex_(kLogLockContentions ? mutex : nullptr),
Ian Rogerscf7f1912014-10-22 22:06:39 -0700146 blocked_tid_(kLogLockContentions ? blocked_tid : 0),
147 owner_tid_(kLogLockContentions ? owner_tid : 0),
148 start_nano_time_(kLogLockContentions ? NanoTime() : 0) {
149 if (ATRACE_ENABLED()) {
150 std::string msg = StringPrintf("Lock contention on %s (owner tid: %" PRIu64 ")",
151 mutex->GetName(), owner_tid);
152 ATRACE_BEGIN(msg.c_str());
153 }
154 }
155
156 ~ScopedContentionRecorder() {
157 ATRACE_END();
158 if (kLogLockContentions) {
159 uint64_t end_nano_time = NanoTime();
160 mutex_->RecordContention(blocked_tid_, owner_tid_, end_nano_time - start_nano_time_);
161 }
162 }
163
164 private:
165 BaseMutex* const mutex_;
166 const uint64_t blocked_tid_;
167 const uint64_t owner_tid_;
168 const uint64_t start_nano_time_;
169};
170
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800171BaseMutex::BaseMutex(const char* name, LockLevel level)
172 : level_(level),
173 name_(name),
174 should_respond_to_empty_checkpoint_request_(false) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700175 if (kLogLockContentions) {
176 ScopedAllMutexesLock mu(this);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700177 std::set<BaseMutex*>** all_mutexes_ptr = &gAllMutexData->all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700178 if (*all_mutexes_ptr == nullptr) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700179 // We leak the global set of all mutexes to avoid ordering issues in global variable
180 // construction/destruction.
181 *all_mutexes_ptr = new std::set<BaseMutex*>();
182 }
183 (*all_mutexes_ptr)->insert(this);
Ian Rogers56edc432013-01-18 16:51:51 -0800184 }
Ian Rogers56edc432013-01-18 16:51:51 -0800185}
186
187BaseMutex::~BaseMutex() {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700188 if (kLogLockContentions) {
189 ScopedAllMutexesLock mu(this);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700190 gAllMutexData->all_mutexes->erase(this);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700191 }
Ian Rogers56edc432013-01-18 16:51:51 -0800192}
193
194void BaseMutex::DumpAll(std::ostream& os) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700195 if (kLogLockContentions) {
196 os << "Mutex logging:\n";
197 ScopedAllMutexesLock mu(reinterpret_cast<const BaseMutex*>(-1));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700198 std::set<BaseMutex*>* all_mutexes = gAllMutexData->all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700199 if (all_mutexes == nullptr) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700200 // No mutexes have been created yet during at startup.
201 return;
202 }
203 typedef std::set<BaseMutex*>::const_iterator It;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700204 os << "(Contended)\n";
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700205 for (It it = all_mutexes->begin(); it != all_mutexes->end(); ++it) {
206 BaseMutex* mutex = *it;
207 if (mutex->HasEverContended()) {
208 mutex->Dump(os);
209 os << "\n";
210 }
211 }
212 os << "(Never contented)\n";
213 for (It it = all_mutexes->begin(); it != all_mutexes->end(); ++it) {
214 BaseMutex* mutex = *it;
215 if (!mutex->HasEverContended()) {
216 mutex->Dump(os);
217 os << "\n";
218 }
219 }
Ian Rogers56edc432013-01-18 16:51:51 -0800220 }
Ian Rogers56edc432013-01-18 16:51:51 -0800221}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700222
Ian Rogers81d425b2012-09-27 16:03:43 -0700223void BaseMutex::CheckSafeToWait(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700224 if (self == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700225 CheckUnattachedThread(level_);
226 return;
227 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700228 if (kDebugLocking) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700229 CHECK(self->GetHeldMutex(level_) == this || level_ == kMonitorLock)
230 << "Waiting on unacquired mutex: " << name_;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700231 bool bad_mutexes_held = false;
Elliott Hughes0f827162013-02-26 12:12:58 -0800232 for (int i = kLockLevelCount - 1; i >= 0; --i) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700233 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700234 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Ian Rogersf3d874c2014-07-17 18:52:42 -0700235 // We expect waits to happen while holding the thread list suspend thread lock.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700236 if (held_mutex != nullptr) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800237 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
238 << "(level " << LockLevel(i) << ") while performing wait on "
239 << "\"" << name_ << "\" (level " << level_ << ")";
Ian Rogers25fd14b2012-09-05 10:56:38 -0700240 bad_mutexes_held = true;
241 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700242 }
243 }
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000244 if (gAborting == 0) { // Avoid recursive aborts.
245 CHECK(!bad_mutexes_held);
246 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700247 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700248}
249
Ian Rogers37f3c962014-07-17 11:25:30 -0700250void BaseMutex::ContentionLogData::AddToWaitTime(uint64_t value) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700251 if (kLogLockContentions) {
252 // Atomically add value to wait_time.
Ian Rogers37f3c962014-07-17 11:25:30 -0700253 wait_time.FetchAndAddSequentiallyConsistent(value);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700254 }
255}
256
Brian Carlstrom0de79852013-07-25 22:29:58 -0700257void BaseMutex::RecordContention(uint64_t blocked_tid,
258 uint64_t owner_tid,
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700259 uint64_t nano_time_blocked) {
260 if (kLogLockContentions) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700261 ContentionLogData* data = contention_log_data_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700262 ++(data->contention_count);
263 data->AddToWaitTime(nano_time_blocked);
264 ContentionLogEntry* log = data->contention_log;
265 // This code is intentionally racy as it is only used for diagnostics.
Ian Rogers3e5cf302014-05-20 16:40:37 -0700266 uint32_t slot = data->cur_content_log_entry.LoadRelaxed();
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700267 if (log[slot].blocked_tid == blocked_tid &&
268 log[slot].owner_tid == blocked_tid) {
269 ++log[slot].count;
270 } else {
271 uint32_t new_slot;
272 do {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700273 slot = data->cur_content_log_entry.LoadRelaxed();
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700274 new_slot = (slot + 1) % kContentionLogSize;
Ian Rogers3e5cf302014-05-20 16:40:37 -0700275 } while (!data->cur_content_log_entry.CompareExchangeWeakRelaxed(slot, new_slot));
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700276 log[new_slot].blocked_tid = blocked_tid;
277 log[new_slot].owner_tid = owner_tid;
Ian Rogers3e5cf302014-05-20 16:40:37 -0700278 log[new_slot].count.StoreRelaxed(1);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700279 }
Ian Rogers56edc432013-01-18 16:51:51 -0800280 }
Ian Rogers56edc432013-01-18 16:51:51 -0800281}
282
Ian Rogers56edc432013-01-18 16:51:51 -0800283void BaseMutex::DumpContention(std::ostream& os) const {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700284 if (kLogLockContentions) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700285 const ContentionLogData* data = contention_log_data_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700286 const ContentionLogEntry* log = data->contention_log;
Ian Rogers37f3c962014-07-17 11:25:30 -0700287 uint64_t wait_time = data->wait_time.LoadRelaxed();
Ian Rogers3e5cf302014-05-20 16:40:37 -0700288 uint32_t contention_count = data->contention_count.LoadRelaxed();
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700289 if (contention_count == 0) {
290 os << "never contended";
291 } else {
292 os << "contended " << contention_count
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700293 << " total wait of contender " << PrettyDuration(wait_time)
294 << " average " << PrettyDuration(wait_time / contention_count);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700295 SafeMap<uint64_t, size_t> most_common_blocker;
296 SafeMap<uint64_t, size_t> most_common_blocked;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700297 for (size_t i = 0; i < kContentionLogSize; ++i) {
298 uint64_t blocked_tid = log[i].blocked_tid;
299 uint64_t owner_tid = log[i].owner_tid;
Ian Rogers3e5cf302014-05-20 16:40:37 -0700300 uint32_t count = log[i].count.LoadRelaxed();
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700301 if (count > 0) {
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700302 auto it = most_common_blocked.find(blocked_tid);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700303 if (it != most_common_blocked.end()) {
304 most_common_blocked.Overwrite(blocked_tid, it->second + count);
305 } else {
306 most_common_blocked.Put(blocked_tid, count);
307 }
308 it = most_common_blocker.find(owner_tid);
309 if (it != most_common_blocker.end()) {
310 most_common_blocker.Overwrite(owner_tid, it->second + count);
311 } else {
312 most_common_blocker.Put(owner_tid, count);
313 }
Ian Rogers56edc432013-01-18 16:51:51 -0800314 }
315 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700316 uint64_t max_tid = 0;
317 size_t max_tid_count = 0;
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700318 for (const auto& pair : most_common_blocked) {
319 if (pair.second > max_tid_count) {
320 max_tid = pair.first;
321 max_tid_count = pair.second;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700322 }
Ian Rogers56edc432013-01-18 16:51:51 -0800323 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700324 if (max_tid != 0) {
325 os << " sample shows most blocked tid=" << max_tid;
Ian Rogers56edc432013-01-18 16:51:51 -0800326 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700327 max_tid = 0;
328 max_tid_count = 0;
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700329 for (const auto& pair : most_common_blocker) {
330 if (pair.second > max_tid_count) {
331 max_tid = pair.first;
332 max_tid_count = pair.second;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700333 }
334 }
335 if (max_tid != 0) {
336 os << " sample shows tid=" << max_tid << " owning during this time";
337 }
Ian Rogers56edc432013-01-18 16:51:51 -0800338 }
339 }
Ian Rogers56edc432013-01-18 16:51:51 -0800340}
341
342
Ian Rogers81d425b2012-09-27 16:03:43 -0700343Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700344 : BaseMutex(name, level), recursive_(recursive), recursion_count_(0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700345#if ART_USE_FUTEXES
Ian Rogersc7190692014-07-08 23:50:26 -0700346 DCHECK_EQ(0, state_.LoadRelaxed());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700347 DCHECK_EQ(0, num_contenders_.LoadRelaxed());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700348#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700349 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, nullptr));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700350#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700351 exclusive_owner_ = 0;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700352}
353
David Sehrf42eb2c2016-10-19 13:20:45 -0700354// Helper to allow checking shutdown while locking for thread safety.
355static bool IsSafeToCallAbortSafe() {
356 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
357 return Locks::IsSafeToCallAbortRacy();
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800358}
359
Elliott Hughes8daa0922011-09-11 13:46:25 -0700360Mutex::~Mutex() {
David Sehrf42eb2c2016-10-19 13:20:45 -0700361 bool safe_to_call_abort = Locks::IsSafeToCallAbortRacy();
Ian Rogersc604d732012-10-14 16:09:54 -0700362#if ART_USE_FUTEXES
Ian Rogersc7190692014-07-08 23:50:26 -0700363 if (state_.LoadRelaxed() != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700364 LOG(safe_to_call_abort ? FATAL : WARNING)
365 << "destroying mutex with owner: " << exclusive_owner_;
Ian Rogersc604d732012-10-14 16:09:54 -0700366 } else {
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800367 if (exclusive_owner_ != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700368 LOG(safe_to_call_abort ? FATAL : WARNING)
369 << "unexpectedly found an owner on unlocked mutex " << name_;
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800370 }
371 if (num_contenders_.LoadSequentiallyConsistent() != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700372 LOG(safe_to_call_abort ? FATAL : WARNING)
373 << "unexpectedly found a contender on mutex " << name_;
Mathieu Chartiercef50f02014-12-09 17:38:52 -0800374 }
Ian Rogersc604d732012-10-14 16:09:54 -0700375 }
376#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700377 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
378 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800379 int rc = pthread_mutex_destroy(&mutex_);
380 if (rc != 0) {
381 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700382 PLOG(safe_to_call_abort ? FATAL : WARNING)
383 << "pthread_mutex_destroy failed for " << name_;
Elliott Hughes6b355752012-01-13 16:49:08 -0800384 }
Ian Rogersc604d732012-10-14 16:09:54 -0700385#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700386}
387
Ian Rogers81d425b2012-09-27 16:03:43 -0700388void Mutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700389 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700390 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700391 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700392 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700393 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700394#if ART_USE_FUTEXES
395 bool done = false;
396 do {
Ian Rogersc7190692014-07-08 23:50:26 -0700397 int32_t cur_state = state_.LoadRelaxed();
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700398 if (LIKELY(cur_state == 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700399 // Change state from 0 to 1 and impose load/store ordering appropriate for lock acquisition.
400 done = state_.CompareExchangeWeakAcquire(0 /* cur_state */, 1 /* new state */);
Ian Rogersc604d732012-10-14 16:09:54 -0700401 } else {
402 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700403 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersb122a4b2013-11-19 18:00:50 -0800404 num_contenders_++;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800405 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
406 self->CheckEmptyCheckpointFromMutex();
407 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700408 if (futex(state_.Address(), FUTEX_WAIT, 1, nullptr, nullptr, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700409 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
410 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
411 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700412 PLOG(FATAL) << "futex wait failed for " << name_;
413 }
414 }
Ian Rogersb122a4b2013-11-19 18:00:50 -0800415 num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700416 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700417 } while (!done);
Ian Rogersc7190692014-07-08 23:50:26 -0700418 DCHECK_EQ(state_.LoadRelaxed(), 1);
Ian Rogersc604d732012-10-14 16:09:54 -0700419#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700420 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700421#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700422 DCHECK_EQ(exclusive_owner_, 0U);
423 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700424 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700425 }
426 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700427 if (kDebugLocking) {
428 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
429 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700430 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700431 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700432}
433
Ian Rogers81d425b2012-09-27 16:03:43 -0700434bool Mutex::ExclusiveTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700435 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700436 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700437 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700438 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700439 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700440#if ART_USE_FUTEXES
441 bool done = false;
442 do {
Ian Rogersc7190692014-07-08 23:50:26 -0700443 int32_t cur_state = state_.LoadRelaxed();
Ian Rogersc604d732012-10-14 16:09:54 -0700444 if (cur_state == 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700445 // Change state from 0 to 1 and impose load/store ordering appropriate for lock acquisition.
446 done = state_.CompareExchangeWeakAcquire(0 /* cur_state */, 1 /* new state */);
Ian Rogersc604d732012-10-14 16:09:54 -0700447 } else {
448 return false;
449 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700450 } while (!done);
Ian Rogersc7190692014-07-08 23:50:26 -0700451 DCHECK_EQ(state_.LoadRelaxed(), 1);
Ian Rogersc604d732012-10-14 16:09:54 -0700452#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700453 int result = pthread_mutex_trylock(&mutex_);
454 if (result == EBUSY) {
455 return false;
456 }
457 if (result != 0) {
458 errno = result;
459 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
460 }
Ian Rogersc604d732012-10-14 16:09:54 -0700461#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700462 DCHECK_EQ(exclusive_owner_, 0U);
463 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700464 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700465 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700466 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700467 if (kDebugLocking) {
468 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
469 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700470 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700471 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700472 return true;
473}
474
Ian Rogers81d425b2012-09-27 16:03:43 -0700475void Mutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartiereb0a1792014-12-15 17:23:45 -0800476 if (kIsDebugBuild && self != nullptr && self != Thread::Current()) {
477 std::string name1 = "<null>";
478 std::string name2 = "<null>";
479 if (self != nullptr) {
480 self->GetThreadName(name1);
481 }
482 if (Thread::Current() != nullptr) {
483 Thread::Current()->GetThreadName(name2);
484 }
Mathieu Chartier4c101102015-01-27 17:14:16 -0800485 LOG(FATAL) << GetName() << " level=" << level_ << " self=" << name1
486 << " Thread::Current()=" << name2;
Mathieu Chartiereb0a1792014-12-15 17:23:45 -0800487 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700488 AssertHeld(self);
Ian Rogersc5f17732014-06-05 20:48:42 -0700489 DCHECK_NE(exclusive_owner_, 0U);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700490 recursion_count_--;
491 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700492 if (kDebugLocking) {
493 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
494 << name_ << " " << recursion_count_;
495 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700496 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700497#if ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700498 bool done = false;
499 do {
Ian Rogersc7190692014-07-08 23:50:26 -0700500 int32_t cur_state = state_.LoadRelaxed();
Ian Rogersc5f17732014-06-05 20:48:42 -0700501 if (LIKELY(cur_state == 1)) {
Ian Rogersc5f17732014-06-05 20:48:42 -0700502 // We're no longer the owner.
503 exclusive_owner_ = 0;
Ian Rogersc7190692014-07-08 23:50:26 -0700504 // Change state to 0 and impose load/store ordering appropriate for lock release.
505 // Note, the relaxed loads below musn't reorder before the CompareExchange.
506 // TODO: the ordering here is non-trivial as state is split across 3 fields, fix by placing
507 // a status bit into the state on contention.
508 done = state_.CompareExchangeWeakSequentiallyConsistent(cur_state, 0 /* new state */);
Ian Rogersc5f17732014-06-05 20:48:42 -0700509 if (LIKELY(done)) { // Spurious fail?
Ian Rogersc7190692014-07-08 23:50:26 -0700510 // Wake a contender.
Ian Rogersc5f17732014-06-05 20:48:42 -0700511 if (UNLIKELY(num_contenders_.LoadRelaxed() > 0)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700512 futex(state_.Address(), FUTEX_WAKE, 1, nullptr, nullptr, 0);
Ian Rogersc5f17732014-06-05 20:48:42 -0700513 }
514 }
515 } else {
516 // Logging acquires the logging lock, avoid infinite recursion in that case.
517 if (this != Locks::logging_lock_) {
518 LOG(FATAL) << "Unexpected state_ in unlock " << cur_state << " for " << name_;
519 } else {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700520 LogHelper::LogLineLowStack(__FILE__,
521 __LINE__,
522 ::android::base::FATAL_WITHOUT_ABORT,
523 StringPrintf("Unexpected state_ %d in unlock for %s",
524 cur_state, name_).c_str());
Ian Rogersc5f17732014-06-05 20:48:42 -0700525 _exit(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700526 }
527 }
Ian Rogersc5f17732014-06-05 20:48:42 -0700528 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700529#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700530 exclusive_owner_ = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700531 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700532#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700533 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700534}
535
Ian Rogers56edc432013-01-18 16:51:51 -0800536void Mutex::Dump(std::ostream& os) const {
537 os << (recursive_ ? "recursive " : "non-recursive ")
538 << name_
539 << " level=" << static_cast<int>(level_)
540 << " rec=" << recursion_count_
541 << " owner=" << GetExclusiveOwnerTid() << " ";
542 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700543}
544
545std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800546 mu.Dump(os);
547 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700548}
549
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800550void Mutex::WakeupToRespondToEmptyCheckpoint() {
551#if ART_USE_FUTEXES
552 // Wake up all the waiters so they will respond to the emtpy checkpoint.
553 DCHECK(should_respond_to_empty_checkpoint_request_);
554 if (UNLIKELY(num_contenders_.LoadRelaxed() > 0)) {
555 futex(state_.Address(), FUTEX_WAKE, -1, nullptr, nullptr, 0);
556 }
557#else
558 LOG(FATAL) << "Non futex case isn't supported.";
559#endif
560}
561
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700562ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level)
563 : BaseMutex(name, level)
Ian Rogers81d425b2012-09-27 16:03:43 -0700564#if ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700565 , state_(0), num_pending_readers_(0), num_pending_writers_(0)
Ian Rogers81d425b2012-09-27 16:03:43 -0700566#endif
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700567{ // NOLINT(whitespace/braces)
Ian Rogers81d425b2012-09-27 16:03:43 -0700568#if !ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700569 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, nullptr));
Ian Rogers81d425b2012-09-27 16:03:43 -0700570#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700571 exclusive_owner_ = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700572}
573
574ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700575#if ART_USE_FUTEXES
Ian Rogersc7190692014-07-08 23:50:26 -0700576 CHECK_EQ(state_.LoadRelaxed(), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700577 CHECK_EQ(exclusive_owner_, 0U);
Ian Rogersc7190692014-07-08 23:50:26 -0700578 CHECK_EQ(num_pending_readers_.LoadRelaxed(), 0);
Ian Rogers3e5cf302014-05-20 16:40:37 -0700579 CHECK_EQ(num_pending_writers_.LoadRelaxed(), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700580#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700581 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
582 // may still be using locks.
583 int rc = pthread_rwlock_destroy(&rwlock_);
584 if (rc != 0) {
585 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700586 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
587 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800588 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700589#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700590}
591
Ian Rogers81d425b2012-09-27 16:03:43 -0700592void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700593 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700594 AssertNotExclusiveHeld(self);
595#if ART_USE_FUTEXES
596 bool done = false;
597 do {
Ian Rogersc7190692014-07-08 23:50:26 -0700598 int32_t cur_state = state_.LoadRelaxed();
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700599 if (LIKELY(cur_state == 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700600 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
601 done = state_.CompareExchangeWeakAcquire(0 /* cur_state*/, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700602 } else {
603 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700604 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersc7190692014-07-08 23:50:26 -0700605 ++num_pending_writers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800606 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
607 self->CheckEmptyCheckpointFromMutex();
608 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700609 if (futex(state_.Address(), FUTEX_WAIT, cur_state, nullptr, nullptr, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700610 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
611 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
612 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700613 PLOG(FATAL) << "futex wait failed for " << name_;
614 }
615 }
Ian Rogersc7190692014-07-08 23:50:26 -0700616 --num_pending_writers_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700617 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700618 } while (!done);
Ian Rogersc7190692014-07-08 23:50:26 -0700619 DCHECK_EQ(state_.LoadRelaxed(), -1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700620#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700621 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700622#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700623 DCHECK_EQ(exclusive_owner_, 0U);
624 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700625 RegisterAsLocked(self);
626 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700627}
628
Ian Rogers81d425b2012-09-27 16:03:43 -0700629void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700630 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700631 AssertExclusiveHeld(self);
632 RegisterAsUnlocked(self);
Ian Rogersc5f17732014-06-05 20:48:42 -0700633 DCHECK_NE(exclusive_owner_, 0U);
Ian Rogers81d425b2012-09-27 16:03:43 -0700634#if ART_USE_FUTEXES
635 bool done = false;
636 do {
Ian Rogersc7190692014-07-08 23:50:26 -0700637 int32_t cur_state = state_.LoadRelaxed();
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700638 if (LIKELY(cur_state == -1)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700639 // We're no longer the owner.
640 exclusive_owner_ = 0;
Ian Rogersc7190692014-07-08 23:50:26 -0700641 // Change state from -1 to 0 and impose load/store ordering appropriate for lock release.
642 // Note, the relaxed loads below musn't reorder before the CompareExchange.
643 // TODO: the ordering here is non-trivial as state is split across 3 fields, fix by placing
644 // a status bit into the state on contention.
645 done = state_.CompareExchangeWeakSequentiallyConsistent(-1 /* cur_state*/, 0 /* new state */);
646 if (LIKELY(done)) { // Weak CAS may fail spuriously.
Ian Rogers81d425b2012-09-27 16:03:43 -0700647 // Wake any waiters.
Ian Rogersc7190692014-07-08 23:50:26 -0700648 if (UNLIKELY(num_pending_readers_.LoadRelaxed() > 0 ||
649 num_pending_writers_.LoadRelaxed() > 0)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700650 futex(state_.Address(), FUTEX_WAKE, -1, nullptr, nullptr, 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700651 }
652 }
653 } else {
654 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
655 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700656 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700657#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700658 exclusive_owner_ = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700659 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700660#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700661}
662
Ian Rogers66aee5c2012-08-15 17:17:47 -0700663#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700664bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700665 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700666#if ART_USE_FUTEXES
667 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700668 timespec end_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800669 InitTimeSpec(true, CLOCK_MONOTONIC, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700670 do {
Ian Rogersc7190692014-07-08 23:50:26 -0700671 int32_t cur_state = state_.LoadRelaxed();
Ian Rogers81d425b2012-09-27 16:03:43 -0700672 if (cur_state == 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700673 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
674 done = state_.CompareExchangeWeakAcquire(0 /* cur_state */, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700675 } else {
676 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700677 timespec now_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800678 InitTimeSpec(true, CLOCK_MONOTONIC, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700679 timespec rel_ts;
680 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
681 return false; // Timed out.
682 }
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700683 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersc7190692014-07-08 23:50:26 -0700684 ++num_pending_writers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800685 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
686 self->CheckEmptyCheckpointFromMutex();
687 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700688 if (futex(state_.Address(), FUTEX_WAIT, cur_state, &rel_ts, nullptr, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700689 if (errno == ETIMEDOUT) {
Ian Rogersc7190692014-07-08 23:50:26 -0700690 --num_pending_writers_;
Ian Rogersc604d732012-10-14 16:09:54 -0700691 return false; // Timed out.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700692 } else if ((errno != EAGAIN) && (errno != EINTR)) {
693 // EAGAIN and EINTR both indicate a spurious failure,
694 // recompute the relative time out from now and try again.
695 // We don't use TEMP_FAILURE_RETRY so we can recompute rel_ts;
Ian Rogers81d425b2012-09-27 16:03:43 -0700696 PLOG(FATAL) << "timed futex wait failed for " << name_;
697 }
698 }
Ian Rogersc7190692014-07-08 23:50:26 -0700699 --num_pending_writers_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700700 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700701 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700702#else
Ian Rogersc604d732012-10-14 16:09:54 -0700703 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700704 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700705 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700706 if (result == ETIMEDOUT) {
707 return false;
708 }
709 if (result != 0) {
710 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700711 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700712 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700713#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700714 exclusive_owner_ = SafeGetTid(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700715 RegisterAsLocked(self);
716 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700717 return true;
718}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700719#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700720
Ian Rogers51d212e2014-10-23 17:48:20 -0700721#if ART_USE_FUTEXES
Ian Rogerscf7f1912014-10-22 22:06:39 -0700722void ReaderWriterMutex::HandleSharedLockContention(Thread* self, int32_t cur_state) {
723 // Owner holds it exclusively, hang up.
724 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
725 ++num_pending_readers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800726 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
727 self->CheckEmptyCheckpointFromMutex();
728 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700729 if (futex(state_.Address(), FUTEX_WAIT, cur_state, nullptr, nullptr, 0) != 0) {
Daniel Colascione6f4d1022016-11-21 14:35:42 -0800730 if (errno != EAGAIN && errno != EINTR) {
Ian Rogerscf7f1912014-10-22 22:06:39 -0700731 PLOG(FATAL) << "futex wait failed for " << name_;
732 }
733 }
734 --num_pending_readers_;
735}
Ian Rogers51d212e2014-10-23 17:48:20 -0700736#endif
Ian Rogerscf7f1912014-10-22 22:06:39 -0700737
Ian Rogers81d425b2012-09-27 16:03:43 -0700738bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700739 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700740#if ART_USE_FUTEXES
741 bool done = false;
742 do {
Ian Rogersc7190692014-07-08 23:50:26 -0700743 int32_t cur_state = state_.LoadRelaxed();
Ian Rogers81d425b2012-09-27 16:03:43 -0700744 if (cur_state >= 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700745 // Add as an extra reader and impose load/store ordering appropriate for lock acquisition.
746 done = state_.CompareExchangeWeakAcquire(cur_state, cur_state + 1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700747 } else {
748 // Owner holds it exclusively.
749 return false;
750 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700751 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700752#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700753 int result = pthread_rwlock_tryrdlock(&rwlock_);
754 if (result == EBUSY) {
755 return false;
756 }
757 if (result != 0) {
758 errno = result;
759 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
760 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700761#endif
762 RegisterAsLocked(self);
763 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700764 return true;
765}
766
Ian Rogers81d425b2012-09-27 16:03:43 -0700767bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700768 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700769 bool result;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700770 if (UNLIKELY(self == nullptr)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700771 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700772 } else {
773 result = (self->GetHeldMutex(level_) == this);
774 }
775 return result;
776}
777
Ian Rogers56edc432013-01-18 16:51:51 -0800778void ReaderWriterMutex::Dump(std::ostream& os) const {
779 os << name_
780 << " level=" << static_cast<int>(level_)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700781 << " owner=" << GetExclusiveOwnerTid()
782#if ART_USE_FUTEXES
783 << " state=" << state_.LoadSequentiallyConsistent()
784 << " num_pending_writers=" << num_pending_writers_.LoadSequentiallyConsistent()
785 << " num_pending_readers=" << num_pending_readers_.LoadSequentiallyConsistent()
786#endif
787 << " ";
Ian Rogers56edc432013-01-18 16:51:51 -0800788 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700789}
790
791std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800792 mu.Dump(os);
793 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700794}
795
Yu Lieac44242015-06-29 10:50:03 +0800796std::ostream& operator<<(std::ostream& os, const MutatorMutex& mu) {
797 mu.Dump(os);
798 return os;
799}
800
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800801void ReaderWriterMutex::WakeupToRespondToEmptyCheckpoint() {
802#if ART_USE_FUTEXES
803 // Wake up all the waiters so they will respond to the emtpy checkpoint.
804 DCHECK(should_respond_to_empty_checkpoint_request_);
805 if (UNLIKELY(num_pending_readers_.LoadRelaxed() > 0 ||
806 num_pending_writers_.LoadRelaxed() > 0)) {
807 futex(state_.Address(), FUTEX_WAKE, -1, nullptr, nullptr, 0);
808 }
809#else
810 LOG(FATAL) << "Non futex case isn't supported.";
811#endif
812}
813
Ian Rogers23055dc2013-04-18 16:29:16 -0700814ConditionVariable::ConditionVariable(const char* name, Mutex& guard)
Ian Rogersc604d732012-10-14 16:09:54 -0700815 : name_(name), guard_(guard) {
816#if ART_USE_FUTEXES
Ian Rogers3e5cf302014-05-20 16:40:37 -0700817 DCHECK_EQ(0, sequence_.LoadRelaxed());
Ian Rogersc604d732012-10-14 16:09:54 -0700818 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700819#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000820 pthread_condattr_t cond_attrs;
Ian Rogersc5f17732014-06-05 20:48:42 -0700821 CHECK_MUTEX_CALL(pthread_condattr_init, (&cond_attrs));
Narayan Kamath51b71022014-03-04 11:57:09 +0000822#if !defined(__APPLE__)
823 // Apple doesn't have CLOCK_MONOTONIC or pthread_condattr_setclock.
Ian Rogers51d212e2014-10-23 17:48:20 -0700824 CHECK_MUTEX_CALL(pthread_condattr_setclock, (&cond_attrs, CLOCK_MONOTONIC));
Narayan Kamath51b71022014-03-04 11:57:09 +0000825#endif
826 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, &cond_attrs));
Ian Rogersc604d732012-10-14 16:09:54 -0700827#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700828}
829
830ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800831#if ART_USE_FUTEXES
832 if (num_waiters_!= 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700833 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
834 LOG(is_safe_to_call_abort ? FATAL : WARNING)
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700835 << "ConditionVariable::~ConditionVariable for " << name_
Ian Rogersd45f2012012-11-28 11:46:23 -0800836 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800837 }
838#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700839 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
840 // may still be using condition variables.
841 int rc = pthread_cond_destroy(&cond_);
842 if (rc != 0) {
843 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700844 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
845 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_cond_destroy failed for " << name_;
Elliott Hughese62934d2012-04-09 11:24:29 -0700846 }
Ian Rogersc604d732012-10-14 16:09:54 -0700847#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700848}
849
Ian Rogersc604d732012-10-14 16:09:54 -0700850void ConditionVariable::Broadcast(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700851 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700852 // TODO: enable below, there's a race in thread creation that causes false failures currently.
853 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700854 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700855#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800856 if (num_waiters_ > 0) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800857 sequence_++; // Indicate the broadcast occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700858 bool done = false;
859 do {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700860 int32_t cur_sequence = sequence_.LoadRelaxed();
Ian Rogersd45f2012012-11-28 11:46:23 -0800861 // Requeue waiters onto mutex. The waiter holds the contender count on the mutex high ensuring
862 // mutex unlocks will awaken the requeued waiter thread.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800863 done = futex(sequence_.Address(), FUTEX_CMP_REQUEUE, 0,
Ian Rogers5bd97c42012-11-27 02:38:26 -0800864 reinterpret_cast<const timespec*>(std::numeric_limits<int32_t>::max()),
Ian Rogersc7190692014-07-08 23:50:26 -0700865 guard_.state_.Address(), cur_sequence) != -1;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800866 if (!done) {
Daniel Colascione6f4d1022016-11-21 14:35:42 -0800867 if (errno != EAGAIN && errno != EINTR) {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800868 PLOG(FATAL) << "futex cmp requeue failed for " << name_;
869 }
Ian Rogers5bd97c42012-11-27 02:38:26 -0800870 }
Ian Rogersc604d732012-10-14 16:09:54 -0700871 } while (!done);
872 }
873#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700874 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700875#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700876}
877
Ian Rogersc604d732012-10-14 16:09:54 -0700878void ConditionVariable::Signal(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700879 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700880 guard_.AssertExclusiveHeld(self);
881#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800882 if (num_waiters_ > 0) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800883 sequence_++; // Indicate a signal occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700884 // Futex wake 1 waiter who will then come and in contend on mutex. It'd be nice to requeue them
885 // to avoid this, however, requeueing can only move all waiters.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700886 int num_woken = futex(sequence_.Address(), FUTEX_WAKE, 1, nullptr, nullptr, 0);
Ian Rogersd45f2012012-11-28 11:46:23 -0800887 // Check something was woken or else we changed sequence_ before they had chance to wait.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800888 CHECK((num_woken == 0) || (num_woken == 1));
Ian Rogersc604d732012-10-14 16:09:54 -0700889 }
890#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700891 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700892#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700893}
894
Ian Rogersc604d732012-10-14 16:09:54 -0700895void ConditionVariable::Wait(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700896 guard_.CheckSafeToWait(self);
897 WaitHoldingLocks(self);
898}
899
900void ConditionVariable::WaitHoldingLocks(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700901 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700902 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700903 unsigned int old_recursion_count = guard_.recursion_count_;
904#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700905 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800906 // Ensure the Mutex is contended so that requeued threads are awoken.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800907 guard_.num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -0700908 guard_.recursion_count_ = 1;
Ian Rogers3e5cf302014-05-20 16:40:37 -0700909 int32_t cur_sequence = sequence_.LoadRelaxed();
Ian Rogersc604d732012-10-14 16:09:54 -0700910 guard_.ExclusiveUnlock(self);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700911 if (futex(sequence_.Address(), FUTEX_WAIT, cur_sequence, nullptr, nullptr, 0) != 0) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800912 // Futex failed, check it is an expected error.
913 // EAGAIN == EWOULDBLK, so we let the caller try again.
914 // EINTR implies a signal was sent to this thread.
915 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700916 PLOG(FATAL) << "futex wait failed for " << name_;
917 }
918 }
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800919 if (self != nullptr) {
920 JNIEnvExt* const env = self->GetJniEnv();
921 if (UNLIKELY(env != nullptr && env->runtime_deleted)) {
922 CHECK(self->IsDaemon());
923 // If the runtime has been deleted, then we cannot proceed. Just sleep forever. This may
924 // occur for user daemon threads that get a spurious wakeup. This occurs for test 132 with
925 // --host and --gdb.
926 // After we wake up, the runtime may have been shutdown, which means that this condition may
927 // have been deleted. It is not safe to retry the wait.
928 SleepForever();
929 }
930 }
Ian Rogersc604d732012-10-14 16:09:54 -0700931 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800932 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700933 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800934 // We awoke and so no longer require awakes from the guard_'s unlock.
Ian Rogers3e5cf302014-05-20 16:40:37 -0700935 CHECK_GE(guard_.num_contenders_.LoadRelaxed(), 0);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800936 guard_.num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700937#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700938 uint64_t old_owner = guard_.exclusive_owner_;
939 guard_.exclusive_owner_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700940 guard_.recursion_count_ = 0;
941 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
Ian Rogersc5f17732014-06-05 20:48:42 -0700942 guard_.exclusive_owner_ = old_owner;
Ian Rogersc604d732012-10-14 16:09:54 -0700943#endif
944 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700945}
946
Ian Rogers7b078e82014-09-10 14:44:24 -0700947bool ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700948 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers7b078e82014-09-10 14:44:24 -0700949 bool timed_out = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700950 guard_.AssertExclusiveHeld(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700951 guard_.CheckSafeToWait(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700952 unsigned int old_recursion_count = guard_.recursion_count_;
953#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700954 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800955 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700956 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800957 // Ensure the Mutex is contended so that requeued threads are awoken.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800958 guard_.num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -0700959 guard_.recursion_count_ = 1;
Ian Rogers3e5cf302014-05-20 16:40:37 -0700960 int32_t cur_sequence = sequence_.LoadRelaxed();
Ian Rogersc604d732012-10-14 16:09:54 -0700961 guard_.ExclusiveUnlock(self);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700962 if (futex(sequence_.Address(), FUTEX_WAIT, cur_sequence, &rel_ts, nullptr, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700963 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800964 // Timed out we're done.
Ian Rogers7b078e82014-09-10 14:44:24 -0700965 timed_out = true;
Brian Carlstrom0de79852013-07-25 22:29:58 -0700966 } else if ((errno == EAGAIN) || (errno == EINTR)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800967 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700968 } else {
969 PLOG(FATAL) << "timed futex wait failed for " << name_;
970 }
971 }
972 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800973 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700974 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800975 // We awoke and so no longer require awakes from the guard_'s unlock.
Ian Rogers3e5cf302014-05-20 16:40:37 -0700976 CHECK_GE(guard_.num_contenders_.LoadRelaxed(), 0);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800977 guard_.num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700978#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000979#if !defined(__APPLE__)
Ian Rogersc604d732012-10-14 16:09:54 -0700980 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700981#else
Ian Rogersc604d732012-10-14 16:09:54 -0700982 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700983#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700984 uint64_t old_owner = guard_.exclusive_owner_;
985 guard_.exclusive_owner_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700986 guard_.recursion_count_ = 0;
987 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700988 InitTimeSpec(true, clock, ms, ns, &ts);
Narayan Kamath51b71022014-03-04 11:57:09 +0000989 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &guard_.mutex_, &ts));
Ian Rogers7b078e82014-09-10 14:44:24 -0700990 if (rc == ETIMEDOUT) {
991 timed_out = true;
992 } else if (rc != 0) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700993 errno = rc;
994 PLOG(FATAL) << "TimedWait failed for " << name_;
995 }
Ian Rogersc5f17732014-06-05 20:48:42 -0700996 guard_.exclusive_owner_ = old_owner;
Ian Rogersc604d732012-10-14 16:09:54 -0700997#endif
998 guard_.recursion_count_ = old_recursion_count;
Ian Rogers7b078e82014-09-10 14:44:24 -0700999 return timed_out;
Elliott Hughes5f791332011-09-15 17:45:30 -07001000}
1001
Ian Rogers719d1a32014-03-06 12:13:39 -08001002void Locks::Init() {
1003 if (logging_lock_ != nullptr) {
1004 // Already initialized.
Nicolas Geoffray7f0a6d62014-05-26 14:01:46 +01001005 if (kRuntimeISA == kX86 || kRuntimeISA == kX86_64) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001006 DCHECK(modify_ldt_lock_ != nullptr);
1007 } else {
1008 DCHECK(modify_ldt_lock_ == nullptr);
1009 }
Ian Rogers719d1a32014-03-06 12:13:39 -08001010 DCHECK(abort_lock_ != nullptr);
Brian Carlstrom306db812014-09-05 13:01:41 -07001011 DCHECK(alloc_tracker_lock_ != nullptr);
Andreas Gampe74240812014-04-17 10:35:09 -07001012 DCHECK(allocated_monitor_ids_lock_ != nullptr);
Chao-ying Fu9e369312014-05-21 11:20:52 -07001013 DCHECK(allocated_thread_ids_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001014 DCHECK(breakpoint_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001015 DCHECK(classlinker_classes_lock_ != nullptr);
Brian Carlstrom306db812014-09-05 13:01:41 -07001016 DCHECK(deoptimization_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001017 DCHECK(heap_bitmap_lock_ != nullptr);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001018 DCHECK(oat_file_manager_lock_ != nullptr);
David Brazdilca3c8c32016-09-06 14:04:48 +01001019 DCHECK(verifier_deps_lock_ != nullptr);
Richard Uhlera206c742016-05-24 15:04:22 -07001020 DCHECK(host_dlopen_handles_lock_ != nullptr);
Brian Carlstrom306db812014-09-05 13:01:41 -07001021 DCHECK(intern_table_lock_ != nullptr);
Andreas Gampec8089542017-01-16 12:41:12 -08001022 DCHECK(jni_function_table_lock_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -07001023 DCHECK(jni_libraries_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001024 DCHECK(logging_lock_ != nullptr);
1025 DCHECK(mutator_lock_ != nullptr);
Brian Carlstrom306db812014-09-05 13:01:41 -07001026 DCHECK(profiler_lock_ != nullptr);
Mingyao Yang063fc772016-08-02 11:02:54 -07001027 DCHECK(cha_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001028 DCHECK(thread_list_lock_ != nullptr);
1029 DCHECK(thread_suspend_count_lock_ != nullptr);
1030 DCHECK(trace_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001031 DCHECK(unexpected_signal_lock_ != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08001032 DCHECK(dex_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001033 } else {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001034 // Create global locks in level order from highest lock level to lowest.
Ian Rogers4ad5cd32014-11-11 23:08:07 -08001035 LockLevel current_lock_level = kInstrumentEntrypointsLock;
1036 DCHECK(instrument_entrypoints_lock_ == nullptr);
1037 instrument_entrypoints_lock_ = new Mutex("instrument entrypoint lock", current_lock_level);
Ian Rogers719d1a32014-03-06 12:13:39 -08001038
Chao-ying Fu9e369312014-05-21 11:20:52 -07001039 #define UPDATE_CURRENT_LOCK_LEVEL(new_level) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001040 if ((new_level) >= current_lock_level) { \
Brian Carlstrom306db812014-09-05 13:01:41 -07001041 /* Do not use CHECKs or FATAL here, abort_lock_ is not setup yet. */ \
1042 fprintf(stderr, "New local level %d is not less than current level %d\n", \
1043 new_level, current_lock_level); \
1044 exit(1); \
1045 } \
Ian Rogersf3d874c2014-07-17 18:52:42 -07001046 current_lock_level = new_level;
1047
1048 UPDATE_CURRENT_LOCK_LEVEL(kMutatorLock);
1049 DCHECK(mutator_lock_ == nullptr);
Yu Lieac44242015-06-29 10:50:03 +08001050 mutator_lock_ = new MutatorMutex("mutator lock", current_lock_level);
Chao-ying Fu9e369312014-05-21 11:20:52 -07001051
1052 UPDATE_CURRENT_LOCK_LEVEL(kHeapBitmapLock);
1053 DCHECK(heap_bitmap_lock_ == nullptr);
1054 heap_bitmap_lock_ = new ReaderWriterMutex("heap bitmap lock", current_lock_level);
1055
Jeff Hao69dbec62014-09-15 18:03:41 -07001056 UPDATE_CURRENT_LOCK_LEVEL(kTraceLock);
1057 DCHECK(trace_lock_ == nullptr);
1058 trace_lock_ = new Mutex("trace lock", current_lock_level);
1059
Chao-ying Fu9e369312014-05-21 11:20:52 -07001060 UPDATE_CURRENT_LOCK_LEVEL(kRuntimeShutdownLock);
1061 DCHECK(runtime_shutdown_lock_ == nullptr);
1062 runtime_shutdown_lock_ = new Mutex("runtime shutdown lock", current_lock_level);
1063
1064 UPDATE_CURRENT_LOCK_LEVEL(kProfilerLock);
1065 DCHECK(profiler_lock_ == nullptr);
1066 profiler_lock_ = new Mutex("profiler lock", current_lock_level);
1067
Brian Carlstrom306db812014-09-05 13:01:41 -07001068 UPDATE_CURRENT_LOCK_LEVEL(kDeoptimizationLock);
1069 DCHECK(deoptimization_lock_ == nullptr);
1070 deoptimization_lock_ = new Mutex("Deoptimization lock", current_lock_level);
1071
1072 UPDATE_CURRENT_LOCK_LEVEL(kAllocTrackerLock);
1073 DCHECK(alloc_tracker_lock_ == nullptr);
1074 alloc_tracker_lock_ = new Mutex("AllocTracker lock", current_lock_level);
1075
Chao-ying Fu9e369312014-05-21 11:20:52 -07001076 UPDATE_CURRENT_LOCK_LEVEL(kThreadListLock);
1077 DCHECK(thread_list_lock_ == nullptr);
1078 thread_list_lock_ = new Mutex("thread list lock", current_lock_level);
1079
Ian Rogers68d8b422014-07-17 11:09:10 -07001080 UPDATE_CURRENT_LOCK_LEVEL(kJniLoadLibraryLock);
1081 DCHECK(jni_libraries_lock_ == nullptr);
1082 jni_libraries_lock_ = new Mutex("JNI shared libraries map lock", current_lock_level);
1083
Chao-ying Fu9e369312014-05-21 11:20:52 -07001084 UPDATE_CURRENT_LOCK_LEVEL(kBreakpointLock);
Ian Rogers719d1a32014-03-06 12:13:39 -08001085 DCHECK(breakpoint_lock_ == nullptr);
Sebastien Hertzed2be172014-08-19 15:33:43 +02001086 breakpoint_lock_ = new ReaderWriterMutex("breakpoint lock", current_lock_level);
Chao-ying Fu9e369312014-05-21 11:20:52 -07001087
Mingyao Yang063fc772016-08-02 11:02:54 -07001088 UPDATE_CURRENT_LOCK_LEVEL(kCHALock);
1089 DCHECK(cha_lock_ == nullptr);
1090 cha_lock_ = new Mutex("CHA lock", current_lock_level);
1091
Chao-ying Fu9e369312014-05-21 11:20:52 -07001092 UPDATE_CURRENT_LOCK_LEVEL(kClassLinkerClassesLock);
Ian Rogers719d1a32014-03-06 12:13:39 -08001093 DCHECK(classlinker_classes_lock_ == nullptr);
1094 classlinker_classes_lock_ = new ReaderWriterMutex("ClassLinker classes lock",
Chao-ying Fu9e369312014-05-21 11:20:52 -07001095 current_lock_level);
1096
Andreas Gampe74240812014-04-17 10:35:09 -07001097 UPDATE_CURRENT_LOCK_LEVEL(kMonitorPoolLock);
1098 DCHECK(allocated_monitor_ids_lock_ == nullptr);
1099 allocated_monitor_ids_lock_ = new Mutex("allocated monitor ids lock", current_lock_level);
1100
Chao-ying Fu9e369312014-05-21 11:20:52 -07001101 UPDATE_CURRENT_LOCK_LEVEL(kAllocatedThreadIdsLock);
1102 DCHECK(allocated_thread_ids_lock_ == nullptr);
1103 allocated_thread_ids_lock_ = new Mutex("allocated thread ids lock", current_lock_level);
1104
Nicolas Geoffray7f0a6d62014-05-26 14:01:46 +01001105 if (kRuntimeISA == kX86 || kRuntimeISA == kX86_64) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001106 UPDATE_CURRENT_LOCK_LEVEL(kModifyLdtLock);
1107 DCHECK(modify_ldt_lock_ == nullptr);
1108 modify_ldt_lock_ = new Mutex("modify_ldt lock", current_lock_level);
1109 }
1110
Andreas Gampecc1b5352016-12-01 16:58:38 -08001111 UPDATE_CURRENT_LOCK_LEVEL(kDexLock);
1112 DCHECK(dex_lock_ == nullptr);
1113 dex_lock_ = new ReaderWriterMutex("ClassLinker dex lock", current_lock_level);
1114
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001115 UPDATE_CURRENT_LOCK_LEVEL(kOatFileManagerLock);
1116 DCHECK(oat_file_manager_lock_ == nullptr);
1117 oat_file_manager_lock_ = new ReaderWriterMutex("OatFile manager lock", current_lock_level);
1118
David Brazdilca3c8c32016-09-06 14:04:48 +01001119 UPDATE_CURRENT_LOCK_LEVEL(kVerifierDepsLock);
1120 DCHECK(verifier_deps_lock_ == nullptr);
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001121 verifier_deps_lock_ = new ReaderWriterMutex("verifier deps lock", current_lock_level);
David Brazdilca3c8c32016-09-06 14:04:48 +01001122
Richard Uhlera206c742016-05-24 15:04:22 -07001123 UPDATE_CURRENT_LOCK_LEVEL(kHostDlOpenHandlesLock);
1124 DCHECK(host_dlopen_handles_lock_ == nullptr);
1125 host_dlopen_handles_lock_ = new Mutex("host dlopen handles lock", current_lock_level);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07001126
Chao-ying Fu9e369312014-05-21 11:20:52 -07001127 UPDATE_CURRENT_LOCK_LEVEL(kInternTableLock);
Ian Rogers719d1a32014-03-06 12:13:39 -08001128 DCHECK(intern_table_lock_ == nullptr);
Chao-ying Fu9e369312014-05-21 11:20:52 -07001129 intern_table_lock_ = new Mutex("InternTable lock", current_lock_level);
1130
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -07001131 UPDATE_CURRENT_LOCK_LEVEL(kReferenceProcessorLock);
1132 DCHECK(reference_processor_lock_ == nullptr);
1133 reference_processor_lock_ = new Mutex("ReferenceProcessor lock", current_lock_level);
1134
1135 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueueClearedReferencesLock);
1136 DCHECK(reference_queue_cleared_references_lock_ == nullptr);
1137 reference_queue_cleared_references_lock_ = new Mutex("ReferenceQueue cleared references lock", current_lock_level);
1138
1139 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueueWeakReferencesLock);
1140 DCHECK(reference_queue_weak_references_lock_ == nullptr);
1141 reference_queue_weak_references_lock_ = new Mutex("ReferenceQueue cleared references lock", current_lock_level);
1142
1143 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueueFinalizerReferencesLock);
1144 DCHECK(reference_queue_finalizer_references_lock_ == nullptr);
1145 reference_queue_finalizer_references_lock_ = new Mutex("ReferenceQueue finalizer references lock", current_lock_level);
1146
1147 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueuePhantomReferencesLock);
1148 DCHECK(reference_queue_phantom_references_lock_ == nullptr);
1149 reference_queue_phantom_references_lock_ = new Mutex("ReferenceQueue phantom references lock", current_lock_level);
1150
1151 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueueSoftReferencesLock);
1152 DCHECK(reference_queue_soft_references_lock_ == nullptr);
1153 reference_queue_soft_references_lock_ = new Mutex("ReferenceQueue soft references lock", current_lock_level);
1154
Andreas Gampe05a364c2016-10-14 13:27:12 -07001155 UPDATE_CURRENT_LOCK_LEVEL(kJniGlobalsLock);
1156 DCHECK(jni_globals_lock_ == nullptr);
1157 jni_globals_lock_ =
1158 new ReaderWriterMutex("JNI global reference table lock", current_lock_level);
1159
1160 UPDATE_CURRENT_LOCK_LEVEL(kJniWeakGlobalsLock);
1161 DCHECK(jni_weak_globals_lock_ == nullptr);
1162 jni_weak_globals_lock_ = new Mutex("JNI weak global reference table lock", current_lock_level);
1163
Andreas Gampec8089542017-01-16 12:41:12 -08001164 UPDATE_CURRENT_LOCK_LEVEL(kJniFunctionTableLock);
1165 DCHECK(jni_function_table_lock_ == nullptr);
1166 jni_function_table_lock_ = new Mutex("JNI function table lock", current_lock_level);
1167
Chao-ying Fu9e369312014-05-21 11:20:52 -07001168 UPDATE_CURRENT_LOCK_LEVEL(kAbortLock);
1169 DCHECK(abort_lock_ == nullptr);
1170 abort_lock_ = new Mutex("abort lock", current_lock_level, true);
1171
1172 UPDATE_CURRENT_LOCK_LEVEL(kThreadSuspendCountLock);
1173 DCHECK(thread_suspend_count_lock_ == nullptr);
1174 thread_suspend_count_lock_ = new Mutex("thread suspend count lock", current_lock_level);
1175
1176 UPDATE_CURRENT_LOCK_LEVEL(kUnexpectedSignalLock);
1177 DCHECK(unexpected_signal_lock_ == nullptr);
1178 unexpected_signal_lock_ = new Mutex("unexpected signal lock", current_lock_level, true);
1179
1180 UPDATE_CURRENT_LOCK_LEVEL(kLoggingLock);
1181 DCHECK(logging_lock_ == nullptr);
1182 logging_lock_ = new Mutex("logging lock", current_lock_level, true);
1183
1184 #undef UPDATE_CURRENT_LOCK_LEVEL
Mathieu Chartier91e56692015-03-03 13:51:04 -08001185
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001186 // List of mutexes that we may hold when accessing a weak ref.
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -08001187 AddToExpectedMutexesOnWeakRefAccess(dex_lock_, /*need_lock*/ false);
1188 AddToExpectedMutexesOnWeakRefAccess(classlinker_classes_lock_, /*need_lock*/ false);
1189 AddToExpectedMutexesOnWeakRefAccess(jni_libraries_lock_, /*need_lock*/ false);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001190
Mathieu Chartier91e56692015-03-03 13:51:04 -08001191 InitConditions();
Ian Rogers719d1a32014-03-06 12:13:39 -08001192 }
1193}
1194
Mathieu Chartier91e56692015-03-03 13:51:04 -08001195void Locks::InitConditions() {
1196 thread_exit_cond_ = new ConditionVariable("thread exit condition variable", *thread_list_lock_);
1197}
Ian Rogers719d1a32014-03-06 12:13:39 -08001198
David Sehrf42eb2c2016-10-19 13:20:45 -07001199void Locks::SetClientCallback(ClientCallback* safe_to_call_abort_cb) {
1200 safe_to_call_abort_callback.StoreRelease(safe_to_call_abort_cb);
1201}
1202
1203// Helper to allow checking shutdown while ignoring locking requirements.
1204bool Locks::IsSafeToCallAbortRacy() {
1205 Locks::ClientCallback* safe_to_call_abort_cb = safe_to_call_abort_callback.LoadAcquire();
1206 return safe_to_call_abort_cb != nullptr && safe_to_call_abort_cb();
1207}
1208
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -08001209void Locks::AddToExpectedMutexesOnWeakRefAccess(BaseMutex* mutex, bool need_lock) {
1210 if (need_lock) {
1211 ScopedExpectedMutexesOnWeakRefAccessLock mu(mutex);
1212 mutex->SetShouldRespondToEmptyCheckpointRequest(true);
1213 expected_mutexes_on_weak_ref_access_.push_back(mutex);
1214 } else {
1215 mutex->SetShouldRespondToEmptyCheckpointRequest(true);
1216 expected_mutexes_on_weak_ref_access_.push_back(mutex);
1217 }
1218}
1219
1220void Locks::RemoveFromExpectedMutexesOnWeakRefAccess(BaseMutex* mutex, bool need_lock) {
1221 if (need_lock) {
1222 ScopedExpectedMutexesOnWeakRefAccessLock mu(mutex);
1223 mutex->SetShouldRespondToEmptyCheckpointRequest(false);
1224 std::vector<BaseMutex*>& list = expected_mutexes_on_weak_ref_access_;
1225 auto it = std::find(list.begin(), list.end(), mutex);
1226 DCHECK(it != list.end());
1227 list.erase(it);
1228 } else {
1229 mutex->SetShouldRespondToEmptyCheckpointRequest(false);
1230 std::vector<BaseMutex*>& list = expected_mutexes_on_weak_ref_access_;
1231 auto it = std::find(list.begin(), list.end(), mutex);
1232 DCHECK(it != list.end());
1233 list.erase(it);
1234 }
1235}
1236
1237bool Locks::IsExpectedOnWeakRefAccess(BaseMutex* mutex) {
1238 ScopedExpectedMutexesOnWeakRefAccessLock mu(mutex);
1239 std::vector<BaseMutex*>& list = expected_mutexes_on_weak_ref_access_;
1240 return std::find(list.begin(), list.end(), mutex) != list.end();
1241}
1242
Elliott Hughese62934d2012-04-09 11:24:29 -07001243} // namespace art