blob: e775fe4505661b807face9c940836790025014d9 [file] [log] [blame]
Ian Rogers693ff612013-02-01 10:56:12 -08001/*
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_INL_H_
18#define ART_RUNTIME_BASE_MUTEX_INL_H_
Ian Rogers693ff612013-02-01 10:56:12 -080019
Ian Rogers220228e2014-01-23 09:08:16 -080020#include <inttypes.h>
21
Ian Rogers693ff612013-02-01 10:56:12 -080022#include "mutex.h"
23
David Sehrc431b9d2018-03-02 12:01:51 -080024#include "base/utils.h"
Ian Rogerscf7f1912014-10-22 22:06:39 -070025#include "base/value_object.h"
Ian Rogers693ff612013-02-01 10:56:12 -080026#include "thread.h"
27
Ian Rogers693ff612013-02-01 10:56:12 -080028#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
Chih-Hung Hsieh729c1cf2014-11-06 10:49:16 -080034#endif // ART_USE_FUTEXES
35
Ian Rogersd6d7c3b2014-11-06 14:26:29 -080036#define CHECK_MUTEX_CALL(call, args) CHECK_PTHREAD_CALL(call, args, name_)
37
Chih-Hung Hsieh729c1cf2014-11-06 10:49:16 -080038namespace art {
39
40#if ART_USE_FUTEXES
Mathieu Chartier2cebb242015-04-21 16:50:40 -070041static inline int futex(volatile int *uaddr, int op, int val, const struct timespec *timeout,
42 volatile int *uaddr2, int val3) {
Ian Rogers693ff612013-02-01 10:56:12 -080043 return syscall(SYS_futex, uaddr, op, val, timeout, uaddr2, val3);
44}
45#endif // ART_USE_FUTEXES
46
Hans Boehm0882af22017-08-31 15:21:57 -070047// 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.
49static_assert(sizeof(pid_t) <= sizeof(int32_t), "pid_t should fit in 32 bits");
50
51static inline pid_t SafeGetTid(const Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070052 if (self != nullptr) {
Hans Boehm0882af22017-08-31 15:21:57 -070053 return self->GetTid();
Ian Rogers693ff612013-02-01 10:56:12 -080054 } else {
Hans Boehm0882af22017-08-31 15:21:57 -070055 return GetTid();
Ian Rogers693ff612013-02-01 10:56:12 -080056 }
57}
58
59static inline void CheckUnattachedThread(LockLevel level) NO_THREAD_SAFETY_ANALYSIS {
60 // The check below enumerates the cases where we expect not to be able to sanity check locks
61 // on a thread. Lock checking is disabled to avoid deadlock when checking shutdown lock.
62 // TODO: tighten this check.
63 if (kDebugLocking) {
David Sehrf42eb2c2016-10-19 13:20:45 -070064 CHECK(!Locks::IsSafeToCallAbortRacy() ||
Chao-ying Fu9e369312014-05-21 11:20:52 -070065 // 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 ||
Nicolas Geoffray9f5f8ac2016-06-29 14:39:59 +010077 // 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 ||
Chao-ying Fu9e369312014-05-21 11:20:52 -070082 // Avoid recursive death.
Alex Lightb284f8d2017-11-21 00:00:48 +000083 level == kAbortLock ||
84 // Locks at the absolute top of the stack can be locked at any time.
85 level == kTopLockLevel) << level;
Ian Rogers693ff612013-02-01 10:56:12 -080086 }
87}
88
Ian Rogersb6c31ea2013-02-04 18:11:33 -080089inline void BaseMutex::RegisterAsLocked(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070090 if (UNLIKELY(self == nullptr)) {
Ian Rogersb6c31ea2013-02-04 18:11:33 -080091 CheckUnattachedThread(level_);
92 return;
93 }
94 if (kDebugLocking) {
95 // Check if a bad Mutex of this level or lower is held.
96 bool bad_mutexes_held = false;
Alex Lightb284f8d2017-11-21 00:00:48 +000097 // Specifically allow a kTopLockLevel lock to be gained when the current thread holds the
98 // mutator_lock_ exclusive. This is because we suspending when holding locks at this level is
99 // not allowed and if we hold the mutator_lock_ exclusive we must unsuspend stuff eventually
100 // so there are no deadlocks.
Roland Levillain9cec9652018-11-06 10:50:20 +0000101 if (level_ == kTopLockLevel &&
Alex Lightb284f8d2017-11-21 00:00:48 +0000102 Locks::mutator_lock_->IsSharedHeld(self) &&
103 !Locks::mutator_lock_->IsExclusiveHeld(self)) {
104 LOG(ERROR) << "Lock level violation: holding \"" << Locks::mutator_lock_->name_ << "\" "
105 << "(level " << kMutatorLock << " - " << static_cast<int>(kMutatorLock)
106 << ") non-exclusive while locking \"" << name_ << "\" "
Roland Levillain9cec9652018-11-06 10:50:20 +0000107 << "(level " << level_ << " - " << static_cast<int>(level_) << ") a top level"
Alex Lightb284f8d2017-11-21 00:00:48 +0000108 << "mutex. This is not allowed.";
109 bad_mutexes_held = true;
110 } else if (this == Locks::mutator_lock_ && self->GetHeldMutex(kTopLockLevel) != nullptr) {
111 LOG(ERROR) << "Lock level violation. Locking mutator_lock_ while already having a "
112 << "kTopLevelLock (" << self->GetHeldMutex(kTopLockLevel)->name_ << "held is "
113 << "not allowed.";
114 bad_mutexes_held = true;
115 }
Roland Levillain9cec9652018-11-06 10:50:20 +0000116 for (int i = level_; i >= 0; --i) {
Andreas Gamped1fbcff2017-04-17 21:40:28 -0700117 LockLevel lock_level_i = static_cast<LockLevel>(i);
118 BaseMutex* held_mutex = self->GetHeldMutex(lock_level_i);
Roland Levillain9cec9652018-11-06 10:50:20 +0000119 if (level_ == kTopLockLevel &&
Alex Lightb284f8d2017-11-21 00:00:48 +0000120 lock_level_i == kMutatorLock &&
121 Locks::mutator_lock_->IsExclusiveHeld(self)) {
122 // This is checked above.
123 continue;
124 } else if (UNLIKELY(held_mutex != nullptr) && lock_level_i != kAbortLock) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800125 LOG(ERROR) << "Lock level violation: holding \"" << held_mutex->name_ << "\" "
Andreas Gamped1fbcff2017-04-17 21:40:28 -0700126 << "(level " << lock_level_i << " - " << i
Ian Rogers62d6c772013-02-27 08:32:07 -0800127 << ") while locking \"" << name_ << "\" "
Roland Levillain9cec9652018-11-06 10:50:20 +0000128 << "(level " << level_ << " - " << static_cast<int>(level_) << ")";
Andreas Gamped1fbcff2017-04-17 21:40:28 -0700129 if (lock_level_i > kAbortLock) {
Ian Rogersb6c31ea2013-02-04 18:11:33 -0800130 // Only abort in the check below if this is more than abort level lock.
131 bad_mutexes_held = true;
132 }
133 }
134 }
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000135 if (gAborting == 0) { // Avoid recursive aborts.
136 CHECK(!bad_mutexes_held);
137 }
Ian Rogersb6c31ea2013-02-04 18:11:33 -0800138 }
139 // Don't record monitors as they are outside the scope of analysis. They may be inspected off of
140 // the monitor list.
Roland Levillain9cec9652018-11-06 10:50:20 +0000141 if (level_ != kMonitorLock) {
142 self->SetHeldMutex(level_, this);
Ian Rogersb6c31ea2013-02-04 18:11:33 -0800143 }
144}
145
Ian Rogers693ff612013-02-01 10:56:12 -0800146inline void BaseMutex::RegisterAsUnlocked(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700147 if (UNLIKELY(self == nullptr)) {
Ian Rogers693ff612013-02-01 10:56:12 -0800148 CheckUnattachedThread(level_);
149 return;
150 }
151 if (level_ != kMonitorLock) {
Charles Munger1ebb52c2018-10-25 15:37:14 -0700152 if (kDebugLocking && gAborting == 0) { // Avoid recursive aborts.
Roland Levillain9cec9652018-11-06 10:50:20 +0000153 CHECK(self->GetHeldMutex(level_) == this) << "Unlocking on unacquired mutex: " << name_;
Charles Munger1ebb52c2018-10-25 15:37:14 -0700154 }
Roland Levillain9cec9652018-11-06 10:50:20 +0000155 self->SetHeldMutex(level_, nullptr);
Ian Rogers693ff612013-02-01 10:56:12 -0800156 }
157}
158
159inline void ReaderWriterMutex::SharedLock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700160 DCHECK(self == nullptr || self == Thread::Current());
Ian Rogers693ff612013-02-01 10:56:12 -0800161#if ART_USE_FUTEXES
162 bool done = false;
163 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000164 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogersc0fa3ad2013-02-05 00:11:55 -0800165 if (LIKELY(cur_state >= 0)) {
Ian Rogers693ff612013-02-01 10:56:12 -0800166 // Add as an extra reader.
Orion Hodson4557b382018-01-03 11:47:54 +0000167 done = state_.CompareAndSetWeakAcquire(cur_state, cur_state + 1);
Ian Rogers693ff612013-02-01 10:56:12 -0800168 } else {
Ian Rogerscf7f1912014-10-22 22:06:39 -0700169 HandleSharedLockContention(self, cur_state);
Ian Rogers693ff612013-02-01 10:56:12 -0800170 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700171 } while (!done);
Ian Rogers693ff612013-02-01 10:56:12 -0800172#else
173 CHECK_MUTEX_CALL(pthread_rwlock_rdlock, (&rwlock_));
174#endif
Hans Boehm0882af22017-08-31 15:21:57 -0700175 DCHECK(GetExclusiveOwnerTid() == 0 || GetExclusiveOwnerTid() == -1);
Ian Rogers693ff612013-02-01 10:56:12 -0800176 RegisterAsLocked(self);
177 AssertSharedHeld(self);
178}
179
180inline void ReaderWriterMutex::SharedUnlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700181 DCHECK(self == nullptr || self == Thread::Current());
Hans Boehm0882af22017-08-31 15:21:57 -0700182 DCHECK(GetExclusiveOwnerTid() == 0 || GetExclusiveOwnerTid() == -1);
Ian Rogers693ff612013-02-01 10:56:12 -0800183 AssertSharedHeld(self);
184 RegisterAsUnlocked(self);
185#if ART_USE_FUTEXES
186 bool done = false;
187 do {
Orion Hodson88591fe2018-03-06 13:35:43 +0000188 int32_t cur_state = state_.load(std::memory_order_relaxed);
Ian Rogers693ff612013-02-01 10:56:12 -0800189 if (LIKELY(cur_state > 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700190 // Reduce state by 1 and impose lock release load/store ordering.
Orion Hodson4557b382018-01-03 11:47:54 +0000191 // Note, the relaxed loads below musn't reorder before the CompareAndSet.
Ian Rogersc7190692014-07-08 23:50:26 -0700192 // TODO: the ordering here is non-trivial as state is split across 3 fields, fix by placing
193 // a status bit into the state on contention.
Orion Hodson4557b382018-01-03 11:47:54 +0000194 done = state_.CompareAndSetWeakSequentiallyConsistent(cur_state, cur_state - 1);
Ian Rogersc7190692014-07-08 23:50:26 -0700195 if (done && (cur_state - 1) == 0) { // Weak CAS may fail spuriously.
Hyangseok Chae240a5642018-07-25 16:45:08 +0900196 if (num_pending_writers_.load(std::memory_order_seq_cst) > 0 ||
197 num_pending_readers_.load(std::memory_order_seq_cst) > 0) {
Ian Rogers693ff612013-02-01 10:56:12 -0800198 // Wake any exclusive waiters as there are now no readers.
Charles Munger7530bae2018-10-29 20:03:51 -0700199 futex(state_.Address(), FUTEX_WAKE_PRIVATE, -1, nullptr, nullptr, 0);
Ian Rogers693ff612013-02-01 10:56:12 -0800200 }
201 }
202 } else {
203 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
204 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700205 } while (!done);
Ian Rogers693ff612013-02-01 10:56:12 -0800206#else
207 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
208#endif
209}
210
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700211inline bool Mutex::IsExclusiveHeld(const Thread* self) const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700212 DCHECK(self == nullptr || self == Thread::Current());
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700213 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
214 if (kDebugLocking) {
215 // Sanity debug check that if we think it is locked we have it in our held mutexes.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700216 if (result && self != nullptr && level_ != kMonitorLock && !gAborting) {
Roland Levillain9cec9652018-11-06 10:50:20 +0000217 CHECK_EQ(self->GetHeldMutex(level_), this);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700218 }
219 }
220 return result;
221}
222
Hans Boehm0882af22017-08-31 15:21:57 -0700223inline pid_t Mutex::GetExclusiveOwnerTid() const {
Orion Hodson88591fe2018-03-06 13:35:43 +0000224 return exclusive_owner_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700225}
226
Andreas Gampeb486a982017-06-01 13:45:54 -0700227inline void Mutex::AssertExclusiveHeld(const Thread* self) const {
228 if (kDebugLocking && (gAborting == 0)) {
229 CHECK(IsExclusiveHeld(self)) << *this;
230 }
231}
232
233inline void Mutex::AssertHeld(const Thread* self) const {
234 AssertExclusiveHeld(self);
235}
236
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700237inline bool ReaderWriterMutex::IsExclusiveHeld(const Thread* self) const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700238 DCHECK(self == nullptr || self == Thread::Current());
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700239 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
240 if (kDebugLocking) {
241 // Sanity that if the pthread thinks we own the lock the Thread agrees.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700242 if (self != nullptr && result) {
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700243 CHECK_EQ(self->GetHeldMutex(level_), this);
244 }
245 }
246 return result;
247}
248
Hans Boehm0882af22017-08-31 15:21:57 -0700249inline pid_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700250#if ART_USE_FUTEXES
Orion Hodson88591fe2018-03-06 13:35:43 +0000251 int32_t state = state_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700252 if (state == 0) {
253 return 0; // No owner.
254 } else if (state > 0) {
255 return -1; // Shared.
256 } else {
Orion Hodson88591fe2018-03-06 13:35:43 +0000257 return exclusive_owner_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700258 }
259#else
Orion Hodson88591fe2018-03-06 13:35:43 +0000260 return exclusive_owner_.load(std::memory_order_relaxed);
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700261#endif
262}
263
Andreas Gampeb486a982017-06-01 13:45:54 -0700264inline void ReaderWriterMutex::AssertExclusiveHeld(const Thread* self) const {
265 if (kDebugLocking && (gAborting == 0)) {
266 CHECK(IsExclusiveHeld(self)) << *this;
267 }
268}
269
270inline void ReaderWriterMutex::AssertWriterHeld(const Thread* self) const {
271 AssertExclusiveHeld(self);
272}
273
Yu Lieac44242015-06-29 10:50:03 +0800274inline void MutatorMutex::TransitionFromRunnableToSuspended(Thread* self) {
275 AssertSharedHeld(self);
276 RegisterAsUnlocked(self);
277}
278
279inline void MutatorMutex::TransitionFromSuspendedToRunnable(Thread* self) {
280 RegisterAsLocked(self);
281 AssertSharedHeld(self);
282}
283
Andreas Gampeb486a982017-06-01 13:45:54 -0700284inline ReaderMutexLock::ReaderMutexLock(Thread* self, ReaderWriterMutex& mu)
285 : self_(self), mu_(mu) {
286 mu_.SharedLock(self_);
287}
288
289inline ReaderMutexLock::~ReaderMutexLock() {
290 mu_.SharedUnlock(self_);
291}
292
Ian Rogers693ff612013-02-01 10:56:12 -0800293} // namespace art
294
Brian Carlstromfc0e3212013-07-17 14:40:12 -0700295#endif // ART_RUNTIME_BASE_MUTEX_INL_H_