blob: 0d5ce15c499d48196ecc55e1b07b8030f6a7e9d9 [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 Gampe2cd21b22019-04-25 12:58:10 -070022#include <sstream>
23
Andreas Gampe46ee31b2016-12-14 10:11:49 -080024#include "android-base/stringprintf.h"
25
David Sehrc431b9d2018-03-02 12:01:51 -080026#include "base/atomic.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080027#include "base/logging.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080028#include "base/systrace.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070029#include "base/time_utils.h"
Ian Rogerscf7f1912014-10-22 22:06:39 -070030#include "base/value_object.h"
Ian Rogers693ff612013-02-01 10:56:12 -080031#include "mutex-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070032#include "scoped_thread_state_change-inl.h"
Ian Rogers04d7aa92013-03-16 14:29:17 -070033#include "thread-inl.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070034
35namespace art {
36
Andreas Gampe46ee31b2016-12-14 10:11:49 -080037using android::base::StringPrintf;
38
Ian Rogers719d1a32014-03-06 12:13:39 -080039struct AllMutexData {
40 // A guard for all_mutexes_ that's not a mutex (Mutexes must CAS to acquire and busy wait).
41 Atomic<const BaseMutex*> all_mutexes_guard;
42 // All created mutexes guarded by all_mutexes_guard_.
43 std::set<BaseMutex*>* all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -070044 AllMutexData() : all_mutexes(nullptr) {}
Ian Rogers719d1a32014-03-06 12:13:39 -080045};
46static struct AllMutexData gAllMutexData[kAllMutexDataSize];
47
Ian Rogersc604d732012-10-14 16:09:54 -070048#if ART_USE_FUTEXES
49static bool ComputeRelativeTimeSpec(timespec* result_ts, const timespec& lhs, const timespec& rhs) {
Brian Carlstromfb6996f2013-07-18 18:21:14 -070050 const int32_t one_sec = 1000 * 1000 * 1000; // one second in nanoseconds.
Ian Rogersc604d732012-10-14 16:09:54 -070051 result_ts->tv_sec = lhs.tv_sec - rhs.tv_sec;
52 result_ts->tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
53 if (result_ts->tv_nsec < 0) {
54 result_ts->tv_sec--;
55 result_ts->tv_nsec += one_sec;
56 } else if (result_ts->tv_nsec > one_sec) {
57 result_ts->tv_sec++;
58 result_ts->tv_nsec -= one_sec;
59 }
60 return result_ts->tv_sec < 0;
61}
62#endif
63
Hans Boehmae915a02017-12-12 11:05:32 -080064// Wait for an amount of time that roughly increases in the argument i.
65// Spin for small arguments and yield/sleep for longer ones.
66static void BackOff(uint32_t i) {
67 static constexpr uint32_t kSpinMax = 10;
68 static constexpr uint32_t kYieldMax = 20;
69 if (i <= kSpinMax) {
70 // TODO: Esp. in very latency-sensitive cases, consider replacing this with an explicit
71 // test-and-test-and-set loop in the caller. Possibly skip entirely on a uniprocessor.
72 volatile uint32_t x = 0;
73 const uint32_t spin_count = 10 * i;
74 for (uint32_t spin = 0; spin < spin_count; ++spin) {
75 ++x; // Volatile; hence should not be optimized away.
76 }
77 // TODO: Consider adding x86 PAUSE and/or ARM YIELD here.
78 } else if (i <= kYieldMax) {
79 sched_yield();
80 } else {
81 NanoSleep(1000ull * (i - kYieldMax));
82 }
83}
84
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010085class ScopedAllMutexesLock final {
Ian Rogers56edc432013-01-18 16:51:51 -080086 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -070087 explicit ScopedAllMutexesLock(const BaseMutex* mutex) : mutex_(mutex) {
Hans Boehmae915a02017-12-12 11:05:32 -080088 for (uint32_t i = 0;
Orion Hodson88591fe2018-03-06 13:35:43 +000089 !gAllMutexData->all_mutexes_guard.CompareAndSetWeakAcquire(nullptr, mutex);
Hans Boehmae915a02017-12-12 11:05:32 -080090 ++i) {
91 BackOff(i);
Ian Rogers56edc432013-01-18 16:51:51 -080092 }
93 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -070094
Ian Rogers56edc432013-01-18 16:51:51 -080095 ~ScopedAllMutexesLock() {
Orion Hodson88591fe2018-03-06 13:35:43 +000096 DCHECK_EQ(gAllMutexData->all_mutexes_guard.load(std::memory_order_relaxed), mutex_);
97 gAllMutexData->all_mutexes_guard.store(nullptr, std::memory_order_release);
Ian Rogers56edc432013-01-18 16:51:51 -080098 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -070099
Ian Rogers56edc432013-01-18 16:51:51 -0800100 private:
101 const BaseMutex* const mutex_;
102};
Ian Rogers56edc432013-01-18 16:51:51 -0800103
Ian Rogerscf7f1912014-10-22 22:06:39 -0700104// Scoped class that generates events at the beginning and end of lock contention.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100105class ScopedContentionRecorder final : public ValueObject {
Ian Rogerscf7f1912014-10-22 22:06:39 -0700106 public:
107 ScopedContentionRecorder(BaseMutex* mutex, uint64_t blocked_tid, uint64_t owner_tid)
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700108 : mutex_(kLogLockContentions ? mutex : nullptr),
Ian Rogerscf7f1912014-10-22 22:06:39 -0700109 blocked_tid_(kLogLockContentions ? blocked_tid : 0),
110 owner_tid_(kLogLockContentions ? owner_tid : 0),
111 start_nano_time_(kLogLockContentions ? NanoTime() : 0) {
Orion Hodson119733d2019-01-30 15:14:41 +0000112 if (ATraceEnabled()) {
Ian Rogerscf7f1912014-10-22 22:06:39 -0700113 std::string msg = StringPrintf("Lock contention on %s (owner tid: %" PRIu64 ")",
114 mutex->GetName(), owner_tid);
Orion Hodson119733d2019-01-30 15:14:41 +0000115 ATraceBegin(msg.c_str());
Ian Rogerscf7f1912014-10-22 22:06:39 -0700116 }
117 }
118
119 ~ScopedContentionRecorder() {
Orion Hodson119733d2019-01-30 15:14:41 +0000120 ATraceEnd();
Ian Rogerscf7f1912014-10-22 22:06:39 -0700121 if (kLogLockContentions) {
122 uint64_t end_nano_time = NanoTime();
123 mutex_->RecordContention(blocked_tid_, owner_tid_, end_nano_time - start_nano_time_);
124 }
125 }
126
127 private:
128 BaseMutex* const mutex_;
129 const uint64_t blocked_tid_;
130 const uint64_t owner_tid_;
131 const uint64_t start_nano_time_;
132};
133
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800134BaseMutex::BaseMutex(const char* name, LockLevel level)
Andreas Gampe5db8b7b2018-05-08 16:10:59 -0700135 : name_(name),
136 level_(level),
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800137 should_respond_to_empty_checkpoint_request_(false) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700138 if (kLogLockContentions) {
139 ScopedAllMutexesLock mu(this);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700140 std::set<BaseMutex*>** all_mutexes_ptr = &gAllMutexData->all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700141 if (*all_mutexes_ptr == nullptr) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700142 // We leak the global set of all mutexes to avoid ordering issues in global variable
143 // construction/destruction.
144 *all_mutexes_ptr = new std::set<BaseMutex*>();
145 }
146 (*all_mutexes_ptr)->insert(this);
Ian Rogers56edc432013-01-18 16:51:51 -0800147 }
Ian Rogers56edc432013-01-18 16:51:51 -0800148}
149
150BaseMutex::~BaseMutex() {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700151 if (kLogLockContentions) {
152 ScopedAllMutexesLock mu(this);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700153 gAllMutexData->all_mutexes->erase(this);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700154 }
Ian Rogers56edc432013-01-18 16:51:51 -0800155}
156
157void BaseMutex::DumpAll(std::ostream& os) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700158 if (kLogLockContentions) {
159 os << "Mutex logging:\n";
160 ScopedAllMutexesLock mu(reinterpret_cast<const BaseMutex*>(-1));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700161 std::set<BaseMutex*>* all_mutexes = gAllMutexData->all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700162 if (all_mutexes == nullptr) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700163 // No mutexes have been created yet during at startup.
164 return;
165 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700166 os << "(Contended)\n";
Andreas Gampec55bb392018-09-21 00:02:02 +0000167 for (const BaseMutex* mutex : *all_mutexes) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700168 if (mutex->HasEverContended()) {
169 mutex->Dump(os);
170 os << "\n";
171 }
172 }
173 os << "(Never contented)\n";
Andreas Gampec55bb392018-09-21 00:02:02 +0000174 for (const BaseMutex* mutex : *all_mutexes) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700175 if (!mutex->HasEverContended()) {
176 mutex->Dump(os);
177 os << "\n";
178 }
179 }
Ian Rogers56edc432013-01-18 16:51:51 -0800180 }
Ian Rogers56edc432013-01-18 16:51:51 -0800181}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700182
Ian Rogers81d425b2012-09-27 16:03:43 -0700183void BaseMutex::CheckSafeToWait(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700184 if (self == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700185 CheckUnattachedThread(level_);
186 return;
187 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700188 if (kDebugLocking) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700189 CHECK(self->GetHeldMutex(level_) == this || level_ == kMonitorLock)
190 << "Waiting on unacquired mutex: " << name_;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700191 bool bad_mutexes_held = false;
Andreas Gampe2cd21b22019-04-25 12:58:10 -0700192 std::string error_msg;
Elliott Hughes0f827162013-02-26 12:12:58 -0800193 for (int i = kLockLevelCount - 1; i >= 0; --i) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700194 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700195 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Alex Light66834462019-04-08 16:28:29 +0000196 // We allow the thread to wait even if the user_code_suspension_lock_ is held so long. This
197 // just means that gc or some other internal process is suspending the thread while it is
198 // trying to suspend some other thread. So long as the current thread is not being suspended
199 // by a SuspendReason::kForUserCode (which needs the user_code_suspension_lock_ to clear)
200 // this is fine. This is needed due to user_code_suspension_lock_ being the way untrusted
201 // code interacts with suspension. One holds the lock to prevent user-code-suspension from
202 // occurring. Since this is only initiated from user-supplied native-code this is safe.
203 if (held_mutex == Locks::user_code_suspension_lock_) {
Alex Light79400aa2017-07-18 15:34:21 -0700204 // No thread safety analysis is fine since we have both the user_code_suspension_lock_
205 // from the line above and the ThreadSuspendCountLock since it is our level_. We use this
206 // lambda to avoid having to annotate the whole function as NO_THREAD_SAFETY_ANALYSIS.
207 auto is_suspending_for_user_code = [self]() NO_THREAD_SAFETY_ANALYSIS {
208 return self->GetUserCodeSuspendCount() != 0;
209 };
210 if (is_suspending_for_user_code()) {
Andreas Gampe2cd21b22019-04-25 12:58:10 -0700211 std::ostringstream oss;
212 oss << "Holding \"" << held_mutex->name_ << "\" "
213 << "(level " << LockLevel(i) << ") while performing wait on "
214 << "\"" << name_ << "\" (level " << level_ << ") "
215 << "with SuspendReason::kForUserCode pending suspensions";
216 error_msg = oss.str();
217 LOG(ERROR) << error_msg;
Alex Light79400aa2017-07-18 15:34:21 -0700218 bad_mutexes_held = true;
219 }
220 } else if (held_mutex != nullptr) {
Andreas Gampe2cd21b22019-04-25 12:58:10 -0700221 std::ostringstream oss;
222 oss << "Holding \"" << held_mutex->name_ << "\" "
223 << "(level " << LockLevel(i) << ") while performing wait on "
224 << "\"" << name_ << "\" (level " << level_ << ")";
225 error_msg = oss.str();
226 LOG(ERROR) << error_msg;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700227 bad_mutexes_held = true;
228 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700229 }
230 }
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000231 if (gAborting == 0) { // Avoid recursive aborts.
Andreas Gampe2cd21b22019-04-25 12:58:10 -0700232 CHECK(!bad_mutexes_held) << error_msg;
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000233 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700234 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700235}
236
Ian Rogers37f3c962014-07-17 11:25:30 -0700237void BaseMutex::ContentionLogData::AddToWaitTime(uint64_t value) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700238 if (kLogLockContentions) {
239 // Atomically add value to wait_time.
Orion Hodson88591fe2018-03-06 13:35:43 +0000240 wait_time.fetch_add(value, std::memory_order_seq_cst);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700241 }
242}
243
Brian Carlstrom0de79852013-07-25 22:29:58 -0700244void BaseMutex::RecordContention(uint64_t blocked_tid,
245 uint64_t owner_tid,
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700246 uint64_t nano_time_blocked) {
247 if (kLogLockContentions) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700248 ContentionLogData* data = contention_log_data_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700249 ++(data->contention_count);
250 data->AddToWaitTime(nano_time_blocked);
251 ContentionLogEntry* log = data->contention_log;
252 // This code is intentionally racy as it is only used for diagnostics.
Orion Hodson88591fe2018-03-06 13:35:43 +0000253 int32_t slot = data->cur_content_log_entry.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700254 if (log[slot].blocked_tid == blocked_tid &&
255 log[slot].owner_tid == blocked_tid) {
256 ++log[slot].count;
257 } else {
258 uint32_t new_slot;
259 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000260 slot = data->cur_content_log_entry.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700261 new_slot = (slot + 1) % kContentionLogSize;
Orion Hodson4557b382018-01-03 11:47:54 +0000262 } while (!data->cur_content_log_entry.CompareAndSetWeakRelaxed(slot, new_slot));
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700263 log[new_slot].blocked_tid = blocked_tid;
264 log[new_slot].owner_tid = owner_tid;
Orion Hodson88591fe2018-03-06 13:35:43 +0000265 log[new_slot].count.store(1, std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700266 }
Ian Rogers56edc432013-01-18 16:51:51 -0800267 }
Ian Rogers56edc432013-01-18 16:51:51 -0800268}
269
Ian Rogers56edc432013-01-18 16:51:51 -0800270void BaseMutex::DumpContention(std::ostream& os) const {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700271 if (kLogLockContentions) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700272 const ContentionLogData* data = contention_log_data_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700273 const ContentionLogEntry* log = data->contention_log;
Orion Hodson88591fe2018-03-06 13:35:43 +0000274 uint64_t wait_time = data->wait_time.load(std::memory_order_relaxed);
275 uint32_t contention_count = data->contention_count.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700276 if (contention_count == 0) {
277 os << "never contended";
278 } else {
279 os << "contended " << contention_count
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700280 << " total wait of contender " << PrettyDuration(wait_time)
281 << " average " << PrettyDuration(wait_time / contention_count);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700282 SafeMap<uint64_t, size_t> most_common_blocker;
283 SafeMap<uint64_t, size_t> most_common_blocked;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700284 for (size_t i = 0; i < kContentionLogSize; ++i) {
285 uint64_t blocked_tid = log[i].blocked_tid;
286 uint64_t owner_tid = log[i].owner_tid;
Orion Hodson88591fe2018-03-06 13:35:43 +0000287 uint32_t count = log[i].count.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700288 if (count > 0) {
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700289 auto it = most_common_blocked.find(blocked_tid);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700290 if (it != most_common_blocked.end()) {
291 most_common_blocked.Overwrite(blocked_tid, it->second + count);
292 } else {
293 most_common_blocked.Put(blocked_tid, count);
294 }
295 it = most_common_blocker.find(owner_tid);
296 if (it != most_common_blocker.end()) {
297 most_common_blocker.Overwrite(owner_tid, it->second + count);
298 } else {
299 most_common_blocker.Put(owner_tid, count);
300 }
Ian Rogers56edc432013-01-18 16:51:51 -0800301 }
302 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700303 uint64_t max_tid = 0;
304 size_t max_tid_count = 0;
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700305 for (const auto& pair : most_common_blocked) {
306 if (pair.second > max_tid_count) {
307 max_tid = pair.first;
308 max_tid_count = pair.second;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700309 }
Ian Rogers56edc432013-01-18 16:51:51 -0800310 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700311 if (max_tid != 0) {
312 os << " sample shows most blocked tid=" << max_tid;
Ian Rogers56edc432013-01-18 16:51:51 -0800313 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700314 max_tid = 0;
315 max_tid_count = 0;
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700316 for (const auto& pair : most_common_blocker) {
317 if (pair.second > max_tid_count) {
318 max_tid = pair.first;
319 max_tid_count = pair.second;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700320 }
321 }
322 if (max_tid != 0) {
323 os << " sample shows tid=" << max_tid << " owning during this time";
324 }
Ian Rogers56edc432013-01-18 16:51:51 -0800325 }
326 }
Ian Rogers56edc432013-01-18 16:51:51 -0800327}
328
329
Ian Rogers81d425b2012-09-27 16:03:43 -0700330Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Andreas Gampe5db8b7b2018-05-08 16:10:59 -0700331 : BaseMutex(name, level), exclusive_owner_(0), recursion_count_(0), recursive_(recursive) {
Ian Rogersc604d732012-10-14 16:09:54 -0700332#if ART_USE_FUTEXES
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700333 DCHECK_EQ(0, state_and_contenders_.load(std::memory_order_relaxed));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700334#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700335 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, nullptr));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700336#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700337}
338
David Sehrf42eb2c2016-10-19 13:20:45 -0700339// Helper to allow checking shutdown while locking for thread safety.
340static bool IsSafeToCallAbortSafe() {
341 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
342 return Locks::IsSafeToCallAbortRacy();
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800343}
344
Elliott Hughes8daa0922011-09-11 13:46:25 -0700345Mutex::~Mutex() {
David Sehrf42eb2c2016-10-19 13:20:45 -0700346 bool safe_to_call_abort = Locks::IsSafeToCallAbortRacy();
Ian Rogersc604d732012-10-14 16:09:54 -0700347#if ART_USE_FUTEXES
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700348 if (state_and_contenders_.load(std::memory_order_relaxed) != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700349 LOG(safe_to_call_abort ? FATAL : WARNING)
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700350 << "destroying mutex with owner or contenders. Owner:" << GetExclusiveOwnerTid();
Ian Rogersc604d732012-10-14 16:09:54 -0700351 } else {
Hans Boehm0882af22017-08-31 15:21:57 -0700352 if (GetExclusiveOwnerTid() != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700353 LOG(safe_to_call_abort ? FATAL : WARNING)
354 << "unexpectedly found an owner on unlocked mutex " << name_;
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800355 }
Ian Rogersc604d732012-10-14 16:09:54 -0700356 }
357#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700358 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
359 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800360 int rc = pthread_mutex_destroy(&mutex_);
361 if (rc != 0) {
362 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700363 PLOG(safe_to_call_abort ? FATAL : WARNING)
364 << "pthread_mutex_destroy failed for " << name_;
Elliott Hughes6b355752012-01-13 16:49:08 -0800365 }
Ian Rogersc604d732012-10-14 16:09:54 -0700366#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700367}
368
Ian Rogers81d425b2012-09-27 16:03:43 -0700369void Mutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700370 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700371 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700372 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700373 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700374 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700375#if ART_USE_FUTEXES
376 bool done = false;
377 do {
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700378 int32_t cur_state = state_and_contenders_.load(std::memory_order_relaxed);
379 if (LIKELY((cur_state & kHeldMask) == 0) /* lock not held */) {
380 done = state_and_contenders_.CompareAndSetWeakAcquire(cur_state, cur_state | kHeldMask);
Ian Rogersc604d732012-10-14 16:09:54 -0700381 } else {
382 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700383 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700384 // Increment contender count. We can't create enough threads for this to overflow.
385 increment_contenders();
386 // Make cur_state again reflect the expected value of state_and_contenders.
387 cur_state += kContenderIncrement;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800388 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
389 self->CheckEmptyCheckpointFromMutex();
390 }
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700391 if (futex(state_and_contenders_.Address(), FUTEX_WAIT_PRIVATE, cur_state,
392 nullptr, nullptr, 0) != 0) {
393 // We only went to sleep after incrementing and contenders and checking that the lock
394 // is still held by someone else.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700395 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
396 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
397 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700398 PLOG(FATAL) << "futex wait failed for " << name_;
399 }
400 }
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700401 decrement_contenders();
Ian Rogersc604d732012-10-14 16:09:54 -0700402 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700403 } while (!done);
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700404 // Confirm that lock is now held.
405 DCHECK_NE(state_and_contenders_.load(std::memory_order_relaxed) & kHeldMask, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700406#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700407 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700408#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700409 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000410 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700411 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700412 }
413 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700414 if (kDebugLocking) {
415 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
416 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700417 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700418 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700419}
420
Ian Rogers81d425b2012-09-27 16:03:43 -0700421bool Mutex::ExclusiveTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700422 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700423 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700424 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700425 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700426 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700427#if ART_USE_FUTEXES
428 bool done = false;
429 do {
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700430 int32_t cur_state = state_and_contenders_.load(std::memory_order_relaxed);
431 if ((cur_state & kHeldMask) == 0) {
432 // Change state to held and impose load/store ordering appropriate for lock acquisition.
433 done = state_and_contenders_.CompareAndSetWeakAcquire(cur_state, cur_state | kHeldMask);
Ian Rogersc604d732012-10-14 16:09:54 -0700434 } else {
435 return false;
436 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700437 } while (!done);
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700438 DCHECK_NE(state_and_contenders_.load(std::memory_order_relaxed) & kHeldMask, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700439#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700440 int result = pthread_mutex_trylock(&mutex_);
441 if (result == EBUSY) {
442 return false;
443 }
444 if (result != 0) {
445 errno = result;
446 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
447 }
Ian Rogersc604d732012-10-14 16:09:54 -0700448#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700449 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000450 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700451 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700452 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700453 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700454 if (kDebugLocking) {
455 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
456 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700457 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700458 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700459 return true;
460}
461
Ian Rogers81d425b2012-09-27 16:03:43 -0700462void Mutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartiereb0a1792014-12-15 17:23:45 -0800463 if (kIsDebugBuild && self != nullptr && self != Thread::Current()) {
464 std::string name1 = "<null>";
465 std::string name2 = "<null>";
466 if (self != nullptr) {
467 self->GetThreadName(name1);
468 }
469 if (Thread::Current() != nullptr) {
470 Thread::Current()->GetThreadName(name2);
471 }
Mathieu Chartier4c101102015-01-27 17:14:16 -0800472 LOG(FATAL) << GetName() << " level=" << level_ << " self=" << name1
473 << " Thread::Current()=" << name2;
Mathieu Chartiereb0a1792014-12-15 17:23:45 -0800474 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700475 AssertHeld(self);
Hans Boehm0882af22017-08-31 15:21:57 -0700476 DCHECK_NE(GetExclusiveOwnerTid(), 0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477 recursion_count_--;
478 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700479 if (kDebugLocking) {
480 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
481 << name_ << " " << recursion_count_;
482 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700483 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700484#if ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700485 bool done = false;
486 do {
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700487 int32_t cur_state = state_and_contenders_.load(std::memory_order_relaxed);
488 if (LIKELY((cur_state & kHeldMask) != 0)) {
Ian Rogersc5f17732014-06-05 20:48:42 -0700489 // We're no longer the owner.
Orion Hodson88591fe2018-03-06 13:35:43 +0000490 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700491 // Change state to not held and impose load/store ordering appropriate for lock release.
492 uint32_t new_state = cur_state & ~kHeldMask; // Same number of contenders.
493 done = state_and_contenders_.CompareAndSetWeakRelease(cur_state, new_state);
494 if (LIKELY(done)) { // Spurious fail or waiters changed ?
495 if (UNLIKELY(new_state != 0) /* have contenders */) {
496 futex(state_and_contenders_.Address(), FUTEX_WAKE_PRIVATE, kWakeOne,
497 nullptr, nullptr, 0);
Ian Rogersc5f17732014-06-05 20:48:42 -0700498 }
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700499 // We only do a futex wait after incrementing contenders and verifying the lock was
500 // still held. If we didn't see waiters, then there couldn't have been any futexes
501 // waiting on this lock when we did the CAS. New arrivals after that cannot wait for us,
502 // since the futex wait call would see the lock available and immediately return.
Ian Rogersc5f17732014-06-05 20:48:42 -0700503 }
504 } else {
505 // Logging acquires the logging lock, avoid infinite recursion in that case.
506 if (this != Locks::logging_lock_) {
507 LOG(FATAL) << "Unexpected state_ in unlock " << cur_state << " for " << name_;
508 } else {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700509 LogHelper::LogLineLowStack(__FILE__,
510 __LINE__,
511 ::android::base::FATAL_WITHOUT_ABORT,
512 StringPrintf("Unexpected state_ %d in unlock for %s",
513 cur_state, name_).c_str());
Ian Rogersc5f17732014-06-05 20:48:42 -0700514 _exit(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700515 }
516 }
Ian Rogersc5f17732014-06-05 20:48:42 -0700517 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700518#else
Orion Hodson88591fe2018-03-06 13:35:43 +0000519 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700520 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700521#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700522 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700523}
524
Ian Rogers56edc432013-01-18 16:51:51 -0800525void Mutex::Dump(std::ostream& os) const {
526 os << (recursive_ ? "recursive " : "non-recursive ")
527 << name_
528 << " level=" << static_cast<int>(level_)
529 << " rec=" << recursion_count_
530 << " owner=" << GetExclusiveOwnerTid() << " ";
531 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700532}
533
534std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800535 mu.Dump(os);
536 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700537}
538
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800539void Mutex::WakeupToRespondToEmptyCheckpoint() {
540#if ART_USE_FUTEXES
541 // Wake up all the waiters so they will respond to the emtpy checkpoint.
542 DCHECK(should_respond_to_empty_checkpoint_request_);
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700543 if (UNLIKELY(get_contenders() != 0)) {
544 futex(state_and_contenders_.Address(), FUTEX_WAKE_PRIVATE, kWakeAll, nullptr, nullptr, 0);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800545 }
546#else
547 LOG(FATAL) << "Non futex case isn't supported.";
548#endif
549}
550
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700551ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level)
552 : BaseMutex(name, level)
Ian Rogers81d425b2012-09-27 16:03:43 -0700553#if ART_USE_FUTEXES
Hans Boehm467b6922019-04-22 16:15:53 -0700554 , state_(0), exclusive_owner_(0), num_contenders_(0)
Ian Rogers81d425b2012-09-27 16:03:43 -0700555#endif
Igor Murashkin5573c372017-11-16 13:34:30 -0800556{
Ian Rogers81d425b2012-09-27 16:03:43 -0700557#if !ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700558 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, nullptr));
Ian Rogers81d425b2012-09-27 16:03:43 -0700559#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700560}
561
562ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700563#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000564 CHECK_EQ(state_.load(std::memory_order_relaxed), 0);
Hans Boehm0882af22017-08-31 15:21:57 -0700565 CHECK_EQ(GetExclusiveOwnerTid(), 0);
Hans Boehm467b6922019-04-22 16:15:53 -0700566 CHECK_EQ(num_contenders_.load(std::memory_order_relaxed), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700567#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700568 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
569 // may still be using locks.
570 int rc = pthread_rwlock_destroy(&rwlock_);
571 if (rc != 0) {
572 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700573 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
574 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800575 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700576#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700577}
578
Ian Rogers81d425b2012-09-27 16:03:43 -0700579void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700580 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700581 AssertNotExclusiveHeld(self);
582#if ART_USE_FUTEXES
583 bool done = false;
584 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000585 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700586 if (LIKELY(cur_state == 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700587 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000588 done = state_.CompareAndSetWeakAcquire(0 /* cur_state*/, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700589 } else {
590 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700591 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Hans Boehm467b6922019-04-22 16:15:53 -0700592 num_contenders_.fetch_add(1);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800593 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
594 self->CheckEmptyCheckpointFromMutex();
595 }
Charles Munger7530bae2018-10-29 20:03:51 -0700596 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, nullptr, nullptr, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700597 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
598 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
599 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700600 PLOG(FATAL) << "futex wait failed for " << name_;
601 }
602 }
Hans Boehm467b6922019-04-22 16:15:53 -0700603 num_contenders_.fetch_sub(1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700604 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700605 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000606 DCHECK_EQ(state_.load(std::memory_order_relaxed), -1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700607#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700608 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700609#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700610 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000611 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700612 RegisterAsLocked(self);
613 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700614}
615
Ian Rogers81d425b2012-09-27 16:03:43 -0700616void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700617 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700618 AssertExclusiveHeld(self);
619 RegisterAsUnlocked(self);
Hans Boehm0882af22017-08-31 15:21:57 -0700620 DCHECK_NE(GetExclusiveOwnerTid(), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700621#if ART_USE_FUTEXES
622 bool done = false;
623 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000624 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700625 if (LIKELY(cur_state == -1)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700626 // We're no longer the owner.
Orion Hodson88591fe2018-03-06 13:35:43 +0000627 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc7190692014-07-08 23:50:26 -0700628 // Change state from -1 to 0 and impose load/store ordering appropriate for lock release.
Hans Boehm467b6922019-04-22 16:15:53 -0700629 // Note, the num_contenders_ load below musn't reorder before the CompareAndSet.
Orion Hodson4557b382018-01-03 11:47:54 +0000630 done = state_.CompareAndSetWeakSequentiallyConsistent(-1 /* cur_state*/, 0 /* new state */);
Ian Rogersc7190692014-07-08 23:50:26 -0700631 if (LIKELY(done)) { // Weak CAS may fail spuriously.
Ian Rogers81d425b2012-09-27 16:03:43 -0700632 // Wake any waiters.
Hans Boehm467b6922019-04-22 16:15:53 -0700633 if (UNLIKELY(num_contenders_.load(std::memory_order_seq_cst) > 0)) {
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700634 futex(state_.Address(), FUTEX_WAKE_PRIVATE, kWakeAll, nullptr, nullptr, 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700635 }
636 }
637 } else {
638 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
639 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700640 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700641#else
Orion Hodson88591fe2018-03-06 13:35:43 +0000642 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700643 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700644#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700645}
646
Ian Rogers66aee5c2012-08-15 17:17:47 -0700647#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700648bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700649 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700650#if ART_USE_FUTEXES
651 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700652 timespec end_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800653 InitTimeSpec(true, CLOCK_MONOTONIC, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700654 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000655 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700656 if (cur_state == 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700657 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000658 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700659 } else {
660 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700661 timespec now_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800662 InitTimeSpec(true, CLOCK_MONOTONIC, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700663 timespec rel_ts;
664 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
665 return false; // Timed out.
666 }
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700667 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Hans Boehm467b6922019-04-22 16:15:53 -0700668 num_contenders_.fetch_add(1);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800669 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
670 self->CheckEmptyCheckpointFromMutex();
671 }
Charles Munger7530bae2018-10-29 20:03:51 -0700672 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, &rel_ts, nullptr, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700673 if (errno == ETIMEDOUT) {
Hans Boehm467b6922019-04-22 16:15:53 -0700674 num_contenders_.fetch_sub(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700675 return false; // Timed out.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700676 } else if ((errno != EAGAIN) && (errno != EINTR)) {
677 // EAGAIN and EINTR both indicate a spurious failure,
678 // recompute the relative time out from now and try again.
679 // We don't use TEMP_FAILURE_RETRY so we can recompute rel_ts;
Ian Rogers81d425b2012-09-27 16:03:43 -0700680 PLOG(FATAL) << "timed futex wait failed for " << name_;
681 }
682 }
Hans Boehm467b6922019-04-22 16:15:53 -0700683 num_contenders_.fetch_sub(1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700684 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700685 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700686#else
Ian Rogersc604d732012-10-14 16:09:54 -0700687 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700688 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700689 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700690 if (result == ETIMEDOUT) {
691 return false;
692 }
693 if (result != 0) {
694 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700695 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700696 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700697#endif
Orion Hodson88591fe2018-03-06 13:35:43 +0000698 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700699 RegisterAsLocked(self);
700 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700701 return true;
702}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700703#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700704
Ian Rogers51d212e2014-10-23 17:48:20 -0700705#if ART_USE_FUTEXES
Ian Rogerscf7f1912014-10-22 22:06:39 -0700706void ReaderWriterMutex::HandleSharedLockContention(Thread* self, int32_t cur_state) {
707 // Owner holds it exclusively, hang up.
Roland Levillaincd72dc92018-02-27 19:15:31 +0000708 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Hans Boehm467b6922019-04-22 16:15:53 -0700709 num_contenders_.fetch_add(1);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800710 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
711 self->CheckEmptyCheckpointFromMutex();
712 }
Charles Munger7530bae2018-10-29 20:03:51 -0700713 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, nullptr, nullptr, 0) != 0) {
Daniel Colascione6f4d1022016-11-21 14:35:42 -0800714 if (errno != EAGAIN && errno != EINTR) {
Ian Rogerscf7f1912014-10-22 22:06:39 -0700715 PLOG(FATAL) << "futex wait failed for " << name_;
716 }
717 }
Hans Boehm467b6922019-04-22 16:15:53 -0700718 num_contenders_.fetch_sub(1);
Ian Rogerscf7f1912014-10-22 22:06:39 -0700719}
Ian Rogers51d212e2014-10-23 17:48:20 -0700720#endif
Ian Rogerscf7f1912014-10-22 22:06:39 -0700721
Ian Rogers81d425b2012-09-27 16:03:43 -0700722bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700723 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700724#if ART_USE_FUTEXES
725 bool done = false;
726 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000727 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700728 if (cur_state >= 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700729 // Add as an extra reader and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000730 done = state_.CompareAndSetWeakAcquire(cur_state, cur_state + 1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700731 } else {
732 // Owner holds it exclusively.
733 return false;
734 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700735 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700736#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700737 int result = pthread_rwlock_tryrdlock(&rwlock_);
738 if (result == EBUSY) {
739 return false;
740 }
741 if (result != 0) {
742 errno = result;
743 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
744 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700745#endif
746 RegisterAsLocked(self);
747 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700748 return true;
749}
750
Ian Rogers81d425b2012-09-27 16:03:43 -0700751bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700752 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700753 bool result;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700754 if (UNLIKELY(self == nullptr)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700755 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700756 } else {
757 result = (self->GetHeldMutex(level_) == this);
758 }
759 return result;
760}
761
Ian Rogers56edc432013-01-18 16:51:51 -0800762void ReaderWriterMutex::Dump(std::ostream& os) const {
763 os << name_
764 << " level=" << static_cast<int>(level_)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700765 << " owner=" << GetExclusiveOwnerTid()
766#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000767 << " state=" << state_.load(std::memory_order_seq_cst)
Hans Boehm467b6922019-04-22 16:15:53 -0700768 << " num_contenders=" << num_contenders_.load(std::memory_order_seq_cst)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700769#endif
770 << " ";
Ian Rogers56edc432013-01-18 16:51:51 -0800771 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700772}
773
774std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800775 mu.Dump(os);
776 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700777}
778
Yu Lieac44242015-06-29 10:50:03 +0800779std::ostream& operator<<(std::ostream& os, const MutatorMutex& mu) {
780 mu.Dump(os);
781 return os;
782}
783
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800784void ReaderWriterMutex::WakeupToRespondToEmptyCheckpoint() {
785#if ART_USE_FUTEXES
786 // Wake up all the waiters so they will respond to the emtpy checkpoint.
787 DCHECK(should_respond_to_empty_checkpoint_request_);
Hans Boehm467b6922019-04-22 16:15:53 -0700788 if (UNLIKELY(num_contenders_.load(std::memory_order_relaxed) > 0)) {
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700789 futex(state_.Address(), FUTEX_WAKE_PRIVATE, kWakeAll, nullptr, nullptr, 0);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800790 }
791#else
792 LOG(FATAL) << "Non futex case isn't supported.";
793#endif
794}
795
Ian Rogers23055dc2013-04-18 16:29:16 -0700796ConditionVariable::ConditionVariable(const char* name, Mutex& guard)
Ian Rogersc604d732012-10-14 16:09:54 -0700797 : name_(name), guard_(guard) {
798#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000799 DCHECK_EQ(0, sequence_.load(std::memory_order_relaxed));
Ian Rogersc604d732012-10-14 16:09:54 -0700800 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700801#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000802 pthread_condattr_t cond_attrs;
Ian Rogersc5f17732014-06-05 20:48:42 -0700803 CHECK_MUTEX_CALL(pthread_condattr_init, (&cond_attrs));
Narayan Kamath51b71022014-03-04 11:57:09 +0000804#if !defined(__APPLE__)
805 // Apple doesn't have CLOCK_MONOTONIC or pthread_condattr_setclock.
Ian Rogers51d212e2014-10-23 17:48:20 -0700806 CHECK_MUTEX_CALL(pthread_condattr_setclock, (&cond_attrs, CLOCK_MONOTONIC));
Narayan Kamath51b71022014-03-04 11:57:09 +0000807#endif
808 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, &cond_attrs));
Ian Rogersc604d732012-10-14 16:09:54 -0700809#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700810}
811
812ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800813#if ART_USE_FUTEXES
814 if (num_waiters_!= 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700815 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
816 LOG(is_safe_to_call_abort ? FATAL : WARNING)
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700817 << "ConditionVariable::~ConditionVariable for " << name_
Ian Rogersd45f2012012-11-28 11:46:23 -0800818 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800819 }
820#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700821 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
822 // may still be using condition variables.
823 int rc = pthread_cond_destroy(&cond_);
824 if (rc != 0) {
825 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700826 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
827 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_cond_destroy failed for " << name_;
Elliott Hughese62934d2012-04-09 11:24:29 -0700828 }
Ian Rogersc604d732012-10-14 16:09:54 -0700829#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700830}
831
Ian Rogersc604d732012-10-14 16:09:54 -0700832void ConditionVariable::Broadcast(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700833 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700834 // TODO: enable below, there's a race in thread creation that causes false failures currently.
835 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700836 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700837#if ART_USE_FUTEXES
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700838 RequeueWaiters(std::numeric_limits<int32_t>::max());
Ian Rogersc604d732012-10-14 16:09:54 -0700839#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700840 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700841#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700842}
843
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700844#if ART_USE_FUTEXES
845void ConditionVariable::RequeueWaiters(int32_t count) {
846 if (num_waiters_ > 0) {
847 sequence_++; // Indicate a signal occurred.
848 // Move waiters from the condition variable's futex to the guard's futex,
849 // so that they will be woken up when the mutex is released.
850 bool done = futex(sequence_.Address(),
Charles Munger7530bae2018-10-29 20:03:51 -0700851 FUTEX_REQUEUE_PRIVATE,
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700852 /* Threads to wake */ 0,
853 /* Threads to requeue*/ reinterpret_cast<const timespec*>(count),
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700854 guard_.state_and_contenders_.Address(),
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700855 0) != -1;
856 if (!done && errno != EAGAIN && errno != EINTR) {
857 PLOG(FATAL) << "futex requeue failed for " << name_;
858 }
859 }
860}
861#endif
862
863
Ian Rogersc604d732012-10-14 16:09:54 -0700864void ConditionVariable::Signal(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700865 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700866 guard_.AssertExclusiveHeld(self);
867#if ART_USE_FUTEXES
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700868 RequeueWaiters(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700869#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700870 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700871#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700872}
873
Ian Rogersc604d732012-10-14 16:09:54 -0700874void ConditionVariable::Wait(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700875 guard_.CheckSafeToWait(self);
876 WaitHoldingLocks(self);
877}
878
879void ConditionVariable::WaitHoldingLocks(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700880 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700881 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700882 unsigned int old_recursion_count = guard_.recursion_count_;
883#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700884 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800885 // Ensure the Mutex is contended so that requeued threads are awoken.
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700886 guard_.increment_contenders();
Ian Rogersc604d732012-10-14 16:09:54 -0700887 guard_.recursion_count_ = 1;
Orion Hodson88591fe2018-03-06 13:35:43 +0000888 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700889 guard_.ExclusiveUnlock(self);
Charles Munger7530bae2018-10-29 20:03:51 -0700890 if (futex(sequence_.Address(), FUTEX_WAIT_PRIVATE, cur_sequence, nullptr, nullptr, 0) != 0) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800891 // Futex failed, check it is an expected error.
892 // EAGAIN == EWOULDBLK, so we let the caller try again.
893 // EINTR implies a signal was sent to this thread.
894 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700895 PLOG(FATAL) << "futex wait failed for " << name_;
896 }
897 }
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800898 if (self != nullptr) {
899 JNIEnvExt* const env = self->GetJniEnv();
Ian Rogers55256cb2017-12-21 17:07:11 -0800900 if (UNLIKELY(env != nullptr && env->IsRuntimeDeleted())) {
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800901 CHECK(self->IsDaemon());
902 // If the runtime has been deleted, then we cannot proceed. Just sleep forever. This may
903 // occur for user daemon threads that get a spurious wakeup. This occurs for test 132 with
904 // --host and --gdb.
905 // After we wake up, the runtime may have been shutdown, which means that this condition may
906 // have been deleted. It is not safe to retry the wait.
907 SleepForever();
908 }
909 }
Ian Rogersc604d732012-10-14 16:09:54 -0700910 guard_.ExclusiveLock(self);
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700911 CHECK_GT(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700912 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800913 // We awoke and so no longer require awakes from the guard_'s unlock.
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700914 CHECK_GT(guard_.get_contenders(), 0);
915 guard_.decrement_contenders();
Ian Rogersc604d732012-10-14 16:09:54 -0700916#else
Hans Boehm0882af22017-08-31 15:21:57 -0700917 pid_t old_owner = guard_.GetExclusiveOwnerTid();
Orion Hodson88591fe2018-03-06 13:35:43 +0000918 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700919 guard_.recursion_count_ = 0;
920 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
Orion Hodson88591fe2018-03-06 13:35:43 +0000921 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700922#endif
923 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700924}
925
Ian Rogers7b078e82014-09-10 14:44:24 -0700926bool ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700927 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers7b078e82014-09-10 14:44:24 -0700928 bool timed_out = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700929 guard_.AssertExclusiveHeld(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700930 guard_.CheckSafeToWait(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700931 unsigned int old_recursion_count = guard_.recursion_count_;
932#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700933 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800934 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700935 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800936 // Ensure the Mutex is contended so that requeued threads are awoken.
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700937 guard_.increment_contenders();
Ian Rogersc604d732012-10-14 16:09:54 -0700938 guard_.recursion_count_ = 1;
Orion Hodson88591fe2018-03-06 13:35:43 +0000939 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700940 guard_.ExclusiveUnlock(self);
Charles Munger7530bae2018-10-29 20:03:51 -0700941 if (futex(sequence_.Address(), FUTEX_WAIT_PRIVATE, cur_sequence, &rel_ts, nullptr, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700942 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800943 // Timed out we're done.
Ian Rogers7b078e82014-09-10 14:44:24 -0700944 timed_out = true;
Brian Carlstrom0de79852013-07-25 22:29:58 -0700945 } else if ((errno == EAGAIN) || (errno == EINTR)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800946 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700947 } else {
948 PLOG(FATAL) << "timed futex wait failed for " << name_;
949 }
950 }
951 guard_.ExclusiveLock(self);
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700952 CHECK_GT(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700953 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800954 // We awoke and so no longer require awakes from the guard_'s unlock.
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700955 CHECK_GT(guard_.get_contenders(), 0);
956 guard_.decrement_contenders();
Ian Rogersc604d732012-10-14 16:09:54 -0700957#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000958#if !defined(__APPLE__)
Ian Rogersc604d732012-10-14 16:09:54 -0700959 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700960#else
Ian Rogersc604d732012-10-14 16:09:54 -0700961 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700962#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700963 pid_t old_owner = guard_.GetExclusiveOwnerTid();
Orion Hodson88591fe2018-03-06 13:35:43 +0000964 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700965 guard_.recursion_count_ = 0;
966 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700967 InitTimeSpec(true, clock, ms, ns, &ts);
Josh Gao2d899c42018-10-17 16:03:42 -0700968 int rc;
969 while ((rc = pthread_cond_timedwait(&cond_, &guard_.mutex_, &ts)) == EINTR) {
970 continue;
971 }
972
Ian Rogers7b078e82014-09-10 14:44:24 -0700973 if (rc == ETIMEDOUT) {
974 timed_out = true;
975 } else if (rc != 0) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700976 errno = rc;
977 PLOG(FATAL) << "TimedWait failed for " << name_;
978 }
Orion Hodson88591fe2018-03-06 13:35:43 +0000979 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700980#endif
981 guard_.recursion_count_ = old_recursion_count;
Ian Rogers7b078e82014-09-10 14:44:24 -0700982 return timed_out;
Elliott Hughes5f791332011-09-15 17:45:30 -0700983}
984
Elliott Hughese62934d2012-04-09 11:24:29 -0700985} // namespace art