blob: d20eb17a3c4e5a097f601fd0abebc788eee02ddd [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
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -070048#if defined(__APPLE__)
49
50// This works on Mac OS 10.6 but hasn't been tested on older releases.
51struct __attribute__((__may_alias__)) darwin_pthread_mutex_t {
52 long padding0; // NOLINT(runtime/int) exact match to darwin type
53 int padding1;
54 uint32_t padding2;
55 int16_t padding3;
56 int16_t padding4;
57 uint32_t padding5;
58 pthread_t darwin_pthread_mutex_owner;
59 // ...other stuff we don't care about.
60};
61
62struct __attribute__((__may_alias__)) darwin_pthread_rwlock_t {
63 long padding0; // NOLINT(runtime/int) exact match to darwin type
64 pthread_mutex_t padding1;
65 int padding2;
66 pthread_cond_t padding3;
67 pthread_cond_t padding4;
68 int padding5;
69 int padding6;
70 pthread_t darwin_pthread_rwlock_owner;
71 // ...other stuff we don't care about.
72};
73
74#endif // __APPLE__
75
76#if defined(__GLIBC__)
77
78struct __attribute__((__may_alias__)) glibc_pthread_mutex_t {
79 int32_t padding0[2];
80 int owner;
81 // ...other stuff we don't care about.
82};
83
84struct __attribute__((__may_alias__)) glibc_pthread_rwlock_t {
85#ifdef __LP64__
86 int32_t padding0[6];
87#else
88 int32_t padding0[7];
89#endif
90 int writer;
91 // ...other stuff we don't care about.
92};
93
94#endif // __GLIBC__
95
Ian Rogers693ff612013-02-01 10:56:12 -080096class ScopedContentionRecorder {
97 public:
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070098 ScopedContentionRecorder(BaseMutex* mutex, uint64_t blocked_tid, uint64_t owner_tid)
99 : mutex_(kLogLockContentions ? mutex : NULL),
100 blocked_tid_(kLogLockContentions ? blocked_tid : 0),
101 owner_tid_(kLogLockContentions ? owner_tid : 0),
102 start_nano_time_(kLogLockContentions ? NanoTime() : 0) {
Ian Rogers220228e2014-01-23 09:08:16 -0800103 std::string msg = StringPrintf("Lock contention on %s (owner tid: %" PRIu64 ")",
Jeff Hao08f2e7b2013-09-09 16:44:02 -0700104 mutex->GetName(), owner_tid);
105 ATRACE_BEGIN(msg.c_str());
Ian Rogers693ff612013-02-01 10:56:12 -0800106 }
107
108 ~ScopedContentionRecorder() {
Jeff Hao08f2e7b2013-09-09 16:44:02 -0700109 ATRACE_END();
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700110 if (kLogLockContentions) {
111 uint64_t end_nano_time = NanoTime();
112 mutex_->RecordContention(blocked_tid_, owner_tid_, end_nano_time - start_nano_time_);
113 }
Ian Rogers693ff612013-02-01 10:56:12 -0800114 }
115
116 private:
117 BaseMutex* const mutex_;
Ian Rogersc0fa3ad2013-02-05 00:11:55 -0800118 const uint64_t blocked_tid_;
119 const uint64_t owner_tid_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -0700120 const uint64_t start_nano_time_;
Ian Rogers693ff612013-02-01 10:56:12 -0800121};
122
123static inline uint64_t SafeGetTid(const Thread* self) {
124 if (self != NULL) {
125 return static_cast<uint64_t>(self->GetTid());
126 } else {
127 return static_cast<uint64_t>(GetTid());
128 }
129}
130
131static inline void CheckUnattachedThread(LockLevel level) NO_THREAD_SAFETY_ANALYSIS {
132 // The check below enumerates the cases where we expect not to be able to sanity check locks
133 // on a thread. Lock checking is disabled to avoid deadlock when checking shutdown lock.
134 // TODO: tighten this check.
135 if (kDebugLocking) {
136 Runtime* runtime = Runtime::Current();
Chao-ying Fu9e369312014-05-21 11:20:52 -0700137 CHECK(runtime == nullptr || !runtime->IsStarted() || runtime->IsShuttingDownLocked() ||
138 // Used during thread creation to avoid races with runtime shutdown. Thread::Current not
139 // yet established.
140 level == kRuntimeShutdownLock ||
141 // Thread Ids are allocated/released before threads are established.
142 level == kAllocatedThreadIdsLock ||
143 // Thread LDT's are initialized without Thread::Current established.
144 level == kModifyLdtLock ||
145 // Threads are unregistered while holding the thread list lock, during this process they
146 // no longer exist and so we expect an unlock with no self.
147 level == kThreadListLock ||
148 // Ignore logging which may or may not have set up thread data structures.
149 level == kLoggingLock ||
150 // Avoid recursive death.
Ian Rogers06abcdf2014-05-23 11:39:11 -0700151 level == kAbortLock) << level;
Ian Rogers693ff612013-02-01 10:56:12 -0800152 }
153}
154
Ian Rogersb6c31ea2013-02-04 18:11:33 -0800155inline void BaseMutex::RegisterAsLocked(Thread* self) {
156 if (UNLIKELY(self == NULL)) {
157 CheckUnattachedThread(level_);
158 return;
159 }
160 if (kDebugLocking) {
161 // Check if a bad Mutex of this level or lower is held.
162 bool bad_mutexes_held = false;
163 for (int i = level_; i >= 0; --i) {
164 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
165 if (UNLIKELY(held_mutex != NULL)) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800166 LOG(ERROR) << "Lock level violation: holding \"" << held_mutex->name_ << "\" "
Ian Rogers62d6c772013-02-27 08:32:07 -0800167 << "(level " << LockLevel(i) << " - " << i
168 << ") while locking \"" << name_ << "\" "
169 << "(level " << level_ << " - " << static_cast<int>(level_) << ")";
Ian Rogersb6c31ea2013-02-04 18:11:33 -0800170 if (i > kAbortLock) {
171 // Only abort in the check below if this is more than abort level lock.
172 bad_mutexes_held = true;
173 }
174 }
175 }
176 CHECK(!bad_mutexes_held);
177 }
178 // Don't record monitors as they are outside the scope of analysis. They may be inspected off of
179 // the monitor list.
180 if (level_ != kMonitorLock) {
181 self->SetHeldMutex(level_, this);
182 }
183}
184
Ian Rogers693ff612013-02-01 10:56:12 -0800185inline void BaseMutex::RegisterAsUnlocked(Thread* self) {
186 if (UNLIKELY(self == NULL)) {
187 CheckUnattachedThread(level_);
188 return;
189 }
190 if (level_ != kMonitorLock) {
191 if (kDebugLocking && !gAborting) {
192 CHECK(self->GetHeldMutex(level_) == this) << "Unlocking on unacquired mutex: " << name_;
193 }
194 self->SetHeldMutex(level_, NULL);
195 }
196}
197
198inline void ReaderWriterMutex::SharedLock(Thread* self) {
199 DCHECK(self == NULL || self == Thread::Current());
200#if ART_USE_FUTEXES
201 bool done = false;
202 do {
203 int32_t cur_state = state_;
Ian Rogersc0fa3ad2013-02-05 00:11:55 -0800204 if (LIKELY(cur_state >= 0)) {
Ian Rogers693ff612013-02-01 10:56:12 -0800205 // Add as an extra reader.
206 done = android_atomic_acquire_cas(cur_state, cur_state + 1, &state_) == 0;
207 } else {
208 // Owner holds it exclusively, hang up.
209 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
210 android_atomic_inc(&num_pending_readers_);
211 if (futex(&state_, FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
212 if (errno != EAGAIN) {
213 PLOG(FATAL) << "futex wait failed for " << name_;
214 }
215 }
216 android_atomic_dec(&num_pending_readers_);
217 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700218 } while (!done);
Ian Rogers693ff612013-02-01 10:56:12 -0800219#else
220 CHECK_MUTEX_CALL(pthread_rwlock_rdlock, (&rwlock_));
221#endif
222 RegisterAsLocked(self);
223 AssertSharedHeld(self);
224}
225
226inline void ReaderWriterMutex::SharedUnlock(Thread* self) {
227 DCHECK(self == NULL || self == Thread::Current());
228 AssertSharedHeld(self);
229 RegisterAsUnlocked(self);
230#if ART_USE_FUTEXES
231 bool done = false;
232 do {
233 int32_t cur_state = state_;
234 if (LIKELY(cur_state > 0)) {
235 // Reduce state by 1.
236 done = android_atomic_release_cas(cur_state, cur_state - 1, &state_) == 0;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700237 if (done && (cur_state - 1) == 0) { // cas may fail due to noise?
Ian Rogers3e5cf302014-05-20 16:40:37 -0700238 if (num_pending_writers_.LoadRelaxed() > 0 || num_pending_readers_ > 0) {
Ian Rogers693ff612013-02-01 10:56:12 -0800239 // Wake any exclusive waiters as there are now no readers.
240 futex(&state_, FUTEX_WAKE, -1, NULL, NULL, 0);
241 }
242 }
243 } else {
244 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
245 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700246 } while (!done);
Ian Rogers693ff612013-02-01 10:56:12 -0800247#else
248 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
249#endif
250}
251
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700252inline bool Mutex::IsExclusiveHeld(const Thread* self) const {
253 DCHECK(self == NULL || self == Thread::Current());
254 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
255 if (kDebugLocking) {
256 // Sanity debug check that if we think it is locked we have it in our held mutexes.
257 if (result && self != NULL && level_ != kMonitorLock && !gAborting) {
258 CHECK_EQ(self->GetHeldMutex(level_), this);
259 }
260 }
261 return result;
262}
263
264inline uint64_t Mutex::GetExclusiveOwnerTid() const {
265#if ART_USE_FUTEXES
266 return exclusive_owner_;
267#elif defined(__BIONIC__)
268 return static_cast<uint64_t>((mutex_.value >> 16) & 0xffff);
269#elif defined(__GLIBC__)
270 return reinterpret_cast<const glibc_pthread_mutex_t*>(&mutex_)->owner;
271#elif defined(__APPLE__)
272 const darwin_pthread_mutex_t* dpmutex = reinterpret_cast<const darwin_pthread_mutex_t*>(&mutex_);
273 pthread_t owner = dpmutex->darwin_pthread_mutex_owner;
274 // 0 for unowned, -1 for PTHREAD_MTX_TID_SWITCHING
275 // TODO: should we make darwin_pthread_mutex_owner volatile and recheck until not -1?
276 if ((owner == (pthread_t)0) || (owner == (pthread_t)-1)) {
277 return 0;
278 }
279 uint64_t tid;
280 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
281 return tid;
282#else
283#error unsupported C library
284#endif
285}
286
287inline bool ReaderWriterMutex::IsExclusiveHeld(const Thread* self) const {
288 DCHECK(self == NULL || self == Thread::Current());
289 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
290 if (kDebugLocking) {
291 // Sanity that if the pthread thinks we own the lock the Thread agrees.
292 if (self != NULL && result) {
293 CHECK_EQ(self->GetHeldMutex(level_), this);
294 }
295 }
296 return result;
297}
298
299inline uint64_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
300#if ART_USE_FUTEXES
301 int32_t state = state_;
302 if (state == 0) {
303 return 0; // No owner.
304 } else if (state > 0) {
305 return -1; // Shared.
306 } else {
307 return exclusive_owner_;
308 }
309#else
310#if defined(__BIONIC__)
311 return rwlock_.writerThreadId;
312#elif defined(__GLIBC__)
313 return reinterpret_cast<const glibc_pthread_rwlock_t*>(&rwlock_)->writer;
314#elif defined(__APPLE__)
315 const darwin_pthread_rwlock_t*
316 dprwlock = reinterpret_cast<const darwin_pthread_rwlock_t*>(&rwlock_);
317 pthread_t owner = dprwlock->darwin_pthread_rwlock_owner;
318 if (owner == (pthread_t)0) {
319 return 0;
320 }
321 uint64_t tid;
322 CHECK_PTHREAD_CALL(pthread_threadid_np, (owner, &tid), __FUNCTION__); // Requires Mac OS 10.6
323 return tid;
324#else
325#error unsupported C library
326#endif
327#endif
328}
329
Ian Rogers693ff612013-02-01 10:56:12 -0800330} // namespace art
331
Brian Carlstromfc0e3212013-07-17 14:40:12 -0700332#endif // ART_RUNTIME_BASE_MUTEX_INL_H_