blob: 3e5cdbadba2d2137c78c36692dc659bc57b24a17 [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
Hiroshi Yamauchib3733082013-08-12 17:28:49 -070026#include "cutils/trace.h"
Ian Rogers576ca0c2014-06-06 15:58:22 -070027
28#include "base/stringprintf.h"
Ian Rogers693ff612013-02-01 10:56:12 -080029#include "runtime.h"
30#include "thread.h"
31
32namespace art {
33
34#define CHECK_MUTEX_CALL(call, args) CHECK_PTHREAD_CALL(call, args, name_)
35
36#if ART_USE_FUTEXES
37#include "linux/futex.h"
38#include "sys/syscall.h"
39#ifndef SYS_futex
40#define SYS_futex __NR_futex
41#endif
42static inline int futex(volatile int *uaddr, int op, int val, const struct timespec *timeout, volatile int *uaddr2, int val3) {
43 return syscall(SYS_futex, uaddr, op, val, timeout, uaddr2, val3);
44}
45#endif // ART_USE_FUTEXES
46
47class ScopedContentionRecorder {
48 public:
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070049 ScopedContentionRecorder(BaseMutex* mutex, uint64_t blocked_tid, uint64_t owner_tid)
50 : mutex_(kLogLockContentions ? mutex : NULL),
51 blocked_tid_(kLogLockContentions ? blocked_tid : 0),
52 owner_tid_(kLogLockContentions ? owner_tid : 0),
53 start_nano_time_(kLogLockContentions ? NanoTime() : 0) {
Ian Rogers220228e2014-01-23 09:08:16 -080054 std::string msg = StringPrintf("Lock contention on %s (owner tid: %" PRIu64 ")",
Jeff Hao08f2e7b2013-09-09 16:44:02 -070055 mutex->GetName(), owner_tid);
56 ATRACE_BEGIN(msg.c_str());
Ian Rogers693ff612013-02-01 10:56:12 -080057 }
58
59 ~ScopedContentionRecorder() {
Jeff Hao08f2e7b2013-09-09 16:44:02 -070060 ATRACE_END();
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070061 if (kLogLockContentions) {
62 uint64_t end_nano_time = NanoTime();
63 mutex_->RecordContention(blocked_tid_, owner_tid_, end_nano_time - start_nano_time_);
64 }
Ian Rogers693ff612013-02-01 10:56:12 -080065 }
66
67 private:
68 BaseMutex* const mutex_;
Ian Rogersc0fa3ad2013-02-05 00:11:55 -080069 const uint64_t blocked_tid_;
70 const uint64_t owner_tid_;
Hiroshi Yamauchi1afde132013-08-06 17:09:30 -070071 const uint64_t start_nano_time_;
Ian Rogers693ff612013-02-01 10:56:12 -080072};
73
74static inline uint64_t SafeGetTid(const Thread* self) {
75 if (self != NULL) {
76 return static_cast<uint64_t>(self->GetTid());
77 } else {
78 return static_cast<uint64_t>(GetTid());
79 }
80}
81
82static inline void CheckUnattachedThread(LockLevel level) NO_THREAD_SAFETY_ANALYSIS {
83 // The check below enumerates the cases where we expect not to be able to sanity check locks
84 // on a thread. Lock checking is disabled to avoid deadlock when checking shutdown lock.
85 // TODO: tighten this check.
86 if (kDebugLocking) {
87 Runtime* runtime = Runtime::Current();
Chao-ying Fu9e369312014-05-21 11:20:52 -070088 CHECK(runtime == nullptr || !runtime->IsStarted() || runtime->IsShuttingDownLocked() ||
89 // Used during thread creation to avoid races with runtime shutdown. Thread::Current not
90 // yet established.
91 level == kRuntimeShutdownLock ||
92 // Thread Ids are allocated/released before threads are established.
93 level == kAllocatedThreadIdsLock ||
94 // Thread LDT's are initialized without Thread::Current established.
95 level == kModifyLdtLock ||
96 // Threads are unregistered while holding the thread list lock, during this process they
97 // no longer exist and so we expect an unlock with no self.
98 level == kThreadListLock ||
99 // Ignore logging which may or may not have set up thread data structures.
100 level == kLoggingLock ||
101 // Avoid recursive death.
Ian Rogers06abcdf2014-05-23 11:39:11 -0700102 level == kAbortLock) << level;
Ian Rogers693ff612013-02-01 10:56:12 -0800103 }
104}
105
Ian Rogersb6c31ea2013-02-04 18:11:33 -0800106inline void BaseMutex::RegisterAsLocked(Thread* self) {
107 if (UNLIKELY(self == NULL)) {
108 CheckUnattachedThread(level_);
109 return;
110 }
111 if (kDebugLocking) {
112 // Check if a bad Mutex of this level or lower is held.
113 bool bad_mutexes_held = false;
114 for (int i = level_; i >= 0; --i) {
115 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
116 if (UNLIKELY(held_mutex != NULL)) {
Elliott Hughes0f827162013-02-26 12:12:58 -0800117 LOG(ERROR) << "Lock level violation: holding \"" << held_mutex->name_ << "\" "
Ian Rogers62d6c772013-02-27 08:32:07 -0800118 << "(level " << LockLevel(i) << " - " << i
119 << ") while locking \"" << name_ << "\" "
120 << "(level " << level_ << " - " << static_cast<int>(level_) << ")";
Ian Rogersb6c31ea2013-02-04 18:11:33 -0800121 if (i > kAbortLock) {
122 // Only abort in the check below if this is more than abort level lock.
123 bad_mutexes_held = true;
124 }
125 }
126 }
127 CHECK(!bad_mutexes_held);
128 }
129 // Don't record monitors as they are outside the scope of analysis. They may be inspected off of
130 // the monitor list.
131 if (level_ != kMonitorLock) {
132 self->SetHeldMutex(level_, this);
133 }
134}
135
Ian Rogers693ff612013-02-01 10:56:12 -0800136inline void BaseMutex::RegisterAsUnlocked(Thread* self) {
137 if (UNLIKELY(self == NULL)) {
138 CheckUnattachedThread(level_);
139 return;
140 }
141 if (level_ != kMonitorLock) {
142 if (kDebugLocking && !gAborting) {
143 CHECK(self->GetHeldMutex(level_) == this) << "Unlocking on unacquired mutex: " << name_;
144 }
145 self->SetHeldMutex(level_, NULL);
146 }
147}
148
149inline void ReaderWriterMutex::SharedLock(Thread* self) {
150 DCHECK(self == NULL || self == Thread::Current());
151#if ART_USE_FUTEXES
152 bool done = false;
153 do {
Ian Rogersc7190692014-07-08 23:50:26 -0700154 int32_t cur_state = state_.LoadRelaxed();
Ian Rogersc0fa3ad2013-02-05 00:11:55 -0800155 if (LIKELY(cur_state >= 0)) {
Ian Rogers693ff612013-02-01 10:56:12 -0800156 // Add as an extra reader.
Ian Rogersc7190692014-07-08 23:50:26 -0700157 done = state_.CompareExchangeWeakAcquire(cur_state, cur_state + 1);
Ian Rogers693ff612013-02-01 10:56:12 -0800158 } else {
159 // Owner holds it exclusively, hang up.
160 ScopedContentionRecorder scr(this, GetExclusiveOwnerTid(), SafeGetTid(self));
Ian Rogersc7190692014-07-08 23:50:26 -0700161 ++num_pending_readers_;
162 if (futex(state_.Address(), FUTEX_WAIT, cur_state, NULL, NULL, 0) != 0) {
Ian Rogers693ff612013-02-01 10:56:12 -0800163 if (errno != EAGAIN) {
164 PLOG(FATAL) << "futex wait failed for " << name_;
165 }
166 }
Ian Rogersc7190692014-07-08 23:50:26 -0700167 --num_pending_readers_;
Ian Rogers693ff612013-02-01 10:56:12 -0800168 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700169 } while (!done);
Ian Rogers693ff612013-02-01 10:56:12 -0800170#else
171 CHECK_MUTEX_CALL(pthread_rwlock_rdlock, (&rwlock_));
172#endif
Ian Rogersc5f17732014-06-05 20:48:42 -0700173 DCHECK(exclusive_owner_ == 0U || exclusive_owner_ == -1U);
Ian Rogers693ff612013-02-01 10:56:12 -0800174 RegisterAsLocked(self);
175 AssertSharedHeld(self);
176}
177
178inline void ReaderWriterMutex::SharedUnlock(Thread* self) {
179 DCHECK(self == NULL || self == Thread::Current());
Ian Rogersc5f17732014-06-05 20:48:42 -0700180 DCHECK(exclusive_owner_ == 0U || exclusive_owner_ == -1U);
Ian Rogers693ff612013-02-01 10:56:12 -0800181 AssertSharedHeld(self);
182 RegisterAsUnlocked(self);
183#if ART_USE_FUTEXES
184 bool done = false;
185 do {
Ian Rogersc7190692014-07-08 23:50:26 -0700186 int32_t cur_state = state_.LoadRelaxed();
Ian Rogers693ff612013-02-01 10:56:12 -0800187 if (LIKELY(cur_state > 0)) {
Ian Rogersc7190692014-07-08 23:50:26 -0700188 // Reduce state by 1 and impose lock release load/store ordering.
189 // Note, the relaxed loads below musn't reorder before the CompareExchange.
190 // TODO: the ordering here is non-trivial as state is split across 3 fields, fix by placing
191 // a status bit into the state on contention.
192 done = state_.CompareExchangeWeakSequentiallyConsistent(cur_state, cur_state - 1);
193 if (done && (cur_state - 1) == 0) { // Weak CAS may fail spuriously.
194 if (num_pending_writers_.LoadRelaxed() > 0 ||
195 num_pending_readers_.LoadRelaxed() > 0) {
Ian Rogers693ff612013-02-01 10:56:12 -0800196 // Wake any exclusive waiters as there are now no readers.
Ian Rogersc7190692014-07-08 23:50:26 -0700197 futex(state_.Address(), FUTEX_WAKE, -1, NULL, NULL, 0);
Ian Rogers693ff612013-02-01 10:56:12 -0800198 }
199 }
200 } else {
201 LOG(FATAL) << "Unexpected state_:" << cur_state << " for " << name_;
202 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700203 } while (!done);
Ian Rogers693ff612013-02-01 10:56:12 -0800204#else
205 CHECK_MUTEX_CALL(pthread_rwlock_unlock, (&rwlock_));
206#endif
207}
208
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700209inline bool Mutex::IsExclusiveHeld(const Thread* self) const {
210 DCHECK(self == NULL || self == Thread::Current());
211 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
212 if (kDebugLocking) {
213 // Sanity debug check that if we think it is locked we have it in our held mutexes.
214 if (result && self != NULL && level_ != kMonitorLock && !gAborting) {
215 CHECK_EQ(self->GetHeldMutex(level_), this);
216 }
217 }
218 return result;
219}
220
221inline uint64_t Mutex::GetExclusiveOwnerTid() const {
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700222 return exclusive_owner_;
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700223}
224
225inline bool ReaderWriterMutex::IsExclusiveHeld(const Thread* self) const {
226 DCHECK(self == NULL || self == Thread::Current());
227 bool result = (GetExclusiveOwnerTid() == SafeGetTid(self));
228 if (kDebugLocking) {
229 // Sanity that if the pthread thinks we own the lock the Thread agrees.
230 if (self != NULL && result) {
231 CHECK_EQ(self->GetHeldMutex(level_), this);
232 }
233 }
234 return result;
235}
236
237inline uint64_t ReaderWriterMutex::GetExclusiveOwnerTid() const {
238#if ART_USE_FUTEXES
Ian Rogersc7190692014-07-08 23:50:26 -0700239 int32_t state = state_.LoadRelaxed();
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700240 if (state == 0) {
241 return 0; // No owner.
242 } else if (state > 0) {
243 return -1; // Shared.
244 } else {
245 return exclusive_owner_;
246 }
247#else
Ian Rogersc5f17732014-06-05 20:48:42 -0700248 return exclusive_owner_;
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -0700249#endif
250}
251
Ian Rogers693ff612013-02-01 10:56:12 -0800252} // namespace art
253
Brian Carlstromfc0e3212013-07-17 14:40:12 -0700254#endif // ART_RUNTIME_BASE_MUTEX_INL_H_