blob: 7aec661c71812971a1965deb104a54eb699dd6e6 [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
Ian Rogers719d1a32014-03-06 12:13:39 -080037struct AllMutexData {
38 // A guard for all_mutexes_ that's not a mutex (Mutexes must CAS to acquire and busy wait).
39 Atomic<const BaseMutex*> all_mutexes_guard;
40 // All created mutexes guarded by all_mutexes_guard_.
41 std::set<BaseMutex*>* all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -070042 AllMutexData() : all_mutexes(nullptr) {}
Ian Rogers719d1a32014-03-06 12:13:39 -080043};
44static struct AllMutexData gAllMutexData[kAllMutexDataSize];
45
Ian Rogersc604d732012-10-14 16:09:54 -070046#if ART_USE_FUTEXES
47static bool ComputeRelativeTimeSpec(timespec* result_ts, const timespec& lhs, const timespec& rhs) {
Brian Carlstromfb6996f2013-07-18 18:21:14 -070048 const int32_t one_sec = 1000 * 1000 * 1000; // one second in nanoseconds.
Ian Rogersc604d732012-10-14 16:09:54 -070049 result_ts->tv_sec = lhs.tv_sec - rhs.tv_sec;
50 result_ts->tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
51 if (result_ts->tv_nsec < 0) {
52 result_ts->tv_sec--;
53 result_ts->tv_nsec += one_sec;
54 } else if (result_ts->tv_nsec > one_sec) {
55 result_ts->tv_sec++;
56 result_ts->tv_nsec -= one_sec;
57 }
58 return result_ts->tv_sec < 0;
59}
60#endif
61
Hans Boehmae915a02017-12-12 11:05:32 -080062// Wait for an amount of time that roughly increases in the argument i.
63// Spin for small arguments and yield/sleep for longer ones.
64static void BackOff(uint32_t i) {
65 static constexpr uint32_t kSpinMax = 10;
66 static constexpr uint32_t kYieldMax = 20;
67 if (i <= kSpinMax) {
68 // TODO: Esp. in very latency-sensitive cases, consider replacing this with an explicit
69 // test-and-test-and-set loop in the caller. Possibly skip entirely on a uniprocessor.
70 volatile uint32_t x = 0;
71 const uint32_t spin_count = 10 * i;
72 for (uint32_t spin = 0; spin < spin_count; ++spin) {
73 ++x; // Volatile; hence should not be optimized away.
74 }
75 // TODO: Consider adding x86 PAUSE and/or ARM YIELD here.
76 } else if (i <= kYieldMax) {
77 sched_yield();
78 } else {
79 NanoSleep(1000ull * (i - kYieldMax));
80 }
81}
82
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010083class ScopedAllMutexesLock final {
Ian Rogers56edc432013-01-18 16:51:51 -080084 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -070085 explicit ScopedAllMutexesLock(const BaseMutex* mutex) : mutex_(mutex) {
Hans Boehmae915a02017-12-12 11:05:32 -080086 for (uint32_t i = 0;
Orion Hodson88591fe2018-03-06 13:35:43 +000087 !gAllMutexData->all_mutexes_guard.CompareAndSetWeakAcquire(nullptr, mutex);
Hans Boehmae915a02017-12-12 11:05:32 -080088 ++i) {
89 BackOff(i);
Ian Rogers56edc432013-01-18 16:51:51 -080090 }
91 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -070092
Ian Rogers56edc432013-01-18 16:51:51 -080093 ~ScopedAllMutexesLock() {
Orion Hodson88591fe2018-03-06 13:35:43 +000094 DCHECK_EQ(gAllMutexData->all_mutexes_guard.load(std::memory_order_relaxed), mutex_);
95 gAllMutexData->all_mutexes_guard.store(nullptr, std::memory_order_release);
Ian Rogers56edc432013-01-18 16:51:51 -080096 }
Ian Rogers6f3dbba2014-10-14 17:41:57 -070097
Ian Rogers56edc432013-01-18 16:51:51 -080098 private:
99 const BaseMutex* const mutex_;
100};
Ian Rogers56edc432013-01-18 16:51:51 -0800101
Ian Rogerscf7f1912014-10-22 22:06:39 -0700102// Scoped class that generates events at the beginning and end of lock contention.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100103class ScopedContentionRecorder final : public ValueObject {
Ian Rogerscf7f1912014-10-22 22:06:39 -0700104 public:
105 ScopedContentionRecorder(BaseMutex* mutex, uint64_t blocked_tid, uint64_t owner_tid)
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700106 : mutex_(kLogLockContentions ? mutex : nullptr),
Ian Rogerscf7f1912014-10-22 22:06:39 -0700107 blocked_tid_(kLogLockContentions ? blocked_tid : 0),
108 owner_tid_(kLogLockContentions ? owner_tid : 0),
109 start_nano_time_(kLogLockContentions ? NanoTime() : 0) {
Orion Hodson119733d2019-01-30 15:14:41 +0000110 if (ATraceEnabled()) {
Ian Rogerscf7f1912014-10-22 22:06:39 -0700111 std::string msg = StringPrintf("Lock contention on %s (owner tid: %" PRIu64 ")",
112 mutex->GetName(), owner_tid);
Orion Hodson119733d2019-01-30 15:14:41 +0000113 ATraceBegin(msg.c_str());
Ian Rogerscf7f1912014-10-22 22:06:39 -0700114 }
115 }
116
117 ~ScopedContentionRecorder() {
Orion Hodson119733d2019-01-30 15:14:41 +0000118 ATraceEnd();
Ian Rogerscf7f1912014-10-22 22:06:39 -0700119 if (kLogLockContentions) {
120 uint64_t end_nano_time = NanoTime();
121 mutex_->RecordContention(blocked_tid_, owner_tid_, end_nano_time - start_nano_time_);
122 }
123 }
124
125 private:
126 BaseMutex* const mutex_;
127 const uint64_t blocked_tid_;
128 const uint64_t owner_tid_;
129 const uint64_t start_nano_time_;
130};
131
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800132BaseMutex::BaseMutex(const char* name, LockLevel level)
Andreas Gampe5db8b7b2018-05-08 16:10:59 -0700133 : name_(name),
134 level_(level),
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800135 should_respond_to_empty_checkpoint_request_(false) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700136 if (kLogLockContentions) {
137 ScopedAllMutexesLock mu(this);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700138 std::set<BaseMutex*>** all_mutexes_ptr = &gAllMutexData->all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700139 if (*all_mutexes_ptr == nullptr) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700140 // We leak the global set of all mutexes to avoid ordering issues in global variable
141 // construction/destruction.
142 *all_mutexes_ptr = new std::set<BaseMutex*>();
143 }
144 (*all_mutexes_ptr)->insert(this);
Ian Rogers56edc432013-01-18 16:51:51 -0800145 }
Ian Rogers56edc432013-01-18 16:51:51 -0800146}
147
148BaseMutex::~BaseMutex() {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700149 if (kLogLockContentions) {
150 ScopedAllMutexesLock mu(this);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700151 gAllMutexData->all_mutexes->erase(this);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700152 }
Ian Rogers56edc432013-01-18 16:51:51 -0800153}
154
155void BaseMutex::DumpAll(std::ostream& os) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700156 if (kLogLockContentions) {
157 os << "Mutex logging:\n";
158 ScopedAllMutexesLock mu(reinterpret_cast<const BaseMutex*>(-1));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700159 std::set<BaseMutex*>* all_mutexes = gAllMutexData->all_mutexes;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700160 if (all_mutexes == nullptr) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700161 // No mutexes have been created yet during at startup.
162 return;
163 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700164 os << "(Contended)\n";
Andreas Gampec55bb392018-09-21 00:02:02 +0000165 for (const BaseMutex* mutex : *all_mutexes) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700166 if (mutex->HasEverContended()) {
167 mutex->Dump(os);
168 os << "\n";
169 }
170 }
171 os << "(Never contented)\n";
Andreas Gampec55bb392018-09-21 00:02:02 +0000172 for (const BaseMutex* mutex : *all_mutexes) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700173 if (!mutex->HasEverContended()) {
174 mutex->Dump(os);
175 os << "\n";
176 }
177 }
Ian Rogers56edc432013-01-18 16:51:51 -0800178 }
Ian Rogers56edc432013-01-18 16:51:51 -0800179}
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700180
Ian Rogers81d425b2012-09-27 16:03:43 -0700181void BaseMutex::CheckSafeToWait(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700182 if (self == nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700183 CheckUnattachedThread(level_);
184 return;
185 }
Ian Rogers25fd14b2012-09-05 10:56:38 -0700186 if (kDebugLocking) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700187 CHECK(self->GetHeldMutex(level_) == this || level_ == kMonitorLock)
188 << "Waiting on unacquired mutex: " << name_;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700189 bool bad_mutexes_held = false;
Elliott Hughes0f827162013-02-26 12:12:58 -0800190 for (int i = kLockLevelCount - 1; i >= 0; --i) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700191 if (i != level_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700192 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
Alex Light79400aa2017-07-18 15:34:21 -0700193 // We allow the thread to wait even if the user_code_suspension_lock_ is held so long as we
194 // are some thread's resume_cond_ (level_ == kThreadSuspendCountLock). This just means that
195 // gc or some other internal process is suspending the thread while it is trying to suspend
196 // some other thread. So long as the current thread is not being suspended by a
197 // SuspendReason::kForUserCode (which needs the user_code_suspension_lock_ to clear) this is
198 // fine.
199 if (held_mutex == Locks::user_code_suspension_lock_ && level_ == kThreadSuspendCountLock) {
200 // No thread safety analysis is fine since we have both the user_code_suspension_lock_
201 // from the line above and the ThreadSuspendCountLock since it is our level_. We use this
202 // lambda to avoid having to annotate the whole function as NO_THREAD_SAFETY_ANALYSIS.
203 auto is_suspending_for_user_code = [self]() NO_THREAD_SAFETY_ANALYSIS {
204 return self->GetUserCodeSuspendCount() != 0;
205 };
206 if (is_suspending_for_user_code()) {
207 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
208 << "(level " << LockLevel(i) << ") while performing wait on "
209 << "\"" << name_ << "\" (level " << level_ << ") "
210 << "with SuspendReason::kForUserCode pending suspensions";
211 bad_mutexes_held = true;
212 }
213 } else if (held_mutex != nullptr) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800214 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
215 << "(level " << LockLevel(i) << ") while performing wait on "
216 << "\"" << name_ << "\" (level " << level_ << ")";
Ian Rogers25fd14b2012-09-05 10:56:38 -0700217 bad_mutexes_held = true;
218 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700219 }
220 }
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000221 if (gAborting == 0) { // Avoid recursive aborts.
Alex Light79400aa2017-07-18 15:34:21 -0700222 CHECK(!bad_mutexes_held) << this;
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000223 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700224 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700225}
226
Ian Rogers37f3c962014-07-17 11:25:30 -0700227void BaseMutex::ContentionLogData::AddToWaitTime(uint64_t value) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700228 if (kLogLockContentions) {
229 // Atomically add value to wait_time.
Orion Hodson88591fe2018-03-06 13:35:43 +0000230 wait_time.fetch_add(value, std::memory_order_seq_cst);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700231 }
232}
233
Brian Carlstrom0de79852013-07-25 22:29:58 -0700234void BaseMutex::RecordContention(uint64_t blocked_tid,
235 uint64_t owner_tid,
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700236 uint64_t nano_time_blocked) {
237 if (kLogLockContentions) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700238 ContentionLogData* data = contention_log_data_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700239 ++(data->contention_count);
240 data->AddToWaitTime(nano_time_blocked);
241 ContentionLogEntry* log = data->contention_log;
242 // This code is intentionally racy as it is only used for diagnostics.
Orion Hodson88591fe2018-03-06 13:35:43 +0000243 int32_t slot = data->cur_content_log_entry.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700244 if (log[slot].blocked_tid == blocked_tid &&
245 log[slot].owner_tid == blocked_tid) {
246 ++log[slot].count;
247 } else {
248 uint32_t new_slot;
249 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000250 slot = data->cur_content_log_entry.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700251 new_slot = (slot + 1) % kContentionLogSize;
Orion Hodson4557b382018-01-03 11:47:54 +0000252 } while (!data->cur_content_log_entry.CompareAndSetWeakRelaxed(slot, new_slot));
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700253 log[new_slot].blocked_tid = blocked_tid;
254 log[new_slot].owner_tid = owner_tid;
Orion Hodson88591fe2018-03-06 13:35:43 +0000255 log[new_slot].count.store(1, std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700256 }
Ian Rogers56edc432013-01-18 16:51:51 -0800257 }
Ian Rogers56edc432013-01-18 16:51:51 -0800258}
259
Ian Rogers56edc432013-01-18 16:51:51 -0800260void BaseMutex::DumpContention(std::ostream& os) const {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700261 if (kLogLockContentions) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700262 const ContentionLogData* data = contention_log_data_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700263 const ContentionLogEntry* log = data->contention_log;
Orion Hodson88591fe2018-03-06 13:35:43 +0000264 uint64_t wait_time = data->wait_time.load(std::memory_order_relaxed);
265 uint32_t contention_count = data->contention_count.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700266 if (contention_count == 0) {
267 os << "never contended";
268 } else {
269 os << "contended " << contention_count
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700270 << " total wait of contender " << PrettyDuration(wait_time)
271 << " average " << PrettyDuration(wait_time / contention_count);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700272 SafeMap<uint64_t, size_t> most_common_blocker;
273 SafeMap<uint64_t, size_t> most_common_blocked;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700274 for (size_t i = 0; i < kContentionLogSize; ++i) {
275 uint64_t blocked_tid = log[i].blocked_tid;
276 uint64_t owner_tid = log[i].owner_tid;
Orion Hodson88591fe2018-03-06 13:35:43 +0000277 uint32_t count = log[i].count.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700278 if (count > 0) {
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700279 auto it = most_common_blocked.find(blocked_tid);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700280 if (it != most_common_blocked.end()) {
281 most_common_blocked.Overwrite(blocked_tid, it->second + count);
282 } else {
283 most_common_blocked.Put(blocked_tid, count);
284 }
285 it = most_common_blocker.find(owner_tid);
286 if (it != most_common_blocker.end()) {
287 most_common_blocker.Overwrite(owner_tid, it->second + count);
288 } else {
289 most_common_blocker.Put(owner_tid, count);
290 }
Ian Rogers56edc432013-01-18 16:51:51 -0800291 }
292 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700293 uint64_t max_tid = 0;
294 size_t max_tid_count = 0;
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700295 for (const auto& pair : most_common_blocked) {
296 if (pair.second > max_tid_count) {
297 max_tid = pair.first;
298 max_tid_count = pair.second;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700299 }
Ian Rogers56edc432013-01-18 16:51:51 -0800300 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700301 if (max_tid != 0) {
302 os << " sample shows most blocked tid=" << max_tid;
Ian Rogers56edc432013-01-18 16:51:51 -0800303 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700304 max_tid = 0;
305 max_tid_count = 0;
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700306 for (const auto& pair : most_common_blocker) {
307 if (pair.second > max_tid_count) {
308 max_tid = pair.first;
309 max_tid_count = pair.second;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700310 }
311 }
312 if (max_tid != 0) {
313 os << " sample shows tid=" << max_tid << " owning during this time";
314 }
Ian Rogers56edc432013-01-18 16:51:51 -0800315 }
316 }
Ian Rogers56edc432013-01-18 16:51:51 -0800317}
318
319
Ian Rogers81d425b2012-09-27 16:03:43 -0700320Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Andreas Gampe5db8b7b2018-05-08 16:10:59 -0700321 : BaseMutex(name, level), exclusive_owner_(0), recursion_count_(0), recursive_(recursive) {
Ian Rogersc604d732012-10-14 16:09:54 -0700322#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000323 DCHECK_EQ(0, state_.load(std::memory_order_relaxed));
324 DCHECK_EQ(0, num_contenders_.load(std::memory_order_relaxed));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700325#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700326 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, nullptr));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700327#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700328}
329
David Sehrf42eb2c2016-10-19 13:20:45 -0700330// Helper to allow checking shutdown while locking for thread safety.
331static bool IsSafeToCallAbortSafe() {
332 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
333 return Locks::IsSafeToCallAbortRacy();
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800334}
335
Elliott Hughes8daa0922011-09-11 13:46:25 -0700336Mutex::~Mutex() {
David Sehrf42eb2c2016-10-19 13:20:45 -0700337 bool safe_to_call_abort = Locks::IsSafeToCallAbortRacy();
Ian Rogersc604d732012-10-14 16:09:54 -0700338#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000339 if (state_.load(std::memory_order_relaxed) != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700340 LOG(safe_to_call_abort ? FATAL : WARNING)
Hans Boehm0882af22017-08-31 15:21:57 -0700341 << "destroying mutex with owner: " << GetExclusiveOwnerTid();
Ian Rogersc604d732012-10-14 16:09:54 -0700342 } else {
Hans Boehm0882af22017-08-31 15:21:57 -0700343 if (GetExclusiveOwnerTid() != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700344 LOG(safe_to_call_abort ? FATAL : WARNING)
345 << "unexpectedly found an owner on unlocked mutex " << name_;
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800346 }
Orion Hodson88591fe2018-03-06 13:35:43 +0000347 if (num_contenders_.load(std::memory_order_seq_cst) != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700348 LOG(safe_to_call_abort ? FATAL : WARNING)
349 << "unexpectedly found a contender on mutex " << name_;
Mathieu Chartiercef50f02014-12-09 17:38:52 -0800350 }
Ian Rogersc604d732012-10-14 16:09:54 -0700351 }
352#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700353 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
354 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800355 int rc = pthread_mutex_destroy(&mutex_);
356 if (rc != 0) {
357 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700358 PLOG(safe_to_call_abort ? FATAL : WARNING)
359 << "pthread_mutex_destroy failed for " << name_;
Elliott Hughes6b355752012-01-13 16:49:08 -0800360 }
Ian Rogersc604d732012-10-14 16:09:54 -0700361#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700362}
363
Ian Rogers81d425b2012-09-27 16:03:43 -0700364void Mutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700365 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700366 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700367 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700368 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700369 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700370#if ART_USE_FUTEXES
371 bool done = false;
372 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000373 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700374 if (LIKELY(cur_state == 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700375 // Change state from 0 to 1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000376 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, 1 /* new state */);
Ian Rogersc604d732012-10-14 16:09:54 -0700377 } else {
378 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700379 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersb122a4b2013-11-19 18:00:50 -0800380 num_contenders_++;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800381 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
382 self->CheckEmptyCheckpointFromMutex();
383 }
Charles Munger7530bae2018-10-29 20:03:51 -0700384 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, 1, nullptr, nullptr, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700385 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
386 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
387 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700388 PLOG(FATAL) << "futex wait failed for " << name_;
389 }
390 }
Ian Rogersb122a4b2013-11-19 18:00:50 -0800391 num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700392 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700393 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000394 DCHECK_EQ(state_.load(std::memory_order_relaxed), 1);
Ian Rogersc604d732012-10-14 16:09:54 -0700395#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700396 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700397#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700398 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000399 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700400 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700401 }
402 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700403 if (kDebugLocking) {
404 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
405 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700406 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700407 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700408}
409
Ian Rogers81d425b2012-09-27 16:03:43 -0700410bool Mutex::ExclusiveTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700411 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700412 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700413 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700414 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700415 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700416#if ART_USE_FUTEXES
417 bool done = false;
418 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000419 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700420 if (cur_state == 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700421 // Change state from 0 to 1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000422 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, 1 /* new state */);
Ian Rogersc604d732012-10-14 16:09:54 -0700423 } else {
424 return false;
425 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700426 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000427 DCHECK_EQ(state_.load(std::memory_order_relaxed), 1);
Ian Rogersc604d732012-10-14 16:09:54 -0700428#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700429 int result = pthread_mutex_trylock(&mutex_);
430 if (result == EBUSY) {
431 return false;
432 }
433 if (result != 0) {
434 errno = result;
435 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
436 }
Ian Rogersc604d732012-10-14 16:09:54 -0700437#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700438 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000439 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700440 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700441 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700442 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700443 if (kDebugLocking) {
444 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
445 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700446 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700447 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700448 return true;
449}
450
Ian Rogers81d425b2012-09-27 16:03:43 -0700451void Mutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartiereb0a1792014-12-15 17:23:45 -0800452 if (kIsDebugBuild && self != nullptr && self != Thread::Current()) {
453 std::string name1 = "<null>";
454 std::string name2 = "<null>";
455 if (self != nullptr) {
456 self->GetThreadName(name1);
457 }
458 if (Thread::Current() != nullptr) {
459 Thread::Current()->GetThreadName(name2);
460 }
Mathieu Chartier4c101102015-01-27 17:14:16 -0800461 LOG(FATAL) << GetName() << " level=" << level_ << " self=" << name1
462 << " Thread::Current()=" << name2;
Mathieu Chartiereb0a1792014-12-15 17:23:45 -0800463 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700464 AssertHeld(self);
Hans Boehm0882af22017-08-31 15:21:57 -0700465 DCHECK_NE(GetExclusiveOwnerTid(), 0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700466 recursion_count_--;
467 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700468 if (kDebugLocking) {
469 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
470 << name_ << " " << recursion_count_;
471 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700472 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700473#if ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700474 bool done = false;
475 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000476 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogersc5f17732014-06-05 20:48:42 -0700477 if (LIKELY(cur_state == 1)) {
Ian Rogersc5f17732014-06-05 20:48:42 -0700478 // We're no longer the owner.
Orion Hodson88591fe2018-03-06 13:35:43 +0000479 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc7190692014-07-08 23:50:26 -0700480 // Change state to 0 and impose load/store ordering appropriate for lock release.
Orion Hodson4557b382018-01-03 11:47:54 +0000481 // Note, the relaxed loads below mustn't reorder before the CompareAndSet.
Ian Rogersc7190692014-07-08 23:50:26 -0700482 // TODO: the ordering here is non-trivial as state is split across 3 fields, fix by placing
483 // a status bit into the state on contention.
Orion Hodson4557b382018-01-03 11:47:54 +0000484 done = state_.CompareAndSetWeakSequentiallyConsistent(cur_state, 0 /* new state */);
Ian Rogersc5f17732014-06-05 20:48:42 -0700485 if (LIKELY(done)) { // Spurious fail?
Ian Rogersc7190692014-07-08 23:50:26 -0700486 // Wake a contender.
Hyangseok Chae240a5642018-07-25 16:45:08 +0900487 if (UNLIKELY(num_contenders_.load(std::memory_order_seq_cst) > 0)) {
Charles Munger7530bae2018-10-29 20:03:51 -0700488 futex(state_.Address(), FUTEX_WAKE_PRIVATE, 1, nullptr, nullptr, 0);
Ian Rogersc5f17732014-06-05 20:48:42 -0700489 }
490 }
491 } else {
492 // Logging acquires the logging lock, avoid infinite recursion in that case.
493 if (this != Locks::logging_lock_) {
494 LOG(FATAL) << "Unexpected state_ in unlock " << cur_state << " for " << name_;
495 } else {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700496 LogHelper::LogLineLowStack(__FILE__,
497 __LINE__,
498 ::android::base::FATAL_WITHOUT_ABORT,
499 StringPrintf("Unexpected state_ %d in unlock for %s",
500 cur_state, name_).c_str());
Ian Rogersc5f17732014-06-05 20:48:42 -0700501 _exit(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700502 }
503 }
Ian Rogersc5f17732014-06-05 20:48:42 -0700504 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700505#else
Orion Hodson88591fe2018-03-06 13:35:43 +0000506 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700507 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700508#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700509 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700510}
511
Ian Rogers56edc432013-01-18 16:51:51 -0800512void Mutex::Dump(std::ostream& os) const {
513 os << (recursive_ ? "recursive " : "non-recursive ")
514 << name_
515 << " level=" << static_cast<int>(level_)
516 << " rec=" << recursion_count_
517 << " owner=" << GetExclusiveOwnerTid() << " ";
518 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700519}
520
521std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800522 mu.Dump(os);
523 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700524}
525
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800526void Mutex::WakeupToRespondToEmptyCheckpoint() {
527#if ART_USE_FUTEXES
528 // Wake up all the waiters so they will respond to the emtpy checkpoint.
529 DCHECK(should_respond_to_empty_checkpoint_request_);
Orion Hodson88591fe2018-03-06 13:35:43 +0000530 if (UNLIKELY(num_contenders_.load(std::memory_order_relaxed) > 0)) {
Charles Munger7530bae2018-10-29 20:03:51 -0700531 futex(state_.Address(), FUTEX_WAKE_PRIVATE, -1, nullptr, nullptr, 0);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800532 }
533#else
534 LOG(FATAL) << "Non futex case isn't supported.";
535#endif
536}
537
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700538ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level)
539 : BaseMutex(name, level)
Ian Rogers81d425b2012-09-27 16:03:43 -0700540#if ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700541 , state_(0), num_pending_readers_(0), num_pending_writers_(0)
Ian Rogers81d425b2012-09-27 16:03:43 -0700542#endif
Igor Murashkin5573c372017-11-16 13:34:30 -0800543{
Ian Rogers81d425b2012-09-27 16:03:43 -0700544#if !ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700545 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, nullptr));
Ian Rogers81d425b2012-09-27 16:03:43 -0700546#endif
Orion Hodson88591fe2018-03-06 13:35:43 +0000547 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700548}
549
550ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700551#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000552 CHECK_EQ(state_.load(std::memory_order_relaxed), 0);
Hans Boehm0882af22017-08-31 15:21:57 -0700553 CHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000554 CHECK_EQ(num_pending_readers_.load(std::memory_order_relaxed), 0);
555 CHECK_EQ(num_pending_writers_.load(std::memory_order_relaxed), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700556#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700557 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
558 // may still be using locks.
559 int rc = pthread_rwlock_destroy(&rwlock_);
560 if (rc != 0) {
561 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700562 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
563 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800564 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700565#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700566}
567
Ian Rogers81d425b2012-09-27 16:03:43 -0700568void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700569 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700570 AssertNotExclusiveHeld(self);
571#if ART_USE_FUTEXES
572 bool done = false;
573 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000574 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700575 if (LIKELY(cur_state == 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700576 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000577 done = state_.CompareAndSetWeakAcquire(0 /* cur_state*/, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700578 } else {
579 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700580 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersc7190692014-07-08 23:50:26 -0700581 ++num_pending_writers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800582 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
583 self->CheckEmptyCheckpointFromMutex();
584 }
Charles Munger7530bae2018-10-29 20:03:51 -0700585 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, nullptr, nullptr, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700586 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
587 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
588 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700589 PLOG(FATAL) << "futex wait failed for " << name_;
590 }
591 }
Ian Rogersc7190692014-07-08 23:50:26 -0700592 --num_pending_writers_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700593 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700594 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000595 DCHECK_EQ(state_.load(std::memory_order_relaxed), -1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700596#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700597 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700598#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700599 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000600 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700601 RegisterAsLocked(self);
602 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700603}
604
Ian Rogers81d425b2012-09-27 16:03:43 -0700605void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700606 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700607 AssertExclusiveHeld(self);
608 RegisterAsUnlocked(self);
Hans Boehm0882af22017-08-31 15:21:57 -0700609 DCHECK_NE(GetExclusiveOwnerTid(), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700610#if ART_USE_FUTEXES
611 bool done = false;
612 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000613 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700614 if (LIKELY(cur_state == -1)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700615 // We're no longer the owner.
Orion Hodson88591fe2018-03-06 13:35:43 +0000616 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc7190692014-07-08 23:50:26 -0700617 // Change state from -1 to 0 and impose load/store ordering appropriate for lock release.
Orion Hodson4557b382018-01-03 11:47:54 +0000618 // Note, the relaxed loads below musn't reorder before the CompareAndSet.
Ian Rogersc7190692014-07-08 23:50:26 -0700619 // TODO: the ordering here is non-trivial as state is split across 3 fields, fix by placing
620 // a status bit into the state on contention.
Orion Hodson4557b382018-01-03 11:47:54 +0000621 done = state_.CompareAndSetWeakSequentiallyConsistent(-1 /* cur_state*/, 0 /* new state */);
Ian Rogersc7190692014-07-08 23:50:26 -0700622 if (LIKELY(done)) { // Weak CAS may fail spuriously.
Ian Rogers81d425b2012-09-27 16:03:43 -0700623 // Wake any waiters.
Hyangseok Chae240a5642018-07-25 16:45:08 +0900624 if (UNLIKELY(num_pending_readers_.load(std::memory_order_seq_cst) > 0 ||
625 num_pending_writers_.load(std::memory_order_seq_cst) > 0)) {
Charles Munger7530bae2018-10-29 20:03:51 -0700626 futex(state_.Address(), FUTEX_WAKE_PRIVATE, -1, nullptr, nullptr, 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700627 }
628 }
629 } else {
630 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
631 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700632 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700633#else
Orion Hodson88591fe2018-03-06 13:35:43 +0000634 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700635 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700636#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700637}
638
Ian Rogers66aee5c2012-08-15 17:17:47 -0700639#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700640bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700641 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700642#if ART_USE_FUTEXES
643 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700644 timespec end_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800645 InitTimeSpec(true, CLOCK_MONOTONIC, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700646 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000647 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700648 if (cur_state == 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700649 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000650 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700651 } else {
652 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700653 timespec now_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800654 InitTimeSpec(true, CLOCK_MONOTONIC, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700655 timespec rel_ts;
656 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
657 return false; // Timed out.
658 }
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700659 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersc7190692014-07-08 23:50:26 -0700660 ++num_pending_writers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800661 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
662 self->CheckEmptyCheckpointFromMutex();
663 }
Charles Munger7530bae2018-10-29 20:03:51 -0700664 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, &rel_ts, nullptr, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700665 if (errno == ETIMEDOUT) {
Ian Rogersc7190692014-07-08 23:50:26 -0700666 --num_pending_writers_;
Ian Rogersc604d732012-10-14 16:09:54 -0700667 return false; // Timed out.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700668 } else if ((errno != EAGAIN) && (errno != EINTR)) {
669 // EAGAIN and EINTR both indicate a spurious failure,
670 // recompute the relative time out from now and try again.
671 // We don't use TEMP_FAILURE_RETRY so we can recompute rel_ts;
Ian Rogers81d425b2012-09-27 16:03:43 -0700672 PLOG(FATAL) << "timed futex wait failed for " << name_;
673 }
674 }
Ian Rogersc7190692014-07-08 23:50:26 -0700675 --num_pending_writers_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700676 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700677 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700678#else
Ian Rogersc604d732012-10-14 16:09:54 -0700679 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700680 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700681 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700682 if (result == ETIMEDOUT) {
683 return false;
684 }
685 if (result != 0) {
686 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700687 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700688 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700689#endif
Orion Hodson88591fe2018-03-06 13:35:43 +0000690 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700691 RegisterAsLocked(self);
692 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700693 return true;
694}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700695#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700696
Ian Rogers51d212e2014-10-23 17:48:20 -0700697#if ART_USE_FUTEXES
Ian Rogerscf7f1912014-10-22 22:06:39 -0700698void ReaderWriterMutex::HandleSharedLockContention(Thread* self, int32_t cur_state) {
699 // Owner holds it exclusively, hang up.
Roland Levillaincd72dc92018-02-27 19:15:31 +0000700 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogerscf7f1912014-10-22 22:06:39 -0700701 ++num_pending_readers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800702 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
703 self->CheckEmptyCheckpointFromMutex();
704 }
Charles Munger7530bae2018-10-29 20:03:51 -0700705 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, nullptr, nullptr, 0) != 0) {
Daniel Colascione6f4d1022016-11-21 14:35:42 -0800706 if (errno != EAGAIN && errno != EINTR) {
Ian Rogerscf7f1912014-10-22 22:06:39 -0700707 PLOG(FATAL) << "futex wait failed for " << name_;
708 }
709 }
710 --num_pending_readers_;
711}
Ian Rogers51d212e2014-10-23 17:48:20 -0700712#endif
Ian Rogerscf7f1912014-10-22 22:06:39 -0700713
Ian Rogers81d425b2012-09-27 16:03:43 -0700714bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700715 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700716#if ART_USE_FUTEXES
717 bool done = false;
718 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000719 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700720 if (cur_state >= 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700721 // Add as an extra reader and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000722 done = state_.CompareAndSetWeakAcquire(cur_state, cur_state + 1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700723 } else {
724 // Owner holds it exclusively.
725 return false;
726 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700727 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700728#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700729 int result = pthread_rwlock_tryrdlock(&rwlock_);
730 if (result == EBUSY) {
731 return false;
732 }
733 if (result != 0) {
734 errno = result;
735 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
736 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700737#endif
738 RegisterAsLocked(self);
739 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700740 return true;
741}
742
Ian Rogers81d425b2012-09-27 16:03:43 -0700743bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700744 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700745 bool result;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700746 if (UNLIKELY(self == nullptr)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700747 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700748 } else {
749 result = (self->GetHeldMutex(level_) == this);
750 }
751 return result;
752}
753
Ian Rogers56edc432013-01-18 16:51:51 -0800754void ReaderWriterMutex::Dump(std::ostream& os) const {
755 os << name_
756 << " level=" << static_cast<int>(level_)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700757 << " owner=" << GetExclusiveOwnerTid()
758#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000759 << " state=" << state_.load(std::memory_order_seq_cst)
760 << " num_pending_writers=" << num_pending_writers_.load(std::memory_order_seq_cst)
761 << " num_pending_readers=" << num_pending_readers_.load(std::memory_order_seq_cst)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700762#endif
763 << " ";
Ian Rogers56edc432013-01-18 16:51:51 -0800764 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700765}
766
767std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800768 mu.Dump(os);
769 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700770}
771
Yu Lieac44242015-06-29 10:50:03 +0800772std::ostream& operator<<(std::ostream& os, const MutatorMutex& mu) {
773 mu.Dump(os);
774 return os;
775}
776
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800777void ReaderWriterMutex::WakeupToRespondToEmptyCheckpoint() {
778#if ART_USE_FUTEXES
779 // Wake up all the waiters so they will respond to the emtpy checkpoint.
780 DCHECK(should_respond_to_empty_checkpoint_request_);
Orion Hodson88591fe2018-03-06 13:35:43 +0000781 if (UNLIKELY(num_pending_readers_.load(std::memory_order_relaxed) > 0 ||
782 num_pending_writers_.load(std::memory_order_relaxed) > 0)) {
Charles Munger7530bae2018-10-29 20:03:51 -0700783 futex(state_.Address(), FUTEX_WAKE_PRIVATE, -1, nullptr, nullptr, 0);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800784 }
785#else
786 LOG(FATAL) << "Non futex case isn't supported.";
787#endif
788}
789
Ian Rogers23055dc2013-04-18 16:29:16 -0700790ConditionVariable::ConditionVariable(const char* name, Mutex& guard)
Ian Rogersc604d732012-10-14 16:09:54 -0700791 : name_(name), guard_(guard) {
792#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000793 DCHECK_EQ(0, sequence_.load(std::memory_order_relaxed));
Ian Rogersc604d732012-10-14 16:09:54 -0700794 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700795#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000796 pthread_condattr_t cond_attrs;
Ian Rogersc5f17732014-06-05 20:48:42 -0700797 CHECK_MUTEX_CALL(pthread_condattr_init, (&cond_attrs));
Narayan Kamath51b71022014-03-04 11:57:09 +0000798#if !defined(__APPLE__)
799 // Apple doesn't have CLOCK_MONOTONIC or pthread_condattr_setclock.
Ian Rogers51d212e2014-10-23 17:48:20 -0700800 CHECK_MUTEX_CALL(pthread_condattr_setclock, (&cond_attrs, CLOCK_MONOTONIC));
Narayan Kamath51b71022014-03-04 11:57:09 +0000801#endif
802 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, &cond_attrs));
Ian Rogersc604d732012-10-14 16:09:54 -0700803#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700804}
805
806ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800807#if ART_USE_FUTEXES
808 if (num_waiters_!= 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700809 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
810 LOG(is_safe_to_call_abort ? FATAL : WARNING)
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700811 << "ConditionVariable::~ConditionVariable for " << name_
Ian Rogersd45f2012012-11-28 11:46:23 -0800812 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800813 }
814#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700815 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
816 // may still be using condition variables.
817 int rc = pthread_cond_destroy(&cond_);
818 if (rc != 0) {
819 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700820 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
821 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_cond_destroy failed for " << name_;
Elliott Hughese62934d2012-04-09 11:24:29 -0700822 }
Ian Rogersc604d732012-10-14 16:09:54 -0700823#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700824}
825
Ian Rogersc604d732012-10-14 16:09:54 -0700826void ConditionVariable::Broadcast(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700827 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700828 // TODO: enable below, there's a race in thread creation that causes false failures currently.
829 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700830 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700831#if ART_USE_FUTEXES
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700832 RequeueWaiters(std::numeric_limits<int32_t>::max());
Ian Rogersc604d732012-10-14 16:09:54 -0700833#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700834 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700835#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700836}
837
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700838#if ART_USE_FUTEXES
839void ConditionVariable::RequeueWaiters(int32_t count) {
840 if (num_waiters_ > 0) {
841 sequence_++; // Indicate a signal occurred.
842 // Move waiters from the condition variable's futex to the guard's futex,
843 // so that they will be woken up when the mutex is released.
844 bool done = futex(sequence_.Address(),
Charles Munger7530bae2018-10-29 20:03:51 -0700845 FUTEX_REQUEUE_PRIVATE,
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700846 /* Threads to wake */ 0,
847 /* Threads to requeue*/ reinterpret_cast<const timespec*>(count),
848 guard_.state_.Address(),
849 0) != -1;
850 if (!done && errno != EAGAIN && errno != EINTR) {
851 PLOG(FATAL) << "futex requeue failed for " << name_;
852 }
853 }
854}
855#endif
856
857
Ian Rogersc604d732012-10-14 16:09:54 -0700858void ConditionVariable::Signal(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700859 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700860 guard_.AssertExclusiveHeld(self);
861#if ART_USE_FUTEXES
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700862 RequeueWaiters(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700863#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700864 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700865#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700866}
867
Ian Rogersc604d732012-10-14 16:09:54 -0700868void ConditionVariable::Wait(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700869 guard_.CheckSafeToWait(self);
870 WaitHoldingLocks(self);
871}
872
873void ConditionVariable::WaitHoldingLocks(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700874 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700875 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700876 unsigned int old_recursion_count = guard_.recursion_count_;
877#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700878 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800879 // Ensure the Mutex is contended so that requeued threads are awoken.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800880 guard_.num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -0700881 guard_.recursion_count_ = 1;
Orion Hodson88591fe2018-03-06 13:35:43 +0000882 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700883 guard_.ExclusiveUnlock(self);
Charles Munger7530bae2018-10-29 20:03:51 -0700884 if (futex(sequence_.Address(), FUTEX_WAIT_PRIVATE, cur_sequence, nullptr, nullptr, 0) != 0) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800885 // Futex failed, check it is an expected error.
886 // EAGAIN == EWOULDBLK, so we let the caller try again.
887 // EINTR implies a signal was sent to this thread.
888 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700889 PLOG(FATAL) << "futex wait failed for " << name_;
890 }
891 }
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800892 if (self != nullptr) {
893 JNIEnvExt* const env = self->GetJniEnv();
Ian Rogers55256cb2017-12-21 17:07:11 -0800894 if (UNLIKELY(env != nullptr && env->IsRuntimeDeleted())) {
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800895 CHECK(self->IsDaemon());
896 // If the runtime has been deleted, then we cannot proceed. Just sleep forever. This may
897 // occur for user daemon threads that get a spurious wakeup. This occurs for test 132 with
898 // --host and --gdb.
899 // After we wake up, the runtime may have been shutdown, which means that this condition may
900 // have been deleted. It is not safe to retry the wait.
901 SleepForever();
902 }
903 }
Ian Rogersc604d732012-10-14 16:09:54 -0700904 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800905 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700906 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800907 // We awoke and so no longer require awakes from the guard_'s unlock.
Orion Hodson88591fe2018-03-06 13:35:43 +0000908 CHECK_GE(guard_.num_contenders_.load(std::memory_order_relaxed), 0);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800909 guard_.num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700910#else
Hans Boehm0882af22017-08-31 15:21:57 -0700911 pid_t old_owner = guard_.GetExclusiveOwnerTid();
Orion Hodson88591fe2018-03-06 13:35:43 +0000912 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700913 guard_.recursion_count_ = 0;
914 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
Orion Hodson88591fe2018-03-06 13:35:43 +0000915 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700916#endif
917 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700918}
919
Ian Rogers7b078e82014-09-10 14:44:24 -0700920bool ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700921 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers7b078e82014-09-10 14:44:24 -0700922 bool timed_out = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700923 guard_.AssertExclusiveHeld(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700924 guard_.CheckSafeToWait(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700925 unsigned int old_recursion_count = guard_.recursion_count_;
926#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700927 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800928 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700929 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800930 // Ensure the Mutex is contended so that requeued threads are awoken.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800931 guard_.num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -0700932 guard_.recursion_count_ = 1;
Orion Hodson88591fe2018-03-06 13:35:43 +0000933 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700934 guard_.ExclusiveUnlock(self);
Charles Munger7530bae2018-10-29 20:03:51 -0700935 if (futex(sequence_.Address(), FUTEX_WAIT_PRIVATE, cur_sequence, &rel_ts, nullptr, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700936 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800937 // Timed out we're done.
Ian Rogers7b078e82014-09-10 14:44:24 -0700938 timed_out = true;
Brian Carlstrom0de79852013-07-25 22:29:58 -0700939 } else if ((errno == EAGAIN) || (errno == EINTR)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800940 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700941 } else {
942 PLOG(FATAL) << "timed futex wait failed for " << name_;
943 }
944 }
945 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800946 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700947 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800948 // We awoke and so no longer require awakes from the guard_'s unlock.
Orion Hodson88591fe2018-03-06 13:35:43 +0000949 CHECK_GE(guard_.num_contenders_.load(std::memory_order_relaxed), 0);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800950 guard_.num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700951#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000952#if !defined(__APPLE__)
Ian Rogersc604d732012-10-14 16:09:54 -0700953 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700954#else
Ian Rogersc604d732012-10-14 16:09:54 -0700955 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700956#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700957 pid_t old_owner = guard_.GetExclusiveOwnerTid();
Orion Hodson88591fe2018-03-06 13:35:43 +0000958 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700959 guard_.recursion_count_ = 0;
960 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700961 InitTimeSpec(true, clock, ms, ns, &ts);
Josh Gao2d899c42018-10-17 16:03:42 -0700962 int rc;
963 while ((rc = pthread_cond_timedwait(&cond_, &guard_.mutex_, &ts)) == EINTR) {
964 continue;
965 }
966
Ian Rogers7b078e82014-09-10 14:44:24 -0700967 if (rc == ETIMEDOUT) {
968 timed_out = true;
969 } else if (rc != 0) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700970 errno = rc;
971 PLOG(FATAL) << "TimedWait failed for " << name_;
972 }
Orion Hodson88591fe2018-03-06 13:35:43 +0000973 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700974#endif
975 guard_.recursion_count_ = old_recursion_count;
Ian Rogers7b078e82014-09-10 14:44:24 -0700976 return timed_out;
Elliott Hughes5f791332011-09-15 17:45:30 -0700977}
978
Elliott Hughese62934d2012-04-09 11:24:29 -0700979} // namespace art