blob: 3b35f5b98a94f31b1a7cc1dfbe290e718ba19f1d [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 Light66834462019-04-08 16:28:29 +0000193 // We allow the thread to wait even if the user_code_suspension_lock_ is held so long. This
194 // just means that gc or some other internal process is suspending the thread while it is
195 // trying to suspend some other thread. So long as the current thread is not being suspended
196 // by a SuspendReason::kForUserCode (which needs the user_code_suspension_lock_ to clear)
197 // this is fine. This is needed due to user_code_suspension_lock_ being the way untrusted
198 // code interacts with suspension. One holds the lock to prevent user-code-suspension from
199 // occurring. Since this is only initiated from user-supplied native-code this is safe.
200 if (held_mutex == Locks::user_code_suspension_lock_) {
Alex Light79400aa2017-07-18 15:34:21 -0700201 // No thread safety analysis is fine since we have both the user_code_suspension_lock_
202 // from the line above and the ThreadSuspendCountLock since it is our level_. We use this
203 // lambda to avoid having to annotate the whole function as NO_THREAD_SAFETY_ANALYSIS.
204 auto is_suspending_for_user_code = [self]() NO_THREAD_SAFETY_ANALYSIS {
205 return self->GetUserCodeSuspendCount() != 0;
206 };
207 if (is_suspending_for_user_code()) {
208 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
209 << "(level " << LockLevel(i) << ") while performing wait on "
210 << "\"" << name_ << "\" (level " << level_ << ") "
211 << "with SuspendReason::kForUserCode pending suspensions";
212 bad_mutexes_held = true;
213 }
214 } else if (held_mutex != nullptr) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800215 LOG(ERROR) << "Holding \"" << held_mutex->name_ << "\" "
216 << "(level " << LockLevel(i) << ") while performing wait on "
217 << "\"" << name_ << "\" (level " << level_ << ")";
Ian Rogers25fd14b2012-09-05 10:56:38 -0700218 bad_mutexes_held = true;
219 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700220 }
221 }
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000222 if (gAborting == 0) { // Avoid recursive aborts.
Alex Light79400aa2017-07-18 15:34:21 -0700223 CHECK(!bad_mutexes_held) << this;
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000224 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700225 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700226}
227
Ian Rogers37f3c962014-07-17 11:25:30 -0700228void BaseMutex::ContentionLogData::AddToWaitTime(uint64_t value) {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700229 if (kLogLockContentions) {
230 // Atomically add value to wait_time.
Orion Hodson88591fe2018-03-06 13:35:43 +0000231 wait_time.fetch_add(value, std::memory_order_seq_cst);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700232 }
233}
234
Brian Carlstrom0de79852013-07-25 22:29:58 -0700235void BaseMutex::RecordContention(uint64_t blocked_tid,
236 uint64_t owner_tid,
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700237 uint64_t nano_time_blocked) {
238 if (kLogLockContentions) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700239 ContentionLogData* data = contention_log_data_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700240 ++(data->contention_count);
241 data->AddToWaitTime(nano_time_blocked);
242 ContentionLogEntry* log = data->contention_log;
243 // This code is intentionally racy as it is only used for diagnostics.
Orion Hodson88591fe2018-03-06 13:35:43 +0000244 int32_t slot = data->cur_content_log_entry.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700245 if (log[slot].blocked_tid == blocked_tid &&
246 log[slot].owner_tid == blocked_tid) {
247 ++log[slot].count;
248 } else {
249 uint32_t new_slot;
250 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000251 slot = data->cur_content_log_entry.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700252 new_slot = (slot + 1) % kContentionLogSize;
Orion Hodson4557b382018-01-03 11:47:54 +0000253 } while (!data->cur_content_log_entry.CompareAndSetWeakRelaxed(slot, new_slot));
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700254 log[new_slot].blocked_tid = blocked_tid;
255 log[new_slot].owner_tid = owner_tid;
Orion Hodson88591fe2018-03-06 13:35:43 +0000256 log[new_slot].count.store(1, std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700257 }
Ian Rogers56edc432013-01-18 16:51:51 -0800258 }
Ian Rogers56edc432013-01-18 16:51:51 -0800259}
260
Ian Rogers56edc432013-01-18 16:51:51 -0800261void BaseMutex::DumpContention(std::ostream& os) const {
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700262 if (kLogLockContentions) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700263 const ContentionLogData* data = contention_log_data_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700264 const ContentionLogEntry* log = data->contention_log;
Orion Hodson88591fe2018-03-06 13:35:43 +0000265 uint64_t wait_time = data->wait_time.load(std::memory_order_relaxed);
266 uint32_t contention_count = data->contention_count.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700267 if (contention_count == 0) {
268 os << "never contended";
269 } else {
270 os << "contended " << contention_count
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700271 << " total wait of contender " << PrettyDuration(wait_time)
272 << " average " << PrettyDuration(wait_time / contention_count);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700273 SafeMap<uint64_t, size_t> most_common_blocker;
274 SafeMap<uint64_t, size_t> most_common_blocked;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700275 for (size_t i = 0; i < kContentionLogSize; ++i) {
276 uint64_t blocked_tid = log[i].blocked_tid;
277 uint64_t owner_tid = log[i].owner_tid;
Orion Hodson88591fe2018-03-06 13:35:43 +0000278 uint32_t count = log[i].count.load(std::memory_order_relaxed);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700279 if (count > 0) {
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700280 auto it = most_common_blocked.find(blocked_tid);
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700281 if (it != most_common_blocked.end()) {
282 most_common_blocked.Overwrite(blocked_tid, it->second + count);
283 } else {
284 most_common_blocked.Put(blocked_tid, count);
285 }
286 it = most_common_blocker.find(owner_tid);
287 if (it != most_common_blocker.end()) {
288 most_common_blocker.Overwrite(owner_tid, it->second + count);
289 } else {
290 most_common_blocker.Put(owner_tid, count);
291 }
Ian Rogers56edc432013-01-18 16:51:51 -0800292 }
293 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700294 uint64_t max_tid = 0;
295 size_t max_tid_count = 0;
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700296 for (const auto& pair : most_common_blocked) {
297 if (pair.second > max_tid_count) {
298 max_tid = pair.first;
299 max_tid_count = pair.second;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700300 }
Ian Rogers56edc432013-01-18 16:51:51 -0800301 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700302 if (max_tid != 0) {
303 os << " sample shows most blocked tid=" << max_tid;
Ian Rogers56edc432013-01-18 16:51:51 -0800304 }
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700305 max_tid = 0;
306 max_tid_count = 0;
Mathieu Chartier73d1e172014-04-11 17:53:48 -0700307 for (const auto& pair : most_common_blocker) {
308 if (pair.second > max_tid_count) {
309 max_tid = pair.first;
310 max_tid_count = pair.second;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700311 }
312 }
313 if (max_tid != 0) {
314 os << " sample shows tid=" << max_tid << " owning during this time";
315 }
Ian Rogers56edc432013-01-18 16:51:51 -0800316 }
317 }
Ian Rogers56edc432013-01-18 16:51:51 -0800318}
319
320
Ian Rogers81d425b2012-09-27 16:03:43 -0700321Mutex::Mutex(const char* name, LockLevel level, bool recursive)
Andreas Gampe5db8b7b2018-05-08 16:10:59 -0700322 : BaseMutex(name, level), exclusive_owner_(0), recursion_count_(0), recursive_(recursive) {
Ian Rogersc604d732012-10-14 16:09:54 -0700323#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000324 DCHECK_EQ(0, state_.load(std::memory_order_relaxed));
325 DCHECK_EQ(0, num_contenders_.load(std::memory_order_relaxed));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700326#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700327 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, nullptr));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700328#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700329}
330
David Sehrf42eb2c2016-10-19 13:20:45 -0700331// Helper to allow checking shutdown while locking for thread safety.
332static bool IsSafeToCallAbortSafe() {
333 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
334 return Locks::IsSafeToCallAbortRacy();
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800335}
336
Elliott Hughes8daa0922011-09-11 13:46:25 -0700337Mutex::~Mutex() {
David Sehrf42eb2c2016-10-19 13:20:45 -0700338 bool safe_to_call_abort = Locks::IsSafeToCallAbortRacy();
Ian Rogersc604d732012-10-14 16:09:54 -0700339#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000340 if (state_.load(std::memory_order_relaxed) != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700341 LOG(safe_to_call_abort ? FATAL : WARNING)
Hans Boehm0882af22017-08-31 15:21:57 -0700342 << "destroying mutex with owner: " << GetExclusiveOwnerTid();
Ian Rogersc604d732012-10-14 16:09:54 -0700343 } else {
Hans Boehm0882af22017-08-31 15:21:57 -0700344 if (GetExclusiveOwnerTid() != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700345 LOG(safe_to_call_abort ? FATAL : WARNING)
346 << "unexpectedly found an owner on unlocked mutex " << name_;
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800347 }
Orion Hodson88591fe2018-03-06 13:35:43 +0000348 if (num_contenders_.load(std::memory_order_seq_cst) != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700349 LOG(safe_to_call_abort ? FATAL : WARNING)
350 << "unexpectedly found a contender on mutex " << name_;
Mathieu Chartiercef50f02014-12-09 17:38:52 -0800351 }
Ian Rogersc604d732012-10-14 16:09:54 -0700352 }
353#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700354 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
355 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800356 int rc = pthread_mutex_destroy(&mutex_);
357 if (rc != 0) {
358 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700359 PLOG(safe_to_call_abort ? FATAL : WARNING)
360 << "pthread_mutex_destroy failed for " << name_;
Elliott Hughes6b355752012-01-13 16:49:08 -0800361 }
Ian Rogersc604d732012-10-14 16:09:54 -0700362#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700363}
364
Ian Rogers81d425b2012-09-27 16:03:43 -0700365void Mutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700366 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700367 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700368 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700369 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700370 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700371#if ART_USE_FUTEXES
372 bool done = false;
373 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000374 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700375 if (LIKELY(cur_state == 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700376 // Change state from 0 to 1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000377 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, 1 /* new state */);
Ian Rogersc604d732012-10-14 16:09:54 -0700378 } else {
379 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700380 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersb122a4b2013-11-19 18:00:50 -0800381 num_contenders_++;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800382 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
383 self->CheckEmptyCheckpointFromMutex();
384 }
Charles Munger7530bae2018-10-29 20:03:51 -0700385 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, 1, nullptr, nullptr, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700386 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
387 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
388 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700389 PLOG(FATAL) << "futex wait failed for " << name_;
390 }
391 }
Ian Rogersb122a4b2013-11-19 18:00:50 -0800392 num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700393 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700394 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000395 DCHECK_EQ(state_.load(std::memory_order_relaxed), 1);
Ian Rogersc604d732012-10-14 16:09:54 -0700396#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700397 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700398#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700399 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000400 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700401 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700402 }
403 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700404 if (kDebugLocking) {
405 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
406 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700407 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700408 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700409}
410
Ian Rogers81d425b2012-09-27 16:03:43 -0700411bool Mutex::ExclusiveTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700412 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700413 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700414 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700415 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700416 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700417#if ART_USE_FUTEXES
418 bool done = false;
419 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000420 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700421 if (cur_state == 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700422 // Change state from 0 to 1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000423 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, 1 /* new state */);
Ian Rogersc604d732012-10-14 16:09:54 -0700424 } else {
425 return false;
426 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700427 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000428 DCHECK_EQ(state_.load(std::memory_order_relaxed), 1);
Ian Rogersc604d732012-10-14 16:09:54 -0700429#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700430 int result = pthread_mutex_trylock(&mutex_);
431 if (result == EBUSY) {
432 return false;
433 }
434 if (result != 0) {
435 errno = result;
436 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
437 }
Ian Rogersc604d732012-10-14 16:09:54 -0700438#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700439 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000440 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700441 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700442 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700443 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700444 if (kDebugLocking) {
445 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
446 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700447 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700448 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700449 return true;
450}
451
Ian Rogers81d425b2012-09-27 16:03:43 -0700452void Mutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartiereb0a1792014-12-15 17:23:45 -0800453 if (kIsDebugBuild && self != nullptr && self != Thread::Current()) {
454 std::string name1 = "<null>";
455 std::string name2 = "<null>";
456 if (self != nullptr) {
457 self->GetThreadName(name1);
458 }
459 if (Thread::Current() != nullptr) {
460 Thread::Current()->GetThreadName(name2);
461 }
Mathieu Chartier4c101102015-01-27 17:14:16 -0800462 LOG(FATAL) << GetName() << " level=" << level_ << " self=" << name1
463 << " Thread::Current()=" << name2;
Mathieu Chartiereb0a1792014-12-15 17:23:45 -0800464 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700465 AssertHeld(self);
Hans Boehm0882af22017-08-31 15:21:57 -0700466 DCHECK_NE(GetExclusiveOwnerTid(), 0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 recursion_count_--;
468 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700469 if (kDebugLocking) {
470 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
471 << name_ << " " << recursion_count_;
472 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700473 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700474#if ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700475 bool done = false;
476 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000477 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogersc5f17732014-06-05 20:48:42 -0700478 if (LIKELY(cur_state == 1)) {
Ian Rogersc5f17732014-06-05 20:48:42 -0700479 // We're no longer the owner.
Orion Hodson88591fe2018-03-06 13:35:43 +0000480 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc7190692014-07-08 23:50:26 -0700481 // Change state to 0 and impose load/store ordering appropriate for lock release.
Orion Hodson4557b382018-01-03 11:47:54 +0000482 // Note, the relaxed loads below mustn't reorder before the CompareAndSet.
Ian Rogersc7190692014-07-08 23:50:26 -0700483 // TODO: the ordering here is non-trivial as state is split across 3 fields, fix by placing
484 // a status bit into the state on contention.
Orion Hodson4557b382018-01-03 11:47:54 +0000485 done = state_.CompareAndSetWeakSequentiallyConsistent(cur_state, 0 /* new state */);
Ian Rogersc5f17732014-06-05 20:48:42 -0700486 if (LIKELY(done)) { // Spurious fail?
Ian Rogersc7190692014-07-08 23:50:26 -0700487 // Wake a contender.
Hyangseok Chae240a5642018-07-25 16:45:08 +0900488 if (UNLIKELY(num_contenders_.load(std::memory_order_seq_cst) > 0)) {
Charles Munger7530bae2018-10-29 20:03:51 -0700489 futex(state_.Address(), FUTEX_WAKE_PRIVATE, 1, nullptr, nullptr, 0);
Ian Rogersc5f17732014-06-05 20:48:42 -0700490 }
491 }
492 } else {
493 // Logging acquires the logging lock, avoid infinite recursion in that case.
494 if (this != Locks::logging_lock_) {
495 LOG(FATAL) << "Unexpected state_ in unlock " << cur_state << " for " << name_;
496 } else {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700497 LogHelper::LogLineLowStack(__FILE__,
498 __LINE__,
499 ::android::base::FATAL_WITHOUT_ABORT,
500 StringPrintf("Unexpected state_ %d in unlock for %s",
501 cur_state, name_).c_str());
Ian Rogersc5f17732014-06-05 20:48:42 -0700502 _exit(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700503 }
504 }
Ian Rogersc5f17732014-06-05 20:48:42 -0700505 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700506#else
Orion Hodson88591fe2018-03-06 13:35:43 +0000507 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700508 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700509#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700510 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700511}
512
Ian Rogers56edc432013-01-18 16:51:51 -0800513void Mutex::Dump(std::ostream& os) const {
514 os << (recursive_ ? "recursive " : "non-recursive ")
515 << name_
516 << " level=" << static_cast<int>(level_)
517 << " rec=" << recursion_count_
518 << " owner=" << GetExclusiveOwnerTid() << " ";
519 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700520}
521
522std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800523 mu.Dump(os);
524 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700525}
526
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800527void Mutex::WakeupToRespondToEmptyCheckpoint() {
528#if ART_USE_FUTEXES
529 // Wake up all the waiters so they will respond to the emtpy checkpoint.
530 DCHECK(should_respond_to_empty_checkpoint_request_);
Orion Hodson88591fe2018-03-06 13:35:43 +0000531 if (UNLIKELY(num_contenders_.load(std::memory_order_relaxed) > 0)) {
Charles Munger7530bae2018-10-29 20:03:51 -0700532 futex(state_.Address(), FUTEX_WAKE_PRIVATE, -1, nullptr, nullptr, 0);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800533 }
534#else
535 LOG(FATAL) << "Non futex case isn't supported.";
536#endif
537}
538
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700539ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level)
540 : BaseMutex(name, level)
Ian Rogers81d425b2012-09-27 16:03:43 -0700541#if ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700542 , state_(0), num_pending_readers_(0), num_pending_writers_(0)
Ian Rogers81d425b2012-09-27 16:03:43 -0700543#endif
Igor Murashkin5573c372017-11-16 13:34:30 -0800544{
Ian Rogers81d425b2012-09-27 16:03:43 -0700545#if !ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700546 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, nullptr));
Ian Rogers81d425b2012-09-27 16:03:43 -0700547#endif
Orion Hodson88591fe2018-03-06 13:35:43 +0000548 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700549}
550
551ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700552#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000553 CHECK_EQ(state_.load(std::memory_order_relaxed), 0);
Hans Boehm0882af22017-08-31 15:21:57 -0700554 CHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000555 CHECK_EQ(num_pending_readers_.load(std::memory_order_relaxed), 0);
556 CHECK_EQ(num_pending_writers_.load(std::memory_order_relaxed), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700557#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700558 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
559 // may still be using locks.
560 int rc = pthread_rwlock_destroy(&rwlock_);
561 if (rc != 0) {
562 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700563 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
564 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800565 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700566#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700567}
568
Ian Rogers81d425b2012-09-27 16:03:43 -0700569void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700570 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700571 AssertNotExclusiveHeld(self);
572#if ART_USE_FUTEXES
573 bool done = false;
574 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000575 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700576 if (LIKELY(cur_state == 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700577 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000578 done = state_.CompareAndSetWeakAcquire(0 /* cur_state*/, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700579 } else {
580 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700581 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersc7190692014-07-08 23:50:26 -0700582 ++num_pending_writers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800583 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
584 self->CheckEmptyCheckpointFromMutex();
585 }
Charles Munger7530bae2018-10-29 20:03:51 -0700586 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, nullptr, nullptr, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700587 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
588 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
589 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700590 PLOG(FATAL) << "futex wait failed for " << name_;
591 }
592 }
Ian Rogersc7190692014-07-08 23:50:26 -0700593 --num_pending_writers_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700594 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700595 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000596 DCHECK_EQ(state_.load(std::memory_order_relaxed), -1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700597#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700598 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700599#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700600 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000601 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700602 RegisterAsLocked(self);
603 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700604}
605
Ian Rogers81d425b2012-09-27 16:03:43 -0700606void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700607 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700608 AssertExclusiveHeld(self);
609 RegisterAsUnlocked(self);
Hans Boehm0882af22017-08-31 15:21:57 -0700610 DCHECK_NE(GetExclusiveOwnerTid(), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700611#if ART_USE_FUTEXES
612 bool done = false;
613 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000614 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700615 if (LIKELY(cur_state == -1)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700616 // We're no longer the owner.
Orion Hodson88591fe2018-03-06 13:35:43 +0000617 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc7190692014-07-08 23:50:26 -0700618 // Change state from -1 to 0 and impose load/store ordering appropriate for lock release.
Orion Hodson4557b382018-01-03 11:47:54 +0000619 // Note, the relaxed loads below musn't reorder before the CompareAndSet.
Ian Rogersc7190692014-07-08 23:50:26 -0700620 // TODO: the ordering here is non-trivial as state is split across 3 fields, fix by placing
621 // a status bit into the state on contention.
Orion Hodson4557b382018-01-03 11:47:54 +0000622 done = state_.CompareAndSetWeakSequentiallyConsistent(-1 /* cur_state*/, 0 /* new state */);
Ian Rogersc7190692014-07-08 23:50:26 -0700623 if (LIKELY(done)) { // Weak CAS may fail spuriously.
Ian Rogers81d425b2012-09-27 16:03:43 -0700624 // Wake any waiters.
Hyangseok Chae240a5642018-07-25 16:45:08 +0900625 if (UNLIKELY(num_pending_readers_.load(std::memory_order_seq_cst) > 0 ||
626 num_pending_writers_.load(std::memory_order_seq_cst) > 0)) {
Charles Munger7530bae2018-10-29 20:03:51 -0700627 futex(state_.Address(), FUTEX_WAKE_PRIVATE, -1, nullptr, nullptr, 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700628 }
629 }
630 } else {
631 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
632 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700633 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700634#else
Orion Hodson88591fe2018-03-06 13:35:43 +0000635 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700636 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700637#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700638}
639
Ian Rogers66aee5c2012-08-15 17:17:47 -0700640#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700641bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700642 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700643#if ART_USE_FUTEXES
644 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700645 timespec end_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800646 InitTimeSpec(true, CLOCK_MONOTONIC, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700647 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000648 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700649 if (cur_state == 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700650 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000651 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700652 } else {
653 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700654 timespec now_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800655 InitTimeSpec(true, CLOCK_MONOTONIC, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700656 timespec rel_ts;
657 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
658 return false; // Timed out.
659 }
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700660 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogersc7190692014-07-08 23:50:26 -0700661 ++num_pending_writers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800662 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
663 self->CheckEmptyCheckpointFromMutex();
664 }
Charles Munger7530bae2018-10-29 20:03:51 -0700665 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, &rel_ts, nullptr, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700666 if (errno == ETIMEDOUT) {
Ian Rogersc7190692014-07-08 23:50:26 -0700667 --num_pending_writers_;
Ian Rogersc604d732012-10-14 16:09:54 -0700668 return false; // Timed out.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700669 } else if ((errno != EAGAIN) && (errno != EINTR)) {
670 // EAGAIN and EINTR both indicate a spurious failure,
671 // recompute the relative time out from now and try again.
672 // We don't use TEMP_FAILURE_RETRY so we can recompute rel_ts;
Ian Rogers81d425b2012-09-27 16:03:43 -0700673 PLOG(FATAL) << "timed futex wait failed for " << name_;
674 }
675 }
Ian Rogersc7190692014-07-08 23:50:26 -0700676 --num_pending_writers_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700677 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700678 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700679#else
Ian Rogersc604d732012-10-14 16:09:54 -0700680 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700681 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700682 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700683 if (result == ETIMEDOUT) {
684 return false;
685 }
686 if (result != 0) {
687 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700688 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700689 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700690#endif
Orion Hodson88591fe2018-03-06 13:35:43 +0000691 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700692 RegisterAsLocked(self);
693 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700694 return true;
695}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700696#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700697
Ian Rogers51d212e2014-10-23 17:48:20 -0700698#if ART_USE_FUTEXES
Ian Rogerscf7f1912014-10-22 22:06:39 -0700699void ReaderWriterMutex::HandleSharedLockContention(Thread* self, int32_t cur_state) {
700 // Owner holds it exclusively, hang up.
Roland Levillaincd72dc92018-02-27 19:15:31 +0000701 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Ian Rogerscf7f1912014-10-22 22:06:39 -0700702 ++num_pending_readers_;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800703 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
704 self->CheckEmptyCheckpointFromMutex();
705 }
Charles Munger7530bae2018-10-29 20:03:51 -0700706 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, nullptr, nullptr, 0) != 0) {
Daniel Colascione6f4d1022016-11-21 14:35:42 -0800707 if (errno != EAGAIN && errno != EINTR) {
Ian Rogerscf7f1912014-10-22 22:06:39 -0700708 PLOG(FATAL) << "futex wait failed for " << name_;
709 }
710 }
711 --num_pending_readers_;
712}
Ian Rogers51d212e2014-10-23 17:48:20 -0700713#endif
Ian Rogerscf7f1912014-10-22 22:06:39 -0700714
Ian Rogers81d425b2012-09-27 16:03:43 -0700715bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700716 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700717#if ART_USE_FUTEXES
718 bool done = false;
719 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000720 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700721 if (cur_state >= 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700722 // Add as an extra reader and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000723 done = state_.CompareAndSetWeakAcquire(cur_state, cur_state + 1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700724 } else {
725 // Owner holds it exclusively.
726 return false;
727 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700728 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700729#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700730 int result = pthread_rwlock_tryrdlock(&rwlock_);
731 if (result == EBUSY) {
732 return false;
733 }
734 if (result != 0) {
735 errno = result;
736 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
737 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700738#endif
739 RegisterAsLocked(self);
740 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700741 return true;
742}
743
Ian Rogers81d425b2012-09-27 16:03:43 -0700744bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700745 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700746 bool result;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700747 if (UNLIKELY(self == nullptr)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700748 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700749 } else {
750 result = (self->GetHeldMutex(level_) == this);
751 }
752 return result;
753}
754
Ian Rogers56edc432013-01-18 16:51:51 -0800755void ReaderWriterMutex::Dump(std::ostream& os) const {
756 os << name_
757 << " level=" << static_cast<int>(level_)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700758 << " owner=" << GetExclusiveOwnerTid()
759#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000760 << " state=" << state_.load(std::memory_order_seq_cst)
761 << " num_pending_writers=" << num_pending_writers_.load(std::memory_order_seq_cst)
762 << " num_pending_readers=" << num_pending_readers_.load(std::memory_order_seq_cst)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700763#endif
764 << " ";
Ian Rogers56edc432013-01-18 16:51:51 -0800765 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700766}
767
768std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800769 mu.Dump(os);
770 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700771}
772
Yu Lieac44242015-06-29 10:50:03 +0800773std::ostream& operator<<(std::ostream& os, const MutatorMutex& mu) {
774 mu.Dump(os);
775 return os;
776}
777
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800778void ReaderWriterMutex::WakeupToRespondToEmptyCheckpoint() {
779#if ART_USE_FUTEXES
780 // Wake up all the waiters so they will respond to the emtpy checkpoint.
781 DCHECK(should_respond_to_empty_checkpoint_request_);
Orion Hodson88591fe2018-03-06 13:35:43 +0000782 if (UNLIKELY(num_pending_readers_.load(std::memory_order_relaxed) > 0 ||
783 num_pending_writers_.load(std::memory_order_relaxed) > 0)) {
Charles Munger7530bae2018-10-29 20:03:51 -0700784 futex(state_.Address(), FUTEX_WAKE_PRIVATE, -1, nullptr, nullptr, 0);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800785 }
786#else
787 LOG(FATAL) << "Non futex case isn't supported.";
788#endif
789}
790
Ian Rogers23055dc2013-04-18 16:29:16 -0700791ConditionVariable::ConditionVariable(const char* name, Mutex& guard)
Ian Rogersc604d732012-10-14 16:09:54 -0700792 : name_(name), guard_(guard) {
793#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000794 DCHECK_EQ(0, sequence_.load(std::memory_order_relaxed));
Ian Rogersc604d732012-10-14 16:09:54 -0700795 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700796#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000797 pthread_condattr_t cond_attrs;
Ian Rogersc5f17732014-06-05 20:48:42 -0700798 CHECK_MUTEX_CALL(pthread_condattr_init, (&cond_attrs));
Narayan Kamath51b71022014-03-04 11:57:09 +0000799#if !defined(__APPLE__)
800 // Apple doesn't have CLOCK_MONOTONIC or pthread_condattr_setclock.
Ian Rogers51d212e2014-10-23 17:48:20 -0700801 CHECK_MUTEX_CALL(pthread_condattr_setclock, (&cond_attrs, CLOCK_MONOTONIC));
Narayan Kamath51b71022014-03-04 11:57:09 +0000802#endif
803 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, &cond_attrs));
Ian Rogersc604d732012-10-14 16:09:54 -0700804#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700805}
806
807ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800808#if ART_USE_FUTEXES
809 if (num_waiters_!= 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700810 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
811 LOG(is_safe_to_call_abort ? FATAL : WARNING)
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700812 << "ConditionVariable::~ConditionVariable for " << name_
Ian Rogersd45f2012012-11-28 11:46:23 -0800813 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800814 }
815#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700816 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
817 // may still be using condition variables.
818 int rc = pthread_cond_destroy(&cond_);
819 if (rc != 0) {
820 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700821 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
822 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_cond_destroy failed for " << name_;
Elliott Hughese62934d2012-04-09 11:24:29 -0700823 }
Ian Rogersc604d732012-10-14 16:09:54 -0700824#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700825}
826
Ian Rogersc604d732012-10-14 16:09:54 -0700827void ConditionVariable::Broadcast(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700828 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700829 // TODO: enable below, there's a race in thread creation that causes false failures currently.
830 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700831 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700832#if ART_USE_FUTEXES
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700833 RequeueWaiters(std::numeric_limits<int32_t>::max());
Ian Rogersc604d732012-10-14 16:09:54 -0700834#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700835 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700836#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700837}
838
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700839#if ART_USE_FUTEXES
840void ConditionVariable::RequeueWaiters(int32_t count) {
841 if (num_waiters_ > 0) {
842 sequence_++; // Indicate a signal occurred.
843 // Move waiters from the condition variable's futex to the guard's futex,
844 // so that they will be woken up when the mutex is released.
845 bool done = futex(sequence_.Address(),
Charles Munger7530bae2018-10-29 20:03:51 -0700846 FUTEX_REQUEUE_PRIVATE,
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700847 /* Threads to wake */ 0,
848 /* Threads to requeue*/ reinterpret_cast<const timespec*>(count),
849 guard_.state_.Address(),
850 0) != -1;
851 if (!done && errno != EAGAIN && errno != EINTR) {
852 PLOG(FATAL) << "futex requeue failed for " << name_;
853 }
854 }
855}
856#endif
857
858
Ian Rogersc604d732012-10-14 16:09:54 -0700859void ConditionVariable::Signal(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700860 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700861 guard_.AssertExclusiveHeld(self);
862#if ART_USE_FUTEXES
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700863 RequeueWaiters(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700864#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700865 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700866#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700867}
868
Ian Rogersc604d732012-10-14 16:09:54 -0700869void ConditionVariable::Wait(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700870 guard_.CheckSafeToWait(self);
871 WaitHoldingLocks(self);
872}
873
874void ConditionVariable::WaitHoldingLocks(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700875 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700876 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700877 unsigned int old_recursion_count = guard_.recursion_count_;
878#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700879 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800880 // Ensure the Mutex is contended so that requeued threads are awoken.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800881 guard_.num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -0700882 guard_.recursion_count_ = 1;
Orion Hodson88591fe2018-03-06 13:35:43 +0000883 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700884 guard_.ExclusiveUnlock(self);
Charles Munger7530bae2018-10-29 20:03:51 -0700885 if (futex(sequence_.Address(), FUTEX_WAIT_PRIVATE, cur_sequence, nullptr, nullptr, 0) != 0) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800886 // Futex failed, check it is an expected error.
887 // EAGAIN == EWOULDBLK, so we let the caller try again.
888 // EINTR implies a signal was sent to this thread.
889 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700890 PLOG(FATAL) << "futex wait failed for " << name_;
891 }
892 }
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800893 if (self != nullptr) {
894 JNIEnvExt* const env = self->GetJniEnv();
Ian Rogers55256cb2017-12-21 17:07:11 -0800895 if (UNLIKELY(env != nullptr && env->IsRuntimeDeleted())) {
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800896 CHECK(self->IsDaemon());
897 // If the runtime has been deleted, then we cannot proceed. Just sleep forever. This may
898 // occur for user daemon threads that get a spurious wakeup. This occurs for test 132 with
899 // --host and --gdb.
900 // After we wake up, the runtime may have been shutdown, which means that this condition may
901 // have been deleted. It is not safe to retry the wait.
902 SleepForever();
903 }
904 }
Ian Rogersc604d732012-10-14 16:09:54 -0700905 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800906 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700907 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800908 // We awoke and so no longer require awakes from the guard_'s unlock.
Orion Hodson88591fe2018-03-06 13:35:43 +0000909 CHECK_GE(guard_.num_contenders_.load(std::memory_order_relaxed), 0);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800910 guard_.num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700911#else
Hans Boehm0882af22017-08-31 15:21:57 -0700912 pid_t old_owner = guard_.GetExclusiveOwnerTid();
Orion Hodson88591fe2018-03-06 13:35:43 +0000913 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700914 guard_.recursion_count_ = 0;
915 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
Orion Hodson88591fe2018-03-06 13:35:43 +0000916 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700917#endif
918 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700919}
920
Ian Rogers7b078e82014-09-10 14:44:24 -0700921bool ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700922 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers7b078e82014-09-10 14:44:24 -0700923 bool timed_out = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700924 guard_.AssertExclusiveHeld(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700925 guard_.CheckSafeToWait(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700926 unsigned int old_recursion_count = guard_.recursion_count_;
927#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700928 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800929 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700930 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800931 // Ensure the Mutex is contended so that requeued threads are awoken.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800932 guard_.num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -0700933 guard_.recursion_count_ = 1;
Orion Hodson88591fe2018-03-06 13:35:43 +0000934 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700935 guard_.ExclusiveUnlock(self);
Charles Munger7530bae2018-10-29 20:03:51 -0700936 if (futex(sequence_.Address(), FUTEX_WAIT_PRIVATE, cur_sequence, &rel_ts, nullptr, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700937 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800938 // Timed out we're done.
Ian Rogers7b078e82014-09-10 14:44:24 -0700939 timed_out = true;
Brian Carlstrom0de79852013-07-25 22:29:58 -0700940 } else if ((errno == EAGAIN) || (errno == EINTR)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800941 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700942 } else {
943 PLOG(FATAL) << "timed futex wait failed for " << name_;
944 }
945 }
946 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800947 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700948 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800949 // We awoke and so no longer require awakes from the guard_'s unlock.
Orion Hodson88591fe2018-03-06 13:35:43 +0000950 CHECK_GE(guard_.num_contenders_.load(std::memory_order_relaxed), 0);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800951 guard_.num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700952#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000953#if !defined(__APPLE__)
Ian Rogersc604d732012-10-14 16:09:54 -0700954 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700955#else
Ian Rogersc604d732012-10-14 16:09:54 -0700956 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700957#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700958 pid_t old_owner = guard_.GetExclusiveOwnerTid();
Orion Hodson88591fe2018-03-06 13:35:43 +0000959 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700960 guard_.recursion_count_ = 0;
961 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700962 InitTimeSpec(true, clock, ms, ns, &ts);
Josh Gao2d899c42018-10-17 16:03:42 -0700963 int rc;
964 while ((rc = pthread_cond_timedwait(&cond_, &guard_.mutex_, &ts)) == EINTR) {
965 continue;
966 }
967
Ian Rogers7b078e82014-09-10 14:44:24 -0700968 if (rc == ETIMEDOUT) {
969 timed_out = true;
970 } else if (rc != 0) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700971 errno = rc;
972 PLOG(FATAL) << "TimedWait failed for " << name_;
973 }
Orion Hodson88591fe2018-03-06 13:35:43 +0000974 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700975#endif
976 guard_.recursion_count_ = old_recursion_count;
Ian Rogers7b078e82014-09-10 14:44:24 -0700977 return timed_out;
Elliott Hughes5f791332011-09-15 17:45:30 -0700978}
979
Elliott Hughese62934d2012-04-09 11:24:29 -0700980} // namespace art