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 #ifndef ART_RUNTIME_BASE_MUTEX_H_ 18 #define ART_RUNTIME_BASE_MUTEX_H_ 19 20 #include <limits.h> // for INT_MAX 21 #include <pthread.h> 22 #include <stdint.h> 23 #include <unistd.h> // for pid_t 24 25 #include <iosfwd> 26 #include <string> 27 28 #include <android-base/logging.h> 29 30 #include "base/aborting.h" 31 #include "base/atomic.h" 32 #include "runtime_globals.h" 33 #include "base/macros.h" 34 #include "locks.h" 35 36 #if defined(__linux__) 37 #define ART_USE_FUTEXES 1 38 #else 39 #define ART_USE_FUTEXES 0 40 #endif 41 42 // Currently Darwin doesn't support locks with timeouts. 43 #if !defined(__APPLE__) 44 #define HAVE_TIMED_RWLOCK 1 45 #else 46 #define HAVE_TIMED_RWLOCK 0 47 #endif 48 49 namespace art { 50 51 class SHARED_LOCKABLE ReaderWriterMutex; 52 class SHARED_LOCKABLE MutatorMutex; 53 class ScopedContentionRecorder; 54 class Thread; 55 class LOCKABLE Mutex; 56 57 constexpr bool kDebugLocking = kIsDebugBuild; 58 59 // Record Log contention information, dumpable via SIGQUIT. 60 #if ART_USE_FUTEXES 61 // To enable lock contention logging, set this to true. 62 constexpr bool kLogLockContentions = false; 63 // FUTEX_WAKE first argument: 64 constexpr int kWakeOne = 1; 65 constexpr int kWakeAll = INT_MAX; 66 #else 67 // Keep this false as lock contention logging is supported only with 68 // futex. 69 constexpr bool kLogLockContentions = false; 70 #endif 71 constexpr size_t kContentionLogSize = 4; 72 constexpr size_t kContentionLogDataSize = kLogLockContentions ? 1 : 0; 73 constexpr size_t kAllMutexDataSize = kLogLockContentions ? 1 : 0; 74 75 // Base class for all Mutex implementations 76 class BaseMutex { 77 public: GetName()78 const char* GetName() const { 79 return name_; 80 } 81 IsMutex()82 virtual bool IsMutex() const { return false; } IsReaderWriterMutex()83 virtual bool IsReaderWriterMutex() const { return false; } IsMutatorMutex()84 virtual bool IsMutatorMutex() const { return false; } 85 86 virtual void Dump(std::ostream& os) const = 0; 87 88 static void DumpAll(std::ostream& os); 89 ShouldRespondToEmptyCheckpointRequest()90 bool ShouldRespondToEmptyCheckpointRequest() const { 91 return should_respond_to_empty_checkpoint_request_; 92 } 93 SetShouldRespondToEmptyCheckpointRequest(bool value)94 void SetShouldRespondToEmptyCheckpointRequest(bool value) { 95 should_respond_to_empty_checkpoint_request_ = value; 96 } 97 98 virtual void WakeupToRespondToEmptyCheckpoint() = 0; 99 100 protected: 101 friend class ConditionVariable; 102 103 BaseMutex(const char* name, LockLevel level); 104 virtual ~BaseMutex(); 105 106 // Add this mutex to those owned by self, and perform appropriate checking. 107 // For this call only, self may also be another suspended thread. 108 void RegisterAsLocked(Thread* self); 109 110 void RegisterAsUnlocked(Thread* self); 111 void CheckSafeToWait(Thread* self); 112 113 friend class ScopedContentionRecorder; 114 115 void RecordContention(uint64_t blocked_tid, uint64_t owner_tid, uint64_t nano_time_blocked); 116 void DumpContention(std::ostream& os) const; 117 118 const char* const name_; 119 120 // A log entry that records contention but makes no guarantee that either tid will be held live. 121 struct ContentionLogEntry { ContentionLogEntryContentionLogEntry122 ContentionLogEntry() : blocked_tid(0), owner_tid(0) {} 123 uint64_t blocked_tid; 124 uint64_t owner_tid; 125 AtomicInteger count; 126 }; 127 struct ContentionLogData { 128 ContentionLogEntry contention_log[kContentionLogSize]; 129 // The next entry in the contention log to be updated. Value ranges from 0 to 130 // kContentionLogSize - 1. 131 AtomicInteger cur_content_log_entry; 132 // Number of times the Mutex has been contended. 133 AtomicInteger contention_count; 134 // Sum of time waited by all contenders in ns. 135 Atomic<uint64_t> wait_time; 136 void AddToWaitTime(uint64_t value); ContentionLogDataContentionLogData137 ContentionLogData() : wait_time(0) {} 138 }; 139 ContentionLogData contention_log_data_[kContentionLogDataSize]; 140 141 const LockLevel level_; // Support for lock hierarchy. 142 bool should_respond_to_empty_checkpoint_request_; 143 144 public: HasEverContended()145 bool HasEverContended() const { 146 if (kLogLockContentions) { 147 return contention_log_data_->contention_count.load(std::memory_order_seq_cst) > 0; 148 } 149 return false; 150 } 151 }; 152 153 // A Mutex is used to achieve mutual exclusion between threads. A Mutex can be used to gain 154 // exclusive access to what it guards. A Mutex can be in one of two states: 155 // - Free - not owned by any thread, 156 // - Exclusive - owned by a single thread. 157 // 158 // The effect of locking and unlocking operations on the state is: 159 // State | ExclusiveLock | ExclusiveUnlock 160 // ------------------------------------------- 161 // Free | Exclusive | error 162 // Exclusive | Block* | Free 163 // * Mutex is not reentrant unless recursive is true. An attempt to ExclusiveLock on a 164 // recursive=false Mutex on a thread already owning the Mutex results in an error. 165 // 166 // TODO(b/140590186): Remove support for recursive == true. 167 // 168 // Some mutexes, including those associated with Java monitors may be accessed (in particular 169 // acquired) by a thread in suspended state. Suspending all threads does NOT prevent mutex state 170 // from changing. 171 std::ostream& operator<<(std::ostream& os, const Mutex& mu); 172 class LOCKABLE Mutex : public BaseMutex { 173 public: 174 explicit Mutex(const char* name, LockLevel level = kDefaultMutexLevel, bool recursive = false); 175 ~Mutex(); 176 IsMutex()177 bool IsMutex() const override { return true; } 178 179 // Block until mutex is free then acquire exclusive access. 180 void ExclusiveLock(Thread* self) ACQUIRE(); Lock(Thread * self)181 void Lock(Thread* self) ACQUIRE() { ExclusiveLock(self); } 182 183 // Returns true if acquires exclusive access, false otherwise. 184 bool ExclusiveTryLock(Thread* self) TRY_ACQUIRE(true); TryLock(Thread * self)185 bool TryLock(Thread* self) TRY_ACQUIRE(true) { return ExclusiveTryLock(self); } 186 // Equivalent to ExclusiveTryLock, but retry for a short period before giving up. 187 bool ExclusiveTryLockWithSpinning(Thread* self) TRY_ACQUIRE(true); 188 189 // Release exclusive access. 190 void ExclusiveUnlock(Thread* self) RELEASE(); Unlock(Thread * self)191 void Unlock(Thread* self) RELEASE() { ExclusiveUnlock(self); } 192 193 // Is the current thread the exclusive holder of the Mutex. 194 ALWAYS_INLINE bool IsExclusiveHeld(const Thread* self) const; 195 196 // Assert that the Mutex is exclusively held by the current thread. 197 ALWAYS_INLINE void AssertExclusiveHeld(const Thread* self) const ASSERT_CAPABILITY(this); 198 ALWAYS_INLINE void AssertHeld(const Thread* self) const ASSERT_CAPABILITY(this); 199 200 // Assert that the Mutex is not held by the current thread. AssertNotHeldExclusive(const Thread * self)201 void AssertNotHeldExclusive(const Thread* self) ASSERT_CAPABILITY(!*this) { 202 if (kDebugLocking && (gAborting == 0)) { 203 CHECK(!IsExclusiveHeld(self)) << *this; 204 } 205 } AssertNotHeld(const Thread * self)206 void AssertNotHeld(const Thread* self) ASSERT_CAPABILITY(!*this) { 207 AssertNotHeldExclusive(self); 208 } 209 210 // Id associated with exclusive owner. No memory ordering semantics if called from a thread 211 // other than the owner. GetTid() == GetExclusiveOwnerTid() is a reliable way to determine 212 // whether we hold the lock; any other information may be invalidated before we return. 213 pid_t GetExclusiveOwnerTid() const; 214 215 // Returns how many times this Mutex has been locked, it is typically better to use 216 // AssertHeld/NotHeld. For a simply held mutex this method returns 1. Should only be called 217 // while holding the mutex or threads are suspended. GetDepth()218 unsigned int GetDepth() const { 219 return recursion_count_; 220 } 221 222 void Dump(std::ostream& os) const override; 223 224 // For negative capabilities in clang annotations. 225 const Mutex& operator!() const { return *this; } 226 227 void WakeupToRespondToEmptyCheckpoint() override; 228 229 #if ART_USE_FUTEXES 230 // Acquire the mutex, possibly on behalf of another thread. Acquisition must be 231 // uncontended. New_owner must be current thread or suspended. 232 // Mutex must be at level kMonitorLock. 233 // Not implementable for the pthreads version, so we must avoid calling it there. 234 void ExclusiveLockUncontendedFor(Thread* new_owner); 235 236 // Undo the effect of the previous calling, setting the mutex back to unheld. 237 // Still assumes no concurrent access. 238 void ExclusiveUnlockUncontended(); 239 #endif // ART_USE_FUTEXES 240 241 private: 242 #if ART_USE_FUTEXES 243 // Low order bit: 0 is unheld, 1 is held. 244 // High order bits: Number of waiting contenders. 245 AtomicInteger state_and_contenders_; 246 247 static constexpr int32_t kHeldMask = 1; 248 249 static constexpr int32_t kContenderShift = 1; 250 251 static constexpr int32_t kContenderIncrement = 1 << kContenderShift; 252 increment_contenders()253 void increment_contenders() { 254 state_and_contenders_.fetch_add(kContenderIncrement); 255 } 256 decrement_contenders()257 void decrement_contenders() { 258 state_and_contenders_.fetch_sub(kContenderIncrement); 259 } 260 get_contenders()261 int32_t get_contenders() { 262 // Result is guaranteed to include any contention added by this thread; otherwise approximate. 263 // Treat contenders as unsigned because we're concerned about overflow; should never matter. 264 return static_cast<uint32_t>(state_and_contenders_.load(std::memory_order_relaxed)) 265 >> kContenderShift; 266 } 267 268 // Exclusive owner. 269 Atomic<pid_t> exclusive_owner_; 270 #else 271 pthread_mutex_t mutex_; 272 Atomic<pid_t> exclusive_owner_; // Guarded by mutex_. Asynchronous reads are OK. 273 #endif 274 275 unsigned int recursion_count_; 276 const bool recursive_; // Can the lock be recursively held? 277 278 friend class ConditionVariable; 279 DISALLOW_COPY_AND_ASSIGN(Mutex); 280 }; 281 282 // A ReaderWriterMutex is used to achieve mutual exclusion between threads, similar to a Mutex. 283 // Unlike a Mutex a ReaderWriterMutex can be used to gain exclusive (writer) or shared (reader) 284 // access to what it guards. A flaw in relation to a Mutex is that it cannot be used with a 285 // condition variable. A ReaderWriterMutex can be in one of three states: 286 // - Free - not owned by any thread, 287 // - Exclusive - owned by a single thread, 288 // - Shared(n) - shared amongst n threads. 289 // 290 // The effect of locking and unlocking operations on the state is: 291 // 292 // State | ExclusiveLock | ExclusiveUnlock | SharedLock | SharedUnlock 293 // ---------------------------------------------------------------------------- 294 // Free | Exclusive | error | SharedLock(1) | error 295 // Exclusive | Block | Free | Block | error 296 // Shared(n) | Block | error | SharedLock(n+1)* | Shared(n-1) or Free 297 // * for large values of n the SharedLock may block. 298 std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu); 299 class SHARED_LOCKABLE ReaderWriterMutex : public BaseMutex { 300 public: 301 explicit ReaderWriterMutex(const char* name, LockLevel level = kDefaultMutexLevel); 302 ~ReaderWriterMutex(); 303 IsReaderWriterMutex()304 bool IsReaderWriterMutex() const override { return true; } 305 306 // Block until ReaderWriterMutex is free then acquire exclusive access. 307 void ExclusiveLock(Thread* self) ACQUIRE(); WriterLock(Thread * self)308 void WriterLock(Thread* self) ACQUIRE() { ExclusiveLock(self); } 309 310 // Release exclusive access. 311 void ExclusiveUnlock(Thread* self) RELEASE(); WriterUnlock(Thread * self)312 void WriterUnlock(Thread* self) RELEASE() { ExclusiveUnlock(self); } 313 314 // Block until ReaderWriterMutex is free and acquire exclusive access. Returns true on success 315 // or false if timeout is reached. 316 #if HAVE_TIMED_RWLOCK 317 bool ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns) 318 EXCLUSIVE_TRYLOCK_FUNCTION(true); 319 #endif 320 321 // Block until ReaderWriterMutex is shared or free then acquire a share on the access. 322 void SharedLock(Thread* self) ACQUIRE_SHARED() ALWAYS_INLINE; ReaderLock(Thread * self)323 void ReaderLock(Thread* self) ACQUIRE_SHARED() { SharedLock(self); } 324 325 // Try to acquire share of ReaderWriterMutex. 326 bool SharedTryLock(Thread* self) SHARED_TRYLOCK_FUNCTION(true); 327 328 // Release a share of the access. 329 void SharedUnlock(Thread* self) RELEASE_SHARED() ALWAYS_INLINE; ReaderUnlock(Thread * self)330 void ReaderUnlock(Thread* self) RELEASE_SHARED() { SharedUnlock(self); } 331 332 // Is the current thread the exclusive holder of the ReaderWriterMutex. 333 ALWAYS_INLINE bool IsExclusiveHeld(const Thread* self) const; 334 335 // Assert the current thread has exclusive access to the ReaderWriterMutex. 336 ALWAYS_INLINE void AssertExclusiveHeld(const Thread* self) const ASSERT_CAPABILITY(this); 337 ALWAYS_INLINE void AssertWriterHeld(const Thread* self) const ASSERT_CAPABILITY(this); 338 339 // Assert the current thread doesn't have exclusive access to the ReaderWriterMutex. AssertNotExclusiveHeld(const Thread * self)340 void AssertNotExclusiveHeld(const Thread* self) ASSERT_CAPABILITY(!this) { 341 if (kDebugLocking && (gAborting == 0)) { 342 CHECK(!IsExclusiveHeld(self)) << *this; 343 } 344 } AssertNotWriterHeld(const Thread * self)345 void AssertNotWriterHeld(const Thread* self) ASSERT_CAPABILITY(!this) { 346 AssertNotExclusiveHeld(self); 347 } 348 349 // Is the current thread a shared holder of the ReaderWriterMutex. 350 bool IsSharedHeld(const Thread* self) const; 351 352 // Assert the current thread has shared access to the ReaderWriterMutex. AssertSharedHeld(const Thread * self)353 ALWAYS_INLINE void AssertSharedHeld(const Thread* self) ASSERT_SHARED_CAPABILITY(this) { 354 if (kDebugLocking && (gAborting == 0)) { 355 // TODO: we can only assert this well when self != null. 356 CHECK(IsSharedHeld(self) || self == nullptr) << *this; 357 } 358 } AssertReaderHeld(const Thread * self)359 ALWAYS_INLINE void AssertReaderHeld(const Thread* self) ASSERT_SHARED_CAPABILITY(this) { 360 AssertSharedHeld(self); 361 } 362 363 // Assert the current thread doesn't hold this ReaderWriterMutex either in shared or exclusive 364 // mode. AssertNotHeld(const Thread * self)365 ALWAYS_INLINE void AssertNotHeld(const Thread* self) ASSERT_CAPABILITY(!this) { 366 if (kDebugLocking && (gAborting == 0)) { 367 CHECK(!IsExclusiveHeld(self)) << *this; 368 CHECK(!IsSharedHeld(self)) << *this; 369 } 370 } 371 372 // Id associated with exclusive owner. No memory ordering semantics if called from a thread other 373 // than the owner. Returns 0 if the lock is not held. Returns either 0 or -1 if it is held by 374 // one or more readers. 375 pid_t GetExclusiveOwnerTid() const; 376 377 void Dump(std::ostream& os) const override; 378 379 // For negative capabilities in clang annotations. 380 const ReaderWriterMutex& operator!() const { return *this; } 381 382 void WakeupToRespondToEmptyCheckpoint() override; 383 384 private: 385 #if ART_USE_FUTEXES 386 // Out-of-inline path for handling contention for a SharedLock. 387 void HandleSharedLockContention(Thread* self, int32_t cur_state); 388 389 // -1 implies held exclusive, >= 0: shared held by state_ many owners. 390 AtomicInteger state_; 391 // Exclusive owner. Modification guarded by this mutex. 392 Atomic<pid_t> exclusive_owner_; 393 // Number of contenders waiting for either a reader share or exclusive access. We only maintain 394 // the sum, since we would otherwise need to read both in all unlock operations. 395 // We keep this separate from the state, since futexes are limited to 32 bits, and obvious 396 // approaches to combining with state_ risk overflow. 397 AtomicInteger num_contenders_; 398 #else 399 pthread_rwlock_t rwlock_; 400 Atomic<pid_t> exclusive_owner_; // Writes guarded by rwlock_. Asynchronous reads are OK. 401 #endif 402 DISALLOW_COPY_AND_ASSIGN(ReaderWriterMutex); 403 }; 404 405 // MutatorMutex is a special kind of ReaderWriterMutex created specifically for the 406 // Locks::mutator_lock_ mutex. The behaviour is identical to the ReaderWriterMutex except that 407 // thread state changes also play a part in lock ownership. The mutator_lock_ will not be truly 408 // held by any mutator threads. However, a thread in the kRunnable state is considered to have 409 // shared ownership of the mutator lock and therefore transitions in and out of the kRunnable 410 // state have associated implications on lock ownership. Extra methods to handle the state 411 // transitions have been added to the interface but are only accessible to the methods dealing 412 // with state transitions. The thread state and flags attributes are used to ensure thread state 413 // transitions are consistent with the permitted behaviour of the mutex. 414 // 415 // *) The most important consequence of this behaviour is that all threads must be in one of the 416 // suspended states before exclusive ownership of the mutator mutex is sought. 417 // 418 std::ostream& operator<<(std::ostream& os, const MutatorMutex& mu); 419 class SHARED_LOCKABLE MutatorMutex : public ReaderWriterMutex { 420 public: 421 explicit MutatorMutex(const char* name, LockLevel level = kDefaultMutexLevel) ReaderWriterMutex(name,level)422 : ReaderWriterMutex(name, level) {} ~MutatorMutex()423 ~MutatorMutex() {} 424 IsMutatorMutex()425 virtual bool IsMutatorMutex() const { return true; } 426 427 // For negative capabilities in clang annotations. 428 const MutatorMutex& operator!() const { return *this; } 429 430 private: 431 friend class Thread; 432 void TransitionFromRunnableToSuspended(Thread* self) UNLOCK_FUNCTION() ALWAYS_INLINE; 433 void TransitionFromSuspendedToRunnable(Thread* self) SHARED_LOCK_FUNCTION() ALWAYS_INLINE; 434 435 DISALLOW_COPY_AND_ASSIGN(MutatorMutex); 436 }; 437 438 // ConditionVariables allow threads to queue and sleep. Threads may then be resumed individually 439 // (Signal) or all at once (Broadcast). 440 class ConditionVariable { 441 public: 442 ConditionVariable(const char* name, Mutex& mutex); 443 ~ConditionVariable(); 444 445 // Requires the mutex to be held. 446 void Broadcast(Thread* self); 447 // Requires the mutex to be held. 448 void Signal(Thread* self); 449 // TODO: No thread safety analysis on Wait and TimedWait as they call mutex operations via their 450 // pointer copy, thereby defeating annotalysis. 451 void Wait(Thread* self) NO_THREAD_SAFETY_ANALYSIS; 452 bool TimedWait(Thread* self, int64_t ms, int32_t ns) NO_THREAD_SAFETY_ANALYSIS; 453 // Variant of Wait that should be used with caution. Doesn't validate that no mutexes are held 454 // when waiting. 455 // TODO: remove this. 456 void WaitHoldingLocks(Thread* self) NO_THREAD_SAFETY_ANALYSIS; 457 CheckSafeToWait(Thread * self)458 void CheckSafeToWait(Thread* self) NO_THREAD_SAFETY_ANALYSIS { 459 if (kDebugLocking) { 460 guard_.CheckSafeToWait(self); 461 } 462 } 463 464 private: 465 const char* const name_; 466 // The Mutex being used by waiters. It is an error to mix condition variables between different 467 // Mutexes. 468 Mutex& guard_; 469 #if ART_USE_FUTEXES 470 // A counter that is modified by signals and broadcasts. This ensures that when a waiter gives up 471 // their Mutex and another thread takes it and signals, the waiting thread observes that sequence_ 472 // changed and doesn't enter the wait. Modified while holding guard_, but is read by futex wait 473 // without guard_ held. 474 AtomicInteger sequence_; 475 // Number of threads that have come into to wait, not the length of the waiters on the futex as 476 // waiters may have been requeued onto guard_. Guarded by guard_. 477 int32_t num_waiters_; 478 479 void RequeueWaiters(int32_t count); 480 #else 481 pthread_cond_t cond_; 482 #endif 483 DISALLOW_COPY_AND_ASSIGN(ConditionVariable); 484 }; 485 486 // Scoped locker/unlocker for a regular Mutex that acquires mu upon construction and releases it 487 // upon destruction. 488 class SCOPED_CAPABILITY MutexLock { 489 public: MutexLock(Thread * self,Mutex & mu)490 MutexLock(Thread* self, Mutex& mu) ACQUIRE(mu) : self_(self), mu_(mu) { 491 mu_.ExclusiveLock(self_); 492 } 493 RELEASE()494 ~MutexLock() RELEASE() { 495 mu_.ExclusiveUnlock(self_); 496 } 497 498 private: 499 Thread* const self_; 500 Mutex& mu_; 501 DISALLOW_COPY_AND_ASSIGN(MutexLock); 502 }; 503 504 // Scoped locker/unlocker for a ReaderWriterMutex that acquires read access to mu upon 505 // construction and releases it upon destruction. 506 class SCOPED_CAPABILITY ReaderMutexLock { 507 public: 508 ALWAYS_INLINE ReaderMutexLock(Thread* self, ReaderWriterMutex& mu) ACQUIRE(mu); 509 510 ALWAYS_INLINE ~ReaderMutexLock() RELEASE(); 511 512 private: 513 Thread* const self_; 514 ReaderWriterMutex& mu_; 515 DISALLOW_COPY_AND_ASSIGN(ReaderMutexLock); 516 }; 517 518 // Scoped locker/unlocker for a ReaderWriterMutex that acquires write access to mu upon 519 // construction and releases it upon destruction. 520 class SCOPED_CAPABILITY WriterMutexLock { 521 public: WriterMutexLock(Thread * self,ReaderWriterMutex & mu)522 WriterMutexLock(Thread* self, ReaderWriterMutex& mu) EXCLUSIVE_LOCK_FUNCTION(mu) : 523 self_(self), mu_(mu) { 524 mu_.ExclusiveLock(self_); 525 } 526 UNLOCK_FUNCTION()527 ~WriterMutexLock() UNLOCK_FUNCTION() { 528 mu_.ExclusiveUnlock(self_); 529 } 530 531 private: 532 Thread* const self_; 533 ReaderWriterMutex& mu_; 534 DISALLOW_COPY_AND_ASSIGN(WriterMutexLock); 535 }; 536 537 } // namespace art 538 539 #endif // ART_RUNTIME_BASE_MUTEX_H_ 540