blob: dd58d75a32d3c46b57e43762c3ff4345c35b936a [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;
Alex Light184f0752018-07-13 11:18:22 -070045Mutex* Locks::custom_tls_lock_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -070046Mutex* Locks::deoptimization_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080047ReaderWriterMutex* Locks::heap_bitmap_lock_ = nullptr;
Mathieu Chartier9ef78b52014-09-25 17:03:12 -070048Mutex* Locks::instrument_entrypoints_lock_ = nullptr;
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -070049Mutex* Locks::intern_table_lock_ = nullptr;
Andreas Gampec8089542017-01-16 12:41:12 -080050Mutex* Locks::jni_function_table_lock_ = nullptr;
Ian Rogers68d8b422014-07-17 11:09:10 -070051Mutex* Locks::jni_libraries_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080052Mutex* Locks::logging_lock_ = nullptr;
Chao-ying Fu9e369312014-05-21 11:20:52 -070053Mutex* Locks::modify_ldt_lock_ = nullptr;
Yu Lieac44242015-06-29 10:50:03 +080054MutatorMutex* Locks::mutator_lock_ = nullptr;
Brian Carlstrom306db812014-09-05 13:01:41 -070055Mutex* Locks::profiler_lock_ = nullptr;
Nicolas Geoffray340dafa2016-11-18 16:03:10 +000056ReaderWriterMutex* Locks::verifier_deps_lock_ = nullptr;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070057ReaderWriterMutex* Locks::oat_file_manager_lock_ = nullptr;
Richard Uhlera206c742016-05-24 15:04:22 -070058Mutex* Locks::host_dlopen_handles_lock_ = nullptr;
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -070059Mutex* Locks::reference_processor_lock_ = nullptr;
60Mutex* Locks::reference_queue_cleared_references_lock_ = nullptr;
61Mutex* Locks::reference_queue_finalizer_references_lock_ = nullptr;
62Mutex* Locks::reference_queue_phantom_references_lock_ = nullptr;
63Mutex* Locks::reference_queue_soft_references_lock_ = nullptr;
64Mutex* Locks::reference_queue_weak_references_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080065Mutex* Locks::runtime_shutdown_lock_ = nullptr;
Mingyao Yang063fc772016-08-02 11:02:54 -070066Mutex* Locks::cha_lock_ = nullptr;
Igor Murashkin495e7832017-10-27 10:56:20 -070067Mutex* Locks::subtype_check_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080068Mutex* Locks::thread_list_lock_ = nullptr;
Mathieu Chartier91e56692015-03-03 13:51:04 -080069ConditionVariable* Locks::thread_exit_cond_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080070Mutex* Locks::thread_suspend_count_lock_ = nullptr;
71Mutex* Locks::trace_lock_ = nullptr;
Ian Rogers719d1a32014-03-06 12:13:39 -080072Mutex* Locks::unexpected_signal_lock_ = nullptr;
Alex Light88fd7202017-06-30 08:31:59 -070073Mutex* Locks::user_code_suspension_lock_ = nullptr;
Andreas Gampe5bdb6552015-07-22 23:44:55 -070074Uninterruptible Roles::uninterruptible_;
Andreas Gampe05a364c2016-10-14 13:27:12 -070075ReaderWriterMutex* Locks::jni_globals_lock_ = nullptr;
76Mutex* Locks::jni_weak_globals_lock_ = nullptr;
Andreas Gampecc1b5352016-12-01 16:58:38 -080077ReaderWriterMutex* Locks::dex_lock_ = nullptr;
David Srbeckyfb3de3d2018-01-29 16:11:49 +000078Mutex* Locks::native_debug_interface_lock_ = nullptr;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -080079std::vector<BaseMutex*> Locks::expected_mutexes_on_weak_ref_access_;
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -080080Atomic<const BaseMutex*> Locks::expected_mutexes_on_weak_ref_access_guard_;
Ian Rogers719d1a32014-03-06 12:13:39 -080081
82struct AllMutexData {
83 // A guard for all_mutexes_ that's not a mutex (Mutexes must CAS to acquire and busy wait).
84 Atomic<const BaseMutex*> all_mutexes_guard;
85 // All created mutexes guarded by all_mutexes_guard_.
86 std::set<BaseMutex*>* all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -070087 AllMutexData() : all_mutexes(nullptr) {}
Ian Rogers719d1a32014-03-06 12:13:39 -080088};
89static struct AllMutexData gAllMutexData[kAllMutexDataSize];
90
Ian Rogersc604d732012-10-14 16:09:54 -070091#if ART_USE_FUTEXES
92static bool ComputeRelativeTimeSpec(timespec* result_ts, const timespec& lhs, const timespec& rhs) {
Brian Carlstromfb6996f2013-07-18 18:21:14 -070093 const int32_t one_sec = 1000 * 1000 * 1000; // one second in nanoseconds.
Ian Rogersc604d732012-10-14 16:09:54 -070094 result_ts->tv_sec = lhs.tv_sec - rhs.tv_sec;
95 result_ts->tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
96 if (result_ts->tv_nsec < 0) {
97 result_ts->tv_sec--;
98 result_ts->tv_nsec += one_sec;
99 } else if (result_ts->tv_nsec > one_sec) {
100 result_ts->tv_sec++;
101 result_ts->tv_nsec -= one_sec;
102 }
103 return result_ts->tv_sec < 0;
104}
105#endif
106
Hans Boehmae915a02017-12-12 11:05:32 -0800107// Wait for an amount of time that roughly increases in the argument i.
108// Spin for small arguments and yield/sleep for longer ones.
109static void BackOff(uint32_t i) {
110 static constexpr uint32_t kSpinMax = 10;
111 static constexpr uint32_t kYieldMax = 20;
112 if (i <= kSpinMax) {
113 // TODO: Esp. in very latency-sensitive cases, consider replacing this with an explicit
114 // test-and-test-and-set loop in the caller. Possibly skip entirely on a uniprocessor.
115 volatile uint32_t x = 0;
116 const uint32_t spin_count = 10 * i;
117 for (uint32_t spin = 0; spin < spin_count; ++spin) {
118 ++x; // Volatile; hence should not be optimized away.
119 }
120 // TODO: Consider adding x86 PAUSE and/or ARM YIELD here.
121 } else if (i <= kYieldMax) {
122 sched_yield();
123 } else {
124 NanoSleep(1000ull * (i - kYieldMax));
125 }
126}
127
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700128class ScopedAllMutexesLock FINAL {
Ian Rogers56edc432013-01-18 16:51:51 -0800129 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700130 explicit ScopedAllMutexesLock(const BaseMutex* mutex) : mutex_(mutex) {
Hans Boehmae915a02017-12-12 11:05:32 -0800131 for (uint32_t i = 0;
Orion Hodson88591fe2018-03-06 13:35:43 +0000132 !gAllMutexData->all_mutexes_guard.CompareAndSetWeakAcquire(nullptr, mutex);
Hans Boehmae915a02017-12-12 11:05:32 -0800133 ++i) {
134 BackOff(i);
Ian Rogers56edc432013-01-18 16:51:51 -0800135 }
136 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700137
Ian Rogers56edc432013-01-18 16:51:51 -0800138 ~ScopedAllMutexesLock() {
Orion Hodson88591fe2018-03-06 13:35:43 +0000139 DCHECK_EQ(gAllMutexData->all_mutexes_guard.load(std::memory_order_relaxed), mutex_);
140 gAllMutexData->all_mutexes_guard.store(nullptr, std::memory_order_release);
Ian Rogers56edc432013-01-18 16:51:51 -0800141 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700142
Ian Rogers56edc432013-01-18 16:51:51 -0800143 private:
144 const BaseMutex* const mutex_;
145};
Ian Rogers56edc432013-01-18 16:51:51 -0800146
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -0800147class Locks::ScopedExpectedMutexesOnWeakRefAccessLock FINAL {
148 public:
149 explicit ScopedExpectedMutexesOnWeakRefAccessLock(const BaseMutex* mutex) : mutex_(mutex) {
Hans Boehmae915a02017-12-12 11:05:32 -0800150 for (uint32_t i = 0;
Orion Hodson88591fe2018-03-06 13:35:43 +0000151 !Locks::expected_mutexes_on_weak_ref_access_guard_.CompareAndSetWeakAcquire(nullptr,
152 mutex);
Hans Boehmae915a02017-12-12 11:05:32 -0800153 ++i) {
154 BackOff(i);
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -0800155 }
156 }
157
158 ~ScopedExpectedMutexesOnWeakRefAccessLock() {
Orion Hodson88591fe2018-03-06 13:35:43 +0000159 DCHECK_EQ(Locks::expected_mutexes_on_weak_ref_access_guard_.load(std::memory_order_relaxed),
160 mutex_);
161 Locks::expected_mutexes_on_weak_ref_access_guard_.store(nullptr, std::memory_order_release);
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -0800162 }
163
164 private:
165 const BaseMutex* const mutex_;
166};
167
Ian Rogerscf7f1912014-10-22 22:06:39 -0700168// Scoped class that generates events at the beginning and end of lock contention.
169class ScopedContentionRecorder FINAL : public ValueObject {
170 public:
171 ScopedContentionRecorder(BaseMutex* mutex, uint64_t blocked_tid, uint64_t owner_tid)
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700172 : mutex_(kLogLockContentions ? mutex : nullptr),
Ian Rogerscf7f1912014-10-22 22:06:39 -0700173 blocked_tid_(kLogLockContentions ? blocked_tid : 0),
174 owner_tid_(kLogLockContentions ? owner_tid : 0),
175 start_nano_time_(kLogLockContentions ? NanoTime() : 0) {
176 if (ATRACE_ENABLED()) {
177 std::string msg = StringPrintf("Lock contention on %s (owner tid: %" PRIu64 ")",
178 mutex->GetName(), owner_tid);
179 ATRACE_BEGIN(msg.c_str());
180 }
181 }
182
183 ~ScopedContentionRecorder() {
184 ATRACE_END();
185 if (kLogLockContentions) {
186 uint64_t end_nano_time = NanoTime();
187 mutex_->RecordContention(blocked_tid_, owner_tid_, end_nano_time - start_nano_time_);
188 }
189 }
190
191 private:
192 BaseMutex* const mutex_;
193 const uint64_t blocked_tid_;
194 const uint64_t owner_tid_;
195 const uint64_t start_nano_time_;
196};
197
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800198BaseMutex::BaseMutex(const char* name, LockLevel level)
Andreas Gampe5db8b7b2018-05-08 16:10:59 -0700199 : name_(name),
200 level_(level),
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800201 should_respond_to_empty_checkpoint_request_(false) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700202 if (kLogLockContentions) {
203 ScopedAllMutexesLock mu(this);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700204 std::set<BaseMutex*>** all_mutexes_ptr = &gAllMutexData->all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700205 if (*all_mutexes_ptr == nullptr) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700206 // We leak the global set of all mutexes to avoid ordering issues in global variable
207 // construction/destruction.
208 *all_mutexes_ptr = new std::set<BaseMutex*>();
209 }
210 (*all_mutexes_ptr)->insert(this);
Ian Rogers56edc432013-01-18 16:51:51 -0800211 }
Ian Rogers56edc432013-01-18 16:51:51 -0800212}
213
214BaseMutex::~BaseMutex() {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700215 if (kLogLockContentions) {
216 ScopedAllMutexesLock mu(this);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700217 gAllMutexData->all_mutexes->erase(this);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700218 }
Ian Rogers56edc432013-01-18 16:51:51 -0800219}
220
221void BaseMutex::DumpAll(std::ostream& os) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700222 if (kLogLockContentions) {
223 os << "Mutex logging:\n";
224 ScopedAllMutexesLock mu(reinterpret_cast<const BaseMutex*>(-1));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700225 std::set<BaseMutex*>* all_mutexes = gAllMutexData->all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700226 if (all_mutexes == nullptr) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700227 // No mutexes have been created yet during at startup.
228 return;
229 }
230 typedef std::set<BaseMutex*>::const_iterator It;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700231 os << "(Contended)\n";
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700232 for (It it = all_mutexes->begin(); it != all_mutexes->end(); ++it) {
233 BaseMutex* mutex = *it;
234 if (mutex->HasEverContended()) {
235 mutex->Dump(os);
236 os << "\n";
237 }
238 }
239 os << "(Never contented)\n";
240 for (It it = all_mutexes->begin(); it != all_mutexes->end(); ++it) {
241 BaseMutex* mutex = *it;
242 if (!mutex->HasEverContended()) {
243 mutex->Dump(os);
244 os << "\n";
245 }
246 }
Ian Rogers56edc432013-01-18 16:51:51 -0800247 }
Ian Rogers56edc432013-01-18 16:51:51 -0800248}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700249
Ian Rogers81d425b2012-09-27 16:03:43 -0700250void BaseMutex::CheckSafeToWait(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700251 if (self == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700252 CheckUnattachedThread(level_);
253 return;
254 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700255 if (kDebugLocking) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700256 CHECK(self->GetHeldMutex(level_) == this || level_ == kMonitorLock)
257 << "Waiting on unacquired mutex: " << name_;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700258 bool bad_mutexes_held = false;
Elliott Hughes0f827162013-02-26 12:12:58 -0800259 for (int i = kLockLevelCount - 1; i >= 0; --i) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700260 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700261 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Alex Light79400aa2017-07-18 15:34:21 -0700262 // We allow the thread to wait even if the user_code_suspension_lock_ is held so long as we
263 // are some thread's resume_cond_ (level_ == kThreadSuspendCountLock). This just means that
264 // gc or some other internal process is suspending the thread while it is trying to suspend
265 // some other thread. So long as the current thread is not being suspended by a
266 // SuspendReason::kForUserCode (which needs the user_code_suspension_lock_ to clear) this is
267 // fine.
268 if (held_mutex == Locks::user_code_suspension_lock_ && level_ == kThreadSuspendCountLock) {
269 // No thread safety analysis is fine since we have both the user_code_suspension_lock_
270 // from the line above and the ThreadSuspendCountLock since it is our level_. We use this
271 // lambda to avoid having to annotate the whole function as NO_THREAD_SAFETY_ANALYSIS.
272 auto is_suspending_for_user_code = [self]() NO_THREAD_SAFETY_ANALYSIS {
273 return self->GetUserCodeSuspendCount() != 0;
274 };
275 if (is_suspending_for_user_code()) {
276 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
277 << "(level " << LockLevel(i) << ") while performing wait on "
278 << "\"" << name_ << "\" (level " << level_ << ") "
279 << "with SuspendReason::kForUserCode pending suspensions";
280 bad_mutexes_held = true;
281 }
282 } else if (held_mutex != nullptr) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800283 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
284 << "(level " << LockLevel(i) << ") while performing wait on "
285 << "\"" << name_ << "\" (level " << level_ << ")";
Ian Rogers25fd14b2012-09-05 10:56:38 -0700286 bad_mutexes_held = true;
287 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700288 }
289 }
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000290 if (gAborting == 0) { // Avoid recursive aborts.
Alex Light79400aa2017-07-18 15:34:21 -0700291 CHECK(!bad_mutexes_held) << this;
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000292 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700293 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700294}
295
Ian Rogers37f3c962014-07-17 11:25:30 -0700296void BaseMutex::ContentionLogData::AddToWaitTime(uint64_t value) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700297 if (kLogLockContentions) {
298 // Atomically add value to wait_time.
Orion Hodson88591fe2018-03-06 13:35:43 +0000299 wait_time.fetch_add(value, std::memory_order_seq_cst);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700300 }
301}
302
Brian Carlstrom0de79852013-07-25 22:29:58 -0700303void BaseMutex::RecordContention(uint64_t blocked_tid,
304 uint64_t owner_tid,
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700305 uint64_t nano_time_blocked) {
306 if (kLogLockContentions) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700307 ContentionLogData* data = contention_log_data_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700308 ++(data->contention_count);
309 data->AddToWaitTime(nano_time_blocked);
310 ContentionLogEntry* log = data->contention_log;
311 // This code is intentionally racy as it is only used for diagnostics.
Orion Hodson88591fe2018-03-06 13:35:43 +0000312 int32_t slot = data->cur_content_log_entry.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700313 if (log[slot].blocked_tid == blocked_tid &&
314 log[slot].owner_tid == blocked_tid) {
315 ++log[slot].count;
316 } else {
317 uint32_t new_slot;
318 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000319 slot = data->cur_content_log_entry.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700320 new_slot = (slot + 1) % kContentionLogSize;
Orion Hodson4557b382018-01-03 11:47:54 +0000321 } while (!data->cur_content_log_entry.CompareAndSetWeakRelaxed(slot, new_slot));
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700322 log[new_slot].blocked_tid = blocked_tid;
323 log[new_slot].owner_tid = owner_tid;
Orion Hodson88591fe2018-03-06 13:35:43 +0000324 log[new_slot].count.store(1, std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700325 }
Ian Rogers56edc432013-01-18 16:51:51 -0800326 }
Ian Rogers56edc432013-01-18 16:51:51 -0800327}
328
Ian Rogers56edc432013-01-18 16:51:51 -0800329void BaseMutex::DumpContention(std::ostream& os) const {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700330 if (kLogLockContentions) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700331 const ContentionLogData* data = contention_log_data_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700332 const ContentionLogEntry* log = data->contention_log;
Orion Hodson88591fe2018-03-06 13:35:43 +0000333 uint64_t wait_time = data->wait_time.load(std::memory_order_relaxed);
334 uint32_t contention_count = data->contention_count.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700335 if (contention_count == 0) {
336 os << "never contended";
337 } else {
338 os << "contended " << contention_count
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700339 << " total wait of contender " << PrettyDuration(wait_time)
340 << " average " << PrettyDuration(wait_time / contention_count);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700341 SafeMap<uint64_t, size_t> most_common_blocker;
342 SafeMap<uint64_t, size_t> most_common_blocked;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700343 for (size_t i = 0; i < kContentionLogSize; ++i) {
344 uint64_t blocked_tid = log[i].blocked_tid;
345 uint64_t owner_tid = log[i].owner_tid;
Orion Hodson88591fe2018-03-06 13:35:43 +0000346 uint32_t count = log[i].count.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700347 if (count > 0) {
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700348 auto it = most_common_blocked.find(blocked_tid);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700349 if (it != most_common_blocked.end()) {
350 most_common_blocked.Overwrite(blocked_tid, it->second + count);
351 } else {
352 most_common_blocked.Put(blocked_tid, count);
353 }
354 it = most_common_blocker.find(owner_tid);
355 if (it != most_common_blocker.end()) {
356 most_common_blocker.Overwrite(owner_tid, it->second + count);
357 } else {
358 most_common_blocker.Put(owner_tid, count);
359 }
Ian Rogers56edc432013-01-18 16:51:51 -0800360 }
361 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700362 uint64_t max_tid = 0;
363 size_t max_tid_count = 0;
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700364 for (const auto& pair : most_common_blocked) {
365 if (pair.second > max_tid_count) {
366 max_tid = pair.first;
367 max_tid_count = pair.second;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700368 }
Ian Rogers56edc432013-01-18 16:51:51 -0800369 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700370 if (max_tid != 0) {
371 os << " sample shows most blocked tid=" << max_tid;
Ian Rogers56edc432013-01-18 16:51:51 -0800372 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700373 max_tid = 0;
374 max_tid_count = 0;
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700375 for (const auto& pair : most_common_blocker) {
376 if (pair.second > max_tid_count) {
377 max_tid = pair.first;
378 max_tid_count = pair.second;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700379 }
380 }
381 if (max_tid != 0) {
382 os << " sample shows tid=" << max_tid << " owning during this time";
383 }
Ian Rogers56edc432013-01-18 16:51:51 -0800384 }
385 }
Ian Rogers56edc432013-01-18 16:51:51 -0800386}
387
388
Ian Rogers81d425b2012-09-27 16:03:43 -0700389Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Andreas Gampe5db8b7b2018-05-08 16:10:59 -0700390 : BaseMutex(name, level), exclusive_owner_(0), recursion_count_(0), recursive_(recursive) {
Ian Rogersc604d732012-10-14 16:09:54 -0700391#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000392 DCHECK_EQ(0, state_.load(std::memory_order_relaxed));
393 DCHECK_EQ(0, num_contenders_.load(std::memory_order_relaxed));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700394#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700395 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, nullptr));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700396#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700397}
398
David Sehrf42eb2c2016-10-19 13:20:45 -0700399// Helper to allow checking shutdown while locking for thread safety.
400static bool IsSafeToCallAbortSafe() {
401 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
402 return Locks::IsSafeToCallAbortRacy();
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800403}
404
Elliott Hughes8daa0922011-09-11 13:46:25 -0700405Mutex::~Mutex() {
David Sehrf42eb2c2016-10-19 13:20:45 -0700406 bool safe_to_call_abort = Locks::IsSafeToCallAbortRacy();
Ian Rogersc604d732012-10-14 16:09:54 -0700407#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000408 if (state_.load(std::memory_order_relaxed) != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700409 LOG(safe_to_call_abort ? FATAL : WARNING)
Hans Boehm0882af22017-08-31 15:21:57 -0700410 << "destroying mutex with owner: " << GetExclusiveOwnerTid();
Ian Rogersc604d732012-10-14 16:09:54 -0700411 } else {
Hans Boehm0882af22017-08-31 15:21:57 -0700412 if (GetExclusiveOwnerTid() != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700413 LOG(safe_to_call_abort ? FATAL : WARNING)
414 << "unexpectedly found an owner on unlocked mutex " << name_;
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800415 }
Orion Hodson88591fe2018-03-06 13:35:43 +0000416 if (num_contenders_.load(std::memory_order_seq_cst) != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700417 LOG(safe_to_call_abort ? FATAL : WARNING)
418 << "unexpectedly found a contender on mutex " << name_;
Mathieu Chartiercef50f02014-12-09 17:38:52 -0800419 }
Ian Rogersc604d732012-10-14 16:09:54 -0700420 }
421#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700422 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
423 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800424 int rc = pthread_mutex_destroy(&mutex_);
425 if (rc != 0) {
426 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700427 PLOG(safe_to_call_abort ? FATAL : WARNING)
428 << "pthread_mutex_destroy failed for " << name_;
Elliott Hughes6b355752012-01-13 16:49:08 -0800429 }
Ian Rogersc604d732012-10-14 16:09:54 -0700430#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700431}
432
Ian Rogers81d425b2012-09-27 16:03:43 -0700433void Mutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700434 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700435 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700436 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700437 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700438 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700439#if ART_USE_FUTEXES
440 bool done = false;
441 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000442 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700443 if (LIKELY(cur_state == 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700444 // Change state from 0 to 1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000445 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, 1 /* new state */);
Ian Rogersc604d732012-10-14 16:09:54 -0700446 } else {
447 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700448 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersb122a4b2013-11-19 18:00:50 -0800449 num_contenders_++;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800450 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
451 self->CheckEmptyCheckpointFromMutex();
452 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700453 if (futex(state_.Address(), FUTEX_WAIT, 1, nullptr, nullptr, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700454 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
455 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
456 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700457 PLOG(FATAL) << "futex wait failed for " << name_;
458 }
459 }
Ian Rogersb122a4b2013-11-19 18:00:50 -0800460 num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700461 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700462 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000463 DCHECK_EQ(state_.load(std::memory_order_relaxed), 1);
Ian Rogersc604d732012-10-14 16:09:54 -0700464#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700465 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700466#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700467 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000468 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700469 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700470 }
471 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700472 if (kDebugLocking) {
473 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
474 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700475 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700476 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700477}
478
Ian Rogers81d425b2012-09-27 16:03:43 -0700479bool Mutex::ExclusiveTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700480 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700481 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700482 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700483 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700484 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700485#if ART_USE_FUTEXES
486 bool done = false;
487 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000488 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700489 if (cur_state == 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700490 // Change state from 0 to 1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000491 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, 1 /* new state */);
Ian Rogersc604d732012-10-14 16:09:54 -0700492 } else {
493 return false;
494 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700495 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000496 DCHECK_EQ(state_.load(std::memory_order_relaxed), 1);
Ian Rogersc604d732012-10-14 16:09:54 -0700497#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700498 int result = pthread_mutex_trylock(&mutex_);
499 if (result == EBUSY) {
500 return false;
501 }
502 if (result != 0) {
503 errno = result;
504 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
505 }
Ian Rogersc604d732012-10-14 16:09:54 -0700506#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700507 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000508 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700509 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700510 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700511 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700512 if (kDebugLocking) {
513 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
514 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700515 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700516 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700517 return true;
518}
519
Ian Rogers81d425b2012-09-27 16:03:43 -0700520void Mutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartiereb0a1792014-12-15 17:23:45 -0800521 if (kIsDebugBuild && self != nullptr && self != Thread::Current()) {
522 std::string name1 = "<null>";
523 std::string name2 = "<null>";
524 if (self != nullptr) {
525 self->GetThreadName(name1);
526 }
527 if (Thread::Current() != nullptr) {
528 Thread::Current()->GetThreadName(name2);
529 }
Mathieu Chartier4c101102015-01-27 17:14:16 -0800530 LOG(FATAL) << GetName() << " level=" << level_ << " self=" << name1
531 << " Thread::Current()=" << name2;
Mathieu Chartiereb0a1792014-12-15 17:23:45 -0800532 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700533 AssertHeld(self);
Hans Boehm0882af22017-08-31 15:21:57 -0700534 DCHECK_NE(GetExclusiveOwnerTid(), 0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700535 recursion_count_--;
536 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700537 if (kDebugLocking) {
538 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
539 << name_ << " " << recursion_count_;
540 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700541 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700542#if ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700543 bool done = false;
544 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000545 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogersc5f17732014-06-05 20:48:42 -0700546 if (LIKELY(cur_state == 1)) {
Ian Rogersc5f17732014-06-05 20:48:42 -0700547 // We're no longer the owner.
Orion Hodson88591fe2018-03-06 13:35:43 +0000548 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc7190692014-07-08 23:50:26 -0700549 // Change state to 0 and impose load/store ordering appropriate for lock release.
Orion Hodson4557b382018-01-03 11:47:54 +0000550 // Note, the relaxed loads below mustn't reorder before the CompareAndSet.
Ian Rogersc7190692014-07-08 23:50:26 -0700551 // TODO: the ordering here is non-trivial as state is split across 3 fields, fix by placing
552 // a status bit into the state on contention.
Orion Hodson4557b382018-01-03 11:47:54 +0000553 done = state_.CompareAndSetWeakSequentiallyConsistent(cur_state, 0 /* new state */);
Ian Rogersc5f17732014-06-05 20:48:42 -0700554 if (LIKELY(done)) { // Spurious fail?
Ian Rogersc7190692014-07-08 23:50:26 -0700555 // Wake a contender.
Orion Hodson88591fe2018-03-06 13:35:43 +0000556 if (UNLIKELY(num_contenders_.load(std::memory_order_relaxed) > 0)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700557 futex(state_.Address(), FUTEX_WAKE, 1, nullptr, nullptr, 0);
Ian Rogersc5f17732014-06-05 20:48:42 -0700558 }
559 }
560 } else {
561 // Logging acquires the logging lock, avoid infinite recursion in that case.
562 if (this != Locks::logging_lock_) {
563 LOG(FATAL) << "Unexpected state_ in unlock " << cur_state << " for " << name_;
564 } else {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700565 LogHelper::LogLineLowStack(__FILE__,
566 __LINE__,
567 ::android::base::FATAL_WITHOUT_ABORT,
568 StringPrintf("Unexpected state_ %d in unlock for %s",
569 cur_state, name_).c_str());
Ian Rogersc5f17732014-06-05 20:48:42 -0700570 _exit(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700571 }
572 }
Ian Rogersc5f17732014-06-05 20:48:42 -0700573 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700574#else
Orion Hodson88591fe2018-03-06 13:35:43 +0000575 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700576 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700577#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700578 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700579}
580
Ian Rogers56edc432013-01-18 16:51:51 -0800581void Mutex::Dump(std::ostream& os) const {
582 os << (recursive_ ? "recursive " : "non-recursive ")
583 << name_
584 << " level=" << static_cast<int>(level_)
585 << " rec=" << recursion_count_
586 << " owner=" << GetExclusiveOwnerTid() << " ";
587 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700588}
589
590std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800591 mu.Dump(os);
592 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700593}
594
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800595void Mutex::WakeupToRespondToEmptyCheckpoint() {
596#if ART_USE_FUTEXES
597 // Wake up all the waiters so they will respond to the emtpy checkpoint.
598 DCHECK(should_respond_to_empty_checkpoint_request_);
Orion Hodson88591fe2018-03-06 13:35:43 +0000599 if (UNLIKELY(num_contenders_.load(std::memory_order_relaxed) > 0)) {
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800600 futex(state_.Address(), FUTEX_WAKE, -1, nullptr, nullptr, 0);
601 }
602#else
603 LOG(FATAL) << "Non futex case isn't supported.";
604#endif
605}
606
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700607ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level)
608 : BaseMutex(name, level)
Ian Rogers81d425b2012-09-27 16:03:43 -0700609#if ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700610 , state_(0), num_pending_readers_(0), num_pending_writers_(0)
Ian Rogers81d425b2012-09-27 16:03:43 -0700611#endif
Igor Murashkin5573c372017-11-16 13:34:30 -0800612{
Ian Rogers81d425b2012-09-27 16:03:43 -0700613#if !ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700614 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, nullptr));
Ian Rogers81d425b2012-09-27 16:03:43 -0700615#endif
Orion Hodson88591fe2018-03-06 13:35:43 +0000616 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700617}
618
619ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700620#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000621 CHECK_EQ(state_.load(std::memory_order_relaxed), 0);
Hans Boehm0882af22017-08-31 15:21:57 -0700622 CHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000623 CHECK_EQ(num_pending_readers_.load(std::memory_order_relaxed), 0);
624 CHECK_EQ(num_pending_writers_.load(std::memory_order_relaxed), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700625#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700626 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
627 // may still be using locks.
628 int rc = pthread_rwlock_destroy(&rwlock_);
629 if (rc != 0) {
630 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700631 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
632 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800633 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700634#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700635}
636
Ian Rogers81d425b2012-09-27 16:03:43 -0700637void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700638 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700639 AssertNotExclusiveHeld(self);
640#if ART_USE_FUTEXES
641 bool done = false;
642 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000643 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700644 if (LIKELY(cur_state == 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700645 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000646 done = state_.CompareAndSetWeakAcquire(0 /* cur_state*/, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700647 } else {
648 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700649 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersc7190692014-07-08 23:50:26 -0700650 ++num_pending_writers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800651 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
652 self->CheckEmptyCheckpointFromMutex();
653 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700654 if (futex(state_.Address(), FUTEX_WAIT, cur_state, nullptr, nullptr, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700655 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
656 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
657 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700658 PLOG(FATAL) << "futex wait failed for " << name_;
659 }
660 }
Ian Rogersc7190692014-07-08 23:50:26 -0700661 --num_pending_writers_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700662 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700663 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000664 DCHECK_EQ(state_.load(std::memory_order_relaxed), -1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700665#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700666 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700667#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700668 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000669 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700670 RegisterAsLocked(self);
671 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700672}
673
Ian Rogers81d425b2012-09-27 16:03:43 -0700674void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700675 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700676 AssertExclusiveHeld(self);
677 RegisterAsUnlocked(self);
Hans Boehm0882af22017-08-31 15:21:57 -0700678 DCHECK_NE(GetExclusiveOwnerTid(), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700679#if ART_USE_FUTEXES
680 bool done = false;
681 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000682 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700683 if (LIKELY(cur_state == -1)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700684 // We're no longer the owner.
Orion Hodson88591fe2018-03-06 13:35:43 +0000685 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc7190692014-07-08 23:50:26 -0700686 // Change state from -1 to 0 and impose load/store ordering appropriate for lock release.
Orion Hodson4557b382018-01-03 11:47:54 +0000687 // Note, the relaxed loads below musn't reorder before the CompareAndSet.
Ian Rogersc7190692014-07-08 23:50:26 -0700688 // TODO: the ordering here is non-trivial as state is split across 3 fields, fix by placing
689 // a status bit into the state on contention.
Orion Hodson4557b382018-01-03 11:47:54 +0000690 done = state_.CompareAndSetWeakSequentiallyConsistent(-1 /* cur_state*/, 0 /* new state */);
Ian Rogersc7190692014-07-08 23:50:26 -0700691 if (LIKELY(done)) { // Weak CAS may fail spuriously.
Ian Rogers81d425b2012-09-27 16:03:43 -0700692 // Wake any waiters.
Orion Hodson88591fe2018-03-06 13:35:43 +0000693 if (UNLIKELY(num_pending_readers_.load(std::memory_order_relaxed) > 0 ||
694 num_pending_writers_.load(std::memory_order_relaxed) > 0)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700695 futex(state_.Address(), FUTEX_WAKE, -1, nullptr, nullptr, 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700696 }
697 }
698 } else {
699 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
700 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700701 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700702#else
Orion Hodson88591fe2018-03-06 13:35:43 +0000703 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700704 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700705#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700706}
707
Ian Rogers66aee5c2012-08-15 17:17:47 -0700708#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700709bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700710 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700711#if ART_USE_FUTEXES
712 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700713 timespec end_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800714 InitTimeSpec(true, CLOCK_MONOTONIC, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700715 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000716 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700717 if (cur_state == 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700718 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000719 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700720 } else {
721 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700722 timespec now_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800723 InitTimeSpec(true, CLOCK_MONOTONIC, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700724 timespec rel_ts;
725 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
726 return false; // Timed out.
727 }
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700728 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersc7190692014-07-08 23:50:26 -0700729 ++num_pending_writers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800730 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
731 self->CheckEmptyCheckpointFromMutex();
732 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700733 if (futex(state_.Address(), FUTEX_WAIT, cur_state, &rel_ts, nullptr, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700734 if (errno == ETIMEDOUT) {
Ian Rogersc7190692014-07-08 23:50:26 -0700735 --num_pending_writers_;
Ian Rogersc604d732012-10-14 16:09:54 -0700736 return false; // Timed out.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700737 } else if ((errno != EAGAIN) && (errno != EINTR)) {
738 // EAGAIN and EINTR both indicate a spurious failure,
739 // recompute the relative time out from now and try again.
740 // We don't use TEMP_FAILURE_RETRY so we can recompute rel_ts;
Ian Rogers81d425b2012-09-27 16:03:43 -0700741 PLOG(FATAL) << "timed futex wait failed for " << name_;
742 }
743 }
Ian Rogersc7190692014-07-08 23:50:26 -0700744 --num_pending_writers_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700745 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700746 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700747#else
Ian Rogersc604d732012-10-14 16:09:54 -0700748 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700749 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700750 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700751 if (result == ETIMEDOUT) {
752 return false;
753 }
754 if (result != 0) {
755 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700756 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700757 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700758#endif
Orion Hodson88591fe2018-03-06 13:35:43 +0000759 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700760 RegisterAsLocked(self);
761 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700762 return true;
763}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700764#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700765
Ian Rogers51d212e2014-10-23 17:48:20 -0700766#if ART_USE_FUTEXES
Ian Rogerscf7f1912014-10-22 22:06:39 -0700767void ReaderWriterMutex::HandleSharedLockContention(Thread* self, int32_t cur_state) {
768 // Owner holds it exclusively, hang up.
Roland Levillaincd72dc92018-02-27 19:15:31 +0000769 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogerscf7f1912014-10-22 22:06:39 -0700770 ++num_pending_readers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800771 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
772 self->CheckEmptyCheckpointFromMutex();
773 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700774 if (futex(state_.Address(), FUTEX_WAIT, cur_state, nullptr, nullptr, 0) != 0) {
Daniel Colascione6f4d1022016-11-21 14:35:42 -0800775 if (errno != EAGAIN && errno != EINTR) {
Ian Rogerscf7f1912014-10-22 22:06:39 -0700776 PLOG(FATAL) << "futex wait failed for " << name_;
777 }
778 }
779 --num_pending_readers_;
780}
Ian Rogers51d212e2014-10-23 17:48:20 -0700781#endif
Ian Rogerscf7f1912014-10-22 22:06:39 -0700782
Ian Rogers81d425b2012-09-27 16:03:43 -0700783bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700784 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700785#if ART_USE_FUTEXES
786 bool done = false;
787 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000788 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700789 if (cur_state >= 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700790 // Add as an extra reader and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000791 done = state_.CompareAndSetWeakAcquire(cur_state, cur_state + 1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700792 } else {
793 // Owner holds it exclusively.
794 return false;
795 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700796 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700797#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700798 int result = pthread_rwlock_tryrdlock(&rwlock_);
799 if (result == EBUSY) {
800 return false;
801 }
802 if (result != 0) {
803 errno = result;
804 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
805 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700806#endif
807 RegisterAsLocked(self);
808 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700809 return true;
810}
811
Ian Rogers81d425b2012-09-27 16:03:43 -0700812bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700813 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700814 bool result;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700815 if (UNLIKELY(self == nullptr)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700816 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700817 } else {
818 result = (self->GetHeldMutex(level_) == this);
819 }
820 return result;
821}
822
Ian Rogers56edc432013-01-18 16:51:51 -0800823void ReaderWriterMutex::Dump(std::ostream& os) const {
824 os << name_
825 << " level=" << static_cast<int>(level_)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700826 << " owner=" << GetExclusiveOwnerTid()
827#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000828 << " state=" << state_.load(std::memory_order_seq_cst)
829 << " num_pending_writers=" << num_pending_writers_.load(std::memory_order_seq_cst)
830 << " num_pending_readers=" << num_pending_readers_.load(std::memory_order_seq_cst)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700831#endif
832 << " ";
Ian Rogers56edc432013-01-18 16:51:51 -0800833 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700834}
835
836std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800837 mu.Dump(os);
838 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700839}
840
Yu Lieac44242015-06-29 10:50:03 +0800841std::ostream& operator<<(std::ostream& os, const MutatorMutex& mu) {
842 mu.Dump(os);
843 return os;
844}
845
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800846void ReaderWriterMutex::WakeupToRespondToEmptyCheckpoint() {
847#if ART_USE_FUTEXES
848 // Wake up all the waiters so they will respond to the emtpy checkpoint.
849 DCHECK(should_respond_to_empty_checkpoint_request_);
Orion Hodson88591fe2018-03-06 13:35:43 +0000850 if (UNLIKELY(num_pending_readers_.load(std::memory_order_relaxed) > 0 ||
851 num_pending_writers_.load(std::memory_order_relaxed) > 0)) {
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800852 futex(state_.Address(), FUTEX_WAKE, -1, nullptr, nullptr, 0);
853 }
854#else
855 LOG(FATAL) << "Non futex case isn't supported.";
856#endif
857}
858
Ian Rogers23055dc2013-04-18 16:29:16 -0700859ConditionVariable::ConditionVariable(const char* name, Mutex& guard)
Ian Rogersc604d732012-10-14 16:09:54 -0700860 : name_(name), guard_(guard) {
861#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000862 DCHECK_EQ(0, sequence_.load(std::memory_order_relaxed));
Ian Rogersc604d732012-10-14 16:09:54 -0700863 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700864#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000865 pthread_condattr_t cond_attrs;
Ian Rogersc5f17732014-06-05 20:48:42 -0700866 CHECK_MUTEX_CALL(pthread_condattr_init, (&cond_attrs));
Narayan Kamath51b71022014-03-04 11:57:09 +0000867#if !defined(__APPLE__)
868 // Apple doesn't have CLOCK_MONOTONIC or pthread_condattr_setclock.
Ian Rogers51d212e2014-10-23 17:48:20 -0700869 CHECK_MUTEX_CALL(pthread_condattr_setclock, (&cond_attrs, CLOCK_MONOTONIC));
Narayan Kamath51b71022014-03-04 11:57:09 +0000870#endif
871 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, &cond_attrs));
Ian Rogersc604d732012-10-14 16:09:54 -0700872#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700873}
874
875ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800876#if ART_USE_FUTEXES
877 if (num_waiters_!= 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700878 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
879 LOG(is_safe_to_call_abort ? FATAL : WARNING)
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700880 << "ConditionVariable::~ConditionVariable for " << name_
Ian Rogersd45f2012012-11-28 11:46:23 -0800881 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800882 }
883#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700884 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
885 // may still be using condition variables.
886 int rc = pthread_cond_destroy(&cond_);
887 if (rc != 0) {
888 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700889 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
890 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_cond_destroy failed for " << name_;
Elliott Hughese62934d2012-04-09 11:24:29 -0700891 }
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::Broadcast(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700896 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700897 // TODO: enable below, there's a race in thread creation that causes false failures currently.
898 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700899 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700900#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800901 if (num_waiters_ > 0) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800902 sequence_++; // Indicate the broadcast occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700903 bool done = false;
904 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000905 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersd45f2012012-11-28 11:46:23 -0800906 // Requeue waiters onto mutex. The waiter holds the contender count on the mutex high ensuring
907 // mutex unlocks will awaken the requeued waiter thread.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800908 done = futex(sequence_.Address(), FUTEX_CMP_REQUEUE, 0,
Ian Rogers5bd97c42012-11-27 02:38:26 -0800909 reinterpret_cast<const timespec*>(std::numeric_limits<int32_t>::max()),
Ian Rogersc7190692014-07-08 23:50:26 -0700910 guard_.state_.Address(), cur_sequence) != -1;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800911 if (!done) {
Daniel Colascione6f4d1022016-11-21 14:35:42 -0800912 if (errno != EAGAIN && errno != EINTR) {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800913 PLOG(FATAL) << "futex cmp requeue failed for " << name_;
914 }
Ian Rogers5bd97c42012-11-27 02:38:26 -0800915 }
Ian Rogersc604d732012-10-14 16:09:54 -0700916 } while (!done);
917 }
918#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700919 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700920#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700921}
922
Ian Rogersc604d732012-10-14 16:09:54 -0700923void ConditionVariable::Signal(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700924 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700925 guard_.AssertExclusiveHeld(self);
926#if ART_USE_FUTEXES
Ian Rogersd45f2012012-11-28 11:46:23 -0800927 if (num_waiters_ > 0) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800928 sequence_++; // Indicate a signal occurred.
Ian Rogersc604d732012-10-14 16:09:54 -0700929 // Futex wake 1 waiter who will then come and in contend on mutex. It'd be nice to requeue them
930 // to avoid this, however, requeueing can only move all waiters.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700931 int num_woken = futex(sequence_.Address(), FUTEX_WAKE, 1, nullptr, nullptr, 0);
Ian Rogersd45f2012012-11-28 11:46:23 -0800932 // Check something was woken or else we changed sequence_ before they had chance to wait.
Ian Rogers5bd97c42012-11-27 02:38:26 -0800933 CHECK((num_woken == 0) || (num_woken == 1));
Ian Rogersc604d732012-10-14 16:09:54 -0700934 }
935#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700936 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700937#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700938}
939
Ian Rogersc604d732012-10-14 16:09:54 -0700940void ConditionVariable::Wait(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700941 guard_.CheckSafeToWait(self);
942 WaitHoldingLocks(self);
943}
944
945void ConditionVariable::WaitHoldingLocks(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700946 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700947 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700948 unsigned int old_recursion_count = guard_.recursion_count_;
949#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700950 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800951 // Ensure the Mutex is contended so that requeued threads are awoken.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800952 guard_.num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -0700953 guard_.recursion_count_ = 1;
Orion Hodson88591fe2018-03-06 13:35:43 +0000954 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700955 guard_.ExclusiveUnlock(self);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700956 if (futex(sequence_.Address(), FUTEX_WAIT, cur_sequence, nullptr, nullptr, 0) != 0) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800957 // Futex failed, check it is an expected error.
958 // EAGAIN == EWOULDBLK, so we let the caller try again.
959 // EINTR implies a signal was sent to this thread.
960 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700961 PLOG(FATAL) << "futex wait failed for " << name_;
962 }
963 }
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800964 if (self != nullptr) {
965 JNIEnvExt* const env = self->GetJniEnv();
Ian Rogers55256cb2017-12-21 17:07:11 -0800966 if (UNLIKELY(env != nullptr && env->IsRuntimeDeleted())) {
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800967 CHECK(self->IsDaemon());
968 // If the runtime has been deleted, then we cannot proceed. Just sleep forever. This may
969 // occur for user daemon threads that get a spurious wakeup. This occurs for test 132 with
970 // --host and --gdb.
971 // After we wake up, the runtime may have been shutdown, which means that this condition may
972 // have been deleted. It is not safe to retry the wait.
973 SleepForever();
974 }
975 }
Ian Rogersc604d732012-10-14 16:09:54 -0700976 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800977 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700978 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800979 // We awoke and so no longer require awakes from the guard_'s unlock.
Orion Hodson88591fe2018-03-06 13:35:43 +0000980 CHECK_GE(guard_.num_contenders_.load(std::memory_order_relaxed), 0);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800981 guard_.num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700982#else
Hans Boehm0882af22017-08-31 15:21:57 -0700983 pid_t old_owner = guard_.GetExclusiveOwnerTid();
Orion Hodson88591fe2018-03-06 13:35:43 +0000984 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700985 guard_.recursion_count_ = 0;
986 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
Orion Hodson88591fe2018-03-06 13:35:43 +0000987 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700988#endif
989 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700990}
991
Ian Rogers7b078e82014-09-10 14:44:24 -0700992bool ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700993 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers7b078e82014-09-10 14:44:24 -0700994 bool timed_out = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700995 guard_.AssertExclusiveHeld(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700996 guard_.CheckSafeToWait(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700997 unsigned int old_recursion_count = guard_.recursion_count_;
998#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700999 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -08001000 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -07001001 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -08001002 // Ensure the Mutex is contended so that requeued threads are awoken.
Ian Rogersb122a4b2013-11-19 18:00:50 -08001003 guard_.num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -07001004 guard_.recursion_count_ = 1;
Orion Hodson88591fe2018-03-06 13:35:43 +00001005 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -07001006 guard_.ExclusiveUnlock(self);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001007 if (futex(sequence_.Address(), FUTEX_WAIT, cur_sequence, &rel_ts, nullptr, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -07001008 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -08001009 // Timed out we're done.
Ian Rogers7b078e82014-09-10 14:44:24 -07001010 timed_out = true;
Brian Carlstrom0de79852013-07-25 22:29:58 -07001011 } else if ((errno == EAGAIN) || (errno == EINTR)) {
Ian Rogersd45f2012012-11-28 11:46:23 -08001012 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -07001013 } else {
1014 PLOG(FATAL) << "timed futex wait failed for " << name_;
1015 }
1016 }
1017 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -08001018 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -07001019 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -08001020 // We awoke and so no longer require awakes from the guard_'s unlock.
Orion Hodson88591fe2018-03-06 13:35:43 +00001021 CHECK_GE(guard_.num_contenders_.load(std::memory_order_relaxed), 0);
Ian Rogersb122a4b2013-11-19 18:00:50 -08001022 guard_.num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -07001023#else
Narayan Kamath51b71022014-03-04 11:57:09 +00001024#if !defined(__APPLE__)
Ian Rogersc604d732012-10-14 16:09:54 -07001025 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -07001026#else
Ian Rogersc604d732012-10-14 16:09:54 -07001027 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -07001028#endif
Hans Boehm0882af22017-08-31 15:21:57 -07001029 pid_t old_owner = guard_.GetExclusiveOwnerTid();
Orion Hodson88591fe2018-03-06 13:35:43 +00001030 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -07001031 guard_.recursion_count_ = 0;
1032 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -07001033 InitTimeSpec(true, clock, ms, ns, &ts);
Narayan Kamath51b71022014-03-04 11:57:09 +00001034 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &guard_.mutex_, &ts));
Ian Rogers7b078e82014-09-10 14:44:24 -07001035 if (rc == ETIMEDOUT) {
1036 timed_out = true;
1037 } else if (rc != 0) {
Elliott Hughes5f791332011-09-15 17:45:30 -07001038 errno = rc;
1039 PLOG(FATAL) << "TimedWait failed for " << name_;
1040 }
Orion Hodson88591fe2018-03-06 13:35:43 +00001041 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -07001042#endif
1043 guard_.recursion_count_ = old_recursion_count;
Ian Rogers7b078e82014-09-10 14:44:24 -07001044 return timed_out;
Elliott Hughes5f791332011-09-15 17:45:30 -07001045}
1046
Ian Rogers719d1a32014-03-06 12:13:39 -08001047void Locks::Init() {
1048 if (logging_lock_ != nullptr) {
1049 // Already initialized.
Vladimir Marko33bff252017-11-01 14:35:42 +00001050 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001051 DCHECK(modify_ldt_lock_ != nullptr);
1052 } else {
1053 DCHECK(modify_ldt_lock_ == nullptr);
1054 }
Ian Rogers719d1a32014-03-06 12:13:39 -08001055 DCHECK(abort_lock_ != nullptr);
Brian Carlstrom306db812014-09-05 13:01:41 -07001056 DCHECK(alloc_tracker_lock_ != nullptr);
Andreas Gampe74240812014-04-17 10:35:09 -07001057 DCHECK(allocated_monitor_ids_lock_ != nullptr);
Chao-ying Fu9e369312014-05-21 11:20:52 -07001058 DCHECK(allocated_thread_ids_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001059 DCHECK(breakpoint_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001060 DCHECK(classlinker_classes_lock_ != nullptr);
Alex Light184f0752018-07-13 11:18:22 -07001061 DCHECK(custom_tls_lock_ != nullptr);
Brian Carlstrom306db812014-09-05 13:01:41 -07001062 DCHECK(deoptimization_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001063 DCHECK(heap_bitmap_lock_ != nullptr);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001064 DCHECK(oat_file_manager_lock_ != nullptr);
David Brazdilca3c8c32016-09-06 14:04:48 +01001065 DCHECK(verifier_deps_lock_ != nullptr);
Richard Uhlera206c742016-05-24 15:04:22 -07001066 DCHECK(host_dlopen_handles_lock_ != nullptr);
Brian Carlstrom306db812014-09-05 13:01:41 -07001067 DCHECK(intern_table_lock_ != nullptr);
Andreas Gampec8089542017-01-16 12:41:12 -08001068 DCHECK(jni_function_table_lock_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -07001069 DCHECK(jni_libraries_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001070 DCHECK(logging_lock_ != nullptr);
1071 DCHECK(mutator_lock_ != nullptr);
Brian Carlstrom306db812014-09-05 13:01:41 -07001072 DCHECK(profiler_lock_ != nullptr);
Mingyao Yang063fc772016-08-02 11:02:54 -07001073 DCHECK(cha_lock_ != nullptr);
Igor Murashkin495e7832017-10-27 10:56:20 -07001074 DCHECK(subtype_check_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001075 DCHECK(thread_list_lock_ != nullptr);
1076 DCHECK(thread_suspend_count_lock_ != nullptr);
1077 DCHECK(trace_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001078 DCHECK(unexpected_signal_lock_ != nullptr);
Alex Light88fd7202017-06-30 08:31:59 -07001079 DCHECK(user_code_suspension_lock_ != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08001080 DCHECK(dex_lock_ != nullptr);
David Srbeckyfb3de3d2018-01-29 16:11:49 +00001081 DCHECK(native_debug_interface_lock_ != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -08001082 } else {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001083 // Create global locks in level order from highest lock level to lowest.
Ian Rogers4ad5cd32014-11-11 23:08:07 -08001084 LockLevel current_lock_level = kInstrumentEntrypointsLock;
1085 DCHECK(instrument_entrypoints_lock_ == nullptr);
1086 instrument_entrypoints_lock_ = new Mutex("instrument entrypoint lock", current_lock_level);
Ian Rogers719d1a32014-03-06 12:13:39 -08001087
Chao-ying Fu9e369312014-05-21 11:20:52 -07001088 #define UPDATE_CURRENT_LOCK_LEVEL(new_level) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07001089 if ((new_level) >= current_lock_level) { \
Brian Carlstrom306db812014-09-05 13:01:41 -07001090 /* Do not use CHECKs or FATAL here, abort_lock_ is not setup yet. */ \
1091 fprintf(stderr, "New local level %d is not less than current level %d\n", \
1092 new_level, current_lock_level); \
1093 exit(1); \
1094 } \
Ian Rogersf3d874c2014-07-17 18:52:42 -07001095 current_lock_level = new_level;
1096
Alex Light88fd7202017-06-30 08:31:59 -07001097 UPDATE_CURRENT_LOCK_LEVEL(kUserCodeSuspensionLock);
1098 DCHECK(user_code_suspension_lock_ == nullptr);
1099 user_code_suspension_lock_ = new Mutex("user code suspension lock", current_lock_level);
1100
Ian Rogersf3d874c2014-07-17 18:52:42 -07001101 UPDATE_CURRENT_LOCK_LEVEL(kMutatorLock);
1102 DCHECK(mutator_lock_ == nullptr);
Yu Lieac44242015-06-29 10:50:03 +08001103 mutator_lock_ = new MutatorMutex("mutator lock", current_lock_level);
Chao-ying Fu9e369312014-05-21 11:20:52 -07001104
1105 UPDATE_CURRENT_LOCK_LEVEL(kHeapBitmapLock);
1106 DCHECK(heap_bitmap_lock_ == nullptr);
1107 heap_bitmap_lock_ = new ReaderWriterMutex("heap bitmap lock", current_lock_level);
1108
Jeff Hao69dbec62014-09-15 18:03:41 -07001109 UPDATE_CURRENT_LOCK_LEVEL(kTraceLock);
1110 DCHECK(trace_lock_ == nullptr);
1111 trace_lock_ = new Mutex("trace lock", current_lock_level);
1112
Chao-ying Fu9e369312014-05-21 11:20:52 -07001113 UPDATE_CURRENT_LOCK_LEVEL(kRuntimeShutdownLock);
1114 DCHECK(runtime_shutdown_lock_ == nullptr);
1115 runtime_shutdown_lock_ = new Mutex("runtime shutdown lock", current_lock_level);
1116
1117 UPDATE_CURRENT_LOCK_LEVEL(kProfilerLock);
1118 DCHECK(profiler_lock_ == nullptr);
1119 profiler_lock_ = new Mutex("profiler lock", current_lock_level);
1120
Brian Carlstrom306db812014-09-05 13:01:41 -07001121 UPDATE_CURRENT_LOCK_LEVEL(kDeoptimizationLock);
1122 DCHECK(deoptimization_lock_ == nullptr);
1123 deoptimization_lock_ = new Mutex("Deoptimization lock", current_lock_level);
1124
1125 UPDATE_CURRENT_LOCK_LEVEL(kAllocTrackerLock);
1126 DCHECK(alloc_tracker_lock_ == nullptr);
1127 alloc_tracker_lock_ = new Mutex("AllocTracker lock", current_lock_level);
1128
Chao-ying Fu9e369312014-05-21 11:20:52 -07001129 UPDATE_CURRENT_LOCK_LEVEL(kThreadListLock);
1130 DCHECK(thread_list_lock_ == nullptr);
1131 thread_list_lock_ = new Mutex("thread list lock", current_lock_level);
1132
Ian Rogers68d8b422014-07-17 11:09:10 -07001133 UPDATE_CURRENT_LOCK_LEVEL(kJniLoadLibraryLock);
1134 DCHECK(jni_libraries_lock_ == nullptr);
1135 jni_libraries_lock_ = new Mutex("JNI shared libraries map lock", current_lock_level);
1136
Chao-ying Fu9e369312014-05-21 11:20:52 -07001137 UPDATE_CURRENT_LOCK_LEVEL(kBreakpointLock);
Ian Rogers719d1a32014-03-06 12:13:39 -08001138 DCHECK(breakpoint_lock_ == nullptr);
Sebastien Hertzed2be172014-08-19 15:33:43 +02001139 breakpoint_lock_ = new ReaderWriterMutex("breakpoint lock", current_lock_level);
Chao-ying Fu9e369312014-05-21 11:20:52 -07001140
Igor Murashkin495e7832017-10-27 10:56:20 -07001141 UPDATE_CURRENT_LOCK_LEVEL(kSubtypeCheckLock);
1142 DCHECK(subtype_check_lock_ == nullptr);
1143 subtype_check_lock_ = new Mutex("SubtypeCheck lock", current_lock_level);
1144
Mingyao Yang063fc772016-08-02 11:02:54 -07001145 UPDATE_CURRENT_LOCK_LEVEL(kCHALock);
1146 DCHECK(cha_lock_ == nullptr);
1147 cha_lock_ = new Mutex("CHA lock", current_lock_level);
1148
Chao-ying Fu9e369312014-05-21 11:20:52 -07001149 UPDATE_CURRENT_LOCK_LEVEL(kClassLinkerClassesLock);
Ian Rogers719d1a32014-03-06 12:13:39 -08001150 DCHECK(classlinker_classes_lock_ == nullptr);
1151 classlinker_classes_lock_ = new ReaderWriterMutex("ClassLinker classes lock",
Chao-ying Fu9e369312014-05-21 11:20:52 -07001152 current_lock_level);
1153
Andreas Gampe74240812014-04-17 10:35:09 -07001154 UPDATE_CURRENT_LOCK_LEVEL(kMonitorPoolLock);
1155 DCHECK(allocated_monitor_ids_lock_ == nullptr);
1156 allocated_monitor_ids_lock_ = new Mutex("allocated monitor ids lock", current_lock_level);
1157
Chao-ying Fu9e369312014-05-21 11:20:52 -07001158 UPDATE_CURRENT_LOCK_LEVEL(kAllocatedThreadIdsLock);
1159 DCHECK(allocated_thread_ids_lock_ == nullptr);
1160 allocated_thread_ids_lock_ = new Mutex("allocated thread ids lock", current_lock_level);
1161
Vladimir Marko33bff252017-11-01 14:35:42 +00001162 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001163 UPDATE_CURRENT_LOCK_LEVEL(kModifyLdtLock);
1164 DCHECK(modify_ldt_lock_ == nullptr);
1165 modify_ldt_lock_ = new Mutex("modify_ldt lock", current_lock_level);
1166 }
1167
Andreas Gampecc1b5352016-12-01 16:58:38 -08001168 UPDATE_CURRENT_LOCK_LEVEL(kDexLock);
1169 DCHECK(dex_lock_ == nullptr);
1170 dex_lock_ = new ReaderWriterMutex("ClassLinker dex lock", current_lock_level);
1171
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001172 UPDATE_CURRENT_LOCK_LEVEL(kOatFileManagerLock);
1173 DCHECK(oat_file_manager_lock_ == nullptr);
1174 oat_file_manager_lock_ = new ReaderWriterMutex("OatFile manager lock", current_lock_level);
1175
David Brazdilca3c8c32016-09-06 14:04:48 +01001176 UPDATE_CURRENT_LOCK_LEVEL(kVerifierDepsLock);
1177 DCHECK(verifier_deps_lock_ == nullptr);
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00001178 verifier_deps_lock_ = new ReaderWriterMutex("verifier deps lock", current_lock_level);
David Brazdilca3c8c32016-09-06 14:04:48 +01001179
Richard Uhlera206c742016-05-24 15:04:22 -07001180 UPDATE_CURRENT_LOCK_LEVEL(kHostDlOpenHandlesLock);
1181 DCHECK(host_dlopen_handles_lock_ == nullptr);
1182 host_dlopen_handles_lock_ = new Mutex("host dlopen handles lock", current_lock_level);
Mathieu Chartiere58991b2015-10-13 07:59:34 -07001183
Chao-ying Fu9e369312014-05-21 11:20:52 -07001184 UPDATE_CURRENT_LOCK_LEVEL(kInternTableLock);
Ian Rogers719d1a32014-03-06 12:13:39 -08001185 DCHECK(intern_table_lock_ == nullptr);
Chao-ying Fu9e369312014-05-21 11:20:52 -07001186 intern_table_lock_ = new Mutex("InternTable lock", current_lock_level);
1187
Mathieu Chartiera5a53ef2014-09-12 12:58:05 -07001188 UPDATE_CURRENT_LOCK_LEVEL(kReferenceProcessorLock);
1189 DCHECK(reference_processor_lock_ == nullptr);
1190 reference_processor_lock_ = new Mutex("ReferenceProcessor lock", current_lock_level);
1191
1192 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueueClearedReferencesLock);
1193 DCHECK(reference_queue_cleared_references_lock_ == nullptr);
1194 reference_queue_cleared_references_lock_ = new Mutex("ReferenceQueue cleared references lock", current_lock_level);
1195
1196 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueueWeakReferencesLock);
1197 DCHECK(reference_queue_weak_references_lock_ == nullptr);
1198 reference_queue_weak_references_lock_ = new Mutex("ReferenceQueue cleared references lock", current_lock_level);
1199
1200 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueueFinalizerReferencesLock);
1201 DCHECK(reference_queue_finalizer_references_lock_ == nullptr);
1202 reference_queue_finalizer_references_lock_ = new Mutex("ReferenceQueue finalizer references lock", current_lock_level);
1203
1204 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueuePhantomReferencesLock);
1205 DCHECK(reference_queue_phantom_references_lock_ == nullptr);
1206 reference_queue_phantom_references_lock_ = new Mutex("ReferenceQueue phantom references lock", current_lock_level);
1207
1208 UPDATE_CURRENT_LOCK_LEVEL(kReferenceQueueSoftReferencesLock);
1209 DCHECK(reference_queue_soft_references_lock_ == nullptr);
1210 reference_queue_soft_references_lock_ = new Mutex("ReferenceQueue soft references lock", current_lock_level);
1211
Andreas Gampe05a364c2016-10-14 13:27:12 -07001212 UPDATE_CURRENT_LOCK_LEVEL(kJniGlobalsLock);
1213 DCHECK(jni_globals_lock_ == nullptr);
1214 jni_globals_lock_ =
1215 new ReaderWriterMutex("JNI global reference table lock", current_lock_level);
1216
1217 UPDATE_CURRENT_LOCK_LEVEL(kJniWeakGlobalsLock);
1218 DCHECK(jni_weak_globals_lock_ == nullptr);
1219 jni_weak_globals_lock_ = new Mutex("JNI weak global reference table lock", current_lock_level);
1220
Andreas Gampec8089542017-01-16 12:41:12 -08001221 UPDATE_CURRENT_LOCK_LEVEL(kJniFunctionTableLock);
1222 DCHECK(jni_function_table_lock_ == nullptr);
1223 jni_function_table_lock_ = new Mutex("JNI function table lock", current_lock_level);
1224
Alex Light184f0752018-07-13 11:18:22 -07001225 UPDATE_CURRENT_LOCK_LEVEL(kCustomTlsLock);
1226 DCHECK(custom_tls_lock_ == nullptr);
1227 custom_tls_lock_ = new Mutex("Thread::custom_tls_ lock", current_lock_level);
1228
David Srbecky440a9b32018-02-15 17:47:29 +00001229 UPDATE_CURRENT_LOCK_LEVEL(kNativeDebugInterfaceLock);
1230 DCHECK(native_debug_interface_lock_ == nullptr);
1231 native_debug_interface_lock_ = new Mutex("Native debug interface lock", current_lock_level);
1232
Chao-ying Fu9e369312014-05-21 11:20:52 -07001233 UPDATE_CURRENT_LOCK_LEVEL(kAbortLock);
1234 DCHECK(abort_lock_ == nullptr);
1235 abort_lock_ = new Mutex("abort lock", current_lock_level, true);
1236
1237 UPDATE_CURRENT_LOCK_LEVEL(kThreadSuspendCountLock);
1238 DCHECK(thread_suspend_count_lock_ == nullptr);
1239 thread_suspend_count_lock_ = new Mutex("thread suspend count lock", current_lock_level);
1240
1241 UPDATE_CURRENT_LOCK_LEVEL(kUnexpectedSignalLock);
1242 DCHECK(unexpected_signal_lock_ == nullptr);
1243 unexpected_signal_lock_ = new Mutex("unexpected signal lock", current_lock_level, true);
1244
1245 UPDATE_CURRENT_LOCK_LEVEL(kLoggingLock);
1246 DCHECK(logging_lock_ == nullptr);
1247 logging_lock_ = new Mutex("logging lock", current_lock_level, true);
1248
1249 #undef UPDATE_CURRENT_LOCK_LEVEL
Mathieu Chartier91e56692015-03-03 13:51:04 -08001250
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001251 // List of mutexes that we may hold when accessing a weak ref.
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -08001252 AddToExpectedMutexesOnWeakRefAccess(dex_lock_, /*need_lock*/ false);
1253 AddToExpectedMutexesOnWeakRefAccess(classlinker_classes_lock_, /*need_lock*/ false);
1254 AddToExpectedMutexesOnWeakRefAccess(jni_libraries_lock_, /*need_lock*/ false);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001255
Mathieu Chartier91e56692015-03-03 13:51:04 -08001256 InitConditions();
Ian Rogers719d1a32014-03-06 12:13:39 -08001257 }
1258}
1259
Mathieu Chartier91e56692015-03-03 13:51:04 -08001260void Locks::InitConditions() {
1261 thread_exit_cond_ = new ConditionVariable("thread exit condition variable", *thread_list_lock_);
1262}
Ian Rogers719d1a32014-03-06 12:13:39 -08001263
David Sehrf42eb2c2016-10-19 13:20:45 -07001264void Locks::SetClientCallback(ClientCallback* safe_to_call_abort_cb) {
Orion Hodson88591fe2018-03-06 13:35:43 +00001265 safe_to_call_abort_callback.store(safe_to_call_abort_cb, std::memory_order_release);
David Sehrf42eb2c2016-10-19 13:20:45 -07001266}
1267
1268// Helper to allow checking shutdown while ignoring locking requirements.
1269bool Locks::IsSafeToCallAbortRacy() {
Orion Hodson88591fe2018-03-06 13:35:43 +00001270 Locks::ClientCallback* safe_to_call_abort_cb =
1271 safe_to_call_abort_callback.load(std::memory_order_acquire);
David Sehrf42eb2c2016-10-19 13:20:45 -07001272 return safe_to_call_abort_cb != nullptr && safe_to_call_abort_cb();
1273}
1274
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -08001275void Locks::AddToExpectedMutexesOnWeakRefAccess(BaseMutex* mutex, bool need_lock) {
1276 if (need_lock) {
1277 ScopedExpectedMutexesOnWeakRefAccessLock mu(mutex);
1278 mutex->SetShouldRespondToEmptyCheckpointRequest(true);
1279 expected_mutexes_on_weak_ref_access_.push_back(mutex);
1280 } else {
1281 mutex->SetShouldRespondToEmptyCheckpointRequest(true);
1282 expected_mutexes_on_weak_ref_access_.push_back(mutex);
1283 }
1284}
1285
1286void Locks::RemoveFromExpectedMutexesOnWeakRefAccess(BaseMutex* mutex, bool need_lock) {
1287 if (need_lock) {
1288 ScopedExpectedMutexesOnWeakRefAccessLock mu(mutex);
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 } else {
1295 mutex->SetShouldRespondToEmptyCheckpointRequest(false);
1296 std::vector<BaseMutex*>& list = expected_mutexes_on_weak_ref_access_;
1297 auto it = std::find(list.begin(), list.end(), mutex);
1298 DCHECK(it != list.end());
1299 list.erase(it);
1300 }
1301}
1302
1303bool Locks::IsExpectedOnWeakRefAccess(BaseMutex* mutex) {
1304 ScopedExpectedMutexesOnWeakRefAccessLock mu(mutex);
1305 std::vector<BaseMutex*>& list = expected_mutexes_on_weak_ref_access_;
1306 return std::find(list.begin(), list.end(), mutex) != list.end();
1307}
1308
Elliott Hughese62934d2012-04-09 11:24:29 -07001309} // namespace art