blob: 1890181342ec49bbbf798bb448c597acf455b43f [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
Hiroshi Yamauchib3733082013-08-12 17:28:49 -070024#define ATRACE_TAG ATRACE_TAG_DALVIK
25
Ian Rogers693ff612013-02-01 10:56:12 -080026#include "cutils/atomic-inline.h"
Hiroshi Yamauchib3733082013-08-12 17:28:49 -070027#include "cutils/trace.h"
Ian Rogers576ca0c2014-06-06 15:58:22 -070028
29#include "base/stringprintf.h"
Ian Rogers693ff612013-02-01 10:56:12 -080030#include "runtime.h"
31#include "thread.h"
32
33namespace art {
34
35#define CHECK_MUTEX_CALL(call, args) CHECK_PTHREAD_CALL(call, args, name_)
36
37#if ART_USE_FUTEXES
38#include "linux/futex.h"
39#include "sys/syscall.h"
40#ifndef SYS_futex
41#define SYS_futex __NR_futex
42#endif
43static inline int futex(volatile int *uaddr, int op, int val, const struct timespec *timeout, volatile int *uaddr2, int val3) {
44 return syscall(SYS_futex, uaddr, op, val, timeout, uaddr2, val3);
45}
46#endif // ART_USE_FUTEXES
47
48class ScopedContentionRecorder {
49 public:
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070050 ScopedContentionRecorder(BaseMutex* mutex, uint64_t blocked_tid, uint64_t owner_tid)
51 : mutex_(kLogLockContentions ? mutex : NULL),
52 blocked_tid_(kLogLockContentions ? blocked_tid : 0),
53 owner_tid_(kLogLockContentions ? owner_tid : 0),
54 start_nano_time_(kLogLockContentions ? NanoTime() : 0) {
Ian Rogers220228e2014-01-23 09:08:16 -080055 std::string msg = StringPrintf("Lock contention on %s (owner tid: %" PRIu64 ")",
Jeff Hao08f2e7b2013-09-09 16:44:02 -070056 mutex->GetName(), owner_tid);
57 ATRACE_BEGIN(msg.c_str());
Ian Rogers693ff612013-02-01 10:56:12 -080058 }
59
60 ~ScopedContentionRecorder() {
Jeff Hao08f2e7b2013-09-09 16:44:02 -070061 ATRACE_END();
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070062 if (kLogLockContentions) {
63 uint64_t end_nano_time = NanoTime();
64 mutex_->RecordContention(blocked_tid_, owner_tid_, end_nano_time - start_nano_time_);
65 }
Ian Rogers693ff612013-02-01 10:56:12 -080066 }
67
68 private:
69 BaseMutex* const mutex_;
Ian Rogersc0fa3ad2013-02-05 00:11:55 -080070 const uint64_t blocked_tid_;
71 const uint64_t owner_tid_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070072 const uint64_t start_nano_time_;
Ian Rogers693ff612013-02-01 10:56:12 -080073};
74
75static inline uint64_t SafeGetTid(const Thread* self) {
76 if (self != NULL) {
77 return static_cast<uint64_t>(self->GetTid());
78 } else {
79 return static_cast<uint64_t>(GetTid());
80 }
81}
82
83static inline void CheckUnattachedThread(LockLevel level) NO_THREAD_SAFETY_ANALYSIS {
84 // The check below enumerates the cases where we expect not to be able to sanity check locks
85 // on a thread. Lock checking is disabled to avoid deadlock when checking shutdown lock.
86 // TODO: tighten this check.
87 if (kDebugLocking) {
88 Runtime* runtime = Runtime::Current();
Chao-ying Fu9e369312014-05-21 11:20:52 -070089 CHECK(runtime == nullptr || !runtime->IsStarted() || runtime->IsShuttingDownLocked() ||
90 // Used during thread creation to avoid races with runtime shutdown. Thread::Current not
91 // yet established.
92 level == kRuntimeShutdownLock ||
93 // Thread Ids are allocated/released before threads are established.
94 level == kAllocatedThreadIdsLock ||
95 // Thread LDT's are initialized without Thread::Current established.
96 level == kModifyLdtLock ||
97 // Threads are unregistered while holding the thread list lock, during this process they
98 // no longer exist and so we expect an unlock with no self.
99 level == kThreadListLock ||
100 // Ignore logging which may or may not have set up thread data structures.
101 level == kLoggingLock ||
102 // Avoid recursive death.
Ian Rogers06abcdf2014-05-23 11:39:11 -0700103 level == kAbortLock) << level;
Ian Rogers693ff612013-02-01 10:56:12 -0800104 }
105}
106
Ian Rogersb6c31ea2013-02-04 18:11:33 -0800107inline void BaseMutex::RegisterAsLocked(Thread* self) {
108 if (UNLIKELY(self == NULL)) {
109 CheckUnattachedThread(level_);
110 return;
111 }
112 if (kDebugLocking) {
113 // Check if a bad Mutex of this level or lower is held.
114 bool bad_mutexes_held = false;
115 for (int i = level_; i >= 0; --i) {
116 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
117 if (UNLIKELY(held_mutex != NULL)) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800118 LOG(ERROR) << "Lock level violation: holding \"" << held_mutex->name_ << "\" "
Ian Rogers62d6c772013-02-27 08:32:07 -0800119 << "(level " << LockLevel(i) << " - " << i
120 << ") while locking \"" << name_ << "\" "
121 << "(level " << level_ << " - " << static_cast<int>(level_) << ")";
Ian Rogersb6c31ea2013-02-04 18:11:33 -0800122 if (i > kAbortLock) {
123 // Only abort in the check below if this is more than abort level lock.
124 bad_mutexes_held = true;
125 }
126 }
127 }
128 CHECK(!bad_mutexes_held);
129 }
130 // Don't record monitors as they are outside the scope of analysis. They may be inspected off of
131 // the monitor list.
132 if (level_ != kMonitorLock) {
133 self->SetHeldMutex(level_, this);
134 }
135}
136
Ian Rogers693ff612013-02-01 10:56:12 -0800137inline void BaseMutex::RegisterAsUnlocked(Thread* self) {
138 if (UNLIKELY(self == NULL)) {
139 CheckUnattachedThread(level_);
140 return;
141 }
142 if (level_ != kMonitorLock) {
143 if (kDebugLocking && !gAborting) {
144 CHECK(self->GetHeldMutex(level_) == this) << "Unlocking on unacquired mutex: " << name_;
145 }
146 self->SetHeldMutex(level_, NULL);
147 }
148}
149
150inline void ReaderWriterMutex::SharedLock(Thread* self) {
151 DCHECK(self == NULL || self == Thread::Current());
152#if ART_USE_FUTEXES
153 bool done = false;
154 do {
155 int32_t cur_state = state_;
Ian Rogersc0fa3ad2013-02-05 00:11:55 -0800156 if (LIKELY(cur_state >= 0)) {
Ian Rogers693ff612013-02-01 10:56:12 -0800157 // Add as an extra reader.
158 done = android_atomic_acquire_cas(cur_state, cur_state + 1, &state_) == 0;
159 } else {
160 // Owner holds it exclusively, hang up.
161 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
162 android_atomic_inc(&num_pending_readers_);
163 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
164 if (errno != EAGAIN) {
165 PLOG(FATAL) << "futex wait failed for " << name_;
166 }
167 }
168 android_atomic_dec(&num_pending_readers_);
169 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700170 } while (!done);
Ian Rogers693ff612013-02-01 10:56:12 -0800171#else
172 CHECK_MUTEX_CALL(pthread_rwlock_rdlock, (&rwlock_));
173#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700174 DCHECK(exclusive_owner_ == 0U || exclusive_owner_ == -1U);
Ian Rogers693ff612013-02-01 10:56:12 -0800175 RegisterAsLocked(self);
176 AssertSharedHeld(self);
177}
178
179inline void ReaderWriterMutex::SharedUnlock(Thread* self) {
180 DCHECK(self == NULL || self == Thread::Current());
Ian Rogersc5f17732014-06-05 20:48:42 -0700181 DCHECK(exclusive_owner_ == 0U || exclusive_owner_ == -1U);
Ian Rogers693ff612013-02-01 10:56:12 -0800182 AssertSharedHeld(self);
183 RegisterAsUnlocked(self);
184#if ART_USE_FUTEXES
185 bool done = false;
186 do {
187 int32_t cur_state = state_;
188 if (LIKELY(cur_state > 0)) {
189 // Reduce state by 1.
190 done = android_atomic_release_cas(cur_state, cur_state - 1, &state_) == 0;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700191 if (done && (cur_state - 1) == 0) { // cas may fail due to noise?
Ian Rogers3e5cf302014-05-20 16:40:37 -0700192 if (num_pending_writers_.LoadRelaxed() > 0 || num_pending_readers_ > 0) {
Ian Rogers693ff612013-02-01 10:56:12 -0800193 // Wake any exclusive waiters as there are now no readers.
194 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
195 }
196 }
197 } else {
198 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
199 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700200 } while (!done);
Ian Rogers693ff612013-02-01 10:56:12 -0800201#else
202 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
203#endif
204}
205
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700206inline bool Mutex::IsExclusiveHeld(const Thread* self) const {
207 DCHECK(self == NULL || self == Thread::Current());
208 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
209 if (kDebugLocking) {
210 // Sanity debug check that if we think it is locked we have it in our held mutexes.
211 if (result && self != NULL && level_ != kMonitorLock && !gAborting) {
212 CHECK_EQ(self->GetHeldMutex(level_), this);
213 }
214 }
215 return result;
216}
217
218inline uint64_t Mutex::GetExclusiveOwnerTid() const {
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700219 return exclusive_owner_;
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700220}
221
222inline bool ReaderWriterMutex::IsExclusiveHeld(const Thread* self) const {
223 DCHECK(self == NULL || self == Thread::Current());
224 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
225 if (kDebugLocking) {
226 // Sanity that if the pthread thinks we own the lock the Thread agrees.
227 if (self != NULL && result) {
228 CHECK_EQ(self->GetHeldMutex(level_), this);
229 }
230 }
231 return result;
232}
233
234inline uint64_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
235#if ART_USE_FUTEXES
236 int32_t state = state_;
237 if (state == 0) {
238 return 0; // No owner.
239 } else if (state > 0) {
240 return -1; // Shared.
241 } else {
242 return exclusive_owner_;
243 }
244#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700245 return exclusive_owner_;
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700246#endif
247}
248
Ian Rogers693ff612013-02-01 10:56:12 -0800249} // namespace art
250
Brian Carlstromfc0e3212013-07-17 14:40:12 -0700251#endif // ART_RUNTIME_BASE_MUTEX_INL_H_