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_THREAD_INL_H_
18 #define ART_RUNTIME_THREAD_INL_H_
19
20 #include "thread.h"
21
22 #include "arch/instruction_set.h"
23 #include "base/aborting.h"
24 #include "base/casts.h"
25 #include "base/mutex-inl.h"
26 #include "base/time_utils.h"
27 #include "jni/jni_env_ext.h"
28 #include "managed_stack-inl.h"
29 #include "obj_ptr.h"
30 #include "thread-current-inl.h"
31 #include "thread_pool.h"
32
33 namespace art {
34
35 // Quickly access the current thread from a JNIEnv.
ThreadForEnv(JNIEnv * env)36 static inline Thread* ThreadForEnv(JNIEnv* env) {
37 JNIEnvExt* full_env(down_cast<JNIEnvExt*>(env));
38 return full_env->GetSelf();
39 }
40
AllowThreadSuspension()41 inline void Thread::AllowThreadSuspension() {
42 DCHECK_EQ(Thread::Current(), this);
43 if (UNLIKELY(TestAllFlags())) {
44 CheckSuspend();
45 }
46 // Invalidate the current thread's object pointers (ObjPtr) to catch possible moving GC bugs due
47 // to missing handles.
48 PoisonObjectPointers();
49 }
50
CheckSuspend()51 inline void Thread::CheckSuspend() {
52 DCHECK_EQ(Thread::Current(), this);
53 for (;;) {
54 if (ReadFlag(kCheckpointRequest)) {
55 RunCheckpointFunction();
56 } else if (ReadFlag(kSuspendRequest)) {
57 FullSuspendCheck();
58 } else if (ReadFlag(kEmptyCheckpointRequest)) {
59 RunEmptyCheckpoint();
60 } else {
61 break;
62 }
63 }
64 }
65
CheckEmptyCheckpointFromWeakRefAccess(BaseMutex * cond_var_mutex)66 inline void Thread::CheckEmptyCheckpointFromWeakRefAccess(BaseMutex* cond_var_mutex) {
67 Thread* self = Thread::Current();
68 DCHECK_EQ(self, this);
69 for (;;) {
70 if (ReadFlag(kEmptyCheckpointRequest)) {
71 RunEmptyCheckpoint();
72 // Check we hold only an expected mutex when accessing weak ref.
73 if (kIsDebugBuild) {
74 for (int i = kLockLevelCount - 1; i >= 0; --i) {
75 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
76 if (held_mutex != nullptr &&
77 held_mutex != Locks::mutator_lock_ &&
78 held_mutex != cond_var_mutex) {
79 CHECK(Locks::IsExpectedOnWeakRefAccess(held_mutex))
80 << "Holding unexpected mutex " << held_mutex->GetName()
81 << " when accessing weak ref";
82 }
83 }
84 }
85 } else {
86 break;
87 }
88 }
89 }
90
CheckEmptyCheckpointFromMutex()91 inline void Thread::CheckEmptyCheckpointFromMutex() {
92 DCHECK_EQ(Thread::Current(), this);
93 for (;;) {
94 if (ReadFlag(kEmptyCheckpointRequest)) {
95 RunEmptyCheckpoint();
96 } else {
97 break;
98 }
99 }
100 }
101
SetState(ThreadState new_state)102 inline ThreadState Thread::SetState(ThreadState new_state) {
103 // Should only be used to change between suspended states.
104 // Cannot use this code to change into or from Runnable as changing to Runnable should
105 // fail if old_state_and_flags.suspend_request is true and changing from Runnable might
106 // miss passing an active suspend barrier.
107 DCHECK_NE(new_state, kRunnable);
108 if (kIsDebugBuild && this != Thread::Current()) {
109 std::string name;
110 GetThreadName(name);
111 LOG(FATAL) << "Thread \"" << name << "\"(" << this << " != Thread::Current()="
112 << Thread::Current() << ") changing state to " << new_state;
113 }
114 union StateAndFlags old_state_and_flags;
115 old_state_and_flags.as_int = tls32_.state_and_flags.as_int;
116 CHECK_NE(old_state_and_flags.as_struct.state, kRunnable);
117 tls32_.state_and_flags.as_struct.state = new_state;
118 return static_cast<ThreadState>(old_state_and_flags.as_struct.state);
119 }
120
IsThreadSuspensionAllowable()121 inline bool Thread::IsThreadSuspensionAllowable() const {
122 if (tls32_.no_thread_suspension != 0) {
123 return false;
124 }
125 for (int i = kLockLevelCount - 1; i >= 0; --i) {
126 if (i != kMutatorLock &&
127 i != kUserCodeSuspensionLock &&
128 GetHeldMutex(static_cast<LockLevel>(i)) != nullptr) {
129 return false;
130 }
131 }
132 // Thread autoanalysis isn't able to understand that the GetHeldMutex(...) or AssertHeld means we
133 // have the mutex meaning we need to do this hack.
134 auto is_suspending_for_user_code = [this]() NO_THREAD_SAFETY_ANALYSIS {
135 return tls32_.user_code_suspend_count != 0;
136 };
137 if (GetHeldMutex(kUserCodeSuspensionLock) != nullptr && is_suspending_for_user_code()) {
138 return false;
139 }
140 return true;
141 }
142
AssertThreadSuspensionIsAllowable(bool check_locks)143 inline void Thread::AssertThreadSuspensionIsAllowable(bool check_locks) const {
144 if (kIsDebugBuild) {
145 if (gAborting == 0) {
146 CHECK_EQ(0u, tls32_.no_thread_suspension) << tlsPtr_.last_no_thread_suspension_cause;
147 }
148 if (check_locks) {
149 bool bad_mutexes_held = false;
150 for (int i = kLockLevelCount - 1; i >= 0; --i) {
151 // We expect no locks except the mutator_lock_. User code suspension lock is OK as long as
152 // we aren't going to be held suspended due to SuspendReason::kForUserCode.
153 if (i != kMutatorLock && i != kUserCodeSuspensionLock) {
154 BaseMutex* held_mutex = GetHeldMutex(static_cast<LockLevel>(i));
155 if (held_mutex != nullptr) {
156 LOG(ERROR) << "holding \"" << held_mutex->GetName()
157 << "\" at point where thread suspension is expected";
158 bad_mutexes_held = true;
159 }
160 }
161 }
162 // Make sure that if we hold the user_code_suspension_lock_ we aren't suspending due to
163 // user_code_suspend_count which would prevent the thread from ever waking up. Thread
164 // autoanalysis isn't able to understand that the GetHeldMutex(...) or AssertHeld means we
165 // have the mutex meaning we need to do this hack.
166 auto is_suspending_for_user_code = [this]() NO_THREAD_SAFETY_ANALYSIS {
167 return tls32_.user_code_suspend_count != 0;
168 };
169 if (GetHeldMutex(kUserCodeSuspensionLock) != nullptr && is_suspending_for_user_code()) {
170 LOG(ERROR) << "suspending due to user-code while holding \""
171 << Locks::user_code_suspension_lock_->GetName() << "\"! Thread would never "
172 << "wake up.";
173 bad_mutexes_held = true;
174 }
175 if (gAborting == 0) {
176 CHECK(!bad_mutexes_held);
177 }
178 }
179 }
180 }
181
TransitionToSuspendedAndRunCheckpoints(ThreadState new_state)182 inline void Thread::TransitionToSuspendedAndRunCheckpoints(ThreadState new_state) {
183 DCHECK_NE(new_state, kRunnable);
184 DCHECK_EQ(GetState(), kRunnable);
185 union StateAndFlags old_state_and_flags;
186 union StateAndFlags new_state_and_flags;
187 while (true) {
188 old_state_and_flags.as_int = tls32_.state_and_flags.as_int;
189 if (UNLIKELY((old_state_and_flags.as_struct.flags & kCheckpointRequest) != 0)) {
190 RunCheckpointFunction();
191 continue;
192 }
193 if (UNLIKELY((old_state_and_flags.as_struct.flags & kEmptyCheckpointRequest) != 0)) {
194 RunEmptyCheckpoint();
195 continue;
196 }
197 // Change the state but keep the current flags (kCheckpointRequest is clear).
198 DCHECK_EQ((old_state_and_flags.as_struct.flags & kCheckpointRequest), 0);
199 DCHECK_EQ((old_state_and_flags.as_struct.flags & kEmptyCheckpointRequest), 0);
200 new_state_and_flags.as_struct.flags = old_state_and_flags.as_struct.flags;
201 new_state_and_flags.as_struct.state = new_state;
202
203 // CAS the value with a memory ordering.
204 bool done =
205 tls32_.state_and_flags.as_atomic_int.CompareAndSetWeakRelease(old_state_and_flags.as_int,
206 new_state_and_flags.as_int);
207 if (LIKELY(done)) {
208 break;
209 }
210 }
211 }
212
PassActiveSuspendBarriers()213 inline void Thread::PassActiveSuspendBarriers() {
214 while (true) {
215 uint16_t current_flags = tls32_.state_and_flags.as_struct.flags;
216 if (LIKELY((current_flags &
217 (kCheckpointRequest | kEmptyCheckpointRequest | kActiveSuspendBarrier)) == 0)) {
218 break;
219 } else if ((current_flags & kActiveSuspendBarrier) != 0) {
220 PassActiveSuspendBarriers(this);
221 } else {
222 // Impossible
223 LOG(FATAL) << "Fatal, thread transitioned into suspended without running the checkpoint";
224 }
225 }
226 }
227
TransitionFromRunnableToSuspended(ThreadState new_state)228 inline void Thread::TransitionFromRunnableToSuspended(ThreadState new_state) {
229 AssertThreadSuspensionIsAllowable();
230 PoisonObjectPointersIfDebug();
231 DCHECK_EQ(this, Thread::Current());
232 // Change to non-runnable state, thereby appearing suspended to the system.
233 TransitionToSuspendedAndRunCheckpoints(new_state);
234 // Mark the release of the share of the mutator_lock_.
235 Locks::mutator_lock_->TransitionFromRunnableToSuspended(this);
236 // Once suspended - check the active suspend barrier flag
237 PassActiveSuspendBarriers();
238 }
239
TransitionFromSuspendedToRunnable()240 inline ThreadState Thread::TransitionFromSuspendedToRunnable() {
241 union StateAndFlags old_state_and_flags;
242 old_state_and_flags.as_int = tls32_.state_and_flags.as_int;
243 int16_t old_state = old_state_and_flags.as_struct.state;
244 DCHECK_NE(static_cast<ThreadState>(old_state), kRunnable);
245 do {
246 Locks::mutator_lock_->AssertNotHeld(this); // Otherwise we starve GC..
247 old_state_and_flags.as_int = tls32_.state_and_flags.as_int;
248 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
249 if (LIKELY(old_state_and_flags.as_struct.flags == 0)) {
250 // Optimize for the return from native code case - this is the fast path.
251 // Atomically change from suspended to runnable if no suspend request pending.
252 union StateAndFlags new_state_and_flags;
253 new_state_and_flags.as_int = old_state_and_flags.as_int;
254 new_state_and_flags.as_struct.state = kRunnable;
255
256 // CAS the value with a memory barrier.
257 if (LIKELY(tls32_.state_and_flags.as_atomic_int.CompareAndSetWeakAcquire(
258 old_state_and_flags.as_int,
259 new_state_and_flags.as_int))) {
260 // Mark the acquisition of a share of the mutator_lock_.
261 Locks::mutator_lock_->TransitionFromSuspendedToRunnable(this);
262 break;
263 }
264 } else if ((old_state_and_flags.as_struct.flags & kActiveSuspendBarrier) != 0) {
265 PassActiveSuspendBarriers(this);
266 } else if ((old_state_and_flags.as_struct.flags &
267 (kCheckpointRequest | kEmptyCheckpointRequest)) != 0) {
268 // Impossible
269 LOG(FATAL) << "Transitioning to runnable with checkpoint flag, "
270 << " flags=" << old_state_and_flags.as_struct.flags
271 << " state=" << old_state_and_flags.as_struct.state;
272 } else if ((old_state_and_flags.as_struct.flags & kSuspendRequest) != 0) {
273 // Wait while our suspend count is non-zero.
274
275 // We pass null to the MutexLock as we may be in a situation where the
276 // runtime is shutting down. Guarding ourselves from that situation
277 // requires to take the shutdown lock, which is undesirable here.
278 Thread* thread_to_pass = nullptr;
279 if (kIsDebugBuild && !IsDaemon()) {
280 // We know we can make our debug locking checks on non-daemon threads,
281 // so re-enable them on debug builds.
282 thread_to_pass = this;
283 }
284 MutexLock mu(thread_to_pass, *Locks::thread_suspend_count_lock_);
285 ScopedTransitioningToRunnable scoped_transitioning_to_runnable(this);
286 old_state_and_flags.as_int = tls32_.state_and_flags.as_int;
287 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
288 while ((old_state_and_flags.as_struct.flags & kSuspendRequest) != 0) {
289 // Re-check when Thread::resume_cond_ is notified.
290 Thread::resume_cond_->Wait(thread_to_pass);
291 old_state_and_flags.as_int = tls32_.state_and_flags.as_int;
292 DCHECK_EQ(old_state_and_flags.as_struct.state, old_state);
293 }
294 DCHECK_EQ(GetSuspendCount(), 0);
295 }
296 } while (true);
297 // Run the flip function, if set.
298 Closure* flip_func = GetFlipFunction();
299 if (flip_func != nullptr) {
300 flip_func->Run(this);
301 }
302 return static_cast<ThreadState>(old_state);
303 }
304
AllocTlab(size_t bytes)305 inline mirror::Object* Thread::AllocTlab(size_t bytes) {
306 DCHECK_GE(TlabSize(), bytes);
307 ++tlsPtr_.thread_local_objects;
308 mirror::Object* ret = reinterpret_cast<mirror::Object*>(tlsPtr_.thread_local_pos);
309 tlsPtr_.thread_local_pos += bytes;
310 return ret;
311 }
312
PushOnThreadLocalAllocationStack(mirror::Object * obj)313 inline bool Thread::PushOnThreadLocalAllocationStack(mirror::Object* obj) {
314 DCHECK_LE(tlsPtr_.thread_local_alloc_stack_top, tlsPtr_.thread_local_alloc_stack_end);
315 if (tlsPtr_.thread_local_alloc_stack_top < tlsPtr_.thread_local_alloc_stack_end) {
316 // There's room.
317 DCHECK_LE(reinterpret_cast<uint8_t*>(tlsPtr_.thread_local_alloc_stack_top) +
318 sizeof(StackReference<mirror::Object>),
319 reinterpret_cast<uint8_t*>(tlsPtr_.thread_local_alloc_stack_end));
320 DCHECK(tlsPtr_.thread_local_alloc_stack_top->AsMirrorPtr() == nullptr);
321 tlsPtr_.thread_local_alloc_stack_top->Assign(obj);
322 ++tlsPtr_.thread_local_alloc_stack_top;
323 return true;
324 }
325 return false;
326 }
327
SetThreadLocalAllocationStack(StackReference<mirror::Object> * start,StackReference<mirror::Object> * end)328 inline void Thread::SetThreadLocalAllocationStack(StackReference<mirror::Object>* start,
329 StackReference<mirror::Object>* end) {
330 DCHECK(Thread::Current() == this) << "Should be called by self";
331 DCHECK(start != nullptr);
332 DCHECK(end != nullptr);
333 DCHECK_ALIGNED(start, sizeof(StackReference<mirror::Object>));
334 DCHECK_ALIGNED(end, sizeof(StackReference<mirror::Object>));
335 DCHECK_LT(start, end);
336 tlsPtr_.thread_local_alloc_stack_end = end;
337 tlsPtr_.thread_local_alloc_stack_top = start;
338 }
339
RevokeThreadLocalAllocationStack()340 inline void Thread::RevokeThreadLocalAllocationStack() {
341 if (kIsDebugBuild) {
342 // Note: self is not necessarily equal to this thread since thread may be suspended.
343 Thread* self = Thread::Current();
344 DCHECK(this == self || IsSuspended() || GetState() == kWaitingPerformingGc)
345 << GetState() << " thread " << this << " self " << self;
346 }
347 tlsPtr_.thread_local_alloc_stack_end = nullptr;
348 tlsPtr_.thread_local_alloc_stack_top = nullptr;
349 }
350
PoisonObjectPointersIfDebug()351 inline void Thread::PoisonObjectPointersIfDebug() {
352 if (kObjPtrPoisoning) {
353 Thread::Current()->PoisonObjectPointers();
354 }
355 }
356
ModifySuspendCount(Thread * self,int delta,AtomicInteger * suspend_barrier,SuspendReason reason)357 inline bool Thread::ModifySuspendCount(Thread* self,
358 int delta,
359 AtomicInteger* suspend_barrier,
360 SuspendReason reason) {
361 if (delta > 0 && ((kUseReadBarrier && this != self) || suspend_barrier != nullptr)) {
362 // When delta > 0 (requesting a suspend), ModifySuspendCountInternal() may fail either if
363 // active_suspend_barriers is full or we are in the middle of a thread flip. Retry in a loop.
364 while (true) {
365 if (LIKELY(ModifySuspendCountInternal(self, delta, suspend_barrier, reason))) {
366 return true;
367 } else {
368 // Failure means the list of active_suspend_barriers is full or we are in the middle of a
369 // thread flip, we should release the thread_suspend_count_lock_ (to avoid deadlock) and
370 // wait till the target thread has executed or Thread::PassActiveSuspendBarriers() or the
371 // flip function. Note that we could not simply wait for the thread to change to a suspended
372 // state, because it might need to run checkpoint function before the state change or
373 // resumes from the resume_cond_, which also needs thread_suspend_count_lock_.
374 //
375 // The list of active_suspend_barriers is very unlikely to be full since more than
376 // kMaxSuspendBarriers threads need to execute SuspendAllInternal() simultaneously, and
377 // target thread stays in kRunnable in the mean time.
378 Locks::thread_suspend_count_lock_->ExclusiveUnlock(self);
379 NanoSleep(100000);
380 Locks::thread_suspend_count_lock_->ExclusiveLock(self);
381 }
382 }
383 } else {
384 return ModifySuspendCountInternal(self, delta, suspend_barrier, reason);
385 }
386 }
387
PushShadowFrame(ShadowFrame * new_top_frame)388 inline ShadowFrame* Thread::PushShadowFrame(ShadowFrame* new_top_frame) {
389 new_top_frame->CheckConsistentVRegs();
390 return tlsPtr_.managed_stack.PushShadowFrame(new_top_frame);
391 }
392
PopShadowFrame()393 inline ShadowFrame* Thread::PopShadowFrame() {
394 return tlsPtr_.managed_stack.PopShadowFrame();
395 }
396
GetStackEndForInterpreter(bool implicit_overflow_check)397 inline uint8_t* Thread::GetStackEndForInterpreter(bool implicit_overflow_check) const {
398 uint8_t* end = tlsPtr_.stack_end + (implicit_overflow_check
399 ? GetStackOverflowReservedBytes(kRuntimeISA)
400 : 0);
401 if (kIsDebugBuild) {
402 // In a debuggable build, but especially under ASAN, the access-checks interpreter has a
403 // potentially humongous stack size. We don't want to take too much of the stack regularly,
404 // so do not increase the regular reserved size (for compiled code etc) and only report the
405 // virtually smaller stack to the interpreter here.
406 end += GetStackOverflowReservedBytes(kRuntimeISA);
407 }
408 return end;
409 }
410
ResetDefaultStackEnd()411 inline void Thread::ResetDefaultStackEnd() {
412 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
413 // to throw a StackOverflowError.
414 tlsPtr_.stack_end = tlsPtr_.stack_begin + GetStackOverflowReservedBytes(kRuntimeISA);
415 }
416
417 } // namespace art
418
419 #endif // ART_RUNTIME_THREAD_INL_H_
420