blob: 136e17af7215db1cf9baa78f6ebe79219aa6d823 [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
Brian Carlstromfc0e3212013-07-17 14:40:12 -070017#ifndef ART_RUNTIME_BASE_MUTEX_H_
18#define ART_RUNTIME_BASE_MUTEX_H_
Elliott Hughes8daa0922011-09-11 13:46:25 -070019
Hans Boehm81dc7ab2019-04-19 17:34:31 -070020#include <limits.h> // for INT_MAX
Elliott Hughes8daa0922011-09-11 13:46:25 -070021#include <pthread.h>
Brian Carlstromcd74c4b2012-01-23 13:21:00 -080022#include <stdint.h>
Hans Boehm0882af22017-08-31 15:21:57 -070023#include <unistd.h> // for pid_t
Elliott Hughesffb465f2012-03-01 18:46:05 -080024
25#include <iosfwd>
Elliott Hughes8daa0922011-09-11 13:46:25 -070026#include <string>
27
Andreas Gampe57943812017-12-06 21:39:13 -080028#include <android-base/logging.h>
29
Andreas Gampe39b378c2017-12-07 15:44:13 -080030#include "base/aborting.h"
David Sehrc431b9d2018-03-02 12:01:51 -080031#include "base/atomic.h"
Andreas Gampe5a0430d2019-01-04 14:33:57 -080032#include "runtime_globals.h"
Elliott Hughes76160052012-12-12 16:31:20 -080033#include "base/macros.h"
Andreas Gampe7cc45fd2018-11-21 16:03:08 -080034#include "locks.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070035
Daniel Colascioneb4dfca52018-04-15 11:15:14 -070036#if defined(__linux__)
Chris Dearmanc0141782013-11-14 17:29:21 -080037#define ART_USE_FUTEXES 1
Daniel Colascioneb4dfca52018-04-15 11:15:14 -070038#else
39#define ART_USE_FUTEXES 0
Ian Rogersab470162012-09-29 23:06:53 -070040#endif
Elliott Hughes8daa0922011-09-11 13:46:25 -070041
Ian Rogers66aee5c2012-08-15 17:17:47 -070042// 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
Elliott Hughes8daa0922011-09-11 13:46:25 -070049namespace art {
50
Mathieu Chartier90443472015-07-16 20:32:27 -070051class SHARED_LOCKABLE ReaderWriterMutex;
52class SHARED_LOCKABLE MutatorMutex;
Ian Rogers56edc432013-01-18 16:51:51 -080053class ScopedContentionRecorder;
Ian Rogers50b35e22012-10-04 10:09:15 -070054class Thread;
Andreas Gampe7cc45fd2018-11-21 16:03:08 -080055class LOCKABLE Mutex;
Ian Rogers719d1a32014-03-06 12:13:39 -080056
Andreas Gampe5db8b7b2018-05-08 16:10:59 -070057constexpr bool kDebugLocking = kIsDebugBuild;
Ian Rogers25fd14b2012-09-05 10:56:38 -070058
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070059// Record Log contention information, dumpable via SIGQUIT.
Hans Boehmd56f7d12019-11-19 06:03:11 +000060#ifdef ART_USE_FUTEXES
Jeff Hao08f2e7b2013-09-09 16:44:02 -070061// To enable lock contention logging, set this to true.
Andreas Gampe5db8b7b2018-05-08 16:10:59 -070062constexpr bool kLogLockContentions = false;
Hans Boehm81dc7ab2019-04-19 17:34:31 -070063// FUTEX_WAKE first argument:
64constexpr int kWakeOne = 1;
65constexpr int kWakeAll = INT_MAX;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070066#else
67// Keep this false as lock contention logging is supported only with
68// futex.
Andreas Gampe5db8b7b2018-05-08 16:10:59 -070069constexpr bool kLogLockContentions = false;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070070#endif
Andreas Gampe5db8b7b2018-05-08 16:10:59 -070071constexpr size_t kContentionLogSize = 4;
72constexpr size_t kContentionLogDataSize = kLogLockContentions ? 1 : 0;
73constexpr size_t kAllMutexDataSize = kLogLockContentions ? 1 : 0;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070074
Ian Rogers00f7d0e2012-07-19 15:28:27 -070075// Base class for all Mutex implementations
76class BaseMutex {
77 public:
Ian Rogersbab74962013-04-19 10:04:10 -070078 const char* GetName() const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070079 return name_;
80 }
81
82 virtual bool IsMutex() const { return false; }
83 virtual bool IsReaderWriterMutex() const { return false; }
Yu Lieac44242015-06-29 10:50:03 +080084 virtual bool IsMutatorMutex() const { return false; }
Ian Rogers00f7d0e2012-07-19 15:28:27 -070085
Ian Rogers56edc432013-01-18 16:51:51 -080086 virtual void Dump(std::ostream& os) const = 0;
87
88 static void DumpAll(std::ostream& os);
89
Hiroshi Yamauchia2224042017-02-08 16:35:45 -080090 bool ShouldRespondToEmptyCheckpointRequest() const {
91 return should_respond_to_empty_checkpoint_request_;
92 }
93
94 void SetShouldRespondToEmptyCheckpointRequest(bool value) {
95 should_respond_to_empty_checkpoint_request_ = value;
96 }
97
98 virtual void WakeupToRespondToEmptyCheckpoint() = 0;
99
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700100 protected:
101 friend class ConditionVariable;
102
Ian Rogers81d425b2012-09-27 16:03:43 -0700103 BaseMutex(const char* name, LockLevel level);
Ian Rogers56edc432013-01-18 16:51:51 -0800104 virtual ~BaseMutex();
Ian Rogers81d425b2012-09-27 16:03:43 -0700105 void RegisterAsLocked(Thread* self);
106 void RegisterAsUnlocked(Thread* self);
107 void CheckSafeToWait(Thread* self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700108
Ian Rogers56edc432013-01-18 16:51:51 -0800109 friend class ScopedContentionRecorder;
110
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700111 void RecordContention(uint64_t blocked_tid, uint64_t owner_tid, uint64_t nano_time_blocked);
Ian Rogers56edc432013-01-18 16:51:51 -0800112 void DumpContention(std::ostream& os) const;
113
Ian Rogersbab74962013-04-19 10:04:10 -0700114 const char* const name_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700115
Ian Rogers56edc432013-01-18 16:51:51 -0800116 // A log entry that records contention but makes no guarantee that either tid will be held live.
117 struct ContentionLogEntry {
118 ContentionLogEntry() : blocked_tid(0), owner_tid(0) {}
119 uint64_t blocked_tid;
120 uint64_t owner_tid;
121 AtomicInteger count;
122 };
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700123 struct ContentionLogData {
124 ContentionLogEntry contention_log[kContentionLogSize];
125 // The next entry in the contention log to be updated. Value ranges from 0 to
126 // kContentionLogSize - 1.
127 AtomicInteger cur_content_log_entry;
128 // Number of times the Mutex has been contended.
129 AtomicInteger contention_count;
130 // Sum of time waited by all contenders in ns.
Ian Rogers37f3c962014-07-17 11:25:30 -0700131 Atomic<uint64_t> wait_time;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700132 void AddToWaitTime(uint64_t value);
133 ContentionLogData() : wait_time(0) {}
134 };
Ian Rogers3e5cf302014-05-20 16:40:37 -0700135 ContentionLogData contention_log_data_[kContentionLogDataSize];
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700136
Andreas Gampe5db8b7b2018-05-08 16:10:59 -0700137 const LockLevel level_; // Support for lock hierarchy.
138 bool should_respond_to_empty_checkpoint_request_;
139
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700140 public:
141 bool HasEverContended() const {
142 if (kLogLockContentions) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000143 return contention_log_data_->contention_count.load(std::memory_order_seq_cst) > 0;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700144 }
145 return false;
146 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700147};
148
149// A Mutex is used to achieve mutual exclusion between threads. A Mutex can be used to gain
150// exclusive access to what it guards. A Mutex can be in one of two states:
151// - Free - not owned by any thread,
152// - Exclusive - owned by a single thread.
153//
154// The effect of locking and unlocking operations on the state is:
155// State | ExclusiveLock | ExclusiveUnlock
156// -------------------------------------------
157// Free | Exclusive | error
158// Exclusive | Block* | Free
159// * Mutex is not reentrant and so an attempt to ExclusiveLock on the same thread will result in
160// an error. Being non-reentrant simplifies Waiting on ConditionVariables.
Ian Rogers01ae5802012-09-28 16:14:01 -0700161std::ostream& operator<<(std::ostream& os, const Mutex& mu);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700162class LOCKABLE Mutex : public BaseMutex {
163 public:
Ian Rogers81d425b2012-09-27 16:03:43 -0700164 explicit Mutex(const char* name, LockLevel level = kDefaultMutexLevel, bool recursive = false);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700165 ~Mutex();
166
Yi Kong39402542019-03-24 02:47:16 -0700167 bool IsMutex() const override { return true; }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700168
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700169 // Block until mutex is free then acquire exclusive access.
Mathieu Chartier90443472015-07-16 20:32:27 -0700170 void ExclusiveLock(Thread* self) ACQUIRE();
171 void Lock(Thread* self) ACQUIRE() { ExclusiveLock(self); }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700172
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700173 // Returns true if acquires exclusive access, false otherwise.
Mathieu Chartier90443472015-07-16 20:32:27 -0700174 bool ExclusiveTryLock(Thread* self) TRY_ACQUIRE(true);
175 bool TryLock(Thread* self) TRY_ACQUIRE(true) { return ExclusiveTryLock(self); }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700176
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700177 // Release exclusive access.
Mathieu Chartier90443472015-07-16 20:32:27 -0700178 void ExclusiveUnlock(Thread* self) RELEASE();
179 void Unlock(Thread* self) RELEASE() { ExclusiveUnlock(self); }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700180
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700181 // Is the current thread the exclusive holder of the Mutex.
Andreas Gampeb486a982017-06-01 13:45:54 -0700182 ALWAYS_INLINE bool IsExclusiveHeld(const Thread* self) const;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700183
184 // Assert that the Mutex is exclusively held by the current thread.
Andreas Gampeb486a982017-06-01 13:45:54 -0700185 ALWAYS_INLINE void AssertExclusiveHeld(const Thread* self) const ASSERT_CAPABILITY(this);
186 ALWAYS_INLINE void AssertHeld(const Thread* self) const ASSERT_CAPABILITY(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700187
188 // Assert that the Mutex is not held by the current thread.
Mathieu Chartier90443472015-07-16 20:32:27 -0700189 void AssertNotHeldExclusive(const Thread* self) ASSERT_CAPABILITY(!*this) {
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000190 if (kDebugLocking && (gAborting == 0)) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700191 CHECK(!IsExclusiveHeld(self)) << *this;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700192 }
193 }
Mathieu Chartier90443472015-07-16 20:32:27 -0700194 void AssertNotHeld(const Thread* self) ASSERT_CAPABILITY(!*this) {
195 AssertNotHeldExclusive(self);
196 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700197
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700198 // Id associated with exclusive owner. No memory ordering semantics if called from a thread
199 // other than the owner. GetTid() == GetExclusiveOwnerTid() is a reliable way to determine
200 // whether we hold the lock; any other information may be invalidated before we return.
Hans Boehm0882af22017-08-31 15:21:57 -0700201 pid_t GetExclusiveOwnerTid() const;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700202
Hans Boehmd56f7d12019-11-19 06:03:11 +0000203 // Returns how many times this Mutex has been locked, it is better to use AssertHeld/NotHeld.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700204 unsigned int GetDepth() const {
205 return recursion_count_;
206 }
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700207
Yi Kong39402542019-03-24 02:47:16 -0700208 void Dump(std::ostream& os) const override;
Ian Rogers01ae5802012-09-28 16:14:01 -0700209
Mathieu Chartier90443472015-07-16 20:32:27 -0700210 // For negative capabilities in clang annotations.
211 const Mutex& operator!() const { return *this; }
212
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100213 void WakeupToRespondToEmptyCheckpoint() override;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800214
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700215 private:
Ian Rogersc604d732012-10-14 16:09:54 -0700216#if ART_USE_FUTEXES
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700217 // Low order bit: 0 is unheld, 1 is held.
218 // High order bits: Number of waiting contenders.
219 AtomicInteger state_and_contenders_;
220
221 static constexpr int32_t kHeldMask = 1;
222
223 static constexpr int32_t kContenderShift = 1;
224
225 static constexpr int32_t kContenderIncrement = 1 << kContenderShift;
226
227 void increment_contenders() {
228 state_and_contenders_.fetch_add(kContenderIncrement);
229 }
230
231 void decrement_contenders() {
232 state_and_contenders_.fetch_sub(kContenderIncrement);
233 }
234
235 int32_t get_contenders() {
236 // Result is guaranteed to include any contention added by this thread; otherwise approximate.
237 // Treat contenders as unsigned because we're paranoid about overflow; should never matter.
238 return static_cast<uint32_t>(state_and_contenders_.load(std::memory_order_relaxed))
239 >> kContenderShift;
240 }
241
Ian Rogersc604d732012-10-14 16:09:54 -0700242 // Exclusive owner.
Hans Boehm0882af22017-08-31 15:21:57 -0700243 Atomic<pid_t> exclusive_owner_;
Ian Rogersc604d732012-10-14 16:09:54 -0700244#else
Elliott Hughes8daa0922011-09-11 13:46:25 -0700245 pthread_mutex_t mutex_;
Hans Boehm0882af22017-08-31 15:21:57 -0700246 Atomic<pid_t> exclusive_owner_; // Guarded by mutex_. Asynchronous reads are OK.
Ian Rogersc604d732012-10-14 16:09:54 -0700247#endif
Andreas Gampe5db8b7b2018-05-08 16:10:59 -0700248
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700249 unsigned int recursion_count_;
Andreas Gampe5db8b7b2018-05-08 16:10:59 -0700250 const bool recursive_; // Can the lock be recursively held?
251
Elliott Hughesf1498432012-03-28 19:34:27 -0700252 friend class ConditionVariable;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700253 DISALLOW_COPY_AND_ASSIGN(Mutex);
254};
255
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700256// A ReaderWriterMutex is used to achieve mutual exclusion between threads, similar to a Mutex.
257// Unlike a Mutex a ReaderWriterMutex can be used to gain exclusive (writer) or shared (reader)
258// access to what it guards. A flaw in relation to a Mutex is that it cannot be used with a
259// condition variable. A ReaderWriterMutex can be in one of three states:
260// - Free - not owned by any thread,
261// - Exclusive - owned by a single thread,
262// - Shared(n) - shared amongst n threads.
263//
264// The effect of locking and unlocking operations on the state is:
265//
266// State | ExclusiveLock | ExclusiveUnlock | SharedLock | SharedUnlock
267// ----------------------------------------------------------------------------
268// Free | Exclusive | error | SharedLock(1) | error
269// Exclusive | Block | Free | Block | error
270// Shared(n) | Block | error | SharedLock(n+1)* | Shared(n-1) or Free
271// * for large values of n the SharedLock may block.
Ian Rogers01ae5802012-09-28 16:14:01 -0700272std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu);
Mathieu Chartier90443472015-07-16 20:32:27 -0700273class SHARED_LOCKABLE ReaderWriterMutex : public BaseMutex {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700274 public:
Ian Rogers81d425b2012-09-27 16:03:43 -0700275 explicit ReaderWriterMutex(const char* name, LockLevel level = kDefaultMutexLevel);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700276 ~ReaderWriterMutex();
277
Yi Kong39402542019-03-24 02:47:16 -0700278 bool IsReaderWriterMutex() const override { return true; }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700279
280 // Block until ReaderWriterMutex is free then acquire exclusive access.
Mathieu Chartier90443472015-07-16 20:32:27 -0700281 void ExclusiveLock(Thread* self) ACQUIRE();
282 void WriterLock(Thread* self) ACQUIRE() { ExclusiveLock(self); }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700283
284 // Release exclusive access.
Mathieu Chartier90443472015-07-16 20:32:27 -0700285 void ExclusiveUnlock(Thread* self) RELEASE();
286 void WriterUnlock(Thread* self) RELEASE() { ExclusiveUnlock(self); }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700287
288 // Block until ReaderWriterMutex is free and acquire exclusive access. Returns true on success
289 // or false if timeout is reached.
Ian Rogers66aee5c2012-08-15 17:17:47 -0700290#if HAVE_TIMED_RWLOCK
Ian Rogersc604d732012-10-14 16:09:54 -0700291 bool ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns)
Ian Rogers81d425b2012-09-27 16:03:43 -0700292 EXCLUSIVE_TRYLOCK_FUNCTION(true);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700293#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700294
295 // Block until ReaderWriterMutex is shared or free then acquire a share on the access.
Mathieu Chartier90443472015-07-16 20:32:27 -0700296 void SharedLock(Thread* self) ACQUIRE_SHARED() ALWAYS_INLINE;
297 void ReaderLock(Thread* self) ACQUIRE_SHARED() { SharedLock(self); }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700298
299 // Try to acquire share of ReaderWriterMutex.
Mathieu Chartier90443472015-07-16 20:32:27 -0700300 bool SharedTryLock(Thread* self) SHARED_TRYLOCK_FUNCTION(true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700301
302 // Release a share of the access.
Mathieu Chartier90443472015-07-16 20:32:27 -0700303 void SharedUnlock(Thread* self) RELEASE_SHARED() ALWAYS_INLINE;
304 void ReaderUnlock(Thread* self) RELEASE_SHARED() { SharedUnlock(self); }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700305
306 // Is the current thread the exclusive holder of the ReaderWriterMutex.
Andreas Gampeb486a982017-06-01 13:45:54 -0700307 ALWAYS_INLINE bool IsExclusiveHeld(const Thread* self) const;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700308
309 // Assert the current thread has exclusive access to the ReaderWriterMutex.
Andreas Gampeb486a982017-06-01 13:45:54 -0700310 ALWAYS_INLINE void AssertExclusiveHeld(const Thread* self) const ASSERT_CAPABILITY(this);
311 ALWAYS_INLINE void AssertWriterHeld(const Thread* self) const ASSERT_CAPABILITY(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700312
313 // Assert the current thread doesn't have exclusive access to the ReaderWriterMutex.
Mathieu Chartier90ef3db2015-08-04 15:19:41 -0700314 void AssertNotExclusiveHeld(const Thread* self) ASSERT_CAPABILITY(!this) {
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000315 if (kDebugLocking && (gAborting == 0)) {
Ian Rogerse3359f72013-06-11 15:14:11 -0700316 CHECK(!IsExclusiveHeld(self)) << *this;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700317 }
318 }
Mathieu Chartier90ef3db2015-08-04 15:19:41 -0700319 void AssertNotWriterHeld(const Thread* self) ASSERT_CAPABILITY(!this) {
320 AssertNotExclusiveHeld(self);
321 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700322
323 // Is the current thread a shared holder of the ReaderWriterMutex.
Ian Rogers81d425b2012-09-27 16:03:43 -0700324 bool IsSharedHeld(const Thread* self) const;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700325
326 // Assert the current thread has shared access to the ReaderWriterMutex.
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700327 ALWAYS_INLINE void AssertSharedHeld(const Thread* self) ASSERT_SHARED_CAPABILITY(this) {
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000328 if (kDebugLocking && (gAborting == 0)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700329 // TODO: we can only assert this well when self != null.
330 CHECK(IsSharedHeld(self) || self == nullptr) << *this;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700331 }
332 }
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700333 ALWAYS_INLINE void AssertReaderHeld(const Thread* self) ASSERT_SHARED_CAPABILITY(this) {
Mathieu Chartier90ef3db2015-08-04 15:19:41 -0700334 AssertSharedHeld(self);
335 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700336
337 // Assert the current thread doesn't hold this ReaderWriterMutex either in shared or exclusive
338 // mode.
Ziang Wan92db59b2019-07-22 21:19:24 +0000339 ALWAYS_INLINE void AssertNotHeld(const Thread* self) ASSERT_CAPABILITY(!this) {
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000340 if (kDebugLocking && (gAborting == 0)) {
Ziang Wan92db59b2019-07-22 21:19:24 +0000341 CHECK(!IsExclusiveHeld(self)) << *this;
Ian Rogers01ae5802012-09-28 16:14:01 -0700342 CHECK(!IsSharedHeld(self)) << *this;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700343 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700344 }
345
Ian Rogersc7190692014-07-08 23:50:26 -0700346 // Id associated with exclusive owner. No memory ordering semantics if called from a thread other
Hans Boehm0882af22017-08-31 15:21:57 -0700347 // than the owner. Returns 0 if the lock is not held. Returns either 0 or -1 if it is held by
348 // one or more readers.
349 pid_t GetExclusiveOwnerTid() const;
Elliott Hughes8daa0922011-09-11 13:46:25 -0700350
Yi Kong39402542019-03-24 02:47:16 -0700351 void Dump(std::ostream& os) const override;
Ian Rogers01ae5802012-09-28 16:14:01 -0700352
Mathieu Chartier90443472015-07-16 20:32:27 -0700353 // For negative capabilities in clang annotations.
354 const ReaderWriterMutex& operator!() const { return *this; }
355
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100356 void WakeupToRespondToEmptyCheckpoint() override;
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800357
Ian Rogers81d425b2012-09-27 16:03:43 -0700358 private:
Ian Rogers51d212e2014-10-23 17:48:20 -0700359#if ART_USE_FUTEXES
Ian Rogerscf7f1912014-10-22 22:06:39 -0700360 // Out-of-inline path for handling contention for a SharedLock.
361 void HandleSharedLockContention(Thread* self, int32_t cur_state);
362
Hans Boehm467b6922019-04-22 16:15:53 -0700363 // -1 implies held exclusive, >= 0: shared held by state_ many owners.
Ian Rogersc7190692014-07-08 23:50:26 -0700364 AtomicInteger state_;
365 // Exclusive owner. Modification guarded by this mutex.
Hans Boehm0882af22017-08-31 15:21:57 -0700366 Atomic<pid_t> exclusive_owner_;
Hans Boehm467b6922019-04-22 16:15:53 -0700367 // Number of contenders waiting for either a reader share or exclusive access. We only maintain
368 // the sum, since we would otherwise need to read both in all unlock operations.
369 // We keep this separate from the state, since futexes are limited to 32 bits, and obvious
370 // approaches to combining with state_ risk overflow.
371 AtomicInteger num_contenders_;
Ian Rogers81d425b2012-09-27 16:03:43 -0700372#else
373 pthread_rwlock_t rwlock_;
Hans Boehm0882af22017-08-31 15:21:57 -0700374 Atomic<pid_t> exclusive_owner_; // Writes guarded by rwlock_. Asynchronous reads are OK.
Ian Rogers81d425b2012-09-27 16:03:43 -0700375#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700376 DISALLOW_COPY_AND_ASSIGN(ReaderWriterMutex);
377};
378
Yu Lieac44242015-06-29 10:50:03 +0800379// MutatorMutex is a special kind of ReaderWriterMutex created specifically for the
380// Locks::mutator_lock_ mutex. The behaviour is identical to the ReaderWriterMutex except that
381// thread state changes also play a part in lock ownership. The mutator_lock_ will not be truly
382// held by any mutator threads. However, a thread in the kRunnable state is considered to have
383// shared ownership of the mutator lock and therefore transitions in and out of the kRunnable
384// state have associated implications on lock ownership. Extra methods to handle the state
385// transitions have been added to the interface but are only accessible to the methods dealing
386// with state transitions. The thread state and flags attributes are used to ensure thread state
387// transitions are consistent with the permitted behaviour of the mutex.
388//
389// *) The most important consequence of this behaviour is that all threads must be in one of the
390// suspended states before exclusive ownership of the mutator mutex is sought.
391//
392std::ostream& operator<<(std::ostream& os, const MutatorMutex& mu);
Mathieu Chartier90443472015-07-16 20:32:27 -0700393class SHARED_LOCKABLE MutatorMutex : public ReaderWriterMutex {
Yu Lieac44242015-06-29 10:50:03 +0800394 public:
395 explicit MutatorMutex(const char* name, LockLevel level = kDefaultMutexLevel)
396 : ReaderWriterMutex(name, level) {}
397 ~MutatorMutex() {}
398
399 virtual bool IsMutatorMutex() const { return true; }
400
Mathieu Chartier90443472015-07-16 20:32:27 -0700401 // For negative capabilities in clang annotations.
402 const MutatorMutex& operator!() const { return *this; }
403
Yu Lieac44242015-06-29 10:50:03 +0800404 private:
405 friend class Thread;
406 void TransitionFromRunnableToSuspended(Thread* self) UNLOCK_FUNCTION() ALWAYS_INLINE;
407 void TransitionFromSuspendedToRunnable(Thread* self) SHARED_LOCK_FUNCTION() ALWAYS_INLINE;
408
409 DISALLOW_COPY_AND_ASSIGN(MutatorMutex);
410};
411
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700412// ConditionVariables allow threads to queue and sleep. Threads may then be resumed individually
413// (Signal) or all at once (Broadcast).
Elliott Hughes5f791332011-09-15 17:45:30 -0700414class ConditionVariable {
415 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100416 ConditionVariable(const char* name, Mutex& mutex);
Elliott Hughes5f791332011-09-15 17:45:30 -0700417 ~ConditionVariable();
418
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700419 // Requires the mutex to be held.
Ian Rogersc604d732012-10-14 16:09:54 -0700420 void Broadcast(Thread* self);
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700421 // Requires the mutex to be held.
Ian Rogersc604d732012-10-14 16:09:54 -0700422 void Signal(Thread* self);
423 // TODO: No thread safety analysis on Wait and TimedWait as they call mutex operations via their
424 // pointer copy, thereby defeating annotalysis.
425 void Wait(Thread* self) NO_THREAD_SAFETY_ANALYSIS;
Ian Rogers7b078e82014-09-10 14:44:24 -0700426 bool TimedWait(Thread* self, int64_t ms, int32_t ns) NO_THREAD_SAFETY_ANALYSIS;
Ian Rogers1d54e732013-05-02 21:10:01 -0700427 // Variant of Wait that should be used with caution. Doesn't validate that no mutexes are held
428 // when waiting.
429 // TODO: remove this.
430 void WaitHoldingLocks(Thread* self) NO_THREAD_SAFETY_ANALYSIS;
Elliott Hughes5f791332011-09-15 17:45:30 -0700431
Alex Light66834462019-04-08 16:28:29 +0000432 void CheckSafeToWait(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
433 if (kDebugLocking) {
434 guard_.CheckSafeToWait(self);
435 }
436 }
437
Elliott Hughes5f791332011-09-15 17:45:30 -0700438 private:
Ian Rogers23055dc2013-04-18 16:29:16 -0700439 const char* const name_;
Ian Rogersc604d732012-10-14 16:09:54 -0700440 // The Mutex being used by waiters. It is an error to mix condition variables between different
441 // Mutexes.
442 Mutex& guard_;
443#if ART_USE_FUTEXES
444 // A counter that is modified by signals and broadcasts. This ensures that when a waiter gives up
Ian Rogersd45f2012012-11-28 11:46:23 -0800445 // their Mutex and another thread takes it and signals, the waiting thread observes that sequence_
446 // changed and doesn't enter the wait. Modified while holding guard_, but is read by futex wait
447 // without guard_ held.
Ian Rogersb122a4b2013-11-19 18:00:50 -0800448 AtomicInteger sequence_;
Ian Rogersc604d732012-10-14 16:09:54 -0700449 // Number of threads that have come into to wait, not the length of the waiters on the futex as
Ian Rogers5bd97c42012-11-27 02:38:26 -0800450 // waiters may have been requeued onto guard_. Guarded by guard_.
Hans Boehm81dc7ab2019-04-19 17:34:31 -0700451 int32_t num_waiters_;
Charles Mungerbcd16ee2018-10-22 13:03:23 -0700452
453 void RequeueWaiters(int32_t count);
Ian Rogersc604d732012-10-14 16:09:54 -0700454#else
455 pthread_cond_t cond_;
456#endif
Elliott Hughes5f791332011-09-15 17:45:30 -0700457 DISALLOW_COPY_AND_ASSIGN(ConditionVariable);
458};
459
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700460// Scoped locker/unlocker for a regular Mutex that acquires mu upon construction and releases it
461// upon destruction.
Mathieu Chartier90443472015-07-16 20:32:27 -0700462class SCOPED_CAPABILITY MutexLock {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700463 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100464 MutexLock(Thread* self, Mutex& mu) ACQUIRE(mu) : self_(self), mu_(mu) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700465 mu_.ExclusiveLock(self_);
466 }
467
Mathieu Chartier4e2cb092015-07-22 16:17:51 -0700468 ~MutexLock() RELEASE() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700469 mu_.ExclusiveUnlock(self_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700470 }
471
472 private:
Ian Rogers81d425b2012-09-27 16:03:43 -0700473 Thread* const self_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700474 Mutex& mu_;
475 DISALLOW_COPY_AND_ASSIGN(MutexLock);
476};
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477
478// Scoped locker/unlocker for a ReaderWriterMutex that acquires read access to mu upon
479// construction and releases it upon destruction.
Mathieu Chartier90443472015-07-16 20:32:27 -0700480class SCOPED_CAPABILITY ReaderMutexLock {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481 public:
Andreas Gampeb486a982017-06-01 13:45:54 -0700482 ALWAYS_INLINE ReaderMutexLock(Thread* self, ReaderWriterMutex& mu) ACQUIRE(mu);
Ian Rogers81d425b2012-09-27 16:03:43 -0700483
Andreas Gampeb486a982017-06-01 13:45:54 -0700484 ALWAYS_INLINE ~ReaderMutexLock() RELEASE();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700485
486 private:
Ian Rogers81d425b2012-09-27 16:03:43 -0700487 Thread* const self_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700488 ReaderWriterMutex& mu_;
489 DISALLOW_COPY_AND_ASSIGN(ReaderMutexLock);
490};
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700491
492// Scoped locker/unlocker for a ReaderWriterMutex that acquires write access to mu upon
493// construction and releases it upon destruction.
Mathieu Chartier90443472015-07-16 20:32:27 -0700494class SCOPED_CAPABILITY WriterMutexLock {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700495 public:
Roland Levillain3887c462015-08-12 18:15:42 +0100496 WriterMutexLock(Thread* self, ReaderWriterMutex& mu) EXCLUSIVE_LOCK_FUNCTION(mu) :
Ian Rogers81d425b2012-09-27 16:03:43 -0700497 self_(self), mu_(mu) {
498 mu_.ExclusiveLock(self_);
499 }
500
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700501 ~WriterMutexLock() UNLOCK_FUNCTION() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700502 mu_.ExclusiveUnlock(self_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700503 }
504
505 private:
Ian Rogers50b35e22012-10-04 10:09:15 -0700506 Thread* const self_;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700507 ReaderWriterMutex& mu_;
508 DISALLOW_COPY_AND_ASSIGN(WriterMutexLock);
509};
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700510
Elliott Hughes8daa0922011-09-11 13:46:25 -0700511} // namespace art
512
Brian Carlstromfc0e3212013-07-17 14:40:12 -0700513#endif // ART_RUNTIME_BASE_MUTEX_H_