1 /*
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>
20 #include <sys/time.h>
21
22 #include <sstream>
23
24 #include "android-base/stringprintf.h"
25
26 #include "base/atomic.h"
27 #include "base/logging.h"
28 #include "base/systrace.h"
29 #include "base/time_utils.h"
30 #include "base/value_object.h"
31 #include "monitor.h"
32 #include "mutex-inl.h"
33 #include "scoped_thread_state_change-inl.h"
34 #include "thread-inl.h"
35 #include "thread.h"
36 #include "thread_list.h"
37
38 namespace art HIDDEN {
39
40 using android::base::StringPrintf;
41
42 static constexpr uint64_t kIntervalMillis = 50;
43 static constexpr int kMonitorTimeoutTryMax = 5;
44
45 static const char* kLastDumpStackTime = "LastDumpStackTime";
46
47 struct AllMutexData {
48 // A guard for all_mutexes_ that's not a mutex (Mutexes must CAS to acquire and busy wait).
49 Atomic<const BaseMutex*> all_mutexes_guard;
50 // All created mutexes guarded by all_mutexes_guard_.
51 std::set<BaseMutex*>* all_mutexes;
AllMutexDataart::AllMutexData52 AllMutexData() : all_mutexes(nullptr) {}
53 };
54 static struct AllMutexData gAllMutexData[kAllMutexDataSize];
55
56 struct DumpStackLastTimeTLSData : public art::TLSData {
DumpStackLastTimeTLSDataart::DumpStackLastTimeTLSData57 explicit DumpStackLastTimeTLSData(uint64_t last_dump_time_ms)
58 : last_dump_time_ms_(last_dump_time_ms) {}
59 std::atomic<uint64_t> last_dump_time_ms_;
60 };
61
62 #if ART_USE_FUTEXES
63 // Compute a relative timespec as *result_ts = lhs - rhs.
64 // Return false (and produce an invalid *result_ts) if lhs < rhs.
ComputeRelativeTimeSpec(timespec * result_ts,const timespec & lhs,const timespec & rhs)65 static bool ComputeRelativeTimeSpec(timespec* result_ts, const timespec& lhs, const timespec& rhs) {
66 const int32_t one_sec = 1000 * 1000 * 1000; // one second in nanoseconds.
67 static_assert(std::is_signed<decltype(result_ts->tv_sec)>::value); // Signed on Linux.
68 result_ts->tv_sec = lhs.tv_sec - rhs.tv_sec;
69 result_ts->tv_nsec = lhs.tv_nsec - rhs.tv_nsec;
70 if (result_ts->tv_nsec < 0) {
71 result_ts->tv_sec--;
72 result_ts->tv_nsec += one_sec;
73 }
74 DCHECK(result_ts->tv_nsec >= 0 && result_ts->tv_nsec < one_sec);
75 return result_ts->tv_sec >= 0;
76 }
77 #endif
78
79 #if ART_USE_FUTEXES
80 // If we wake up from a futex wake, and the runtime disappeared while we were asleep,
81 // it's important to stop in our tracks before we touch deallocated memory.
SleepIfRuntimeDeleted(Thread * self)82 static inline void SleepIfRuntimeDeleted(Thread* self) {
83 if (self != nullptr) {
84 JNIEnvExt* const env = self->GetJniEnv();
85 if (UNLIKELY(env != nullptr && env->IsRuntimeDeleted())) {
86 DCHECK(self->IsDaemon());
87 // If the runtime has been deleted, then we cannot proceed. Just sleep forever. This may
88 // occur for user daemon threads that get a spurious wakeup. This occurs for test 132 with
89 // --host and --gdb.
90 // After we wake up, the runtime may have been shutdown, which means that this condition may
91 // have been deleted. It is not safe to retry the wait.
92 SleepForever();
93 }
94 }
95 }
96 #else
97 // We should be doing this for pthreads to, but it seems to be impossible for something
98 // like a condition variable wait. Thus we don't bother trying.
99 #endif
100
101 // Wait for an amount of time that roughly increases in the argument i.
102 // Spin for small arguments and yield/sleep for longer ones.
BackOff(uint32_t i)103 static void BackOff(uint32_t i) {
104 static constexpr uint32_t kSpinMax = 10;
105 static constexpr uint32_t kYieldMax = 20;
106 if (i <= kSpinMax) {
107 // TODO: Esp. in very latency-sensitive cases, consider replacing this with an explicit
108 // test-and-test-and-set loop in the caller. Possibly skip entirely on a uniprocessor.
109 volatile uint32_t x = 0;
110 const uint32_t spin_count = 10 * i;
111 for (uint32_t spin = 0; spin < spin_count; ++spin) {
112 x = x + 1; // Volatile; hence should not be optimized away.
113 }
114 // TODO: Consider adding x86 PAUSE and/or ARM YIELD here.
115 } else if (i <= kYieldMax) {
116 sched_yield();
117 } else {
118 NanoSleep(1000ull * (i - kYieldMax));
119 }
120 }
121
122 // Wait until pred(testLoc->load(std::memory_order_relaxed)) holds, or until a
123 // short time interval, on the order of kernel context-switch time, passes.
124 // Return true if the predicate test succeeded, false if we timed out.
125 template<typename Pred>
WaitBrieflyFor(AtomicInteger * testLoc,Thread * self,Pred pred)126 static inline bool WaitBrieflyFor(AtomicInteger* testLoc, Thread* self, Pred pred) {
127 // TODO: Tune these parameters correctly. BackOff(3) should take on the order of 100 cycles. So
128 // this should result in retrying <= 10 times, usually waiting around 100 cycles each. The
129 // maximum delay should be significantly less than the expected futex() context switch time, so
130 // there should be little danger of this worsening things appreciably. If the lock was only
131 // held briefly by a running thread, this should help immensely.
132 static constexpr uint32_t kMaxBackOff = 3; // Should probably be <= kSpinMax above.
133 static constexpr uint32_t kMaxIters = 50;
134 JNIEnvExt* const env = self == nullptr ? nullptr : self->GetJniEnv();
135 for (uint32_t i = 1; i <= kMaxIters; ++i) {
136 BackOff(std::min(i, kMaxBackOff));
137 if (pred(testLoc->load(std::memory_order_relaxed))) {
138 return true;
139 }
140 if (UNLIKELY(env != nullptr && env->IsRuntimeDeleted())) {
141 // This returns true once we've started shutting down. We then try to reach a quiescent
142 // state as soon as possible to avoid touching data that may be deallocated by the shutdown
143 // process. It currently relies on a timeout.
144 return false;
145 }
146 }
147 return false;
148 }
149
150 class ScopedAllMutexesLock final {
151 public:
ScopedAllMutexesLock(const BaseMutex * mutex)152 explicit ScopedAllMutexesLock(const BaseMutex* mutex) : mutex_(mutex) {
153 for (uint32_t i = 0;
154 !gAllMutexData->all_mutexes_guard.CompareAndSetWeakAcquire(nullptr, mutex);
155 ++i) {
156 BackOff(i);
157 }
158 }
159
~ScopedAllMutexesLock()160 ~ScopedAllMutexesLock() {
161 DCHECK_EQ(gAllMutexData->all_mutexes_guard.load(std::memory_order_relaxed), mutex_);
162 gAllMutexData->all_mutexes_guard.store(nullptr, std::memory_order_release);
163 }
164
165 private:
166 const BaseMutex* const mutex_;
167 };
168
169 // Scoped class that generates events at the beginning and end of lock contention.
170 class ScopedContentionRecorder final : public ValueObject {
171 public:
ScopedContentionRecorder(BaseMutex * mutex,uint64_t blocked_tid,uint64_t owner_tid)172 ScopedContentionRecorder(BaseMutex* mutex, uint64_t blocked_tid, uint64_t owner_tid)
173 : mutex_(kLogLockContentions ? mutex : nullptr),
174 blocked_tid_(kLogLockContentions ? blocked_tid : 0),
175 owner_tid_(kLogLockContentions ? owner_tid : 0),
176 start_nano_time_(kLogLockContentions ? NanoTime() : 0) {
177 if (ATraceEnabled()) {
178 std::string msg = StringPrintf("Lock contention on %s (owner tid: %" PRIu64 ")",
179 mutex->GetName(), owner_tid);
180 ATraceBegin(msg.c_str());
181 }
182 }
183
~ScopedContentionRecorder()184 ~ScopedContentionRecorder() {
185 ATraceEnd();
186 if (kLogLockContentions) {
187 uint64_t end_nano_time = NanoTime();
188 mutex_->RecordContention(blocked_tid_, owner_tid_, end_nano_time - start_nano_time_);
189 }
190 }
191
192 private:
193 BaseMutex* const mutex_;
194 const uint64_t blocked_tid_;
195 const uint64_t owner_tid_;
196 const uint64_t start_nano_time_;
197 };
198
BaseMutex(const char * name,LockLevel level)199 BaseMutex::BaseMutex(const char* name, LockLevel level)
200 : name_(name),
201 level_(level),
202 should_respond_to_empty_checkpoint_request_(false) {
203 if (kLogLockContentions) {
204 ScopedAllMutexesLock mu(this);
205 std::set<BaseMutex*>** all_mutexes_ptr = &gAllMutexData->all_mutexes;
206 if (*all_mutexes_ptr == nullptr) {
207 // We leak the global set of all mutexes to avoid ordering issues in global variable
208 // construction/destruction.
209 *all_mutexes_ptr = new std::set<BaseMutex*>();
210 }
211 (*all_mutexes_ptr)->insert(this);
212 }
213 }
214
~BaseMutex()215 BaseMutex::~BaseMutex() {
216 if (kLogLockContentions) {
217 ScopedAllMutexesLock mu(this);
218 gAllMutexData->all_mutexes->erase(this);
219 }
220 }
221
DumpAll(std::ostream & os)222 void BaseMutex::DumpAll(std::ostream& os) {
223 if (kLogLockContentions) {
224 os << "Mutex logging:\n";
225 ScopedAllMutexesLock mu(reinterpret_cast<const BaseMutex*>(-1));
226 std::set<BaseMutex*>* all_mutexes = gAllMutexData->all_mutexes;
227 if (all_mutexes == nullptr) {
228 // No mutexes have been created yet during at startup.
229 return;
230 }
231 os << "(Contended)\n";
232 for (const BaseMutex* mutex : *all_mutexes) {
233 if (mutex->HasEverContended()) {
234 mutex->Dump(os);
235 os << "\n";
236 }
237 }
238 os << "(Never contented)\n";
239 for (const BaseMutex* mutex : *all_mutexes) {
240 if (!mutex->HasEverContended()) {
241 mutex->Dump(os);
242 os << "\n";
243 }
244 }
245 }
246 }
247
CheckSafeToWait(Thread * self)248 void BaseMutex::CheckSafeToWait(Thread* self) {
249 if (!kDebugLocking) {
250 return;
251 }
252 // Avoid repeated reporting of the same violation in the common case.
253 // We somewhat ignore races in the duplicate elision code. The first kMaxReports and the first
254 // report for a given level_ should always appear.
255 static std::atomic<uint> last_level_reported(kLockLevelCount);
256 static constexpr int kMaxReports = 5;
257 static std::atomic<uint> num_reports(0); // For the current level, more or less.
258
259 if (self == nullptr) {
260 CheckUnattachedThread(level_);
261 } else if (num_reports.load(std::memory_order_relaxed) > kMaxReports &&
262 last_level_reported.load(std::memory_order_relaxed) == level_) {
263 LOG(ERROR) << "Eliding probably redundant CheckSafeToWait() complaints";
264 return;
265 } else {
266 CHECK(self->GetHeldMutex(level_) == this || level_ == kMonitorLock)
267 << "Waiting on unacquired mutex: " << name_;
268 bool bad_mutexes_held = false;
269 std::string error_msg;
270 for (int i = kLockLevelCount - 1; i >= 0; --i) {
271 if (i != level_) {
272 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
273 // We allow the thread to wait even if the user_code_suspension_lock_ is held so long. This
274 // just means that gc or some other internal process is suspending the thread while it is
275 // trying to suspend some other thread. So long as the current thread is not being suspended
276 // by a SuspendReason::kForUserCode (which needs the user_code_suspension_lock_ to clear)
277 // this is fine. This is needed due to user_code_suspension_lock_ being the way untrusted
278 // code interacts with suspension. One holds the lock to prevent user-code-suspension from
279 // occurring. Since this is only initiated from user-supplied native-code this is safe.
280 if (held_mutex == Locks::user_code_suspension_lock_) {
281 // No thread safety analysis is fine since we have both the user_code_suspension_lock_
282 // from the line above and the ThreadSuspendCountLock since it is our level_. We use this
283 // lambda to avoid having to annotate the whole function as NO_THREAD_SAFETY_ANALYSIS.
284 auto is_suspending_for_user_code = [self]() NO_THREAD_SAFETY_ANALYSIS {
285 return self->GetUserCodeSuspendCount() != 0;
286 };
287 if (is_suspending_for_user_code()) {
288 std::ostringstream oss;
289 oss << "Holding \"" << held_mutex->name_ << "\" "
290 << "(level " << LockLevel(i) << ") while performing wait on "
291 << "\"" << name_ << "\" (level " << level_ << ") "
292 << "with SuspendReason::kForUserCode pending suspensions";
293 error_msg = oss.str();
294 LOG(ERROR) << error_msg;
295 bad_mutexes_held = true;
296 }
297 } else if (held_mutex != nullptr) {
298 if (last_level_reported.load(std::memory_order_relaxed) == level_) {
299 num_reports.fetch_add(1, std::memory_order_relaxed);
300 } else {
301 last_level_reported.store(level_, std::memory_order_relaxed);
302 num_reports.store(0, std::memory_order_relaxed);
303 }
304 std::ostringstream oss;
305 oss << "Holding \"" << held_mutex->name_ << "\" "
306 << "(level " << LockLevel(i) << ") while performing wait on "
307 << "\"" << name_ << "\" (level " << level_ << ")";
308 error_msg = oss.str();
309 LOG(ERROR) << error_msg;
310 bad_mutexes_held = true;
311 }
312 }
313 }
314 if (gAborting == 0) { // Avoid recursive aborts.
315 CHECK(!bad_mutexes_held) << error_msg;
316 }
317 }
318 }
319
AddToWaitTime(uint64_t value)320 void BaseMutex::ContentionLogData::AddToWaitTime(uint64_t value) {
321 if (kLogLockContentions) {
322 // Atomically add value to wait_time.
323 wait_time.fetch_add(value, std::memory_order_seq_cst);
324 }
325 }
326
RecordContention(uint64_t blocked_tid,uint64_t owner_tid,uint64_t nano_time_blocked)327 void BaseMutex::RecordContention(uint64_t blocked_tid,
328 uint64_t owner_tid,
329 uint64_t nano_time_blocked) {
330 if (kLogLockContentions) {
331 ContentionLogData* data = contention_log_data_;
332 ++(data->contention_count);
333 data->AddToWaitTime(nano_time_blocked);
334 ContentionLogEntry* log = data->contention_log;
335 // This code is intentionally racy as it is only used for diagnostics.
336 int32_t slot = data->cur_content_log_entry.load(std::memory_order_relaxed);
337 if (log[slot].blocked_tid == blocked_tid &&
338 log[slot].owner_tid == blocked_tid) {
339 ++log[slot].count;
340 } else {
341 uint32_t new_slot;
342 do {
343 slot = data->cur_content_log_entry.load(std::memory_order_relaxed);
344 new_slot = (slot + 1) % kContentionLogSize;
345 } while (!data->cur_content_log_entry.CompareAndSetWeakRelaxed(slot, new_slot));
346 log[new_slot].blocked_tid = blocked_tid;
347 log[new_slot].owner_tid = owner_tid;
348 log[new_slot].count.store(1, std::memory_order_relaxed);
349 }
350 }
351 }
352
DumpContention(std::ostream & os) const353 void BaseMutex::DumpContention(std::ostream& os) const {
354 if (kLogLockContentions) {
355 const ContentionLogData* data = contention_log_data_;
356 const ContentionLogEntry* log = data->contention_log;
357 uint64_t wait_time = data->wait_time.load(std::memory_order_relaxed);
358 uint32_t contention_count = data->contention_count.load(std::memory_order_relaxed);
359 if (contention_count == 0) {
360 os << "never contended";
361 } else {
362 os << "contended " << contention_count
363 << " total wait of contender " << PrettyDuration(wait_time)
364 << " average " << PrettyDuration(wait_time / contention_count);
365 SafeMap<uint64_t, size_t> most_common_blocker;
366 SafeMap<uint64_t, size_t> most_common_blocked;
367 for (size_t i = 0; i < kContentionLogSize; ++i) {
368 uint64_t blocked_tid = log[i].blocked_tid;
369 uint64_t owner_tid = log[i].owner_tid;
370 uint32_t count = log[i].count.load(std::memory_order_relaxed);
371 if (count > 0) {
372 auto it = most_common_blocked.find(blocked_tid);
373 if (it != most_common_blocked.end()) {
374 most_common_blocked.Overwrite(blocked_tid, it->second + count);
375 } else {
376 most_common_blocked.Put(blocked_tid, count);
377 }
378 it = most_common_blocker.find(owner_tid);
379 if (it != most_common_blocker.end()) {
380 most_common_blocker.Overwrite(owner_tid, it->second + count);
381 } else {
382 most_common_blocker.Put(owner_tid, count);
383 }
384 }
385 }
386 uint64_t max_tid = 0;
387 size_t max_tid_count = 0;
388 for (const auto& pair : most_common_blocked) {
389 if (pair.second > max_tid_count) {
390 max_tid = pair.first;
391 max_tid_count = pair.second;
392 }
393 }
394 if (max_tid != 0) {
395 os << " sample shows most blocked tid=" << max_tid;
396 }
397 max_tid = 0;
398 max_tid_count = 0;
399 for (const auto& pair : most_common_blocker) {
400 if (pair.second > max_tid_count) {
401 max_tid = pair.first;
402 max_tid_count = pair.second;
403 }
404 }
405 if (max_tid != 0) {
406 os << " sample shows tid=" << max_tid << " owning during this time";
407 }
408 }
409 }
410 }
411
412
Mutex(const char * name,LockLevel level,bool recursive)413 Mutex::Mutex(const char* name, LockLevel level, bool recursive)
414 : BaseMutex(name, level), exclusive_owner_(0), recursion_count_(0), recursive_(recursive) {
415 #if ART_USE_FUTEXES
416 DCHECK_EQ(0, state_and_contenders_.load(std::memory_order_relaxed));
417 #else
418 CHECK_MUTEX_CALL(pthread_mutex_init, (&mutex_, nullptr));
419 #endif
420 }
421
422 // Helper to allow checking shutdown while locking for thread safety.
IsSafeToCallAbortSafe()423 static bool IsSafeToCallAbortSafe() {
424 MutexLock mu(Thread::Current(), *Locks::runtime_shutdown_lock_);
425 return Locks::IsSafeToCallAbortRacy();
426 }
427
~Mutex()428 Mutex::~Mutex() {
429 bool safe_to_call_abort = Locks::IsSafeToCallAbortRacy();
430 #if ART_USE_FUTEXES
431 if (state_and_contenders_.load(std::memory_order_relaxed) != 0) {
432 LOG(safe_to_call_abort ? FATAL : WARNING)
433 << "destroying mutex with owner or contenders. Owner:" << GetExclusiveOwnerTid();
434 } else {
435 if (GetExclusiveOwnerTid() != 0) {
436 LOG(safe_to_call_abort ? FATAL : WARNING)
437 << "unexpectedly found an owner on unlocked mutex " << name_;
438 }
439 }
440 #else
441 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
442 // may still be using locks.
443 int rc = pthread_mutex_destroy(&mutex_);
444 if (rc != 0) {
445 errno = rc;
446 PLOG(safe_to_call_abort ? FATAL : WARNING)
447 << "pthread_mutex_destroy failed for " << name_;
448 }
449 #endif
450 }
451
ExclusiveLock(Thread * self)452 void Mutex::ExclusiveLock(Thread* self) {
453 DCHECK(self == nullptr || self == Thread::Current());
454 if (kDebugLocking && !recursive_) {
455 AssertNotHeld(self);
456 }
457 if (!recursive_ || !IsExclusiveHeld(self)) {
458 #if ART_USE_FUTEXES
459 bool done = false;
460 do {
461 int32_t cur_state = state_and_contenders_.load(std::memory_order_relaxed);
462 if (LIKELY((cur_state & kHeldMask) == 0) /* lock not held */) {
463 done = state_and_contenders_.CompareAndSetWeakAcquire(cur_state, cur_state | kHeldMask);
464 } else {
465 // Failed to acquire, hang up.
466 // We don't hold the mutex: GetExclusiveOwnerTid() is usually, but not always, correct.
467 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
468 // Empirically, it appears important to spin again each time through the loop; if we
469 // bother to go to sleep and wake up, we should be fairly persistent in trying for the
470 // lock.
471 if (!WaitBrieflyFor(&state_and_contenders_, self,
472 [](int32_t v) { return (v & kHeldMask) == 0; })) {
473 // Increment contender count. We can't create enough threads for this to overflow.
474 increment_contenders();
475 // Make cur_state again reflect the expected value of state_and_contenders.
476 cur_state += kContenderIncrement;
477 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
478 self->CheckEmptyCheckpointFromMutex();
479 }
480
481 uint64_t wait_start_ms = enable_monitor_timeout_ ? MilliTime() : 0;
482 uint64_t try_times = 0;
483 do {
484 timespec timeout_ts;
485 timeout_ts.tv_sec = 0;
486 // NB: Some tests use the mutex without the runtime.
487 timeout_ts.tv_nsec = Runtime::Current() != nullptr
488 ? Runtime::Current()->GetMonitorTimeoutNs()
489 : Monitor::kDefaultMonitorTimeoutMs;
490 if (futex(state_and_contenders_.Address(), FUTEX_WAIT_PRIVATE, cur_state,
491 enable_monitor_timeout_ ? &timeout_ts : nullptr , nullptr, 0) != 0) {
492 // We only went to sleep after incrementing and contenders and checking that the
493 // lock is still held by someone else. EAGAIN and EINTR both indicate a spurious
494 // failure, try again from the beginning. We don't use TEMP_FAILURE_RETRY so we can
495 // intentionally retry to acquire the lock.
496 if ((errno != EAGAIN) && (errno != EINTR)) {
497 if (errno == ETIMEDOUT) {
498 try_times++;
499 if (try_times <= kMonitorTimeoutTryMax) {
500 DumpStack(self, wait_start_ms, try_times);
501 }
502 } else {
503 PLOG(FATAL) << "futex wait failed for " << name_;
504 }
505 }
506 }
507 SleepIfRuntimeDeleted(self);
508 // Retry until not held. In heavy contention situations we otherwise get redundant
509 // futex wakeups as a result of repeatedly decrementing and incrementing contenders.
510 cur_state = state_and_contenders_.load(std::memory_order_relaxed);
511 } while ((cur_state & kHeldMask) != 0);
512 decrement_contenders();
513 }
514 }
515 } while (!done);
516 // Confirm that lock is now held.
517 DCHECK_NE(state_and_contenders_.load(std::memory_order_relaxed) & kHeldMask, 0);
518 #else
519 CHECK_MUTEX_CALL(pthread_mutex_lock, (&mutex_));
520 #endif
521 DCHECK_EQ(GetExclusiveOwnerTid(), 0) << " my tid = " << SafeGetTid(self)
522 << " recursive_ = " << recursive_;
523 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
524 RegisterAsLocked(self);
525 }
526 recursion_count_++;
527 if (kDebugLocking) {
528 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
529 << name_ << " " << recursion_count_;
530 AssertHeld(self);
531 }
532 }
533
DumpStack(Thread * self,uint64_t wait_start_ms,uint64_t try_times)534 void Mutex::DumpStack(Thread* self, uint64_t wait_start_ms, uint64_t try_times) {
535 ScopedObjectAccess soa(self);
536 Locks::thread_list_lock_->ExclusiveLock(self);
537 std::string owner_stack_dump;
538 pid_t owner_tid = GetExclusiveOwnerTid();
539 CHECK(Runtime::Current() != nullptr);
540 Thread *owner = Runtime::Current()->GetThreadList()->FindThreadByTid(owner_tid);
541 if (owner != nullptr) {
542 if (IsDumpFrequent(owner, try_times)) {
543 Locks::thread_list_lock_->ExclusiveUnlock(self);
544 LOG(WARNING) << "Contention with tid " << owner_tid << ", monitor id " << monitor_id_;
545 return;
546 }
547 struct CollectStackTrace : public Closure {
548 void Run(art::Thread* thread) override
549 REQUIRES_SHARED(art::Locks::mutator_lock_) {
550 if (IsDumpFrequent(thread)) {
551 return;
552 }
553 DumpStackLastTimeTLSData* tls_data =
554 reinterpret_cast<DumpStackLastTimeTLSData*>(thread->GetCustomTLS(kLastDumpStackTime));
555 if (tls_data == nullptr) {
556 thread->SetCustomTLS(kLastDumpStackTime, new DumpStackLastTimeTLSData(MilliTime()));
557 } else {
558 tls_data->last_dump_time_ms_.store(MilliTime());
559 }
560 thread->DumpJavaStack(oss);
561 }
562 std::ostringstream oss;
563 };
564 CollectStackTrace owner_trace;
565 owner->RequestSynchronousCheckpoint(&owner_trace);
566 owner_stack_dump = owner_trace.oss.str();
567 uint64_t wait_ms = MilliTime() - wait_start_ms;
568 LOG(WARNING) << "Monitor contention with tid " << owner_tid << ", wait time: " << wait_ms
569 << "ms, monitor id: " << monitor_id_
570 << "\nPerfMonitor owner thread(" << owner_tid << ") stack is:\n"
571 << owner_stack_dump;
572 } else {
573 Locks::thread_list_lock_->ExclusiveUnlock(self);
574 }
575 }
576
IsDumpFrequent(Thread * thread,uint64_t try_times)577 bool Mutex::IsDumpFrequent(Thread* thread, uint64_t try_times) {
578 uint64_t last_dump_time_ms = 0;
579 DumpStackLastTimeTLSData* tls_data =
580 reinterpret_cast<DumpStackLastTimeTLSData*>(thread->GetCustomTLS(kLastDumpStackTime));
581 if (tls_data != nullptr) {
582 last_dump_time_ms = tls_data->last_dump_time_ms_.load();
583 }
584 uint64_t interval = MilliTime() - last_dump_time_ms;
585 if (interval < kIntervalMillis * try_times) {
586 return true;
587 } else {
588 return false;
589 }
590 }
591
592 template <bool kCheck>
ExclusiveTryLock(Thread * self)593 bool Mutex::ExclusiveTryLock(Thread* self) {
594 DCHECK(self == nullptr || self == Thread::Current());
595 if (kDebugLocking && !recursive_) {
596 AssertNotHeld(self);
597 }
598 if (!recursive_ || !IsExclusiveHeld(self)) {
599 #if ART_USE_FUTEXES
600 bool done = false;
601 do {
602 int32_t cur_state = state_and_contenders_.load(std::memory_order_relaxed);
603 if ((cur_state & kHeldMask) == 0) {
604 // Change state to held and impose load/store ordering appropriate for lock acquisition.
605 done = state_and_contenders_.CompareAndSetWeakAcquire(cur_state, cur_state | kHeldMask);
606 } else {
607 return false;
608 }
609 } while (!done);
610 DCHECK_NE(state_and_contenders_.load(std::memory_order_relaxed) & kHeldMask, 0);
611 #else
612 int result = pthread_mutex_trylock(&mutex_);
613 if (result == EBUSY) {
614 return false;
615 }
616 if (result != 0) {
617 errno = result;
618 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
619 }
620 #endif
621 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
622 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
623 RegisterAsLocked(self, kCheck);
624 }
625 recursion_count_++;
626 if (kDebugLocking) {
627 CHECK(recursion_count_ == 1 || recursive_) << "Unexpected recursion count on mutex: "
628 << name_ << " " << recursion_count_;
629 AssertHeld(self);
630 }
631 return true;
632 }
633
634 template bool Mutex::ExclusiveTryLock<false>(Thread* self);
635 template bool Mutex::ExclusiveTryLock<true>(Thread* self);
636
ExclusiveTryLockWithSpinning(Thread * self)637 bool Mutex::ExclusiveTryLockWithSpinning(Thread* self) {
638 // Spin a small number of times, since this affects our ability to respond to suspension
639 // requests. We spin repeatedly only if the mutex repeatedly becomes available and unavailable
640 // in rapid succession, and then we will typically not spin for the maximal period.
641 const int kMaxSpins = 5;
642 for (int i = 0; i < kMaxSpins; ++i) {
643 if (ExclusiveTryLock(self)) {
644 return true;
645 }
646 #if ART_USE_FUTEXES
647 if (!WaitBrieflyFor(&state_and_contenders_, self,
648 [](int32_t v) { return (v & kHeldMask) == 0; })) {
649 return false;
650 }
651 #endif
652 }
653 return ExclusiveTryLock(self);
654 }
655
656 #if ART_USE_FUTEXES
ExclusiveLockUncontendedFor(Thread * new_owner)657 void Mutex::ExclusiveLockUncontendedFor(Thread* new_owner) {
658 DCHECK_EQ(level_, kMonitorLock);
659 DCHECK(!recursive_);
660 state_and_contenders_.store(kHeldMask, std::memory_order_relaxed);
661 recursion_count_ = 1;
662 exclusive_owner_.store(SafeGetTid(new_owner), std::memory_order_relaxed);
663 // Don't call RegisterAsLocked(). It wouldn't register anything anyway. And
664 // this happens as we're inflating a monitor, which doesn't logically affect
665 // held "locks"; it effectively just converts a thin lock to a mutex. By doing
666 // this while the lock is already held, we're delaying the acquisition of a
667 // logically held mutex, which can introduce bogus lock order violations.
668 }
669
ExclusiveUnlockUncontended()670 void Mutex::ExclusiveUnlockUncontended() {
671 DCHECK_EQ(level_, kMonitorLock);
672 state_and_contenders_.store(0, std::memory_order_relaxed);
673 recursion_count_ = 0;
674 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
675 // Skip RegisterAsUnlocked(), which wouldn't do anything anyway.
676 }
677 #endif // ART_USE_FUTEXES
678
ExclusiveUnlock(Thread * self)679 void Mutex::ExclusiveUnlock(Thread* self) {
680 if (kIsDebugBuild && self != nullptr && self != Thread::Current()) {
681 std::string name1 = "<null>";
682 std::string name2 = "<null>";
683 if (self != nullptr) {
684 self->GetThreadName(name1);
685 }
686 if (Thread::Current() != nullptr) {
687 Thread::Current()->GetThreadName(name2);
688 }
689 LOG(FATAL) << GetName() << " level=" << level_ << " self=" << name1
690 << " Thread::Current()=" << name2;
691 }
692 AssertHeld(self);
693 DCHECK_NE(GetExclusiveOwnerTid(), 0);
694 recursion_count_--;
695 if (!recursive_ || recursion_count_ == 0) {
696 if (kDebugLocking) {
697 CHECK(recursion_count_ == 0 || recursive_) << "Unexpected recursion count on mutex: "
698 << name_ << " " << recursion_count_;
699 }
700 RegisterAsUnlocked(self);
701 #if ART_USE_FUTEXES
702 bool done = false;
703 do {
704 int32_t cur_state = state_and_contenders_.load(std::memory_order_relaxed);
705 if (LIKELY((cur_state & kHeldMask) != 0)) {
706 // We're no longer the owner.
707 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
708 // Change state to not held and impose load/store ordering appropriate for lock release.
709 uint32_t new_state = cur_state & ~kHeldMask; // Same number of contenders.
710 done = state_and_contenders_.CompareAndSetWeakRelease(cur_state, new_state);
711 if (LIKELY(done)) { // Spurious fail or waiters changed ?
712 if (UNLIKELY(new_state != 0) /* have contenders */) {
713 futex(state_and_contenders_.Address(), FUTEX_WAKE_PRIVATE, kWakeOne,
714 nullptr, nullptr, 0);
715 }
716 // We only do a futex wait after incrementing contenders and verifying the lock was
717 // still held. If we didn't see waiters, then there couldn't have been any futexes
718 // waiting on this lock when we did the CAS. New arrivals after that cannot wait for us,
719 // since the futex wait call would see the lock available and immediately return.
720 }
721 } else {
722 // Logging acquires the logging lock, avoid infinite recursion in that case.
723 if (this != Locks::logging_lock_) {
724 LOG(FATAL) << "Unexpected state_ in unlock " << cur_state << " for " << name_;
725 } else {
726 LogHelper::LogLineLowStack(__FILE__,
727 __LINE__,
728 ::android::base::FATAL_WITHOUT_ABORT,
729 StringPrintf("Unexpected state_ %d in unlock for %s",
730 cur_state, name_).c_str());
731 _exit(1);
732 }
733 }
734 } while (!done);
735 #else
736 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
737 CHECK_MUTEX_CALL(pthread_mutex_unlock, (&mutex_));
738 #endif
739 }
740 }
741
Dump(std::ostream & os) const742 void Mutex::Dump(std::ostream& os) const {
743 os << (recursive_ ? "recursive " : "non-recursive ") << name_
744 << " level=" << static_cast<int>(level_) << " rec=" << recursion_count_
745 #if ART_USE_FUTEXES
746 << " state_and_contenders = " << std::hex << state_and_contenders_ << std::dec
747 #endif
748 << " owner=" << GetExclusiveOwnerTid() << " ";
749 DumpContention(os);
750 }
751
operator <<(std::ostream & os,const Mutex & mu)752 std::ostream& operator<<(std::ostream& os, const Mutex& mu) {
753 mu.Dump(os);
754 return os;
755 }
756
WakeupToRespondToEmptyCheckpoint()757 void Mutex::WakeupToRespondToEmptyCheckpoint() {
758 #if ART_USE_FUTEXES
759 // Wake up all the waiters so they will respond to the emtpy checkpoint.
760 DCHECK(should_respond_to_empty_checkpoint_request_);
761 if (UNLIKELY(get_contenders() != 0)) {
762 futex(state_and_contenders_.Address(), FUTEX_WAKE_PRIVATE, kWakeAll, nullptr, nullptr, 0);
763 }
764 #else
765 LOG(FATAL) << "Non futex case isn't supported.";
766 #endif
767 }
768
ReaderWriterMutex(const char * name,LockLevel level)769 ReaderWriterMutex::ReaderWriterMutex(const char* name, LockLevel level)
770 : BaseMutex(name, level)
771 #if ART_USE_FUTEXES
772 , state_(0), exclusive_owner_(0), num_contenders_(0)
773 #endif
774 {
775 #if !ART_USE_FUTEXES
776 CHECK_MUTEX_CALL(pthread_rwlock_init, (&rwlock_, nullptr));
777 #endif
778 }
779
~ReaderWriterMutex()780 ReaderWriterMutex::~ReaderWriterMutex() {
781 #if ART_USE_FUTEXES
782 CHECK_EQ(state_.load(std::memory_order_relaxed), 0);
783 CHECK_EQ(GetExclusiveOwnerTid(), 0);
784 CHECK_EQ(num_contenders_.load(std::memory_order_relaxed), 0);
785 #else
786 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
787 // may still be using locks.
788 int rc = pthread_rwlock_destroy(&rwlock_);
789 if (rc != 0) {
790 errno = rc;
791 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
792 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_rwlock_destroy failed for " << name_;
793 }
794 #endif
795 }
796
ExclusiveLock(Thread * self)797 void ReaderWriterMutex::ExclusiveLock(Thread* self) {
798 DCHECK(self == nullptr || self == Thread::Current());
799 AssertNotExclusiveHeld(self);
800 #if ART_USE_FUTEXES
801 bool done = false;
802 do {
803 int32_t cur_state = state_.load(std::memory_order_relaxed);
804 if (LIKELY(cur_state == 0)) {
805 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
806 done = state_.CompareAndSetWeakAcquire(0 /* cur_state*/, -1 /* new state */);
807 } else {
808 // Failed to acquire, hang up.
809 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
810 if (!WaitBrieflyFor(&state_, self, [](int32_t v) { return v == 0; })) {
811 num_contenders_.fetch_add(1);
812 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
813 self->CheckEmptyCheckpointFromMutex();
814 }
815 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, nullptr, nullptr, 0) != 0) {
816 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
817 // We don't use TEMP_FAILURE_RETRY so we can intentionally retry to acquire the lock.
818 if ((errno != EAGAIN) && (errno != EINTR)) {
819 PLOG(FATAL) << "futex wait failed for " << name_;
820 }
821 }
822 SleepIfRuntimeDeleted(self);
823 num_contenders_.fetch_sub(1);
824 }
825 }
826 } while (!done);
827 DCHECK_EQ(state_.load(std::memory_order_relaxed), -1);
828 #else
829 CHECK_MUTEX_CALL(pthread_rwlock_wrlock, (&rwlock_));
830 #endif
831 DCHECK_EQ(GetExclusiveOwnerTid(), 0);
832 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
833 RegisterAsLocked(self);
834 AssertExclusiveHeld(self);
835 }
836
ExclusiveUnlock(Thread * self)837 void ReaderWriterMutex::ExclusiveUnlock(Thread* self) {
838 DCHECK(self == nullptr || self == Thread::Current());
839 AssertExclusiveHeld(self);
840 RegisterAsUnlocked(self);
841 DCHECK_NE(GetExclusiveOwnerTid(), 0);
842 #if ART_USE_FUTEXES
843 bool done = false;
844 do {
845 int32_t cur_state = state_.load(std::memory_order_relaxed);
846 if (LIKELY(cur_state == -1)) {
847 // We're no longer the owner.
848 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
849 // Change state from -1 to 0 and impose load/store ordering appropriate for lock release.
850 // Note, the num_contenders_ load below musn't reorder before the CompareAndSet.
851 done = state_.CompareAndSetWeakSequentiallyConsistent(-1 /* cur_state*/, 0 /* new state */);
852 if (LIKELY(done)) { // Weak CAS may fail spuriously.
853 // Wake any waiters.
854 if (UNLIKELY(num_contenders_.load(std::memory_order_seq_cst) > 0)) {
855 futex(state_.Address(), FUTEX_WAKE_PRIVATE, kWakeAll, nullptr, nullptr, 0);
856 }
857 }
858 } else {
859 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
860 }
861 } while (!done);
862 #else
863 exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
864 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
865 #endif
866 }
867
868 #if HAVE_TIMED_RWLOCK
ExclusiveLockWithTimeout(Thread * self,int64_t ms,int32_t ns)869 bool ReaderWriterMutex::ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) {
870 DCHECK(self == nullptr || self == Thread::Current());
871 #if ART_USE_FUTEXES
872 bool done = false;
873 timespec end_abs_ts;
874 InitTimeSpec(true, CLOCK_MONOTONIC, ms, ns, &end_abs_ts);
875 do {
876 int32_t cur_state = state_.load(std::memory_order_relaxed);
877 if (cur_state == 0) {
878 // Change state from 0 to -1 and impose load/store ordering appropriate for lock acquisition.
879 done = state_.CompareAndSetWeakAcquire(0 /* cur_state */, -1 /* new state */);
880 } else {
881 // Failed to acquire, hang up.
882 timespec now_abs_ts;
883 InitTimeSpec(true, CLOCK_MONOTONIC, 0, 0, &now_abs_ts);
884 timespec rel_ts;
885 if (!ComputeRelativeTimeSpec(&rel_ts, end_abs_ts, now_abs_ts)) {
886 return false; // Timed out.
887 }
888 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
889 if (!WaitBrieflyFor(&state_, self, [](int32_t v) { return v == 0; })) {
890 num_contenders_.fetch_add(1);
891 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
892 self->CheckEmptyCheckpointFromMutex();
893 }
894 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, &rel_ts, nullptr, 0) != 0) {
895 if (errno == ETIMEDOUT) {
896 num_contenders_.fetch_sub(1);
897 return false; // Timed out.
898 } else if ((errno != EAGAIN) && (errno != EINTR)) {
899 // EAGAIN and EINTR both indicate a spurious failure,
900 // recompute the relative time out from now and try again.
901 // We don't use TEMP_FAILURE_RETRY so we can recompute rel_ts;
902 num_contenders_.fetch_sub(1); // Unlikely to matter.
903 PLOG(FATAL) << "timed futex wait failed for " << name_;
904 }
905 }
906 SleepIfRuntimeDeleted(self);
907 num_contenders_.fetch_sub(1);
908 }
909 }
910 } while (!done);
911 #else
912 timespec ts;
913 InitTimeSpec(true, CLOCK_REALTIME, ms, ns, &ts);
914 int result = pthread_rwlock_timedwrlock(&rwlock_, &ts);
915 if (result == ETIMEDOUT) {
916 return false;
917 }
918 if (result != 0) {
919 errno = result;
920 PLOG(FATAL) << "pthread_rwlock_timedwrlock failed for " << name_;
921 }
922 #endif
923 exclusive_owner_.store(SafeGetTid(self), std::memory_order_relaxed);
924 RegisterAsLocked(self);
925 AssertSharedHeld(self);
926 return true;
927 }
928 #endif
929
930 #if ART_USE_FUTEXES
HandleSharedLockContention(Thread * self,int32_t cur_state)931 void ReaderWriterMutex::HandleSharedLockContention(Thread* self, int32_t cur_state) {
932 // Owner holds it exclusively, hang up.
933 ScopedContentionRecorder scr(this, SafeGetTid(self), GetExclusiveOwnerTid());
934 if (!WaitBrieflyFor(&state_, self, [](int32_t v) { return v >= 0; })) {
935 num_contenders_.fetch_add(1);
936 if (UNLIKELY(should_respond_to_empty_checkpoint_request_)) {
937 self->CheckEmptyCheckpointFromMutex();
938 }
939 if (futex(state_.Address(), FUTEX_WAIT_PRIVATE, cur_state, nullptr, nullptr, 0) != 0) {
940 if (errno != EAGAIN && errno != EINTR) {
941 PLOG(FATAL) << "futex wait failed for " << name_;
942 }
943 }
944 SleepIfRuntimeDeleted(self);
945 num_contenders_.fetch_sub(1);
946 }
947 }
948 #endif
949
SharedTryLock(Thread * self,bool check)950 bool ReaderWriterMutex::SharedTryLock(Thread* self, bool check) {
951 DCHECK(self == nullptr || self == Thread::Current());
952 #if ART_USE_FUTEXES
953 bool done = false;
954 do {
955 int32_t cur_state = state_.load(std::memory_order_relaxed);
956 if (cur_state >= 0) {
957 // Add as an extra reader and impose load/store ordering appropriate for lock acquisition.
958 done = state_.CompareAndSetWeakAcquire(cur_state, cur_state + 1);
959 } else {
960 // Owner holds it exclusively.
961 return false;
962 }
963 } while (!done);
964 #else
965 int result = pthread_rwlock_tryrdlock(&rwlock_);
966 if (result == EBUSY) {
967 return false;
968 }
969 if (result != 0) {
970 errno = result;
971 PLOG(FATAL) << "pthread_mutex_trylock failed for " << name_;
972 }
973 #endif
974 RegisterAsLocked(self, check);
975 AssertSharedHeld(self);
976 return true;
977 }
978
IsSharedHeld(const Thread * self) const979 bool ReaderWriterMutex::IsSharedHeld(const Thread* self) const {
980 DCHECK(self == nullptr || self == Thread::Current());
981 bool result;
982 if (UNLIKELY(self == nullptr)) { // Handle unattached threads.
983 result = IsExclusiveHeld(self); // TODO: a better best effort here.
984 } else {
985 result = (self->GetHeldMutex(level_) == this);
986 }
987 return result;
988 }
989
Dump(std::ostream & os) const990 void ReaderWriterMutex::Dump(std::ostream& os) const {
991 os << name_
992 << " level=" << static_cast<int>(level_)
993 << " owner=" << GetExclusiveOwnerTid()
994 #if ART_USE_FUTEXES
995 << " state=" << state_.load(std::memory_order_seq_cst)
996 << " num_contenders=" << num_contenders_.load(std::memory_order_seq_cst)
997 #endif
998 << " ";
999 DumpContention(os);
1000 }
1001
operator <<(std::ostream & os,const ReaderWriterMutex & mu)1002 std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu) {
1003 mu.Dump(os);
1004 return os;
1005 }
1006
operator <<(std::ostream & os,const MutatorMutex & mu)1007 std::ostream& operator<<(std::ostream& os, const MutatorMutex& mu) {
1008 mu.Dump(os);
1009 return os;
1010 }
1011
WakeupToRespondToEmptyCheckpoint()1012 void ReaderWriterMutex::WakeupToRespondToEmptyCheckpoint() {
1013 #if ART_USE_FUTEXES
1014 // Wake up all the waiters so they will respond to the emtpy checkpoint.
1015 DCHECK(should_respond_to_empty_checkpoint_request_);
1016 if (UNLIKELY(num_contenders_.load(std::memory_order_relaxed) > 0)) {
1017 futex(state_.Address(), FUTEX_WAKE_PRIVATE, kWakeAll, nullptr, nullptr, 0);
1018 }
1019 #else
1020 LOG(FATAL) << "Non futex case isn't supported.";
1021 #endif
1022 }
1023
ConditionVariable(const char * name,Mutex & guard)1024 ConditionVariable::ConditionVariable(const char* name, Mutex& guard)
1025 : name_(name), guard_(guard) {
1026 #if ART_USE_FUTEXES
1027 DCHECK_EQ(0, sequence_.load(std::memory_order_relaxed));
1028 num_waiters_ = 0;
1029 #else
1030 pthread_condattr_t cond_attrs;
1031 CHECK_MUTEX_CALL(pthread_condattr_init, (&cond_attrs));
1032 #if !defined(__APPLE__)
1033 // Apple doesn't have CLOCK_MONOTONIC or pthread_condattr_setclock.
1034 CHECK_MUTEX_CALL(pthread_condattr_setclock, (&cond_attrs, CLOCK_MONOTONIC));
1035 #endif
1036 CHECK_MUTEX_CALL(pthread_cond_init, (&cond_, &cond_attrs));
1037 #endif
1038 }
1039
~ConditionVariable()1040 ConditionVariable::~ConditionVariable() {
1041 #if ART_USE_FUTEXES
1042 if (num_waiters_!= 0) {
1043 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
1044 LOG(is_safe_to_call_abort ? FATAL : WARNING)
1045 << "ConditionVariable::~ConditionVariable for " << name_
1046 << " called with " << num_waiters_ << " waiters.";
1047 }
1048 #else
1049 // We can't use CHECK_MUTEX_CALL here because on shutdown a suspended daemon thread
1050 // may still be using condition variables.
1051 int rc = pthread_cond_destroy(&cond_);
1052 if (rc != 0) {
1053 errno = rc;
1054 bool is_safe_to_call_abort = IsSafeToCallAbortSafe();
1055 PLOG(is_safe_to_call_abort ? FATAL : WARNING) << "pthread_cond_destroy failed for " << name_;
1056 }
1057 #endif
1058 }
1059
Broadcast(Thread * self)1060 void ConditionVariable::Broadcast(Thread* self) {
1061 DCHECK(self == nullptr || self == Thread::Current());
1062 // TODO: enable below, there's a race in thread creation that causes false failures currently.
1063 // guard_.AssertExclusiveHeld(self);
1064 DCHECK_EQ(guard_.GetExclusiveOwnerTid(), SafeGetTid(self));
1065 #if ART_USE_FUTEXES
1066 RequeueWaiters(std::numeric_limits<int32_t>::max());
1067 #else
1068 CHECK_MUTEX_CALL(pthread_cond_broadcast, (&cond_));
1069 #endif
1070 }
1071
1072 #if ART_USE_FUTEXES
RequeueWaiters(int32_t count)1073 void ConditionVariable::RequeueWaiters(int32_t count) {
1074 if (num_waiters_ > 0) {
1075 sequence_++; // Indicate a signal occurred.
1076 // Move waiters from the condition variable's futex to the guard's futex,
1077 // so that they will be woken up when the mutex is released.
1078 bool done = futex(sequence_.Address(),
1079 FUTEX_REQUEUE_PRIVATE,
1080 /* Threads to wake */ 0,
1081 /* Threads to requeue*/ reinterpret_cast<const timespec*>(count),
1082 guard_.state_and_contenders_.Address(),
1083 0) != -1;
1084 if (!done && errno != EAGAIN && errno != EINTR) {
1085 PLOG(FATAL) << "futex requeue failed for " << name_;
1086 }
1087 }
1088 }
1089 #endif
1090
1091
Signal(Thread * self)1092 void ConditionVariable::Signal(Thread* self) {
1093 DCHECK(self == nullptr || self == Thread::Current());
1094 guard_.AssertExclusiveHeld(self);
1095 #if ART_USE_FUTEXES
1096 RequeueWaiters(1);
1097 #else
1098 CHECK_MUTEX_CALL(pthread_cond_signal, (&cond_));
1099 #endif
1100 }
1101
Wait(Thread * self)1102 void ConditionVariable::Wait(Thread* self) {
1103 guard_.CheckSafeToWait(self);
1104 WaitHoldingLocks(self);
1105 }
1106
WaitHoldingLocks(Thread * self)1107 void ConditionVariable::WaitHoldingLocks(Thread* self) {
1108 DCHECK(self == nullptr || self == Thread::Current());
1109 guard_.AssertExclusiveHeld(self);
1110 unsigned int old_recursion_count = guard_.recursion_count_;
1111 #if ART_USE_FUTEXES
1112 num_waiters_++;
1113 // Ensure the Mutex is contended so that requeued threads are awoken.
1114 guard_.increment_contenders();
1115 guard_.recursion_count_ = 1;
1116 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
1117 guard_.ExclusiveUnlock(self);
1118 if (futex(sequence_.Address(), FUTEX_WAIT_PRIVATE, cur_sequence, nullptr, nullptr, 0) != 0) {
1119 // Futex failed, check it is an expected error.
1120 // EAGAIN == EWOULDBLK, so we let the caller try again.
1121 // EINTR implies a signal was sent to this thread.
1122 if ((errno != EINTR) && (errno != EAGAIN)) {
1123 PLOG(FATAL) << "futex wait failed for " << name_;
1124 }
1125 }
1126 SleepIfRuntimeDeleted(self);
1127 guard_.ExclusiveLock(self);
1128 CHECK_GT(num_waiters_, 0);
1129 num_waiters_--;
1130 // We awoke and so no longer require awakes from the guard_'s unlock.
1131 CHECK_GT(guard_.get_contenders(), 0);
1132 guard_.decrement_contenders();
1133 #else
1134 pid_t old_owner = guard_.GetExclusiveOwnerTid();
1135 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
1136 guard_.recursion_count_ = 0;
1137 CHECK_MUTEX_CALL(pthread_cond_wait, (&cond_, &guard_.mutex_));
1138 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
1139 #endif
1140 guard_.recursion_count_ = old_recursion_count;
1141 }
1142
TimedWait(Thread * self,int64_t ms,int32_t ns)1143 bool ConditionVariable::TimedWait(Thread* self, int64_t ms, int32_t ns) {
1144 DCHECK(self == nullptr || self == Thread::Current());
1145 bool timed_out = false;
1146 guard_.AssertExclusiveHeld(self);
1147 guard_.CheckSafeToWait(self);
1148 unsigned int old_recursion_count = guard_.recursion_count_;
1149 #if ART_USE_FUTEXES
1150 timespec rel_ts;
1151 InitTimeSpec(false, CLOCK_REALTIME, ms, ns, &rel_ts);
1152 num_waiters_++;
1153 // Ensure the Mutex is contended so that requeued threads are awoken.
1154 guard_.increment_contenders();
1155 guard_.recursion_count_ = 1;
1156 int32_t cur_sequence = sequence_.load(std::memory_order_relaxed);
1157 guard_.ExclusiveUnlock(self);
1158 if (futex(sequence_.Address(), FUTEX_WAIT_PRIVATE, cur_sequence, &rel_ts, nullptr, 0) != 0) {
1159 if (errno == ETIMEDOUT) {
1160 // Timed out we're done.
1161 timed_out = true;
1162 } else if ((errno == EAGAIN) || (errno == EINTR)) {
1163 // A signal or ConditionVariable::Signal/Broadcast has come in.
1164 } else {
1165 PLOG(FATAL) << "timed futex wait failed for " << name_;
1166 }
1167 }
1168 SleepIfRuntimeDeleted(self);
1169 guard_.ExclusiveLock(self);
1170 CHECK_GT(num_waiters_, 0);
1171 num_waiters_--;
1172 // We awoke and so no longer require awakes from the guard_'s unlock.
1173 CHECK_GT(guard_.get_contenders(), 0);
1174 guard_.decrement_contenders();
1175 #else
1176 #if !defined(__APPLE__)
1177 int clock = CLOCK_MONOTONIC;
1178 #else
1179 int clock = CLOCK_REALTIME;
1180 #endif
1181 pid_t old_owner = guard_.GetExclusiveOwnerTid();
1182 guard_.exclusive_owner_.store(0 /* pid */, std::memory_order_relaxed);
1183 guard_.recursion_count_ = 0;
1184 timespec ts;
1185 InitTimeSpec(true, clock, ms, ns, &ts);
1186 int rc;
1187 while ((rc = pthread_cond_timedwait(&cond_, &guard_.mutex_, &ts)) == EINTR) {
1188 continue;
1189 }
1190
1191 if (rc == ETIMEDOUT) {
1192 timed_out = true;
1193 } else if (rc != 0) {
1194 errno = rc;
1195 PLOG(FATAL) << "TimedWait failed for " << name_;
1196 }
1197 guard_.exclusive_owner_.store(old_owner, std::memory_order_relaxed);
1198 #endif
1199 guard_.recursion_count_ = old_recursion_count;
1200 return timed_out;
1201 }
1202
1203 } // namespace art
1204