blob: da286d7e4195809dbb0dfe43590ed68a9f325f85 [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
David Sehrc431b9d2018-03-02 12:01:51 -080024#include "base/atomic.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080025#include "base/logging.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080026#include "base/systrace.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070027#include "base/time_utils.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;
Igor Murashkin495e7832017-10-27 10:56:20 -070066Mutex* Locks::subtype_check_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080067Mutex* Locks::thread_list_lock_ = nullptr;
Mathieu Chartier91e56692015-03-03 13:51:04 -080068ConditionVariable* Locks::thread_exit_cond_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080069Mutex* Locks::thread_suspend_count_lock_ = nullptr;
70Mutex* Locks::trace_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080071Mutex* Locks::unexpected_signal_lock_ = nullptr;
Alex Light88fd7202017-06-30 08:31:59 -070072Mutex* Locks::user_code_suspension_lock_ = nullptr;
Andreas Gampe5bdb6552015-07-22 23:44:55 -070073Uninterruptible Roles::uninterruptible_;
Andreas Gampe05a364c2016-10-14 13:27:12 -070074ReaderWriterMutex* Locks::jni_globals_lock_ = nullptr;
75Mutex* Locks::jni_weak_globals_lock_ = nullptr;
Andreas Gampecc1b5352016-12-01 16:58:38 -080076ReaderWriterMutex* Locks::dex_lock_ = nullptr;
David Srbeckyfb3de3d2018-01-29 16:11:49 +000077Mutex* Locks::native_debug_interface_lock_ = nullptr;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -080078std::vector<BaseMutex*> Locks::expected_mutexes_on_weak_ref_access_;
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -080079Atomic<const BaseMutex*> Locks::expected_mutexes_on_weak_ref_access_guard_;
Ian Rogers719d1a32014-03-06 12:13:39 -080080
81struct AllMutexData {
82 // A guard for all_mutexes_ that's not a mutex (Mutexes must CAS to acquire and busy wait).
83 Atomic<const BaseMutex*> all_mutexes_guard;
84 // All created mutexes guarded by all_mutexes_guard_.
85 std::set<BaseMutex*>* all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -070086 AllMutexData() : all_mutexes(nullptr) {}
Ian Rogers719d1a32014-03-06 12:13:39 -080087};
88static struct AllMutexData gAllMutexData[kAllMutexDataSize];
89
Ian Rogersc604d732012-10-14 16:09:54 -070090#if ART_USE_FUTEXES
91static bool ComputeRelativeTimeSpec(timespec* result_ts, const timespec& lhs, const timespec& rhs) {
Brian Carlstromfb6996f2013-07-18 18:21:14 -070092 const int32_t one_sec = 1000 * 1000 * 1000; // one second in nanoseconds.
Ian Rogersc604d732012-10-14 16:09:54 -070093 result_ts->tv_sec = lhs.tv_sec - rhs.tv_sec;
94 result_ts->tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
95 if (result_ts->tv_nsec < 0) {
96 result_ts->tv_sec--;
97 result_ts->tv_nsec += one_sec;
98 } else if (result_ts->tv_nsec > one_sec) {
99 result_ts->tv_sec++;
100 result_ts->tv_nsec -= one_sec;
101 }
102 return result_ts->tv_sec < 0;
103}
104#endif
105
Hans Boehmae915a02017-12-12 11:05:32 -0800106// Wait for an amount of time that roughly increases in the argument i.
107// Spin for small arguments and yield/sleep for longer ones.
108static void BackOff(uint32_t i) {
109 static constexpr uint32_t kSpinMax = 10;
110 static constexpr uint32_t kYieldMax = 20;
111 if (i <= kSpinMax) {
112 // TODO: Esp. in very latency-sensitive cases, consider replacing this with an explicit
113 // test-and-test-and-set loop in the caller. Possibly skip entirely on a uniprocessor.
114 volatile uint32_t x = 0;
115 const uint32_t spin_count = 10 * i;
116 for (uint32_t spin = 0; spin < spin_count; ++spin) {
117 ++x; // Volatile; hence should not be optimized away.
118 }
119 // TODO: Consider adding x86 PAUSE and/or ARM YIELD here.
120 } else if (i <= kYieldMax) {
121 sched_yield();
122 } else {
123 NanoSleep(1000ull * (i - kYieldMax));
124 }
125}
126
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700127class ScopedAllMutexesLock FINAL {
Ian Rogers56edc432013-01-18 16:51:51 -0800128 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700129 explicit ScopedAllMutexesLock(const BaseMutex* mutex) : mutex_(mutex) {
Hans Boehmae915a02017-12-12 11:05:32 -0800130 for (uint32_t i = 0;
Orion Hodson88591fe2018-03-06 13:35:43 +0000131 !gAllMutexData->all_mutexes_guard.CompareAndSetWeakAcquire(nullptr, mutex);
Hans Boehmae915a02017-12-12 11:05:32 -0800132 ++i) {
133 BackOff(i);
Ian Rogers56edc432013-01-18 16:51:51 -0800134 }
135 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700136
Ian Rogers56edc432013-01-18 16:51:51 -0800137 ~ScopedAllMutexesLock() {
Orion Hodson88591fe2018-03-06 13:35:43 +0000138 DCHECK_EQ(gAllMutexData->all_mutexes_guard.load(std::memory_order_relaxed), mutex_);
139 gAllMutexData->all_mutexes_guard.store(nullptr, std::memory_order_release);
Ian Rogers56edc432013-01-18 16:51:51 -0800140 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700141
Ian Rogers56edc432013-01-18 16:51:51 -0800142 private:
143 const BaseMutex* const mutex_;
144};
Ian Rogers56edc432013-01-18 16:51:51 -0800145
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -0800146class Locks::ScopedExpectedMutexesOnWeakRefAccessLock FINAL {
147 public:
148 explicit ScopedExpectedMutexesOnWeakRefAccessLock(const BaseMutex* mutex) : mutex_(mutex) {
Hans Boehmae915a02017-12-12 11:05:32 -0800149 for (uint32_t i = 0;
Orion Hodson88591fe2018-03-06 13:35:43 +0000150 !Locks::expected_mutexes_on_weak_ref_access_guard_.CompareAndSetWeakAcquire(nullptr,
151 mutex);
Hans Boehmae915a02017-12-12 11:05:32 -0800152 ++i) {
153 BackOff(i);
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -0800154 }
155 }
156
157 ~ScopedExpectedMutexesOnWeakRefAccessLock() {
Orion Hodson88591fe2018-03-06 13:35:43 +0000158 DCHECK_EQ(Locks::expected_mutexes_on_weak_ref_access_guard_.load(std::memory_order_relaxed),
159 mutex_);
160 Locks::expected_mutexes_on_weak_ref_access_guard_.store(nullptr, std::memory_order_release);
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -0800161 }
162
163 private:
164 const BaseMutex* const mutex_;
165};
166
Ian Rogerscf7f1912014-10-22 22:06:39 -0700167// Scoped class that generates events at the beginning and end of lock contention.
168class ScopedContentionRecorder FINAL : public ValueObject {
169 public:
170 ScopedContentionRecorder(BaseMutex* mutex, uint64_t blocked_tid, uint64_t owner_tid)
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700171 : mutex_(kLogLockContentions ? mutex : nullptr),
Ian Rogerscf7f1912014-10-22 22:06:39 -0700172 blocked_tid_(kLogLockContentions ? blocked_tid : 0),
173 owner_tid_(kLogLockContentions ? owner_tid : 0),
174 start_nano_time_(kLogLockContentions ? NanoTime() : 0) {
175 if (ATRACE_ENABLED()) {
176 std::string msg = StringPrintf("Lock contention on %s (owner tid: %" PRIu64 ")",
177 mutex->GetName(), owner_tid);
178 ATRACE_BEGIN(msg.c_str());
179 }
180 }
181
182 ~ScopedContentionRecorder() {
183 ATRACE_END();
184 if (kLogLockContentions) {
185 uint64_t end_nano_time = NanoTime();
186 mutex_->RecordContention(blocked_tid_, owner_tid_, end_nano_time - start_nano_time_);
187 }
188 }
189
190 private:
191 BaseMutex* const mutex_;
192 const uint64_t blocked_tid_;
193 const uint64_t owner_tid_;
194 const uint64_t start_nano_time_;
195};
196
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800197BaseMutex::BaseMutex(const char* name, LockLevel level)
Andreas Gampe5db8b7b2018-05-08 16:10:59 -0700198 : name_(name),
199 level_(level),
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800200 should_respond_to_empty_checkpoint_request_(false) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700201 if (kLogLockContentions) {
202 ScopedAllMutexesLock mu(this);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700203 std::set<BaseMutex*>** all_mutexes_ptr = &gAllMutexData->all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700204 if (*all_mutexes_ptr == nullptr) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700205 // We leak the global set of all mutexes to avoid ordering issues in global variable
206 // construction/destruction.
207 *all_mutexes_ptr = new std::set<BaseMutex*>();
208 }
209 (*all_mutexes_ptr)->insert(this);
Ian Rogers56edc432013-01-18 16:51:51 -0800210 }
Ian Rogers56edc432013-01-18 16:51:51 -0800211}
212
213BaseMutex::~BaseMutex() {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700214 if (kLogLockContentions) {
215 ScopedAllMutexesLock mu(this);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700216 gAllMutexData->all_mutexes->erase(this);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700217 }
Ian Rogers56edc432013-01-18 16:51:51 -0800218}
219
220void BaseMutex::DumpAll(std::ostream& os) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700221 if (kLogLockContentions) {
222 os << "Mutex logging:\n";
223 ScopedAllMutexesLock mu(reinterpret_cast<const BaseMutex*>(-1));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700224 std::set<BaseMutex*>* all_mutexes = gAllMutexData->all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700225 if (all_mutexes == nullptr) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700226 // No mutexes have been created yet during at startup.
227 return;
228 }
229 typedef std::set<BaseMutex*>::const_iterator It;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700230 os << "(Contended)\n";
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700231 for (It it = all_mutexes->begin(); it != all_mutexes->end(); ++it) {
232 BaseMutex* mutex = *it;
233 if (mutex->HasEverContended()) {
234 mutex->Dump(os);
235 os << "\n";
236 }
237 }
238 os << "(Never contented)\n";
239 for (It it = all_mutexes->begin(); it != all_mutexes->end(); ++it) {
240 BaseMutex* mutex = *it;
241 if (!mutex->HasEverContended()) {
242 mutex->Dump(os);
243 os << "\n";
244 }
245 }
Ian Rogers56edc432013-01-18 16:51:51 -0800246 }
Ian Rogers56edc432013-01-18 16:51:51 -0800247}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700248
Ian Rogers81d425b2012-09-27 16:03:43 -0700249void BaseMutex::CheckSafeToWait(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700250 if (self == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700251 CheckUnattachedThread(level_);
252 return;
253 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700254 if (kDebugLocking) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700255 CHECK(self->GetHeldMutex(level_) == this || level_ == kMonitorLock)
256 << "Waiting on unacquired mutex: " << name_;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700257 bool bad_mutexes_held = false;
Elliott Hughes0f827162013-02-26 12:12:58 -0800258 for (int i = kLockLevelCount - 1; i >= 0; --i) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700259 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700260 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Alex Light79400aa2017-07-18 15:34:21 -0700261 // We allow the thread to wait even if the user_code_suspension_lock_ is held so long as we
262 // are some thread's resume_cond_ (level_ == kThreadSuspendCountLock). This just means that
263 // gc or some other internal process is suspending the thread while it is trying to suspend
264 // some other thread. So long as the current thread is not being suspended by a
265 // SuspendReason::kForUserCode (which needs the user_code_suspension_lock_ to clear) this is
266 // fine.
267 if (held_mutex == Locks::user_code_suspension_lock_ && level_ == kThreadSuspendCountLock) {
268 // No thread safety analysis is fine since we have both the user_code_suspension_lock_
269 // from the line above and the ThreadSuspendCountLock since it is our level_. We use this
270 // lambda to avoid having to annotate the whole function as NO_THREAD_SAFETY_ANALYSIS.
271 auto is_suspending_for_user_code = [self]() NO_THREAD_SAFETY_ANALYSIS {
272 return self->GetUserCodeSuspendCount() != 0;
273 };
274 if (is_suspending_for_user_code()) {
275 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
276 << "(level " << LockLevel(i) << ") while performing wait on "
277 << "\"" << name_ << "\" (level " << level_ << ") "
278 << "with SuspendReason::kForUserCode pending suspensions";
279 bad_mutexes_held = true;
280 }
281 } else if (held_mutex != nullptr) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800282 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
283 << "(level " << LockLevel(i) << ") while performing wait on "
284 << "\"" << name_ << "\" (level " << level_ << ")";
Ian Rogers25fd14b2012-09-05 10:56:38 -0700285 bad_mutexes_held = true;
286 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700287 }
288 }
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000289 if (gAborting == 0) { // Avoid recursive aborts.
Alex Light79400aa2017-07-18 15:34:21 -0700290 CHECK(!bad_mutexes_held) << this;
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000291 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700292 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700293}
294
Ian Rogers37f3c962014-07-17 11:25:30 -0700295void BaseMutex::ContentionLogData::AddToWaitTime(uint64_t value) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700296 if (kLogLockContentions) {
297 // Atomically add value to wait_time.
Orion Hodson88591fe2018-03-06 13:35:43 +0000298 wait_time.fetch_add(value, std::memory_order_seq_cst);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700299 }
300}
301
Brian Carlstrom0de79852013-07-25 22:29:58 -0700302void BaseMutex::RecordContention(uint64_t blocked_tid,
303 uint64_t owner_tid,
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700304 uint64_t nano_time_blocked) {
305 if (kLogLockContentions) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700306 ContentionLogData* data = contention_log_data_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700307 ++(data->contention_count);
308 data->AddToWaitTime(nano_time_blocked);
309 ContentionLogEntry* log = data->contention_log;
310 // This code is intentionally racy as it is only used for diagnostics.
Orion Hodson88591fe2018-03-06 13:35:43 +0000311 int32_t slot = data->cur_content_log_entry.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700312 if (log[slot].blocked_tid == blocked_tid &&
313 log[slot].owner_tid == blocked_tid) {
314 ++log[slot].count;
315 } else {
316 uint32_t new_slot;
317 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000318 slot = data->cur_content_log_entry.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700319 new_slot = (slot + 1) % kContentionLogSize;
Orion Hodson4557b382018-01-03 11:47:54 +0000320 } while (!data->cur_content_log_entry.CompareAndSetWeakRelaxed(slot, new_slot));
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700321 log[new_slot].blocked_tid = blocked_tid;
322 log[new_slot].owner_tid = owner_tid;
Orion Hodson88591fe2018-03-06 13:35:43 +0000323 log[new_slot].count.store(1, std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700324 }
Ian Rogers56edc432013-01-18 16:51:51 -0800325 }
Ian Rogers56edc432013-01-18 16:51:51 -0800326}
327
Ian Rogers56edc432013-01-18 16:51:51 -0800328void BaseMutex::DumpContention(std::ostream& os) const {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700329 if (kLogLockContentions) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700330 const ContentionLogData* data = contention_log_data_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700331 const ContentionLogEntry* log = data->contention_log;
Orion Hodson88591fe2018-03-06 13:35:43 +0000332 uint64_t wait_time = data->wait_time.load(std::memory_order_relaxed);
333 uint32_t contention_count = data->contention_count.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700334 if (contention_count == 0) {
335 os << "never contended";
336 } else {
337 os << "contended " << contention_count
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700338 << " total wait of contender " << PrettyDuration(wait_time)
339 << " average " << PrettyDuration(wait_time / contention_count);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700340 SafeMap<uint64_t, size_t> most_common_blocker;
341 SafeMap<uint64_t, size_t> most_common_blocked;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700342 for (size_t i = 0; i < kContentionLogSize; ++i) {
343 uint64_t blocked_tid = log[i].blocked_tid;
344 uint64_t owner_tid = log[i].owner_tid;
Orion Hodson88591fe2018-03-06 13:35:43 +0000345 uint32_t count = log[i].count.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700346 if (count > 0) {
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700347 auto it = most_common_blocked.find(blocked_tid);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700348 if (it != most_common_blocked.end()) {
349 most_common_blocked.Overwrite(blocked_tid, it->second + count);
350 } else {
351 most_common_blocked.Put(blocked_tid, count);
352 }
353 it = most_common_blocker.find(owner_tid);
354 if (it != most_common_blocker.end()) {
355 most_common_blocker.Overwrite(owner_tid, it->second + count);
356 } else {
357 most_common_blocker.Put(owner_tid, count);
358 }
Ian Rogers56edc432013-01-18 16:51:51 -0800359 }
360 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700361 uint64_t max_tid = 0;
362 size_t max_tid_count = 0;
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700363 for (const auto& pair : most_common_blocked) {
364 if (pair.second > max_tid_count) {
365 max_tid = pair.first;
366 max_tid_count = pair.second;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700367 }
Ian Rogers56edc432013-01-18 16:51:51 -0800368 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700369 if (max_tid != 0) {
370 os << " sample shows most blocked tid=" << max_tid;
Ian Rogers56edc432013-01-18 16:51:51 -0800371 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700372 max_tid = 0;
373 max_tid_count = 0;
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700374 for (const auto& pair : most_common_blocker) {
375 if (pair.second > max_tid_count) {
376 max_tid = pair.first;
377 max_tid_count = pair.second;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700378 }
379 }
380 if (max_tid != 0) {
381 os << " sample shows tid=" << max_tid << " owning during this time";
382 }
Ian Rogers56edc432013-01-18 16:51:51 -0800383 }
384 }
Ian Rogers56edc432013-01-18 16:51:51 -0800385}
386
387
Ian Rogers81d425b2012-09-27 16:03:43 -0700388Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Andreas Gampe5db8b7b2018-05-08 16:10:59 -0700389 : BaseMutex(name, level), exclusive_owner_(0), recursion_count_(0), recursive_(recursive) {
Ian Rogersc604d732012-10-14 16:09:54 -0700390#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000391 DCHECK_EQ(0, state_.load(std::memory_order_relaxed));
392 DCHECK_EQ(0, num_contenders_.load(std::memory_order_relaxed));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700393#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700394 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, nullptr));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700395#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700396}
397
David Sehrf42eb2c2016-10-19 13:20:45 -0700398// Helper to allow checking shutdown while locking for thread safety.
399static bool IsSafeToCallAbortSafe() {
400 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
401 return Locks::IsSafeToCallAbortRacy();
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800402}
403
Elliott Hughes8daa0922011-09-11 13:46:25 -0700404Mutex::~Mutex() {
David Sehrf42eb2c2016-10-19 13:20:45 -0700405 bool safe_to_call_abort = Locks::IsSafeToCallAbortRacy();
Ian Rogersc604d732012-10-14 16:09:54 -0700406#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000407 if (state_.load(std::memory_order_relaxed) != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700408 LOG(safe_to_call_abort ? FATAL : WARNING)
Hans Boehm0882af22017-08-31 15:21:57 -0700409 << "destroying mutex with owner: " << GetExclusiveOwnerTid();
Ian Rogersc604d732012-10-14 16:09:54 -0700410 } else {
Hans Boehm0882af22017-08-31 15:21:57 -0700411 if (GetExclusiveOwnerTid() != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700412 LOG(safe_to_call_abort ? FATAL : WARNING)
413 << "unexpectedly found an owner on unlocked mutex " << name_;
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800414 }
Orion Hodson88591fe2018-03-06 13:35:43 +0000415 if (num_contenders_.load(std::memory_order_seq_cst) != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700416 LOG(safe_to_call_abort ? FATAL : WARNING)
417 << "unexpectedly found a contender on mutex " << name_;
Mathieu Chartiercef50f02014-12-09 17:38:52 -0800418 }
Ian Rogersc604d732012-10-14 16:09:54 -0700419 }
420#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700421 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
422 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800423 int rc = pthread_mutex_destroy(&mutex_);
424 if (rc != 0) {
425 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700426 PLOG(safe_to_call_abort ? FATAL : WARNING)
427 << "pthread_mutex_destroy failed for " << name_;
Elliott Hughes6b355752012-01-13 16:49:08 -0800428 }
Ian Rogersc604d732012-10-14 16:09:54 -0700429#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700430}
431
Ian Rogers81d425b2012-09-27 16:03:43 -0700432void Mutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700433 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700434 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700435 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700436 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700437 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700438#if ART_USE_FUTEXES
439 bool done = false;
440 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000441 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700442 if (LIKELY(cur_state == 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700443 // Change state from 0 to 1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000444 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, 1 /* new state */);
Ian Rogersc604d732012-10-14 16:09:54 -0700445 } else {
446 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700447 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersb122a4b2013-11-19 18:00:50 -0800448 num_contenders_++;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800449 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
450 self->CheckEmptyCheckpointFromMutex();
451 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700452 if (futex(state_.Address(), FUTEX_WAIT, 1, nullptr, nullptr, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700453 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
454 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
455 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700456 PLOG(FATAL) << "futex wait failed for " << name_;
457 }
458 }
Ian Rogersb122a4b2013-11-19 18:00:50 -0800459 num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700460 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700461 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000462 DCHECK_EQ(state_.load(std::memory_order_relaxed), 1);
Ian Rogersc604d732012-10-14 16:09:54 -0700463#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700465#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700466 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000467 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700468 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469 }
470 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700471 if (kDebugLocking) {
472 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
473 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700474 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700475 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700476}
477
Ian Rogers81d425b2012-09-27 16:03:43 -0700478bool Mutex::ExclusiveTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700479 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700480 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700481 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700482 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700483 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700484#if ART_USE_FUTEXES
485 bool done = false;
486 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000487 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700488 if (cur_state == 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700489 // Change state from 0 to 1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000490 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, 1 /* new state */);
Ian Rogersc604d732012-10-14 16:09:54 -0700491 } else {
492 return false;
493 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700494 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000495 DCHECK_EQ(state_.load(std::memory_order_relaxed), 1);
Ian Rogersc604d732012-10-14 16:09:54 -0700496#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700497 int result = pthread_mutex_trylock(&mutex_);
498 if (result == EBUSY) {
499 return false;
500 }
501 if (result != 0) {
502 errno = result;
503 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
504 }
Ian Rogersc604d732012-10-14 16:09:54 -0700505#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700506 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000507 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700508 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700509 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700510 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700511 if (kDebugLocking) {
512 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
513 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700514 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700515 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700516 return true;
517}
518
Ian Rogers81d425b2012-09-27 16:03:43 -0700519void Mutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartiereb0a1792014-12-15 17:23:45 -0800520 if (kIsDebugBuild && self != nullptr && self != Thread::Current()) {
521 std::string name1 = "<null>";
522 std::string name2 = "<null>";
523 if (self != nullptr) {
524 self->GetThreadName(name1);
525 }
526 if (Thread::Current() != nullptr) {
527 Thread::Current()->GetThreadName(name2);
528 }
Mathieu Chartier4c101102015-01-27 17:14:16 -0800529 LOG(FATAL) << GetName() << " level=" << level_ << " self=" << name1
530 << " Thread::Current()=" << name2;
Mathieu Chartiereb0a1792014-12-15 17:23:45 -0800531 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700532 AssertHeld(self);
Hans Boehm0882af22017-08-31 15:21:57 -0700533 DCHECK_NE(GetExclusiveOwnerTid(), 0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700534 recursion_count_--;
535 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700536 if (kDebugLocking) {
537 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
538 << name_ << " " << recursion_count_;
539 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700540 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700541#if ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700542 bool done = false;
543 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000544 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogersc5f17732014-06-05 20:48:42 -0700545 if (LIKELY(cur_state == 1)) {
Ian Rogersc5f17732014-06-05 20:48:42 -0700546 // We're no longer the owner.
Orion Hodson88591fe2018-03-06 13:35:43 +0000547 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc7190692014-07-08 23:50:26 -0700548 // Change state to 0 and impose load/store ordering appropriate for lock release.
Orion Hodson4557b382018-01-03 11:47:54 +0000549 // Note, the relaxed loads below mustn't reorder before the CompareAndSet.
Ian Rogersc7190692014-07-08 23:50:26 -0700550 // TODO: the ordering here is non-trivial as state is split across 3 fields, fix by placing
551 // a status bit into the state on contention.
Orion Hodson4557b382018-01-03 11:47:54 +0000552 done = state_.CompareAndSetWeakSequentiallyConsistent(cur_state, 0 /* new state */);
Ian Rogersc5f17732014-06-05 20:48:42 -0700553 if (LIKELY(done)) { // Spurious fail?
Ian Rogersc7190692014-07-08 23:50:26 -0700554 // Wake a contender.
Orion Hodson88591fe2018-03-06 13:35:43 +0000555 if (UNLIKELY(num_contenders_.load(std::memory_order_relaxed) > 0)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700556 futex(state_.Address(), FUTEX_WAKE, 1, nullptr, nullptr, 0);
Ian Rogersc5f17732014-06-05 20:48:42 -0700557 }
558 }
559 } else {
560 // Logging acquires the logging lock, avoid infinite recursion in that case.
561 if (this != Locks::logging_lock_) {
562 LOG(FATAL) << "Unexpected state_ in unlock " << cur_state << " for " << name_;
563 } else {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700564 LogHelper::LogLineLowStack(__FILE__,
565 __LINE__,
566 ::android::base::FATAL_WITHOUT_ABORT,
567 StringPrintf("Unexpected state_ %d in unlock for %s",
568 cur_state, name_).c_str());
Ian Rogersc5f17732014-06-05 20:48:42 -0700569 _exit(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700570 }
571 }
Ian Rogersc5f17732014-06-05 20:48:42 -0700572 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700573#else
Orion Hodson88591fe2018-03-06 13:35:43 +0000574 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700575 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700576#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700577 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700578}
579
Ian Rogers56edc432013-01-18 16:51:51 -0800580void Mutex::Dump(std::ostream& os) const {
581 os << (recursive_ ? "recursive " : "non-recursive ")
582 << name_
583 << " level=" << static_cast<int>(level_)
584 << " rec=" << recursion_count_
585 << " owner=" << GetExclusiveOwnerTid() << " ";
586 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700587}
588
589std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800590 mu.Dump(os);
591 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700592}
593
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800594void Mutex::WakeupToRespondToEmptyCheckpoint() {
595#if ART_USE_FUTEXES
596 // Wake up all the waiters so they will respond to the emtpy checkpoint.
597 DCHECK(should_respond_to_empty_checkpoint_request_);
Orion Hodson88591fe2018-03-06 13:35:43 +0000598 if (UNLIKELY(num_contenders_.load(std::memory_order_relaxed) > 0)) {
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800599 futex(state_.Address(), FUTEX_WAKE, -1, nullptr, nullptr, 0);
600 }
601#else
602 LOG(FATAL) << "Non futex case isn't supported.";
603#endif
604}
605
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700606ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level)
607 : BaseMutex(name, level)
Ian Rogers81d425b2012-09-27 16:03:43 -0700608#if ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700609 , state_(0), num_pending_readers_(0), num_pending_writers_(0)
Ian Rogers81d425b2012-09-27 16:03:43 -0700610#endif
Igor Murashkin5573c372017-11-16 13:34:30 -0800611{
Ian Rogers81d425b2012-09-27 16:03:43 -0700612#if !ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700613 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, nullptr));
Ian Rogers81d425b2012-09-27 16:03:43 -0700614#endif
Orion Hodson88591fe2018-03-06 13:35:43 +0000615 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700616}
617
618ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700619#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000620 CHECK_EQ(state_.load(std::memory_order_relaxed), 0);
Hans Boehm0882af22017-08-31 15:21:57 -0700621 CHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000622 CHECK_EQ(num_pending_readers_.load(std::memory_order_relaxed), 0);
623 CHECK_EQ(num_pending_writers_.load(std::memory_order_relaxed), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700624#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700625 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
626 // may still be using locks.
627 int rc = pthread_rwlock_destroy(&rwlock_);
628 if (rc != 0) {
629 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700630 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
631 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800632 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700633#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700634}
635
Ian Rogers81d425b2012-09-27 16:03:43 -0700636void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700637 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700638 AssertNotExclusiveHeld(self);
639#if ART_USE_FUTEXES
640 bool done = false;
641 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000642 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700643 if (LIKELY(cur_state == 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700644 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000645 done = state_.CompareAndSetWeakAcquire(0 /* cur_state*/, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700646 } else {
647 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700648 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersc7190692014-07-08 23:50:26 -0700649 ++num_pending_writers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800650 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
651 self->CheckEmptyCheckpointFromMutex();
652 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700653 if (futex(state_.Address(), FUTEX_WAIT, cur_state, nullptr, nullptr, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700654 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
655 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
656 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700657 PLOG(FATAL) << "futex wait failed for " << name_;
658 }
659 }
Ian Rogersc7190692014-07-08 23:50:26 -0700660 --num_pending_writers_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700661 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700662 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000663 DCHECK_EQ(state_.load(std::memory_order_relaxed), -1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700664#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700665 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700666#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700667 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000668 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700669 RegisterAsLocked(self);
670 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700671}
672
Ian Rogers81d425b2012-09-27 16:03:43 -0700673void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700674 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700675 AssertExclusiveHeld(self);
676 RegisterAsUnlocked(self);
Hans Boehm0882af22017-08-31 15:21:57 -0700677 DCHECK_NE(GetExclusiveOwnerTid(), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700678#if ART_USE_FUTEXES
679 bool done = false;
680 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000681 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700682 if (LIKELY(cur_state == -1)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700683 // We're no longer the owner.
Orion Hodson88591fe2018-03-06 13:35:43 +0000684 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc7190692014-07-08 23:50:26 -0700685 // Change state from -1 to 0 and impose load/store ordering appropriate for lock release.
Orion Hodson4557b382018-01-03 11:47:54 +0000686 // Note, the relaxed loads below musn't reorder before the CompareAndSet.
Ian Rogersc7190692014-07-08 23:50:26 -0700687 // TODO: the ordering here is non-trivial as state is split across 3 fields, fix by placing
688 // a status bit into the state on contention.
Orion Hodson4557b382018-01-03 11:47:54 +0000689 done = state_.CompareAndSetWeakSequentiallyConsistent(-1 /* cur_state*/, 0 /* new state */);
Ian Rogersc7190692014-07-08 23:50:26 -0700690 if (LIKELY(done)) { // Weak CAS may fail spuriously.
Ian Rogers81d425b2012-09-27 16:03:43 -0700691 // Wake any waiters.
Orion Hodson88591fe2018-03-06 13:35:43 +0000692 if (UNLIKELY(num_pending_readers_.load(std::memory_order_relaxed) > 0 ||
693 num_pending_writers_.load(std::memory_order_relaxed) > 0)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700694 futex(state_.Address(), FUTEX_WAKE, -1, nullptr, nullptr, 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700695 }
696 }
697 } else {
698 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
699 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700700 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700701#else
Orion Hodson88591fe2018-03-06 13:35:43 +0000702 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700703 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700704#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700705}
706
Ian Rogers66aee5c2012-08-15 17:17:47 -0700707#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700708bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700709 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700710#if ART_USE_FUTEXES
711 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700712 timespec end_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800713 InitTimeSpec(true, CLOCK_MONOTONIC, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700714 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000715 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700716 if (cur_state == 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700717 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000718 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700719 } else {
720 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700721 timespec now_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800722 InitTimeSpec(true, CLOCK_MONOTONIC, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700723 timespec rel_ts;
724 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
725 return false; // Timed out.
726 }
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700727 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersc7190692014-07-08 23:50:26 -0700728 ++num_pending_writers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800729 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
730 self->CheckEmptyCheckpointFromMutex();
731 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700732 if (futex(state_.Address(), FUTEX_WAIT, cur_state, &rel_ts, nullptr, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700733 if (errno == ETIMEDOUT) {
Ian Rogersc7190692014-07-08 23:50:26 -0700734 --num_pending_writers_;
Ian Rogersc604d732012-10-14 16:09:54 -0700735 return false; // Timed out.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700736 } else if ((errno != EAGAIN) && (errno != EINTR)) {
737 // EAGAIN and EINTR both indicate a spurious failure,
738 // recompute the relative time out from now and try again.
739 // We don't use TEMP_FAILURE_RETRY so we can recompute rel_ts;
Ian Rogers81d425b2012-09-27 16:03:43 -0700740 PLOG(FATAL) << "timed futex wait failed for " << name_;
741 }
742 }
Ian Rogersc7190692014-07-08 23:50:26 -0700743 --num_pending_writers_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700744 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700745 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700746#else
Ian Rogersc604d732012-10-14 16:09:54 -0700747 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700748 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700749 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700750 if (result == ETIMEDOUT) {
751 return false;
752 }
753 if (result != 0) {
754 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700755 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700756 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700757#endif
Orion Hodson88591fe2018-03-06 13:35:43 +0000758 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700759 RegisterAsLocked(self);
760 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700761 return true;
762}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700763#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700764
Ian Rogers51d212e2014-10-23 17:48:20 -0700765#if ART_USE_FUTEXES
Ian Rogerscf7f1912014-10-22 22:06:39 -0700766void ReaderWriterMutex::HandleSharedLockContention(Thread* self, int32_t cur_state) {
767 // Owner holds it exclusively, hang up.
Roland Levillaincd72dc92018-02-27 19:15:31 +0000768 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogerscf7f1912014-10-22 22:06:39 -0700769 ++num_pending_readers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800770 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
771 self->CheckEmptyCheckpointFromMutex();
772 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700773 if (futex(state_.Address(), FUTEX_WAIT, cur_state, nullptr, nullptr, 0) != 0) {
Daniel Colascione6f4d1022016-11-21 14:35:42 -0800774 if (errno != EAGAIN && errno != EINTR) {
Ian Rogerscf7f1912014-10-22 22:06:39 -0700775 PLOG(FATAL) << "futex wait failed for " << name_;
776 }
777 }
778 --num_pending_readers_;
779}
Ian Rogers51d212e2014-10-23 17:48:20 -0700780#endif
Ian Rogerscf7f1912014-10-22 22:06:39 -0700781
Ian Rogers81d425b2012-09-27 16:03:43 -0700782bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700783 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700784#if ART_USE_FUTEXES
785 bool done = false;
786 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000787 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700788 if (cur_state >= 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700789 // Add as an extra reader and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000790 done = state_.CompareAndSetWeakAcquire(cur_state, cur_state + 1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700791 } else {
792 // Owner holds it exclusively.
793 return false;
794 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700795 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700796#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700797 int result = pthread_rwlock_tryrdlock(&rwlock_);
798 if (result == EBUSY) {
799 return false;
800 }
801 if (result != 0) {
802 errno = result;
803 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
804 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700805#endif
806 RegisterAsLocked(self);
807 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700808 return true;
809}
810
Ian Rogers81d425b2012-09-27 16:03:43 -0700811bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700812 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700813 bool result;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700814 if (UNLIKELY(self == nullptr)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700815 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700816 } else {
817 result = (self->GetHeldMutex(level_) == this);
818 }
819 return result;
820}
821
Ian Rogers56edc432013-01-18 16:51:51 -0800822void ReaderWriterMutex::Dump(std::ostream& os) const {
823 os << name_
824 << " level=" << static_cast<int>(level_)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700825 << " owner=" << GetExclusiveOwnerTid()
826#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000827 << " state=" << state_.load(std::memory_order_seq_cst)
828 << " num_pending_writers=" << num_pending_writers_.load(std::memory_order_seq_cst)
829 << " num_pending_readers=" << num_pending_readers_.load(std::memory_order_seq_cst)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700830#endif
831 << " ";
Ian Rogers56edc432013-01-18 16:51:51 -0800832 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700833}
834
835std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800836 mu.Dump(os);
837 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700838}
839
Yu Lieac44242015-06-29 10:50:03 +0800840std::ostream& operator<<(std::ostream& os, const MutatorMutex& mu) {
841 mu.Dump(os);
842 return os;
843}
844
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800845void ReaderWriterMutex::WakeupToRespondToEmptyCheckpoint() {
846#if ART_USE_FUTEXES
847 // Wake up all the waiters so they will respond to the emtpy checkpoint.
848 DCHECK(should_respond_to_empty_checkpoint_request_);
Orion Hodson88591fe2018-03-06 13:35:43 +0000849 if (UNLIKELY(num_pending_readers_.load(std::memory_order_relaxed) > 0 ||
850 num_pending_writers_.load(std::memory_order_relaxed) > 0)) {
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800851 futex(state_.Address(), FUTEX_WAKE, -1, nullptr, nullptr, 0);
852 }
853#else
854 LOG(FATAL) << "Non futex case isn't supported.";
855#endif
856}
857
Ian Rogers23055dc2013-04-18 16:29:16 -0700858ConditionVariable::ConditionVariable(const char* name, Mutex& guard)
Ian Rogersc604d732012-10-14 16:09:54 -0700859 : name_(name), guard_(guard) {
860#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000861 DCHECK_EQ(0, sequence_.load(std::memory_order_relaxed));
Ian Rogersc604d732012-10-14 16:09:54 -0700862 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700863#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000864 pthread_condattr_t cond_attrs;
Ian Rogersc5f17732014-06-05 20:48:42 -0700865 CHECK_MUTEX_CALL(pthread_condattr_init, (&cond_attrs));
Narayan Kamath51b71022014-03-04 11:57:09 +0000866#if !defined(__APPLE__)
867 // Apple doesn't have CLOCK_MONOTONIC or pthread_condattr_setclock.
Ian Rogers51d212e2014-10-23 17:48:20 -0700868 CHECK_MUTEX_CALL(pthread_condattr_setclock, (&cond_attrs, CLOCK_MONOTONIC));
Narayan Kamath51b71022014-03-04 11:57:09 +0000869#endif
870 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, &cond_attrs));
Ian Rogersc604d732012-10-14 16:09:54 -0700871#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700872}
873
874ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800875#if ART_USE_FUTEXES
876 if (num_waiters_!= 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700877 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
878 LOG(is_safe_to_call_abort ? FATAL : WARNING)
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700879 << "ConditionVariable::~ConditionVariable for " << name_
Ian Rogersd45f2012012-11-28 11:46:23 -0800880 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800881 }
882#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700883 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
884 // may still be using condition variables.
885 int rc = pthread_cond_destroy(&cond_);
886 if (rc != 0) {
887 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700888 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
889 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_cond_destroy failed for " << name_;
Elliott Hughese62934d2012-04-09 11:24:29 -0700890 }
Ian Rogersc604d732012-10-14 16:09:54 -0700891#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700892}
893
Ian Rogersc604d732012-10-14 16:09:54 -0700894void ConditionVariable::Broadcast(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700895 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700896 // TODO: enable below, there's a race in thread creation that causes false failures currently.
897 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700898 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700899#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800900 if (num_waiters_ > 0) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800901 sequence_++; // Indicate the broadcast occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700902 bool done = false;
903 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000904 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersd45f2012012-11-28 11:46:23 -0800905 // Requeue waiters onto mutex. The waiter holds the contender count on the mutex high ensuring
906 // mutex unlocks will awaken the requeued waiter thread.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800907 done = futex(sequence_.Address(), FUTEX_CMP_REQUEUE, 0,
Ian Rogers5bd97c42012-11-27 02:38:26 -0800908 reinterpret_cast<const timespec*>(std::numeric_limits<int32_t>::max()),
Ian Rogersc7190692014-07-08 23:50:26 -0700909 guard_.state_.Address(), cur_sequence) != -1;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800910 if (!done) {
Daniel Colascione6f4d1022016-11-21 14:35:42 -0800911 if (errno != EAGAIN && errno != EINTR) {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800912 PLOG(FATAL) << "futex cmp requeue failed for " << name_;
913 }
Ian Rogers5bd97c42012-11-27 02:38:26 -0800914 }
Ian Rogersc604d732012-10-14 16:09:54 -0700915 } while (!done);
916 }
917#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700918 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700919#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700920}
921
Ian Rogersc604d732012-10-14 16:09:54 -0700922void ConditionVariable::Signal(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700923 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700924 guard_.AssertExclusiveHeld(self);
925#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800926 if (num_waiters_ > 0) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800927 sequence_++; // Indicate a signal occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700928 // Futex wake 1 waiter who will then come and in contend on mutex. It'd be nice to requeue them
929 // to avoid this, however, requeueing can only move all waiters.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700930 int num_woken = futex(sequence_.Address(), FUTEX_WAKE, 1, nullptr, nullptr, 0);
Ian Rogersd45f2012012-11-28 11:46:23 -0800931 // Check something was woken or else we changed sequence_ before they had chance to wait.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800932 CHECK((num_woken == 0) || (num_woken == 1));
Ian Rogersc604d732012-10-14 16:09:54 -0700933 }
934#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700935 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700936#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700937}
938
Ian Rogersc604d732012-10-14 16:09:54 -0700939void ConditionVariable::Wait(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700940 guard_.CheckSafeToWait(self);
941 WaitHoldingLocks(self);
942}
943
944void ConditionVariable::WaitHoldingLocks(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700945 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700946 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700947 unsigned int old_recursion_count = guard_.recursion_count_;
948#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700949 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800950 // Ensure the Mutex is contended so that requeued threads are awoken.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800951 guard_.num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -0700952 guard_.recursion_count_ = 1;
Orion Hodson88591fe2018-03-06 13:35:43 +0000953 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700954 guard_.ExclusiveUnlock(self);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700955 if (futex(sequence_.Address(), FUTEX_WAIT, cur_sequence, nullptr, nullptr, 0) != 0) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800956 // Futex failed, check it is an expected error.
957 // EAGAIN == EWOULDBLK, so we let the caller try again.
958 // EINTR implies a signal was sent to this thread.
959 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700960 PLOG(FATAL) << "futex wait failed for " << name_;
961 }
962 }
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800963 if (self != nullptr) {
964 JNIEnvExt* const env = self->GetJniEnv();
Ian Rogers55256cb2017-12-21 17:07:11 -0800965 if (UNLIKELY(env != nullptr && env->IsRuntimeDeleted())) {
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800966 CHECK(self->IsDaemon());
967 // If the runtime has been deleted, then we cannot proceed. Just sleep forever. This may
968 // occur for user daemon threads that get a spurious wakeup. This occurs for test 132 with
969 // --host and --gdb.
970 // After we wake up, the runtime may have been shutdown, which means that this condition may
971 // have been deleted. It is not safe to retry the wait.
972 SleepForever();
973 }
974 }
Ian Rogersc604d732012-10-14 16:09:54 -0700975 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800976 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700977 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800978 // We awoke and so no longer require awakes from the guard_'s unlock.
Orion Hodson88591fe2018-03-06 13:35:43 +0000979 CHECK_GE(guard_.num_contenders_.load(std::memory_order_relaxed), 0);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800980 guard_.num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700981#else
Hans Boehm0882af22017-08-31 15:21:57 -0700982 pid_t old_owner = guard_.GetExclusiveOwnerTid();
Orion Hodson88591fe2018-03-06 13:35:43 +0000983 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700984 guard_.recursion_count_ = 0;
985 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
Orion Hodson88591fe2018-03-06 13:35:43 +0000986 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700987#endif
988 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700989}
990
Ian Rogers7b078e82014-09-10 14:44:24 -0700991bool ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700992 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers7b078e82014-09-10 14:44:24 -0700993 bool timed_out = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700994 guard_.AssertExclusiveHeld(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700995 guard_.CheckSafeToWait(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700996 unsigned int old_recursion_count = guard_.recursion_count_;
997#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700998 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800999 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -07001000 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -08001001 // Ensure the Mutex is contended so that requeued threads are awoken.
Ian Rogersb122a4b2013-11-19 18:00:50 -08001002 guard_.num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -07001003 guard_.recursion_count_ = 1;
Orion Hodson88591fe2018-03-06 13:35:43 +00001004 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -07001005 guard_.ExclusiveUnlock(self);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001006 if (futex(sequence_.Address(), FUTEX_WAIT, cur_sequence, &rel_ts, nullptr, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -07001007 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -08001008 // Timed out we're done.
Ian Rogers7b078e82014-09-10 14:44:24 -07001009 timed_out = true;
Brian Carlstrom0de79852013-07-25 22:29:58 -07001010 } else if ((errno == EAGAIN) || (errno == EINTR)) {
Ian Rogersd45f2012012-11-28 11:46:23 -08001011 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -07001012 } else {
1013 PLOG(FATAL) << "timed futex wait failed for " << name_;
1014 }
1015 }
1016 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -08001017 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -07001018 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -08001019 // We awoke and so no longer require awakes from the guard_'s unlock.
Orion Hodson88591fe2018-03-06 13:35:43 +00001020 CHECK_GE(guard_.num_contenders_.load(std::memory_order_relaxed), 0);
Ian Rogersb122a4b2013-11-19 18:00:50 -08001021 guard_.num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -07001022#else
Narayan Kamath51b71022014-03-04 11:57:09 +00001023#if !defined(__APPLE__)
Ian Rogersc604d732012-10-14 16:09:54 -07001024 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -07001025#else
Ian Rogersc604d732012-10-14 16:09:54 -07001026 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -07001027#endif
Hans Boehm0882af22017-08-31 15:21:57 -07001028 pid_t old_owner = guard_.GetExclusiveOwnerTid();
Orion Hodson88591fe2018-03-06 13:35:43 +00001029 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -07001030 guard_.recursion_count_ = 0;
1031 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -07001032 InitTimeSpec(true, clock, ms, ns, &ts);
Narayan Kamath51b71022014-03-04 11:57:09 +00001033 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &guard_.mutex_, &ts));
Ian Rogers7b078e82014-09-10 14:44:24 -07001034 if (rc == ETIMEDOUT) {
1035 timed_out = true;
1036 } else if (rc != 0) {
Elliott Hughes5f791332011-09-15 17:45:30 -07001037 errno = rc;
1038 PLOG(FATAL) << "TimedWait failed for " << name_;
1039 }
Orion Hodson88591fe2018-03-06 13:35:43 +00001040 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -07001041#endif
1042 guard_.recursion_count_ = old_recursion_count;
Ian Rogers7b078e82014-09-10 14:44:24 -07001043 return timed_out;
Elliott Hughes5f791332011-09-15 17:45:30 -07001044}
1045
Ian Rogers719d1a32014-03-06 12:13:39 -08001046void Locks::Init() {
1047 if (logging_lock_ != nullptr) {
1048 // Already initialized.
Vladimir Marko33bff252017-11-01 14:35:42 +00001049 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001050 DCHECK(modify_ldt_lock_ != nullptr);
1051 } else {
1052 DCHECK(modify_ldt_lock_ == nullptr);
1053 }
Ian Rogers719d1a32014-03-06 12:13:39 -08001054 DCHECK(abort_lock_ != nullptr);
Brian Carlstrom306db812014-09-05 13:01:41 -07001055 DCHECK(alloc_tracker_lock_ != nullptr);
Andreas Gampe74240812014-04-17 10:35:09 -07001056 DCHECK(allocated_monitor_ids_lock_ != nullptr);
Chao-ying Fu9e369312014-05-21 11:20:52 -07001057 DCHECK(allocated_thread_ids_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001058 DCHECK(breakpoint_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001059 DCHECK(classlinker_classes_lock_ != nullptr);
Brian Carlstrom306db812014-09-05 13:01:41 -07001060 DCHECK(deoptimization_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001061 DCHECK(heap_bitmap_lock_ != nullptr);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001062 DCHECK(oat_file_manager_lock_ != nullptr);
David Brazdilca3c8c32016-09-06 14:04:48 +01001063 DCHECK(verifier_deps_lock_ != nullptr);
Richard Uhlera206c742016-05-24 15:04:22 -07001064 DCHECK(host_dlopen_handles_lock_ != nullptr);
Brian Carlstrom306db812014-09-05 13:01:41 -07001065 DCHECK(intern_table_lock_ != nullptr);
Andreas Gampec8089542017-01-16 12:41:12 -08001066 DCHECK(jni_function_table_lock_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -07001067 DCHECK(jni_libraries_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001068 DCHECK(logging_lock_ != nullptr);
1069 DCHECK(mutator_lock_ != nullptr);
Brian Carlstrom306db812014-09-05 13:01:41 -07001070 DCHECK(profiler_lock_ != nullptr);
Mingyao Yang063fc772016-08-02 11:02:54 -07001071 DCHECK(cha_lock_ != nullptr);
Igor Murashkin495e7832017-10-27 10:56:20 -07001072 DCHECK(subtype_check_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001073 DCHECK(thread_list_lock_ != nullptr);
1074 DCHECK(thread_suspend_count_lock_ != nullptr);
1075 DCHECK(trace_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001076 DCHECK(unexpected_signal_lock_ != nullptr);
Alex Light88fd7202017-06-30 08:31:59 -07001077 DCHECK(user_code_suspension_lock_ != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08001078 DCHECK(dex_lock_ != nullptr);
David Srbeckyfb3de3d2018-01-29 16:11:49 +00001079 DCHECK(native_debug_interface_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001080 } else {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001081 // Create global locks in level order from highest lock level to lowest.
Ian Rogers4ad5cd32014-11-11 23:08:07 -08001082 LockLevel current_lock_level = kInstrumentEntrypointsLock;
1083 DCHECK(instrument_entrypoints_lock_ == nullptr);
1084 instrument_entrypoints_lock_ = new Mutex("instrument entrypoint lock", current_lock_level);
Ian Rogers719d1a32014-03-06 12:13:39 -08001085
Chao-ying Fu9e369312014-05-21 11:20:52 -07001086 #define UPDATE_CURRENT_LOCK_LEVEL(new_level) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001087 if ((new_level) >= current_lock_level) { \
Brian Carlstrom306db812014-09-05 13:01:41 -07001088 /* Do not use CHECKs or FATAL here, abort_lock_ is not setup yet. */ \
1089 fprintf(stderr, "New local level %d is not less than current level %d\n", \
1090 new_level, current_lock_level); \
1091 exit(1); \
1092 } \
Ian Rogersf3d874c2014-07-17 18:52:42 -07001093 current_lock_level = new_level;
1094
Alex Light88fd7202017-06-30 08:31:59 -07001095 UPDATE_CURRENT_LOCK_LEVEL(kUserCodeSuspensionLock);
1096 DCHECK(user_code_suspension_lock_ == nullptr);
1097 user_code_suspension_lock_ = new Mutex("user code suspension lock", current_lock_level);
1098
Ian Rogersf3d874c2014-07-17 18:52:42 -07001099 UPDATE_CURRENT_LOCK_LEVEL(kMutatorLock);
1100 DCHECK(mutator_lock_ == nullptr);
Yu Lieac44242015-06-29 10:50:03 +08001101 mutator_lock_ = new MutatorMutex("mutator lock", current_lock_level);
Chao-ying Fu9e369312014-05-21 11:20:52 -07001102
1103 UPDATE_CURRENT_LOCK_LEVEL(kHeapBitmapLock);
1104 DCHECK(heap_bitmap_lock_ == nullptr);
1105 heap_bitmap_lock_ = new ReaderWriterMutex("heap bitmap lock", current_lock_level);
1106
Jeff Hao69dbec62014-09-15 18:03:41 -07001107 UPDATE_CURRENT_LOCK_LEVEL(kTraceLock);
1108 DCHECK(trace_lock_ == nullptr);
1109 trace_lock_ = new Mutex("trace lock", current_lock_level);
1110
Chao-ying Fu9e369312014-05-21 11:20:52 -07001111 UPDATE_CURRENT_LOCK_LEVEL(kRuntimeShutdownLock);
1112 DCHECK(runtime_shutdown_lock_ == nullptr);
1113 runtime_shutdown_lock_ = new Mutex("runtime shutdown lock", current_lock_level);
1114
1115 UPDATE_CURRENT_LOCK_LEVEL(kProfilerLock);
1116 DCHECK(profiler_lock_ == nullptr);
1117 profiler_lock_ = new Mutex("profiler lock", current_lock_level);
1118
Brian Carlstrom306db812014-09-05 13:01:41 -07001119 UPDATE_CURRENT_LOCK_LEVEL(kDeoptimizationLock);
1120 DCHECK(deoptimization_lock_ == nullptr);
1121 deoptimization_lock_ = new Mutex("Deoptimization lock", current_lock_level);
1122
1123 UPDATE_CURRENT_LOCK_LEVEL(kAllocTrackerLock);
1124 DCHECK(alloc_tracker_lock_ == nullptr);
1125 alloc_tracker_lock_ = new Mutex("AllocTracker lock", current_lock_level);
1126
Chao-ying Fu9e369312014-05-21 11:20:52 -07001127 UPDATE_CURRENT_LOCK_LEVEL(kThreadListLock);
1128 DCHECK(thread_list_lock_ == nullptr);
1129 thread_list_lock_ = new Mutex("thread list lock", current_lock_level);
1130
Ian Rogers68d8b422014-07-17 11:09:10 -07001131 UPDATE_CURRENT_LOCK_LEVEL(kJniLoadLibraryLock);
1132 DCHECK(jni_libraries_lock_ == nullptr);
1133 jni_libraries_lock_ = new Mutex("JNI shared libraries map lock", current_lock_level);
1134
Chao-ying Fu9e369312014-05-21 11:20:52 -07001135 UPDATE_CURRENT_LOCK_LEVEL(kBreakpointLock);
Ian Rogers719d1a32014-03-06 12:13:39 -08001136 DCHECK(breakpoint_lock_ == nullptr);
Sebastien Hertzed2be172014-08-19 15:33:43 +02001137 breakpoint_lock_ = new ReaderWriterMutex("breakpoint lock", current_lock_level);
Chao-ying Fu9e369312014-05-21 11:20:52 -07001138
Igor Murashkin495e7832017-10-27 10:56:20 -07001139 UPDATE_CURRENT_LOCK_LEVEL(kSubtypeCheckLock);
1140 DCHECK(subtype_check_lock_ == nullptr);
1141 subtype_check_lock_ = new Mutex("SubtypeCheck lock", current_lock_level);
1142
Mingyao Yang063fc772016-08-02 11:02:54 -07001143 UPDATE_CURRENT_LOCK_LEVEL(kCHALock);
1144 DCHECK(cha_lock_ == nullptr);
1145 cha_lock_ = new Mutex("CHA lock", current_lock_level);
1146
Chao-ying Fu9e369312014-05-21 11:20:52 -07001147 UPDATE_CURRENT_LOCK_LEVEL(kClassLinkerClassesLock);
Ian Rogers719d1a32014-03-06 12:13:39 -08001148 DCHECK(classlinker_classes_lock_ == nullptr);
1149 classlinker_classes_lock_ = new ReaderWriterMutex("ClassLinker classes lock",
Chao-ying Fu9e369312014-05-21 11:20:52 -07001150 current_lock_level);
1151
Andreas Gampe74240812014-04-17 10:35:09 -07001152 UPDATE_CURRENT_LOCK_LEVEL(kMonitorPoolLock);
1153 DCHECK(allocated_monitor_ids_lock_ == nullptr);
1154 allocated_monitor_ids_lock_ = new Mutex("allocated monitor ids lock", current_lock_level);
1155
Chao-ying Fu9e369312014-05-21 11:20:52 -07001156 UPDATE_CURRENT_LOCK_LEVEL(kAllocatedThreadIdsLock);
1157 DCHECK(allocated_thread_ids_lock_ == nullptr);
1158 allocated_thread_ids_lock_ = new Mutex("allocated thread ids lock", current_lock_level);
1159
Vladimir Marko33bff252017-11-01 14:35:42 +00001160 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001161 UPDATE_CURRENT_LOCK_LEVEL(kModifyLdtLock);
1162 DCHECK(modify_ldt_lock_ == nullptr);
1163 modify_ldt_lock_ = new Mutex("modify_ldt lock", current_lock_level);
1164 }
1165
Andreas Gampecc1b5352016-12-01 16:58:38 -08001166 UPDATE_CURRENT_LOCK_LEVEL(kDexLock);
1167 DCHECK(dex_lock_ == nullptr);
1168 dex_lock_ = new ReaderWriterMutex("ClassLinker dex lock", current_lock_level);
1169
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001170 UPDATE_CURRENT_LOCK_LEVEL(kOatFileManagerLock);
1171 DCHECK(oat_file_manager_lock_ == nullptr);
1172 oat_file_manager_lock_ = new ReaderWriterMutex("OatFile manager lock", current_lock_level);
1173
David Brazdilca3c8c32016-09-06 14:04:48 +01001174 UPDATE_CURRENT_LOCK_LEVEL(kVerifierDepsLock);
1175 DCHECK(verifier_deps_lock_ == nullptr);
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001176 verifier_deps_lock_ = new ReaderWriterMutex("verifier deps lock", current_lock_level);
David Brazdilca3c8c32016-09-06 14:04:48 +01001177
Richard Uhlera206c742016-05-24 15:04:22 -07001178 UPDATE_CURRENT_LOCK_LEVEL(kHostDlOpenHandlesLock);
1179 DCHECK(host_dlopen_handles_lock_ == nullptr);
1180 host_dlopen_handles_lock_ = new Mutex("host dlopen handles lock", current_lock_level);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07001181
Chao-ying Fu9e369312014-05-21 11:20:52 -07001182 UPDATE_CURRENT_LOCK_LEVEL(kInternTableLock);
Ian Rogers719d1a32014-03-06 12:13:39 -08001183 DCHECK(intern_table_lock_ == nullptr);
Chao-ying Fu9e369312014-05-21 11:20:52 -07001184 intern_table_lock_ = new Mutex("InternTable lock", current_lock_level);
1185
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -07001186 UPDATE_CURRENT_LOCK_LEVEL(kReferenceProcessorLock);
1187 DCHECK(reference_processor_lock_ == nullptr);
1188 reference_processor_lock_ = new Mutex("ReferenceProcessor lock", current_lock_level);
1189
1190 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueueClearedReferencesLock);
1191 DCHECK(reference_queue_cleared_references_lock_ == nullptr);
1192 reference_queue_cleared_references_lock_ = new Mutex("ReferenceQueue cleared references lock", current_lock_level);
1193
1194 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueueWeakReferencesLock);
1195 DCHECK(reference_queue_weak_references_lock_ == nullptr);
1196 reference_queue_weak_references_lock_ = new Mutex("ReferenceQueue cleared references lock", current_lock_level);
1197
1198 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueueFinalizerReferencesLock);
1199 DCHECK(reference_queue_finalizer_references_lock_ == nullptr);
1200 reference_queue_finalizer_references_lock_ = new Mutex("ReferenceQueue finalizer references lock", current_lock_level);
1201
1202 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueuePhantomReferencesLock);
1203 DCHECK(reference_queue_phantom_references_lock_ == nullptr);
1204 reference_queue_phantom_references_lock_ = new Mutex("ReferenceQueue phantom references lock", current_lock_level);
1205
1206 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueueSoftReferencesLock);
1207 DCHECK(reference_queue_soft_references_lock_ == nullptr);
1208 reference_queue_soft_references_lock_ = new Mutex("ReferenceQueue soft references lock", current_lock_level);
1209
Andreas Gampe05a364c2016-10-14 13:27:12 -07001210 UPDATE_CURRENT_LOCK_LEVEL(kJniGlobalsLock);
1211 DCHECK(jni_globals_lock_ == nullptr);
1212 jni_globals_lock_ =
1213 new ReaderWriterMutex("JNI global reference table lock", current_lock_level);
1214
1215 UPDATE_CURRENT_LOCK_LEVEL(kJniWeakGlobalsLock);
1216 DCHECK(jni_weak_globals_lock_ == nullptr);
1217 jni_weak_globals_lock_ = new Mutex("JNI weak global reference table lock", current_lock_level);
1218
Andreas Gampec8089542017-01-16 12:41:12 -08001219 UPDATE_CURRENT_LOCK_LEVEL(kJniFunctionTableLock);
1220 DCHECK(jni_function_table_lock_ == nullptr);
1221 jni_function_table_lock_ = new Mutex("JNI function table lock", current_lock_level);
1222
David Srbecky440a9b32018-02-15 17:47:29 +00001223 UPDATE_CURRENT_LOCK_LEVEL(kNativeDebugInterfaceLock);
1224 DCHECK(native_debug_interface_lock_ == nullptr);
1225 native_debug_interface_lock_ = new Mutex("Native debug interface lock", current_lock_level);
1226
Chao-ying Fu9e369312014-05-21 11:20:52 -07001227 UPDATE_CURRENT_LOCK_LEVEL(kAbortLock);
1228 DCHECK(abort_lock_ == nullptr);
1229 abort_lock_ = new Mutex("abort lock", current_lock_level, true);
1230
1231 UPDATE_CURRENT_LOCK_LEVEL(kThreadSuspendCountLock);
1232 DCHECK(thread_suspend_count_lock_ == nullptr);
1233 thread_suspend_count_lock_ = new Mutex("thread suspend count lock", current_lock_level);
1234
1235 UPDATE_CURRENT_LOCK_LEVEL(kUnexpectedSignalLock);
1236 DCHECK(unexpected_signal_lock_ == nullptr);
1237 unexpected_signal_lock_ = new Mutex("unexpected signal lock", current_lock_level, true);
1238
1239 UPDATE_CURRENT_LOCK_LEVEL(kLoggingLock);
1240 DCHECK(logging_lock_ == nullptr);
1241 logging_lock_ = new Mutex("logging lock", current_lock_level, true);
1242
1243 #undef UPDATE_CURRENT_LOCK_LEVEL
Mathieu Chartier91e56692015-03-03 13:51:04 -08001244
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001245 // List of mutexes that we may hold when accessing a weak ref.
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -08001246 AddToExpectedMutexesOnWeakRefAccess(dex_lock_, /*need_lock*/ false);
1247 AddToExpectedMutexesOnWeakRefAccess(classlinker_classes_lock_, /*need_lock*/ false);
1248 AddToExpectedMutexesOnWeakRefAccess(jni_libraries_lock_, /*need_lock*/ false);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001249
Mathieu Chartier91e56692015-03-03 13:51:04 -08001250 InitConditions();
Ian Rogers719d1a32014-03-06 12:13:39 -08001251 }
1252}
1253
Mathieu Chartier91e56692015-03-03 13:51:04 -08001254void Locks::InitConditions() {
1255 thread_exit_cond_ = new ConditionVariable("thread exit condition variable", *thread_list_lock_);
1256}
Ian Rogers719d1a32014-03-06 12:13:39 -08001257
David Sehrf42eb2c2016-10-19 13:20:45 -07001258void Locks::SetClientCallback(ClientCallback* safe_to_call_abort_cb) {
Orion Hodson88591fe2018-03-06 13:35:43 +00001259 safe_to_call_abort_callback.store(safe_to_call_abort_cb, std::memory_order_release);
David Sehrf42eb2c2016-10-19 13:20:45 -07001260}
1261
1262// Helper to allow checking shutdown while ignoring locking requirements.
1263bool Locks::IsSafeToCallAbortRacy() {
Orion Hodson88591fe2018-03-06 13:35:43 +00001264 Locks::ClientCallback* safe_to_call_abort_cb =
1265 safe_to_call_abort_callback.load(std::memory_order_acquire);
David Sehrf42eb2c2016-10-19 13:20:45 -07001266 return safe_to_call_abort_cb != nullptr && safe_to_call_abort_cb();
1267}
1268
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -08001269void Locks::AddToExpectedMutexesOnWeakRefAccess(BaseMutex* mutex, bool need_lock) {
1270 if (need_lock) {
1271 ScopedExpectedMutexesOnWeakRefAccessLock mu(mutex);
1272 mutex->SetShouldRespondToEmptyCheckpointRequest(true);
1273 expected_mutexes_on_weak_ref_access_.push_back(mutex);
1274 } else {
1275 mutex->SetShouldRespondToEmptyCheckpointRequest(true);
1276 expected_mutexes_on_weak_ref_access_.push_back(mutex);
1277 }
1278}
1279
1280void Locks::RemoveFromExpectedMutexesOnWeakRefAccess(BaseMutex* mutex, bool need_lock) {
1281 if (need_lock) {
1282 ScopedExpectedMutexesOnWeakRefAccessLock mu(mutex);
1283 mutex->SetShouldRespondToEmptyCheckpointRequest(false);
1284 std::vector<BaseMutex*>& list = expected_mutexes_on_weak_ref_access_;
1285 auto it = std::find(list.begin(), list.end(), mutex);
1286 DCHECK(it != list.end());
1287 list.erase(it);
1288 } else {
1289 mutex->SetShouldRespondToEmptyCheckpointRequest(false);
1290 std::vector<BaseMutex*>& list = expected_mutexes_on_weak_ref_access_;
1291 auto it = std::find(list.begin(), list.end(), mutex);
1292 DCHECK(it != list.end());
1293 list.erase(it);
1294 }
1295}
1296
1297bool Locks::IsExpectedOnWeakRefAccess(BaseMutex* mutex) {
1298 ScopedExpectedMutexesOnWeakRefAccessLock mu(mutex);
1299 std::vector<BaseMutex*>& list = expected_mutexes_on_weak_ref_access_;
1300 return std::find(list.begin(), list.end(), mutex) != list.end();
1301}
1302
Elliott Hughese62934d2012-04-09 11:24:29 -07001303} // namespace art