blob: e9fa46cdacd17ea6003a0a73caac70d9df6e99b4 [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
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700324 DCHECK_EQ(0, state_and_contenders_.load(std::memory_order_relaxed));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700325#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700326 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, nullptr));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700327#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700328}
329
David Sehrf42eb2c2016-10-19 13:20:45 -0700330// Helper to allow checking shutdown while locking for thread safety.
331static bool IsSafeToCallAbortSafe() {
332 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
333 return Locks::IsSafeToCallAbortRacy();
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800334}
335
Elliott Hughes8daa0922011-09-11 13:46:25 -0700336Mutex::~Mutex() {
David Sehrf42eb2c2016-10-19 13:20:45 -0700337 bool safe_to_call_abort = Locks::IsSafeToCallAbortRacy();
Ian Rogersc604d732012-10-14 16:09:54 -0700338#if ART_USE_FUTEXES
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700339 if (state_and_contenders_.load(std::memory_order_relaxed) != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700340 LOG(safe_to_call_abort ? FATAL : WARNING)
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700341 << "destroying mutex with owner or contenders. Owner:" << GetExclusiveOwnerTid();
Ian Rogersc604d732012-10-14 16:09:54 -0700342 } else {
Hans Boehm0882af22017-08-31 15:21:57 -0700343 if (GetExclusiveOwnerTid() != 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700344 LOG(safe_to_call_abort ? FATAL : WARNING)
345 << "unexpectedly found an owner on unlocked mutex " << name_;
Andreas Gampe8f1fa102015-01-22 19:48:51 -0800346 }
Ian Rogersc604d732012-10-14 16:09:54 -0700347 }
348#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700349 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
350 // may still be using locks.
Elliott Hughes6b355752012-01-13 16:49:08 -0800351 int rc = pthread_mutex_destroy(&mutex_);
352 if (rc != 0) {
353 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700354 PLOG(safe_to_call_abort ? FATAL : WARNING)
355 << "pthread_mutex_destroy failed for " << name_;
Elliott Hughes6b355752012-01-13 16:49:08 -0800356 }
Ian Rogersc604d732012-10-14 16:09:54 -0700357#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -0700358}
359
Ian Rogers81d425b2012-09-27 16:03:43 -0700360void Mutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700361 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700362 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700363 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700364 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700365 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700366#if ART_USE_FUTEXES
367 bool done = false;
368 do {
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700369 int32_t cur_state = state_and_contenders_.load(std::memory_order_relaxed);
370 if (LIKELY((cur_state & kHeldMask) == 0) /* lock not held */) {
371 done = state_and_contenders_.CompareAndSetWeakAcquire(cur_state, cur_state | kHeldMask);
Ian Rogersc604d732012-10-14 16:09:54 -0700372 } else {
373 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700374 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700375 // Increment contender count. We can't create enough threads for this to overflow.
376 increment_contenders();
377 // Make cur_state again reflect the expected value of state_and_contenders.
378 cur_state += kContenderIncrement;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800379 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
380 self->CheckEmptyCheckpointFromMutex();
381 }
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700382 if (futex(state_and_contenders_.Address(), FUTEX_WAIT_PRIVATE, cur_state,
383 nullptr, nullptr, 0) != 0) {
384 // We only went to sleep after incrementing and contenders and checking that the lock
385 // is still held by someone else.
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 }
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700392 decrement_contenders();
Ian Rogersc604d732012-10-14 16:09:54 -0700393 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700394 } while (!done);
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700395 // Confirm that lock is now held.
396 DCHECK_NE(state_and_contenders_.load(std::memory_order_relaxed) & kHeldMask, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700397#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700398 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700399#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700400 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000401 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700402 RegisterAsLocked(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700403 }
404 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700405 if (kDebugLocking) {
406 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
407 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700408 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700409 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700410}
411
Ian Rogers81d425b2012-09-27 16:03:43 -0700412bool Mutex::ExclusiveTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700413 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers25fd14b2012-09-05 10:56:38 -0700414 if (kDebugLocking && !recursive_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700415 AssertNotHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700416 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700417 if (!recursive_ || !IsExclusiveHeld(self)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700418#if ART_USE_FUTEXES
419 bool done = false;
420 do {
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700421 int32_t cur_state = state_and_contenders_.load(std::memory_order_relaxed);
422 if ((cur_state & kHeldMask) == 0) {
423 // Change state to held and impose load/store ordering appropriate for lock acquisition.
424 done = state_and_contenders_.CompareAndSetWeakAcquire(cur_state, cur_state | kHeldMask);
Ian Rogersc604d732012-10-14 16:09:54 -0700425 } else {
426 return false;
427 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700428 } while (!done);
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700429 DCHECK_NE(state_and_contenders_.load(std::memory_order_relaxed) & kHeldMask, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700430#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700431 int result = pthread_mutex_trylock(&mutex_);
432 if (result == EBUSY) {
433 return false;
434 }
435 if (result != 0) {
436 errno = result;
437 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
438 }
Ian Rogersc604d732012-10-14 16:09:54 -0700439#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700440 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000441 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700442 RegisterAsLocked(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700443 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700444 recursion_count_++;
Ian Rogers25fd14b2012-09-05 10:56:38 -0700445 if (kDebugLocking) {
446 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
447 << name_ << " " << recursion_count_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700448 AssertHeld(self);
Ian Rogers25fd14b2012-09-05 10:56:38 -0700449 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700450 return true;
451}
452
Ian Rogers81d425b2012-09-27 16:03:43 -0700453void Mutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartiereb0a1792014-12-15 17:23:45 -0800454 if (kIsDebugBuild && self != nullptr && self != Thread::Current()) {
455 std::string name1 = "<null>";
456 std::string name2 = "<null>";
457 if (self != nullptr) {
458 self->GetThreadName(name1);
459 }
460 if (Thread::Current() != nullptr) {
461 Thread::Current()->GetThreadName(name2);
462 }
Mathieu Chartier4c101102015-01-27 17:14:16 -0800463 LOG(FATAL) << GetName() << " level=" << level_ << " self=" << name1
464 << " Thread::Current()=" << name2;
Mathieu Chartiereb0a1792014-12-15 17:23:45 -0800465 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700466 AssertHeld(self);
Hans Boehm0882af22017-08-31 15:21:57 -0700467 DCHECK_NE(GetExclusiveOwnerTid(), 0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700468 recursion_count_--;
469 if (!recursive_ || recursion_count_ == 0) {
Ian Rogers25fd14b2012-09-05 10:56:38 -0700470 if (kDebugLocking) {
471 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
472 << name_ << " " << recursion_count_;
473 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700474 RegisterAsUnlocked(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700475#if ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700476 bool done = false;
477 do {
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700478 int32_t cur_state = state_and_contenders_.load(std::memory_order_relaxed);
479 if (LIKELY((cur_state & kHeldMask) != 0)) {
Ian Rogersc5f17732014-06-05 20:48:42 -0700480 // We're no longer the owner.
Orion Hodson88591fe2018-03-06 13:35:43 +0000481 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700482 // Change state to not held and impose load/store ordering appropriate for lock release.
483 uint32_t new_state = cur_state & ~kHeldMask; // Same number of contenders.
484 done = state_and_contenders_.CompareAndSetWeakRelease(cur_state, new_state);
485 if (LIKELY(done)) { // Spurious fail or waiters changed ?
486 if (UNLIKELY(new_state != 0) /* have contenders */) {
487 futex(state_and_contenders_.Address(), FUTEX_WAKE_PRIVATE, kWakeOne,
488 nullptr, nullptr, 0);
Ian Rogersc5f17732014-06-05 20:48:42 -0700489 }
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700490 // We only do a futex wait after incrementing contenders and verifying the lock was
491 // still held. If we didn't see waiters, then there couldn't have been any futexes
492 // waiting on this lock when we did the CAS. New arrivals after that cannot wait for us,
493 // since the futex wait call would see the lock available and immediately return.
Ian Rogersc5f17732014-06-05 20:48:42 -0700494 }
495 } else {
496 // Logging acquires the logging lock, avoid infinite recursion in that case.
497 if (this != Locks::logging_lock_) {
498 LOG(FATAL) << "Unexpected state_ in unlock " << cur_state << " for " << name_;
499 } else {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700500 LogHelper::LogLineLowStack(__FILE__,
501 __LINE__,
502 ::android::base::FATAL_WITHOUT_ABORT,
503 StringPrintf("Unexpected state_ %d in unlock for %s",
504 cur_state, name_).c_str());
Ian Rogersc5f17732014-06-05 20:48:42 -0700505 _exit(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700506 }
507 }
Ian Rogersc5f17732014-06-05 20:48:42 -0700508 } while (!done);
Ian Rogersc604d732012-10-14 16:09:54 -0700509#else
Orion Hodson88591fe2018-03-06 13:35:43 +0000510 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700511 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
Ian Rogersc604d732012-10-14 16:09:54 -0700512#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700513 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700514}
515
Ian Rogers56edc432013-01-18 16:51:51 -0800516void Mutex::Dump(std::ostream& os) const {
517 os << (recursive_ ? "recursive " : "non-recursive ")
518 << name_
519 << " level=" << static_cast<int>(level_)
520 << " rec=" << recursion_count_
521 << " owner=" << GetExclusiveOwnerTid() << " ";
522 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700523}
524
525std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800526 mu.Dump(os);
527 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700528}
529
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800530void Mutex::WakeupToRespondToEmptyCheckpoint() {
531#if ART_USE_FUTEXES
532 // Wake up all the waiters so they will respond to the emtpy checkpoint.
533 DCHECK(should_respond_to_empty_checkpoint_request_);
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700534 if (UNLIKELY(get_contenders() != 0)) {
535 futex(state_and_contenders_.Address(), FUTEX_WAKE_PRIVATE, kWakeAll, nullptr, nullptr, 0);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800536 }
537#else
538 LOG(FATAL) << "Non futex case isn't supported.";
539#endif
540}
541
Brian Carlstrom02c8cc62013-07-18 15:54:44 -0700542ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level)
543 : BaseMutex(name, level)
Ian Rogers81d425b2012-09-27 16:03:43 -0700544#if ART_USE_FUTEXES
Hans Boehm467b6922019-04-22 16:15:53 -0700545 , state_(0), exclusive_owner_(0), num_contenders_(0)
Ian Rogers81d425b2012-09-27 16:03:43 -0700546#endif
Igor Murashkin5573c372017-11-16 13:34:30 -0800547{
Ian Rogers81d425b2012-09-27 16:03:43 -0700548#if !ART_USE_FUTEXES
Ian Rogersc5f17732014-06-05 20:48:42 -0700549 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, nullptr));
Ian Rogers81d425b2012-09-27 16:03:43 -0700550#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700551}
552
553ReaderWriterMutex::~ReaderWriterMutex() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700554#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000555 CHECK_EQ(state_.load(std::memory_order_relaxed), 0);
Hans Boehm0882af22017-08-31 15:21:57 -0700556 CHECK_EQ(GetExclusiveOwnerTid(), 0);
Hans Boehm467b6922019-04-22 16:15:53 -0700557 CHECK_EQ(num_contenders_.load(std::memory_order_relaxed), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700558#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700559 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
560 // may still be using locks.
561 int rc = pthread_rwlock_destroy(&rwlock_);
562 if (rc != 0) {
563 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700564 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
565 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_rwlock_destroy failed for " << name_;
Brian Carlstromcd74c4b2012-01-23 13:21:00 -0800566 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700567#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700568}
569
Ian Rogers81d425b2012-09-27 16:03:43 -0700570void ReaderWriterMutex::ExclusiveLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700571 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700572 AssertNotExclusiveHeld(self);
573#if ART_USE_FUTEXES
574 bool done = false;
575 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000576 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700577 if (LIKELY(cur_state == 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700578 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000579 done = state_.CompareAndSetWeakAcquire(0 /* cur_state*/, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700580 } else {
581 // Failed to acquire, hang up.
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700582 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Hans Boehm467b6922019-04-22 16:15:53 -0700583 num_contenders_.fetch_add(1);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800584 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
585 self->CheckEmptyCheckpointFromMutex();
586 }
Charles Munger7530bae2018-10-29 20:03:51 -0700587 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, nullptr, nullptr, 0) != 0) {
Brian Carlstrom0de79852013-07-25 22:29:58 -0700588 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
589 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
590 if ((errno != EAGAIN) && (errno != EINTR)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700591 PLOG(FATAL) << "futex wait failed for " << name_;
592 }
593 }
Hans Boehm467b6922019-04-22 16:15:53 -0700594 num_contenders_.fetch_sub(1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700595 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700596 } while (!done);
Orion Hodson88591fe2018-03-06 13:35:43 +0000597 DCHECK_EQ(state_.load(std::memory_order_relaxed), -1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700598#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700599 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700600#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700601 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
Orion Hodson88591fe2018-03-06 13:35:43 +0000602 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700603 RegisterAsLocked(self);
604 AssertExclusiveHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700605}
606
Ian Rogers81d425b2012-09-27 16:03:43 -0700607void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700608 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700609 AssertExclusiveHeld(self);
610 RegisterAsUnlocked(self);
Hans Boehm0882af22017-08-31 15:21:57 -0700611 DCHECK_NE(GetExclusiveOwnerTid(), 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700612#if ART_USE_FUTEXES
613 bool done = false;
614 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000615 int32_t cur_state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700616 if (LIKELY(cur_state == -1)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700617 // We're no longer the owner.
Orion Hodson88591fe2018-03-06 13:35:43 +0000618 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc7190692014-07-08 23:50:26 -0700619 // Change state from -1 to 0 and impose load/store ordering appropriate for lock release.
Hans Boehm467b6922019-04-22 16:15:53 -0700620 // Note, the num_contenders_ load below musn't reorder before the CompareAndSet.
Orion Hodson4557b382018-01-03 11:47:54 +0000621 done = state_.CompareAndSetWeakSequentiallyConsistent(-1 /* cur_state*/, 0 /* new state */);
Ian Rogersc7190692014-07-08 23:50:26 -0700622 if (LIKELY(done)) { // Weak CAS may fail spuriously.
Ian Rogers81d425b2012-09-27 16:03:43 -0700623 // Wake any waiters.
Hans Boehm467b6922019-04-22 16:15:53 -0700624 if (UNLIKELY(num_contenders_.load(std::memory_order_seq_cst) > 0)) {
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700625 futex(state_.Address(), FUTEX_WAKE_PRIVATE, kWakeAll, nullptr, nullptr, 0);
Ian Rogers81d425b2012-09-27 16:03:43 -0700626 }
627 }
628 } else {
629 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
630 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700631 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700632#else
Orion Hodson88591fe2018-03-06 13:35:43 +0000633 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700634 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
Ian Rogers81d425b2012-09-27 16:03:43 -0700635#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700636}
637
Ian Rogers66aee5c2012-08-15 17:17:47 -0700638#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700639bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700640 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700641#if ART_USE_FUTEXES
642 bool done = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700643 timespec end_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800644 InitTimeSpec(true, CLOCK_MONOTONIC, ms, ns, &end_abs_ts);
Ian Rogers81d425b2012-09-27 16:03:43 -0700645 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000646 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700647 if (cur_state == 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700648 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000649 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, -1 /* new state */);
Ian Rogers81d425b2012-09-27 16:03:43 -0700650 } else {
651 // Failed to acquire, hang up.
Ian Rogersc604d732012-10-14 16:09:54 -0700652 timespec now_abs_ts;
tony.ys_liu071e48e2015-01-14 18:28:03 +0800653 InitTimeSpec(true, CLOCK_MONOTONIC, 0, 0, &now_abs_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700654 timespec rel_ts;
655 if (ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
656 return false; // Timed out.
657 }
Hiroshi Yamauchib3733082013-08-12 17:28:49 -0700658 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Hans Boehm467b6922019-04-22 16:15:53 -0700659 num_contenders_.fetch_add(1);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800660 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
661 self->CheckEmptyCheckpointFromMutex();
662 }
Charles Munger7530bae2018-10-29 20:03:51 -0700663 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, &rel_ts, nullptr, 0) != 0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700664 if (errno == ETIMEDOUT) {
Hans Boehm467b6922019-04-22 16:15:53 -0700665 num_contenders_.fetch_sub(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700666 return false; // Timed out.
Brian Carlstrom0de79852013-07-25 22:29:58 -0700667 } else if ((errno != EAGAIN) && (errno != EINTR)) {
668 // EAGAIN and EINTR both indicate a spurious failure,
669 // recompute the relative time out from now and try again.
670 // We don't use TEMP_FAILURE_RETRY so we can recompute rel_ts;
Ian Rogers81d425b2012-09-27 16:03:43 -0700671 PLOG(FATAL) << "timed futex wait failed for " << name_;
672 }
673 }
Hans Boehm467b6922019-04-22 16:15:53 -0700674 num_contenders_.fetch_sub(1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700675 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700676 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700677#else
Ian Rogersc604d732012-10-14 16:09:54 -0700678 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700679 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700680 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700681 if (result == ETIMEDOUT) {
682 return false;
683 }
684 if (result != 0) {
685 errno = result;
Ian Rogersa5acfd32012-08-15 11:50:10 -0700686 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700687 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700688#endif
Orion Hodson88591fe2018-03-06 13:35:43 +0000689 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700690 RegisterAsLocked(self);
691 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700692 return true;
693}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700694#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700695
Ian Rogers51d212e2014-10-23 17:48:20 -0700696#if ART_USE_FUTEXES
Ian Rogerscf7f1912014-10-22 22:06:39 -0700697void ReaderWriterMutex::HandleSharedLockContention(Thread* self, int32_t cur_state) {
698 // Owner holds it exclusively, hang up.
Roland Levillaincd72dc92018-02-27 19:15:31 +0000699 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
Hans Boehm467b6922019-04-22 16:15:53 -0700700 num_contenders_.fetch_add(1);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800701 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
702 self->CheckEmptyCheckpointFromMutex();
703 }
Charles Munger7530bae2018-10-29 20:03:51 -0700704 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, nullptr, nullptr, 0) != 0) {
Daniel Colascione6f4d1022016-11-21 14:35:42 -0800705 if (errno != EAGAIN && errno != EINTR) {
Ian Rogerscf7f1912014-10-22 22:06:39 -0700706 PLOG(FATAL) << "futex wait failed for " << name_;
707 }
708 }
Hans Boehm467b6922019-04-22 16:15:53 -0700709 num_contenders_.fetch_sub(1);
Ian Rogerscf7f1912014-10-22 22:06:39 -0700710}
Ian Rogers51d212e2014-10-23 17:48:20 -0700711#endif
Ian Rogerscf7f1912014-10-22 22:06:39 -0700712
Ian Rogers81d425b2012-09-27 16:03:43 -0700713bool ReaderWriterMutex::SharedTryLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700714 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers81d425b2012-09-27 16:03:43 -0700715#if ART_USE_FUTEXES
716 bool done = false;
717 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000718 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers81d425b2012-09-27 16:03:43 -0700719 if (cur_state >= 0) {
Ian Rogersc7190692014-07-08 23:50:26 -0700720 // Add as an extra reader and impose load/store ordering appropriate for lock acquisition.
Orion Hodson4557b382018-01-03 11:47:54 +0000721 done = state_.CompareAndSetWeakAcquire(cur_state, cur_state + 1);
Ian Rogers81d425b2012-09-27 16:03:43 -0700722 } else {
723 // Owner holds it exclusively.
724 return false;
725 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700726 } while (!done);
Ian Rogers81d425b2012-09-27 16:03:43 -0700727#else
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700728 int result = pthread_rwlock_tryrdlock(&rwlock_);
729 if (result == EBUSY) {
730 return false;
731 }
732 if (result != 0) {
733 errno = result;
734 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
735 }
Ian Rogers81d425b2012-09-27 16:03:43 -0700736#endif
737 RegisterAsLocked(self);
738 AssertSharedHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700739 return true;
740}
741
Ian Rogers81d425b2012-09-27 16:03:43 -0700742bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700743 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700744 bool result;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700745 if (UNLIKELY(self == nullptr)) { // Handle unattached threads.
Ian Rogers01ae5802012-09-28 16:14:01 -0700746 result = IsExclusiveHeld(self); // TODO: a better best effort here.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700747 } else {
748 result = (self->GetHeldMutex(level_) == this);
749 }
750 return result;
751}
752
Ian Rogers56edc432013-01-18 16:51:51 -0800753void ReaderWriterMutex::Dump(std::ostream& os) const {
754 os << name_
755 << " level=" << static_cast<int>(level_)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700756 << " owner=" << GetExclusiveOwnerTid()
757#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000758 << " state=" << state_.load(std::memory_order_seq_cst)
Hans Boehm467b6922019-04-22 16:15:53 -0700759 << " num_contenders=" << num_contenders_.load(std::memory_order_seq_cst)
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700760#endif
761 << " ";
Ian Rogers56edc432013-01-18 16:51:51 -0800762 DumpContention(os);
Ian Rogers01ae5802012-09-28 16:14:01 -0700763}
764
765std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
Ian Rogers56edc432013-01-18 16:51:51 -0800766 mu.Dump(os);
767 return os;
Ian Rogers01ae5802012-09-28 16:14:01 -0700768}
769
Yu Lieac44242015-06-29 10:50:03 +0800770std::ostream& operator<<(std::ostream& os, const MutatorMutex& mu) {
771 mu.Dump(os);
772 return os;
773}
774
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800775void ReaderWriterMutex::WakeupToRespondToEmptyCheckpoint() {
776#if ART_USE_FUTEXES
777 // Wake up all the waiters so they will respond to the emtpy checkpoint.
778 DCHECK(should_respond_to_empty_checkpoint_request_);
Hans Boehm467b6922019-04-22 16:15:53 -0700779 if (UNLIKELY(num_contenders_.load(std::memory_order_relaxed) > 0)) {
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700780 futex(state_.Address(), FUTEX_WAKE_PRIVATE, kWakeAll, nullptr, nullptr, 0);
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800781 }
782#else
783 LOG(FATAL) << "Non futex case isn't supported.";
784#endif
785}
786
Ian Rogers23055dc2013-04-18 16:29:16 -0700787ConditionVariable::ConditionVariable(const char* name, Mutex& guard)
Ian Rogersc604d732012-10-14 16:09:54 -0700788 : name_(name), guard_(guard) {
789#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000790 DCHECK_EQ(0, sequence_.load(std::memory_order_relaxed));
Ian Rogersc604d732012-10-14 16:09:54 -0700791 num_waiters_ = 0;
Ian Rogersc604d732012-10-14 16:09:54 -0700792#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000793 pthread_condattr_t cond_attrs;
Ian Rogersc5f17732014-06-05 20:48:42 -0700794 CHECK_MUTEX_CALL(pthread_condattr_init, (&cond_attrs));
Narayan Kamath51b71022014-03-04 11:57:09 +0000795#if !defined(__APPLE__)
796 // Apple doesn't have CLOCK_MONOTONIC or pthread_condattr_setclock.
Ian Rogers51d212e2014-10-23 17:48:20 -0700797 CHECK_MUTEX_CALL(pthread_condattr_setclock, (&cond_attrs, CLOCK_MONOTONIC));
Narayan Kamath51b71022014-03-04 11:57:09 +0000798#endif
799 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, &cond_attrs));
Ian Rogersc604d732012-10-14 16:09:54 -0700800#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700801}
802
803ConditionVariable::~ConditionVariable() {
Ian Rogers5bd97c42012-11-27 02:38:26 -0800804#if ART_USE_FUTEXES
805 if (num_waiters_!= 0) {
David Sehrf42eb2c2016-10-19 13:20:45 -0700806 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
807 LOG(is_safe_to_call_abort ? FATAL : WARNING)
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700808 << "ConditionVariable::~ConditionVariable for " << name_
Ian Rogersd45f2012012-11-28 11:46:23 -0800809 << " called with " << num_waiters_ << " waiters.";
Ian Rogers5bd97c42012-11-27 02:38:26 -0800810 }
811#else
Elliott Hughese62934d2012-04-09 11:24:29 -0700812 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
813 // may still be using condition variables.
814 int rc = pthread_cond_destroy(&cond_);
815 if (rc != 0) {
816 errno = rc;
David Sehrf42eb2c2016-10-19 13:20:45 -0700817 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
818 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_cond_destroy failed for " << name_;
Elliott Hughese62934d2012-04-09 11:24:29 -0700819 }
Ian Rogersc604d732012-10-14 16:09:54 -0700820#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700821}
822
Ian Rogersc604d732012-10-14 16:09:54 -0700823void ConditionVariable::Broadcast(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700824 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700825 // TODO: enable below, there's a race in thread creation that causes false failures currently.
826 // guard_.AssertExclusiveHeld(self);
Mathieu Chartiere46cd752012-10-31 16:56:18 -0700827 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc604d732012-10-14 16:09:54 -0700828#if ART_USE_FUTEXES
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700829 RequeueWaiters(std::numeric_limits<int32_t>::max());
Ian Rogersc604d732012-10-14 16:09:54 -0700830#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700831 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700832#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700833}
834
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700835#if ART_USE_FUTEXES
836void ConditionVariable::RequeueWaiters(int32_t count) {
837 if (num_waiters_ > 0) {
838 sequence_++; // Indicate a signal occurred.
839 // Move waiters from the condition variable's futex to the guard's futex,
840 // so that they will be woken up when the mutex is released.
841 bool done = futex(sequence_.Address(),
Charles Munger7530bae2018-10-29 20:03:51 -0700842 FUTEX_REQUEUE_PRIVATE,
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700843 /* Threads to wake */ 0,
844 /* Threads to requeue*/ reinterpret_cast<const timespec*>(count),
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700845 guard_.state_and_contenders_.Address(),
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700846 0) != -1;
847 if (!done && errno != EAGAIN && errno != EINTR) {
848 PLOG(FATAL) << "futex requeue failed for " << name_;
849 }
850 }
851}
852#endif
853
854
Ian Rogersc604d732012-10-14 16:09:54 -0700855void ConditionVariable::Signal(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700856 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700857 guard_.AssertExclusiveHeld(self);
858#if ART_USE_FUTEXES
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700859 RequeueWaiters(1);
Ian Rogersc604d732012-10-14 16:09:54 -0700860#else
Elliott Hughes5f791332011-09-15 17:45:30 -0700861 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
Ian Rogersc604d732012-10-14 16:09:54 -0700862#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700863}
864
Ian Rogersc604d732012-10-14 16:09:54 -0700865void ConditionVariable::Wait(Thread* self) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700866 guard_.CheckSafeToWait(self);
867 WaitHoldingLocks(self);
868}
869
870void ConditionVariable::WaitHoldingLocks(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700871 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogersc604d732012-10-14 16:09:54 -0700872 guard_.AssertExclusiveHeld(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700873 unsigned int old_recursion_count = guard_.recursion_count_;
874#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700875 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800876 // Ensure the Mutex is contended so that requeued threads are awoken.
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700877 guard_.increment_contenders();
Ian Rogersc604d732012-10-14 16:09:54 -0700878 guard_.recursion_count_ = 1;
Orion Hodson88591fe2018-03-06 13:35:43 +0000879 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700880 guard_.ExclusiveUnlock(self);
Charles Munger7530bae2018-10-29 20:03:51 -0700881 if (futex(sequence_.Address(), FUTEX_WAIT_PRIVATE, cur_sequence, nullptr, nullptr, 0) != 0) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800882 // Futex failed, check it is an expected error.
883 // EAGAIN == EWOULDBLK, so we let the caller try again.
884 // EINTR implies a signal was sent to this thread.
885 if ((errno != EINTR) && (errno != EAGAIN)) {
Ian Rogersc604d732012-10-14 16:09:54 -0700886 PLOG(FATAL) << "futex wait failed for " << name_;
887 }
888 }
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800889 if (self != nullptr) {
890 JNIEnvExt* const env = self->GetJniEnv();
Ian Rogers55256cb2017-12-21 17:07:11 -0800891 if (UNLIKELY(env != nullptr && env->IsRuntimeDeleted())) {
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800892 CHECK(self->IsDaemon());
893 // If the runtime has been deleted, then we cannot proceed. Just sleep forever. This may
894 // occur for user daemon threads that get a spurious wakeup. This occurs for test 132 with
895 // --host and --gdb.
896 // After we wake up, the runtime may have been shutdown, which means that this condition may
897 // have been deleted. It is not safe to retry the wait.
898 SleepForever();
899 }
900 }
Ian Rogersc604d732012-10-14 16:09:54 -0700901 guard_.ExclusiveLock(self);
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700902 CHECK_GT(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700903 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800904 // We awoke and so no longer require awakes from the guard_'s unlock.
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700905 CHECK_GT(guard_.get_contenders(), 0);
906 guard_.decrement_contenders();
Ian Rogersc604d732012-10-14 16:09:54 -0700907#else
Hans Boehm0882af22017-08-31 15:21:57 -0700908 pid_t old_owner = guard_.GetExclusiveOwnerTid();
Orion Hodson88591fe2018-03-06 13:35:43 +0000909 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700910 guard_.recursion_count_ = 0;
911 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
Orion Hodson88591fe2018-03-06 13:35:43 +0000912 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700913#endif
914 guard_.recursion_count_ = old_recursion_count;
Elliott Hughes5f791332011-09-15 17:45:30 -0700915}
916
Ian Rogers7b078e82014-09-10 14:44:24 -0700917bool ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700918 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers7b078e82014-09-10 14:44:24 -0700919 bool timed_out = false;
Ian Rogersc604d732012-10-14 16:09:54 -0700920 guard_.AssertExclusiveHeld(self);
Ian Rogers1d54e732013-05-02 21:10:01 -0700921 guard_.CheckSafeToWait(self);
Ian Rogersc604d732012-10-14 16:09:54 -0700922 unsigned int old_recursion_count = guard_.recursion_count_;
923#if ART_USE_FUTEXES
Ian Rogersc604d732012-10-14 16:09:54 -0700924 timespec rel_ts;
Ian Rogers5bd97c42012-11-27 02:38:26 -0800925 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
Ian Rogersc604d732012-10-14 16:09:54 -0700926 num_waiters_++;
Ian Rogersd45f2012012-11-28 11:46:23 -0800927 // Ensure the Mutex is contended so that requeued threads are awoken.
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700928 guard_.increment_contenders();
Ian Rogersc604d732012-10-14 16:09:54 -0700929 guard_.recursion_count_ = 1;
Orion Hodson88591fe2018-03-06 13:35:43 +0000930 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700931 guard_.ExclusiveUnlock(self);
Charles Munger7530bae2018-10-29 20:03:51 -0700932 if (futex(sequence_.Address(), FUTEX_WAIT_PRIVATE, cur_sequence, &rel_ts, nullptr, 0) != 0) {
Ian Rogersc604d732012-10-14 16:09:54 -0700933 if (errno == ETIMEDOUT) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800934 // Timed out we're done.
Ian Rogers7b078e82014-09-10 14:44:24 -0700935 timed_out = true;
Brian Carlstrom0de79852013-07-25 22:29:58 -0700936 } else if ((errno == EAGAIN) || (errno == EINTR)) {
Ian Rogersd45f2012012-11-28 11:46:23 -0800937 // A signal or ConditionVariable::Signal/Broadcast has come in.
Ian Rogersc604d732012-10-14 16:09:54 -0700938 } else {
939 PLOG(FATAL) << "timed futex wait failed for " << name_;
940 }
941 }
942 guard_.ExclusiveLock(self);
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700943 CHECK_GT(num_waiters_, 0);
Ian Rogersc604d732012-10-14 16:09:54 -0700944 num_waiters_--;
Ian Rogersd45f2012012-11-28 11:46:23 -0800945 // We awoke and so no longer require awakes from the guard_'s unlock.
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700946 CHECK_GT(guard_.get_contenders(), 0);
947 guard_.decrement_contenders();
Ian Rogersc604d732012-10-14 16:09:54 -0700948#else
Narayan Kamath51b71022014-03-04 11:57:09 +0000949#if !defined(__APPLE__)
Ian Rogersc604d732012-10-14 16:09:54 -0700950 int clock = CLOCK_MONOTONIC;
Elliott Hughes5f791332011-09-15 17:45:30 -0700951#else
Ian Rogersc604d732012-10-14 16:09:54 -0700952 int clock = CLOCK_REALTIME;
Elliott Hughes5f791332011-09-15 17:45:30 -0700953#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700954 pid_t old_owner = guard_.GetExclusiveOwnerTid();
Orion Hodson88591fe2018-03-06 13:35:43 +0000955 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700956 guard_.recursion_count_ = 0;
957 timespec ts;
Brian Carlstrombcc29262012-11-02 11:36:03 -0700958 InitTimeSpec(true, clock, ms, ns, &ts);
Josh Gao2d899c42018-10-17 16:03:42 -0700959 int rc;
960 while ((rc = pthread_cond_timedwait(&cond_, &guard_.mutex_, &ts)) == EINTR) {
961 continue;
962 }
963
Ian Rogers7b078e82014-09-10 14:44:24 -0700964 if (rc == ETIMEDOUT) {
965 timed_out = true;
966 } else if (rc != 0) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700967 errno = rc;
968 PLOG(FATAL) << "TimedWait failed for " << name_;
969 }
Orion Hodson88591fe2018-03-06 13:35:43 +0000970 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
Ian Rogersc604d732012-10-14 16:09:54 -0700971#endif
972 guard_.recursion_count_ = old_recursion_count;
Ian Rogers7b078e82014-09-10 14:44:24 -0700973 return timed_out;
Elliott Hughes5f791332011-09-15 17:45:30 -0700974}
975
Elliott Hughese62934d2012-04-09 11:24:29 -0700976} // namespace art