blob: e965447e304ed471255c462e8087b662c5374044 [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
Hans Boehm467b6922019-04-22 16:15:53 -0700542 , state_(0), exclusive_owner_(0), num_contenders_(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
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);
Hans Boehm467b6922019-04-22 16:15:53 -0700554 CHECK_EQ(num_contenders_.load(std::memory_order_relaxed), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700555#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700556 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
557 // may still be using locks.
558 int rc = pthread_rwlock_destroy(&rwlock_);
559 if (rc != 0) {
560 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700561 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
562 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800563 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700564#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700565}
566
Ian Rogers81d425b2012-09-27 16:03:43 -0700567void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700568 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700569 AssertNotExclusiveHeld(self);
570#if ART_USE_FUTEXES
571 bool done = false;
572 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000573 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700574 if (LIKELY(cur_state == 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700575 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000576 done = state_.CompareAndSetWeakAcquire(0 /* cur_state*/, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700577 } else {
578 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700579 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Hans Boehm467b6922019-04-22 16:15:53 -0700580 num_contenders_.fetch_add(1);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800581 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
582 self->CheckEmptyCheckpointFromMutex();
583 }
Charles Munger7530bae2018-10-29 20:03:51 -0700584 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, nullptr, nullptr, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700585 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
586 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
587 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700588 PLOG(FATAL) << "futex wait failed for " << name_;
589 }
590 }
Hans Boehm467b6922019-04-22 16:15:53 -0700591 num_contenders_.fetch_sub(1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700592 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700593 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000594 DCHECK_EQ(state_.load(std::memory_order_relaxed), -1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700595#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700596 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700597#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700598 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000599 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700600 RegisterAsLocked(self);
601 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700602}
603
Ian Rogers81d425b2012-09-27 16:03:43 -0700604void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700605 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700606 AssertExclusiveHeld(self);
607 RegisterAsUnlocked(self);
Hans Boehm0882af22017-08-31 15:21:57 -0700608 DCHECK_NE(GetExclusiveOwnerTid(), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700609#if ART_USE_FUTEXES
610 bool done = false;
611 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000612 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700613 if (LIKELY(cur_state == -1)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700614 // We're no longer the owner.
Orion Hodson88591fe2018-03-06 13:35:43 +0000615 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc7190692014-07-08 23:50:26 -0700616 // Change state from -1 to 0 and impose load/store ordering appropriate for lock release.
Hans Boehm467b6922019-04-22 16:15:53 -0700617 // Note, the num_contenders_ load below musn't reorder before the CompareAndSet.
Orion Hodson4557b382018-01-03 11:47:54 +0000618 done = state_.CompareAndSetWeakSequentiallyConsistent(-1 /* cur_state*/, 0 /* new state */);
Ian Rogersc7190692014-07-08 23:50:26 -0700619 if (LIKELY(done)) { // Weak CAS may fail spuriously.
Ian Rogers81d425b2012-09-27 16:03:43 -0700620 // Wake any waiters.
Hans Boehm467b6922019-04-22 16:15:53 -0700621 if (UNLIKELY(num_contenders_.load(std::memory_order_seq_cst) > 0)) {
Charles Munger7530bae2018-10-29 20:03:51 -0700622 futex(state_.Address(), FUTEX_WAKE_PRIVATE, -1, nullptr, nullptr, 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700623 }
624 }
625 } else {
626 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
627 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700628 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700629#else
Orion Hodson88591fe2018-03-06 13:35:43 +0000630 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700631 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700632#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700633}
634
Ian Rogers66aee5c2012-08-15 17:17:47 -0700635#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700636bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700637 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700638#if ART_USE_FUTEXES
639 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700640 timespec end_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800641 InitTimeSpec(true, CLOCK_MONOTONIC, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700642 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000643 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700644 if (cur_state == 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700645 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000646 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700647 } else {
648 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700649 timespec now_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800650 InitTimeSpec(true, CLOCK_MONOTONIC, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700651 timespec rel_ts;
652 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
653 return false; // Timed out.
654 }
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700655 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Hans Boehm467b6922019-04-22 16:15:53 -0700656 num_contenders_.fetch_add(1);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800657 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
658 self->CheckEmptyCheckpointFromMutex();
659 }
Charles Munger7530bae2018-10-29 20:03:51 -0700660 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, &rel_ts, nullptr, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700661 if (errno == ETIMEDOUT) {
Hans Boehm467b6922019-04-22 16:15:53 -0700662 num_contenders_.fetch_sub(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700663 return false; // Timed out.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700664 } else if ((errno != EAGAIN) && (errno != EINTR)) {
665 // EAGAIN and EINTR both indicate a spurious failure,
666 // recompute the relative time out from now and try again.
667 // We don't use TEMP_FAILURE_RETRY so we can recompute rel_ts;
Ian Rogers81d425b2012-09-27 16:03:43 -0700668 PLOG(FATAL) << "timed futex wait failed for " << name_;
669 }
670 }
Hans Boehm467b6922019-04-22 16:15:53 -0700671 num_contenders_.fetch_sub(1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700672 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700673 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700674#else
Ian Rogersc604d732012-10-14 16:09:54 -0700675 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700676 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700677 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700678 if (result == ETIMEDOUT) {
679 return false;
680 }
681 if (result != 0) {
682 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700683 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700684 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700685#endif
Orion Hodson88591fe2018-03-06 13:35:43 +0000686 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700687 RegisterAsLocked(self);
688 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700689 return true;
690}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700691#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700692
Ian Rogers51d212e2014-10-23 17:48:20 -0700693#if ART_USE_FUTEXES
Ian Rogerscf7f1912014-10-22 22:06:39 -0700694void ReaderWriterMutex::HandleSharedLockContention(Thread* self, int32_t cur_state) {
695 // Owner holds it exclusively, hang up.
Roland Levillaincd72dc92018-02-27 19:15:31 +0000696 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Hans Boehm467b6922019-04-22 16:15:53 -0700697 num_contenders_.fetch_add(1);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800698 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
699 self->CheckEmptyCheckpointFromMutex();
700 }
Charles Munger7530bae2018-10-29 20:03:51 -0700701 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, nullptr, nullptr, 0) != 0) {
Daniel Colascione6f4d1022016-11-21 14:35:42 -0800702 if (errno != EAGAIN && errno != EINTR) {
Ian Rogerscf7f1912014-10-22 22:06:39 -0700703 PLOG(FATAL) << "futex wait failed for " << name_;
704 }
705 }
Hans Boehm467b6922019-04-22 16:15:53 -0700706 num_contenders_.fetch_sub(1);
Ian Rogerscf7f1912014-10-22 22:06:39 -0700707}
Ian Rogers51d212e2014-10-23 17:48:20 -0700708#endif
Ian Rogerscf7f1912014-10-22 22:06:39 -0700709
Ian Rogers81d425b2012-09-27 16:03:43 -0700710bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700711 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700712#if ART_USE_FUTEXES
713 bool done = false;
714 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000715 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700716 if (cur_state >= 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700717 // Add as an extra reader and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000718 done = state_.CompareAndSetWeakAcquire(cur_state, cur_state + 1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700719 } else {
720 // Owner holds it exclusively.
721 return false;
722 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700723 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700724#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700725 int result = pthread_rwlock_tryrdlock(&rwlock_);
726 if (result == EBUSY) {
727 return false;
728 }
729 if (result != 0) {
730 errno = result;
731 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
732 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700733#endif
734 RegisterAsLocked(self);
735 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700736 return true;
737}
738
Ian Rogers81d425b2012-09-27 16:03:43 -0700739bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700740 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700741 bool result;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700742 if (UNLIKELY(self == nullptr)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700743 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700744 } else {
745 result = (self->GetHeldMutex(level_) == this);
746 }
747 return result;
748}
749
Ian Rogers56edc432013-01-18 16:51:51 -0800750void ReaderWriterMutex::Dump(std::ostream& os) const {
751 os << name_
752 << " level=" << static_cast<int>(level_)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700753 << " owner=" << GetExclusiveOwnerTid()
754#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000755 << " state=" << state_.load(std::memory_order_seq_cst)
Hans Boehm467b6922019-04-22 16:15:53 -0700756 << " num_contenders=" << num_contenders_.load(std::memory_order_seq_cst)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700757#endif
758 << " ";
Ian Rogers56edc432013-01-18 16:51:51 -0800759 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700760}
761
762std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800763 mu.Dump(os);
764 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700765}
766
Yu Lieac44242015-06-29 10:50:03 +0800767std::ostream& operator<<(std::ostream& os, const MutatorMutex& mu) {
768 mu.Dump(os);
769 return os;
770}
771
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800772void ReaderWriterMutex::WakeupToRespondToEmptyCheckpoint() {
773#if ART_USE_FUTEXES
774 // Wake up all the waiters so they will respond to the emtpy checkpoint.
775 DCHECK(should_respond_to_empty_checkpoint_request_);
Hans Boehm467b6922019-04-22 16:15:53 -0700776 if (UNLIKELY(num_contenders_.load(std::memory_order_relaxed) > 0)) {
Charles Munger7530bae2018-10-29 20:03:51 -0700777 futex(state_.Address(), FUTEX_WAKE_PRIVATE, -1, nullptr, nullptr, 0);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800778 }
779#else
780 LOG(FATAL) << "Non futex case isn't supported.";
781#endif
782}
783
Ian Rogers23055dc2013-04-18 16:29:16 -0700784ConditionVariable::ConditionVariable(const char* name, Mutex& guard)
Ian Rogersc604d732012-10-14 16:09:54 -0700785 : name_(name), guard_(guard) {
786#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000787 DCHECK_EQ(0, sequence_.load(std::memory_order_relaxed));
Ian Rogersc604d732012-10-14 16:09:54 -0700788 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700789#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000790 pthread_condattr_t cond_attrs;
Ian Rogersc5f17732014-06-05 20:48:42 -0700791 CHECK_MUTEX_CALL(pthread_condattr_init, (&cond_attrs));
Narayan Kamath51b71022014-03-04 11:57:09 +0000792#if !defined(__APPLE__)
793 // Apple doesn't have CLOCK_MONOTONIC or pthread_condattr_setclock.
Ian Rogers51d212e2014-10-23 17:48:20 -0700794 CHECK_MUTEX_CALL(pthread_condattr_setclock, (&cond_attrs, CLOCK_MONOTONIC));
Narayan Kamath51b71022014-03-04 11:57:09 +0000795#endif
796 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, &cond_attrs));
Ian Rogersc604d732012-10-14 16:09:54 -0700797#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700798}
799
800ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800801#if ART_USE_FUTEXES
802 if (num_waiters_!= 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700803 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
804 LOG(is_safe_to_call_abort ? FATAL : WARNING)
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700805 << "ConditionVariable::~ConditionVariable for " << name_
Ian Rogersd45f2012012-11-28 11:46:23 -0800806 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800807 }
808#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700809 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
810 // may still be using condition variables.
811 int rc = pthread_cond_destroy(&cond_);
812 if (rc != 0) {
813 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700814 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
815 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_cond_destroy failed for " << name_;
Elliott Hughese62934d2012-04-09 11:24:29 -0700816 }
Ian Rogersc604d732012-10-14 16:09:54 -0700817#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700818}
819
Ian Rogersc604d732012-10-14 16:09:54 -0700820void ConditionVariable::Broadcast(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700821 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700822 // TODO: enable below, there's a race in thread creation that causes false failures currently.
823 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700824 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700825#if ART_USE_FUTEXES
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700826 RequeueWaiters(std::numeric_limits<int32_t>::max());
Ian Rogersc604d732012-10-14 16:09:54 -0700827#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700828 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700829#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700830}
831
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700832#if ART_USE_FUTEXES
833void ConditionVariable::RequeueWaiters(int32_t count) {
834 if (num_waiters_ > 0) {
835 sequence_++; // Indicate a signal occurred.
836 // Move waiters from the condition variable's futex to the guard's futex,
837 // so that they will be woken up when the mutex is released.
838 bool done = futex(sequence_.Address(),
Charles Munger7530bae2018-10-29 20:03:51 -0700839 FUTEX_REQUEUE_PRIVATE,
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700840 /* Threads to wake */ 0,
841 /* Threads to requeue*/ reinterpret_cast<const timespec*>(count),
842 guard_.state_.Address(),
843 0) != -1;
844 if (!done && errno != EAGAIN && errno != EINTR) {
845 PLOG(FATAL) << "futex requeue failed for " << name_;
846 }
847 }
848}
849#endif
850
851
Ian Rogersc604d732012-10-14 16:09:54 -0700852void ConditionVariable::Signal(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700853 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700854 guard_.AssertExclusiveHeld(self);
855#if ART_USE_FUTEXES
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700856 RequeueWaiters(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700857#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700858 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700859#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700860}
861
Ian Rogersc604d732012-10-14 16:09:54 -0700862void ConditionVariable::Wait(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700863 guard_.CheckSafeToWait(self);
864 WaitHoldingLocks(self);
865}
866
867void ConditionVariable::WaitHoldingLocks(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700868 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700869 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700870 unsigned int old_recursion_count = guard_.recursion_count_;
871#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700872 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800873 // Ensure the Mutex is contended so that requeued threads are awoken.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800874 guard_.num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -0700875 guard_.recursion_count_ = 1;
Orion Hodson88591fe2018-03-06 13:35:43 +0000876 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700877 guard_.ExclusiveUnlock(self);
Charles Munger7530bae2018-10-29 20:03:51 -0700878 if (futex(sequence_.Address(), FUTEX_WAIT_PRIVATE, cur_sequence, nullptr, nullptr, 0) != 0) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800879 // Futex failed, check it is an expected error.
880 // EAGAIN == EWOULDBLK, so we let the caller try again.
881 // EINTR implies a signal was sent to this thread.
882 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700883 PLOG(FATAL) << "futex wait failed for " << name_;
884 }
885 }
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800886 if (self != nullptr) {
887 JNIEnvExt* const env = self->GetJniEnv();
Ian Rogers55256cb2017-12-21 17:07:11 -0800888 if (UNLIKELY(env != nullptr && env->IsRuntimeDeleted())) {
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800889 CHECK(self->IsDaemon());
890 // If the runtime has been deleted, then we cannot proceed. Just sleep forever. This may
891 // occur for user daemon threads that get a spurious wakeup. This occurs for test 132 with
892 // --host and --gdb.
893 // After we wake up, the runtime may have been shutdown, which means that this condition may
894 // have been deleted. It is not safe to retry the wait.
895 SleepForever();
896 }
897 }
Ian Rogersc604d732012-10-14 16:09:54 -0700898 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800899 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700900 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800901 // We awoke and so no longer require awakes from the guard_'s unlock.
Orion Hodson88591fe2018-03-06 13:35:43 +0000902 CHECK_GE(guard_.num_contenders_.load(std::memory_order_relaxed), 0);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800903 guard_.num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700904#else
Hans Boehm0882af22017-08-31 15:21:57 -0700905 pid_t old_owner = guard_.GetExclusiveOwnerTid();
Orion Hodson88591fe2018-03-06 13:35:43 +0000906 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700907 guard_.recursion_count_ = 0;
908 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
Orion Hodson88591fe2018-03-06 13:35:43 +0000909 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700910#endif
911 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700912}
913
Ian Rogers7b078e82014-09-10 14:44:24 -0700914bool ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700915 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers7b078e82014-09-10 14:44:24 -0700916 bool timed_out = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700917 guard_.AssertExclusiveHeld(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700918 guard_.CheckSafeToWait(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700919 unsigned int old_recursion_count = guard_.recursion_count_;
920#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700921 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800922 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700923 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800924 // Ensure the Mutex is contended so that requeued threads are awoken.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800925 guard_.num_contenders_++;
Ian Rogersc604d732012-10-14 16:09:54 -0700926 guard_.recursion_count_ = 1;
Orion Hodson88591fe2018-03-06 13:35:43 +0000927 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700928 guard_.ExclusiveUnlock(self);
Charles Munger7530bae2018-10-29 20:03:51 -0700929 if (futex(sequence_.Address(), FUTEX_WAIT_PRIVATE, cur_sequence, &rel_ts, nullptr, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700930 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800931 // Timed out we're done.
Ian Rogers7b078e82014-09-10 14:44:24 -0700932 timed_out = true;
Brian Carlstrom0de79852013-07-25 22:29:58 -0700933 } else if ((errno == EAGAIN) || (errno == EINTR)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800934 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700935 } else {
936 PLOG(FATAL) << "timed futex wait failed for " << name_;
937 }
938 }
939 guard_.ExclusiveLock(self);
Ian Rogersd45f2012012-11-28 11:46:23 -0800940 CHECK_GE(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700941 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800942 // We awoke and so no longer require awakes from the guard_'s unlock.
Orion Hodson88591fe2018-03-06 13:35:43 +0000943 CHECK_GE(guard_.num_contenders_.load(std::memory_order_relaxed), 0);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800944 guard_.num_contenders_--;
Ian Rogersc604d732012-10-14 16:09:54 -0700945#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000946#if !defined(__APPLE__)
Ian Rogersc604d732012-10-14 16:09:54 -0700947 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700948#else
Ian Rogersc604d732012-10-14 16:09:54 -0700949 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700950#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700951 pid_t old_owner = guard_.GetExclusiveOwnerTid();
Orion Hodson88591fe2018-03-06 13:35:43 +0000952 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700953 guard_.recursion_count_ = 0;
954 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700955 InitTimeSpec(true, clock, ms, ns, &ts);
Josh Gao2d899c42018-10-17 16:03:42 -0700956 int rc;
957 while ((rc = pthread_cond_timedwait(&cond_, &guard_.mutex_, &ts)) == EINTR) {
958 continue;
959 }
960
Ian Rogers7b078e82014-09-10 14:44:24 -0700961 if (rc == ETIMEDOUT) {
962 timed_out = true;
963 } else if (rc != 0) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700964 errno = rc;
965 PLOG(FATAL) << "TimedWait failed for " << name_;
966 }
Orion Hodson88591fe2018-03-06 13:35:43 +0000967 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700968#endif
969 guard_.recursion_count_ = old_recursion_count;
Ian Rogers7b078e82014-09-10 14:44:24 -0700970 return timed_out;
Elliott Hughes5f791332011-09-15 17:45:30 -0700971}
972
Elliott Hughese62934d2012-04-09 11:24:29 -0700973} // namespace art