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_INL_H_
18 #define ART_RUNTIME_BASE_MUTEX_INL_H_
19
20 #include <inttypes.h>
21
22 #include "mutex.h"
23
24 #include "base/utils.h"
25 #include "base/value_object.h"
26 #include "thread.h"
27
28 #if ART_USE_FUTEXES
29 #include <linux/futex.h>
30 #include <sys/syscall.h>
31 #endif // ART_USE_FUTEXES
32
33 #define CHECK_MUTEX_CALL(call, args) CHECK_PTHREAD_CALL(call, args, name_)
34
35 namespace art HIDDEN {
36
37 #if ART_USE_FUTEXES
futex(volatile int * uaddr,int op,int val,const struct timespec * timeout,volatile int * uaddr2,int val3)38 static inline int futex(volatile int *uaddr, int op, int val, const struct timespec *timeout,
39 volatile int *uaddr2, int val3) {
40 return syscall(SYS_futex, uaddr, op, val, timeout, uaddr2, val3);
41 }
42 #endif // ART_USE_FUTEXES
43
44 // The following isn't strictly necessary, but we want updates on Atomic<pid_t> to be lock-free.
45 // TODO: Use std::atomic::is_always_lock_free after switching to C++17 atomics.
46 static_assert(sizeof(pid_t) <= sizeof(int32_t), "pid_t should fit in 32 bits");
47
SafeGetTid(const Thread * self)48 static inline pid_t SafeGetTid(const Thread* self) {
49 if (self != nullptr) {
50 return self->GetTid();
51 } else {
52 return GetTid();
53 }
54 }
55
CheckUnattachedThread(LockLevel level)56 static inline void CheckUnattachedThread(LockLevel level) NO_THREAD_SAFETY_ANALYSIS {
57 // The check below enumerates the cases where we expect not to be able to check the validity of
58 // locks on a thread. Lock checking is disabled to avoid deadlock when checking shutdown lock.
59 // TODO: tighten this check.
60 CHECK(!Locks::IsSafeToCallAbortRacy() ||
61 // Used during thread creation to avoid races with runtime shutdown. Thread::Current not
62 // yet established.
63 level == kRuntimeShutdownLock ||
64 // Thread Ids are allocated/released before threads are established.
65 level == kAllocatedThreadIdsLock ||
66 // Thread LDT's are initialized without Thread::Current established.
67 level == kModifyLdtLock ||
68 // Threads are unregistered while holding the thread list lock, during this process they
69 // no longer exist and so we expect an unlock with no self.
70 level == kThreadListLock ||
71 // Ignore logging which may or may not have set up thread data structures.
72 level == kLoggingLock ||
73 // When transitioning from suspended to runnable, a daemon thread might be in
74 // a situation where the runtime is shutting down. To not crash our debug locking
75 // mechanism we just pass null Thread* to the MutexLock during that transition
76 // (see Thread::TransitionFromSuspendedToRunnable).
77 level == kThreadSuspendCountLock ||
78 // Avoid recursive death.
79 level == kAbortLock ||
80 // Locks at the absolute top of the stack can be locked at any time.
81 level == kTopLockLevel ||
82 // The unexpected signal handler may be catching signals from any thread.
83 level == kUnexpectedSignalLock)
84 << level;
85 }
86
RegisterAsLocked(Thread * self,bool check)87 inline void BaseMutex::RegisterAsLocked(Thread* self, bool check) {
88 if (UNLIKELY(self == nullptr)) {
89 if (check) {
90 CheckUnattachedThread(level_);
91 }
92 } else {
93 RegisterAsLockedImpl(self, level_, check);
94 }
95 }
96
RegisterAsLockedImpl(Thread * self,LockLevel level,bool check)97 inline void BaseMutex::RegisterAsLockedImpl(Thread* self, LockLevel level, bool check) {
98 DCHECK(self != nullptr);
99 DCHECK_EQ(level_, level);
100 // It would be nice to avoid this condition checking in the non-debug case,
101 // but that would make the various methods that check if a mutex is held not
102 // work properly for thread wait locks. Since the vast majority of lock
103 // acquisitions are not thread wait locks, this check should not be too
104 // expensive.
105 if (UNLIKELY(level == kThreadWaitLock) && self->GetHeldMutex(kThreadWaitLock) != nullptr) {
106 level = kThreadWaitWakeLock;
107 }
108 if (check) {
109 // Check if a bad Mutex of this level or lower is held.
110 bool bad_mutexes_held = false;
111 // Specifically allow a kTopLockLevel lock to be gained when the current thread holds the
112 // mutator_lock_ exclusive. This is because we suspending when holding locks at this level is
113 // not allowed and if we hold the mutator_lock_ exclusive we must unsuspend stuff eventually
114 // so there are no deadlocks.
115 if (level == kTopLockLevel &&
116 Locks::mutator_lock_->IsSharedHeld(self) &&
117 !Locks::mutator_lock_->IsExclusiveHeld(self)) {
118 LOG(ERROR) << "Lock level violation: holding \"" << Locks::mutator_lock_->name_ << "\" "
119 << "(level " << kMutatorLock << " - " << static_cast<int>(kMutatorLock)
120 << ") non-exclusive while locking \"" << name_ << "\" "
121 << "(level " << level << " - " << static_cast<int>(level) << ") a top level"
122 << "mutex. This is not allowed.";
123 bad_mutexes_held = true;
124 } else if (this == Locks::mutator_lock_ && self->GetHeldMutex(kTopLockLevel) != nullptr) {
125 LOG(ERROR) << "Lock level violation. Locking mutator_lock_ while already having a "
126 << "kTopLevelLock (" << self->GetHeldMutex(kTopLockLevel)->name_ << "held is "
127 << "not allowed.";
128 bad_mutexes_held = true;
129 }
130 for (int i = level; i >= 0; --i) {
131 LockLevel lock_level_i = static_cast<LockLevel>(i);
132 BaseMutex* held_mutex = self->GetHeldMutex(lock_level_i);
133 if (level == kTopLockLevel &&
134 lock_level_i == kMutatorLock &&
135 Locks::mutator_lock_->IsExclusiveHeld(self)) {
136 // This is checked above.
137 continue;
138 } else if (UNLIKELY(held_mutex != nullptr) && lock_level_i != kAbortLock) {
139 LOG(ERROR) << "Lock level violation: holding \"" << held_mutex->name_ << "\" "
140 << "(level " << lock_level_i << " - " << i
141 << ") while locking \"" << name_ << "\" "
142 << "(level " << level << " - " << static_cast<int>(level) << ")";
143 if (lock_level_i > kAbortLock) {
144 // Only abort in the check below if this is more than abort level lock.
145 bad_mutexes_held = true;
146 }
147 }
148 }
149 if (gAborting == 0) { // Avoid recursive aborts.
150 CHECK(!bad_mutexes_held);
151 }
152 }
153 // Don't record monitors as they are outside the scope of analysis. They may be inspected off of
154 // the monitor list.
155 if (level != kMonitorLock) {
156 self->SetHeldMutex(level, this);
157 }
158 }
159
RegisterAsUnlocked(Thread * self)160 inline void BaseMutex::RegisterAsUnlocked(Thread* self) {
161 if (UNLIKELY(self == nullptr)) {
162 if (kDebugLocking) {
163 CheckUnattachedThread(level_);
164 }
165 } else {
166 RegisterAsUnlockedImpl(self, level_);
167 }
168 }
169
RegisterAsUnlockedImpl(Thread * self,LockLevel level)170 inline void BaseMutex::RegisterAsUnlockedImpl(Thread* self, LockLevel level) {
171 DCHECK(self != nullptr);
172 DCHECK_EQ(level_, level);
173 if (level != kMonitorLock) {
174 if (UNLIKELY(level == kThreadWaitLock) && self->GetHeldMutex(kThreadWaitWakeLock) == this) {
175 level = kThreadWaitWakeLock;
176 }
177 if (kDebugLocking && gAborting == 0) { // Avoid recursive aborts.
178 if (level == kThreadWaitWakeLock) {
179 CHECK(self->GetHeldMutex(kThreadWaitLock) != nullptr) << "Held " << kThreadWaitWakeLock << " without " << kThreadWaitLock;;
180 }
181 CHECK(self->GetHeldMutex(level) == this) << "Unlocking on unacquired mutex: " << name_;
182 }
183 self->SetHeldMutex(level, nullptr);
184 }
185 }
186
SharedLock(Thread * self)187 inline void ReaderWriterMutex::SharedLock(Thread* self) {
188 DCHECK(self == nullptr || self == Thread::Current());
189 #if ART_USE_FUTEXES
190 bool done = false;
191 do {
192 int32_t cur_state = state_.load(std::memory_order_relaxed);
193 if (LIKELY(cur_state >= 0)) {
194 // Add as an extra reader.
195 done = state_.CompareAndSetWeakAcquire(cur_state, cur_state + 1);
196 } else {
197 HandleSharedLockContention(self, cur_state);
198 }
199 } while (!done);
200 #else
201 CHECK_MUTEX_CALL(pthread_rwlock_rdlock, (&rwlock_));
202 #endif
203 DCHECK(GetExclusiveOwnerTid() == 0 || GetExclusiveOwnerTid() == -1);
204 RegisterAsLocked(self);
205 AssertSharedHeld(self);
206 }
207
SharedUnlock(Thread * self)208 inline void ReaderWriterMutex::SharedUnlock(Thread* self) {
209 DCHECK(self == nullptr || self == Thread::Current());
210 DCHECK(GetExclusiveOwnerTid() == 0 || GetExclusiveOwnerTid() == -1);
211 AssertSharedHeld(self);
212 RegisterAsUnlocked(self);
213 #if ART_USE_FUTEXES
214 bool done = false;
215 do {
216 int32_t cur_state = state_.load(std::memory_order_relaxed);
217 if (LIKELY(cur_state > 0)) {
218 // Reduce state by 1 and impose lock release load/store ordering.
219 // Note, the num_contenders_ load below musn't reorder before the CompareAndSet.
220 done = state_.CompareAndSetWeakSequentiallyConsistent(cur_state, cur_state - 1);
221 if (done && (cur_state - 1) == 0) { // Weak CAS may fail spuriously.
222 if (num_contenders_.load(std::memory_order_seq_cst) > 0) {
223 // Wake any exclusive waiters as there are now no readers.
224 futex(state_.Address(), FUTEX_WAKE_PRIVATE, kWakeAll, nullptr, nullptr, 0);
225 }
226 }
227 } else {
228 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
229 }
230 } while (!done);
231 #else
232 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
233 #endif
234 }
235
IsExclusiveHeld(const Thread * self)236 inline bool Mutex::IsExclusiveHeld(const Thread* self) const {
237 DCHECK(self == nullptr || self == Thread::Current());
238 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
239 if (kDebugLocking) {
240 // Debug check that if we think it is locked we have it in our held mutexes.
241 if (result && self != nullptr && level_ != kMonitorLock && !gAborting) {
242 if (level_ == kThreadWaitLock && self->GetHeldMutex(kThreadWaitLock) != this) {
243 CHECK_EQ(self->GetHeldMutex(kThreadWaitWakeLock), this);
244 } else {
245 CHECK_EQ(self->GetHeldMutex(level_), this);
246 }
247 }
248 }
249 return result;
250 }
251
GetExclusiveOwnerTid()252 inline pid_t Mutex::GetExclusiveOwnerTid() const {
253 return exclusive_owner_.load(std::memory_order_relaxed);
254 }
255
AssertExclusiveHeld(const Thread * self)256 inline void Mutex::AssertExclusiveHeld(const Thread* self) const {
257 if (kDebugLocking && (gAborting == 0)) {
258 CHECK(IsExclusiveHeld(self)) << *this;
259 }
260 }
261
AssertHeld(const Thread * self)262 inline void Mutex::AssertHeld(const Thread* self) const {
263 AssertExclusiveHeld(self);
264 }
265
IsExclusiveHeld(const Thread * self)266 inline bool ReaderWriterMutex::IsExclusiveHeld(const Thread* self) const {
267 DCHECK(self == nullptr || self == Thread::Current());
268 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
269 if (kDebugLocking) {
270 // Verify that if the pthread thinks we own the lock the Thread agrees.
271 if (self != nullptr && result) {
272 CHECK_EQ(self->GetHeldMutex(level_), this);
273 }
274 }
275 return result;
276 }
277
GetExclusiveOwnerTid()278 inline pid_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
279 #if ART_USE_FUTEXES
280 int32_t state = state_.load(std::memory_order_relaxed);
281 if (state == 0) {
282 return 0; // No owner.
283 } else if (state > 0) {
284 return -1; // Shared.
285 } else {
286 return exclusive_owner_.load(std::memory_order_relaxed);
287 }
288 #else
289 return exclusive_owner_.load(std::memory_order_relaxed);
290 #endif
291 }
292
AssertExclusiveHeld(const Thread * self)293 inline void ReaderWriterMutex::AssertExclusiveHeld(const Thread* self) const {
294 if (kDebugLocking && (gAborting == 0)) {
295 CHECK(IsExclusiveHeld(self)) << *this;
296 }
297 }
298
AssertWriterHeld(const Thread * self)299 inline void ReaderWriterMutex::AssertWriterHeld(const Thread* self) const {
300 AssertExclusiveHeld(self);
301 }
302
TransitionFromRunnableToSuspended(Thread * self)303 inline void MutatorMutex::TransitionFromRunnableToSuspended(Thread* self) {
304 AssertSharedHeld(self);
305 RegisterAsUnlockedImpl(self, kMutatorLock);
306 }
307
TransitionFromSuspendedToRunnable(Thread * self)308 inline void MutatorMutex::TransitionFromSuspendedToRunnable(Thread* self) {
309 RegisterAsLockedImpl(self, kMutatorLock, kDebugLocking);
310 AssertSharedHeld(self);
311 }
312
ReaderMutexLock(Thread * self,ReaderWriterMutex & mu)313 inline ReaderMutexLock::ReaderMutexLock(Thread* self, ReaderWriterMutex& mu)
314 : self_(self), mu_(mu) {
315 mu_.SharedLock(self_);
316 }
317
~ReaderMutexLock()318 inline ReaderMutexLock::~ReaderMutexLock() {
319 mu_.SharedUnlock(self_);
320 }
321
322 } // namespace art
323
324 #endif // ART_RUNTIME_BASE_MUTEX_INL_H_
325