• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef SYS_futex
32 #define SYS_futex __NR_futex
33 #endif
34 #endif  // ART_USE_FUTEXES
35 
36 #define CHECK_MUTEX_CALL(call, args) CHECK_PTHREAD_CALL(call, args, name_)
37 
38 namespace art {
39 
40 #if ART_USE_FUTEXES
futex(volatile int * uaddr,int op,int val,const struct timespec * timeout,volatile int * uaddr2,int val3)41 static inline int futex(volatile int *uaddr, int op, int val, const struct timespec *timeout,
42                         volatile int *uaddr2, int val3) {
43   return syscall(SYS_futex, uaddr, op, val, timeout, uaddr2, val3);
44 }
45 #endif  // ART_USE_FUTEXES
46 
47 // The following isn't strictly necessary, but we want updates on Atomic<pid_t> to be lock-free.
48 // TODO: Use std::atomic::is_always_lock_free after switching to C++17 atomics.
49 static_assert(sizeof(pid_t) <= sizeof(int32_t), "pid_t should fit in 32 bits");
50 
SafeGetTid(const Thread * self)51 static inline pid_t SafeGetTid(const Thread* self) {
52   if (self != nullptr) {
53     return self->GetTid();
54   } else {
55     return GetTid();
56   }
57 }
58 
CheckUnattachedThread(LockLevel level)59 static inline void CheckUnattachedThread(LockLevel level) NO_THREAD_SAFETY_ANALYSIS {
60   // The check below enumerates the cases where we expect not to be able to check the validity of
61   // locks on a thread. Lock checking is disabled to avoid deadlock when checking shutdown lock.
62   // TODO: tighten this check.
63   if (kDebugLocking) {
64     CHECK(!Locks::IsSafeToCallAbortRacy() ||
65           // Used during thread creation to avoid races with runtime shutdown. Thread::Current not
66           // yet established.
67           level == kRuntimeShutdownLock ||
68           // Thread Ids are allocated/released before threads are established.
69           level == kAllocatedThreadIdsLock ||
70           // Thread LDT's are initialized without Thread::Current established.
71           level == kModifyLdtLock ||
72           // Threads are unregistered while holding the thread list lock, during this process they
73           // no longer exist and so we expect an unlock with no self.
74           level == kThreadListLock ||
75           // Ignore logging which may or may not have set up thread data structures.
76           level == kLoggingLock ||
77           // When transitioning from suspended to runnable, a daemon thread might be in
78           // a situation where the runtime is shutting down. To not crash our debug locking
79           // mechanism we just pass null Thread* to the MutexLock during that transition
80           // (see Thread::TransitionFromSuspendedToRunnable).
81           level == kThreadSuspendCountLock ||
82           // Avoid recursive death.
83           level == kAbortLock ||
84           // Locks at the absolute top of the stack can be locked at any time.
85           level == kTopLockLevel ||
86           // The unexpected signal handler may be catching signals from any thread.
87           level == kUnexpectedSignalLock) << level;
88   }
89 }
90 
RegisterAsLocked(Thread * self)91 inline void BaseMutex::RegisterAsLocked(Thread* self) {
92   if (UNLIKELY(self == nullptr)) {
93     CheckUnattachedThread(level_);
94     return;
95   }
96   RegisterAsLockedImpl(self, level_);
97 }
98 
RegisterAsLockedImpl(Thread * self,LockLevel level)99 inline void BaseMutex::RegisterAsLockedImpl(Thread* self, LockLevel level) {
100   DCHECK(self != nullptr);
101   DCHECK_EQ(level_, level);
102   // It would be nice to avoid this condition checking in the non-debug case,
103   // but that would make the various methods that check if a mutex is held not
104   // work properly for thread wait locks. Since the vast majority of lock
105   // acquisitions are not thread wait locks, this check should not be too
106   // expensive.
107   if (UNLIKELY(level == kThreadWaitLock) && self->GetHeldMutex(kThreadWaitLock) != nullptr) {
108     level = kThreadWaitWakeLock;
109   }
110   if (kDebugLocking) {
111     // Check if a bad Mutex of this level or lower is held.
112     bool bad_mutexes_held = false;
113     // Specifically allow a kTopLockLevel lock to be gained when the current thread holds the
114     // mutator_lock_ exclusive. This is because we suspending when holding locks at this level is
115     // not allowed and if we hold the mutator_lock_ exclusive we must unsuspend stuff eventually
116     // so there are no deadlocks.
117     if (level == kTopLockLevel &&
118         Locks::mutator_lock_->IsSharedHeld(self) &&
119         !Locks::mutator_lock_->IsExclusiveHeld(self)) {
120       LOG(ERROR) << "Lock level violation: holding \"" << Locks::mutator_lock_->name_ << "\" "
121                   << "(level " << kMutatorLock << " - " << static_cast<int>(kMutatorLock)
122                   << ") non-exclusive while locking \"" << name_ << "\" "
123                   << "(level " << level << " - " << static_cast<int>(level) << ") a top level"
124                   << "mutex. This is not allowed.";
125       bad_mutexes_held = true;
126     } else if (this == Locks::mutator_lock_ && self->GetHeldMutex(kTopLockLevel) != nullptr) {
127       LOG(ERROR) << "Lock level violation. Locking mutator_lock_ while already having a "
128                  << "kTopLevelLock (" << self->GetHeldMutex(kTopLockLevel)->name_ << "held is "
129                  << "not allowed.";
130       bad_mutexes_held = true;
131     }
132     for (int i = level; i >= 0; --i) {
133       LockLevel lock_level_i = static_cast<LockLevel>(i);
134       BaseMutex* held_mutex = self->GetHeldMutex(lock_level_i);
135       if (level == kTopLockLevel &&
136           lock_level_i == kMutatorLock &&
137           Locks::mutator_lock_->IsExclusiveHeld(self)) {
138         // This is checked above.
139         continue;
140       } else if (UNLIKELY(held_mutex != nullptr) && lock_level_i != kAbortLock) {
141         LOG(ERROR) << "Lock level violation: holding \"" << held_mutex->name_ << "\" "
142                    << "(level " << lock_level_i << " - " << i
143                    << ") while locking \"" << name_ << "\" "
144                    << "(level " << level << " - " << static_cast<int>(level) << ")";
145         if (lock_level_i > kAbortLock) {
146           // Only abort in the check below if this is more than abort level lock.
147           bad_mutexes_held = true;
148         }
149       }
150     }
151     if (gAborting == 0) {  // Avoid recursive aborts.
152       CHECK(!bad_mutexes_held);
153     }
154   }
155   // Don't record monitors as they are outside the scope of analysis. They may be inspected off of
156   // the monitor list.
157   if (level != kMonitorLock) {
158     self->SetHeldMutex(level, this);
159   }
160 }
161 
RegisterAsUnlocked(Thread * self)162 inline void BaseMutex::RegisterAsUnlocked(Thread* self) {
163   if (UNLIKELY(self == nullptr)) {
164     CheckUnattachedThread(level_);
165     return;
166   }
167   RegisterAsUnlockedImpl(self , level_);
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);
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