blob: 324cd3787aea95e0e278b54e18fc6ccecdcb7ca4 [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_THREAD_INL_H_
18#define ART_RUNTIME_THREAD_INL_H_
Ian Rogers693ff612013-02-01 10:56:12 -080019
20#include "thread.h"
21
Andreas Gampe639b2b12019-01-08 10:32:50 -080022#include "arch/instruction_set.h"
Andreas Gampe39b378c2017-12-07 15:44:13 -080023#include "base/aborting.h"
Ian Rogers1eb512d2013-10-18 15:42:20 -070024#include "base/casts.h"
Ian Rogers693ff612013-02-01 10:56:12 -080025#include "base/mutex-inl.h"
Andreas Gamped4901292017-05-30 18:41:34 -070026#include "base/time_utils.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010027#include "jni/jni_env_ext.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070028#include "managed_stack-inl.h"
Andreas Gampec73cb642017-02-22 10:11:30 -080029#include "obj_ptr.h"
Andreas Gampe0c2313c2019-05-14 09:47:00 -070030#include "suspend_reason.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070031#include "thread-current-inl.h"
Mathieu Chartier3cf22532015-07-09 15:15:09 -070032#include "thread_pool.h"
Ian Rogers693ff612013-02-01 10:56:12 -080033
34namespace art {
35
Ian Rogers1eb512d2013-10-18 15:42:20 -070036// Quickly access the current thread from a JNIEnv.
37static inline Thread* ThreadForEnv(JNIEnv* env) {
38 JNIEnvExt* full_env(down_cast<JNIEnvExt*>(env));
Ian Rogers55256cb2017-12-21 17:07:11 -080039 return full_env->GetSelf();
Ian Rogers1eb512d2013-10-18 15:42:20 -070040}
41
Ian Rogers7b078e82014-09-10 14:44:24 -070042inline void Thread::AllowThreadSuspension() {
Vladimir Marko254a8582021-11-29 14:08:37 +000043 CheckSuspend();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -070044 // Invalidate the current thread's object pointers (ObjPtr) to catch possible moving GC bugs due
45 // to missing handles.
Mathieu Chartier3f7f03c2016-09-26 11:39:52 -070046 PoisonObjectPointers();
Ian Rogers7b078e82014-09-10 14:44:24 -070047}
48
Vladimir Markoe45883e2022-01-11 12:38:35 +000049inline void Thread::CheckSuspend(bool implicit) {
Ian Rogers7b078e82014-09-10 14:44:24 -070050 DCHECK_EQ(Thread::Current(), this);
Vladimir Marko254a8582021-11-29 14:08:37 +000051 while (true) {
Vladimir Marko9c0f7642021-12-06 16:17:52 +000052 StateAndFlags state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
Vladimir Marko254a8582021-11-29 14:08:37 +000053 if (LIKELY(!state_and_flags.IsAnyOfFlagsSet(SuspendOrCheckpointRequestFlags()))) {
54 break;
55 } else if (state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest)) {
Ian Rogers7b078e82014-09-10 14:44:24 -070056 RunCheckpointFunction();
Vladimir Markoddf4fd32021-11-22 16:31:57 +000057 } else if (state_and_flags.IsFlagSet(ThreadFlag::kSuspendRequest)) {
Vladimir Markoe45883e2022-01-11 12:38:35 +000058 FullSuspendCheck(implicit);
59 implicit = false; // We do not need to `MadviseAwayAlternateSignalStack()` anymore.
Hiroshi Yamauchi30493242016-11-03 13:06:52 -070060 } else {
Vladimir Marko254a8582021-11-29 14:08:37 +000061 DCHECK(state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest));
62 RunEmptyCheckpoint();
Hiroshi Yamauchi30493242016-11-03 13:06:52 -070063 }
64 }
Vladimir Markoe45883e2022-01-11 12:38:35 +000065 if (implicit) {
66 // For implicit suspend check we want to `madvise()` away
67 // the alternate signal stack to avoid wasting memory.
68 MadviseAwayAlternateSignalStack();
69 }
Hiroshi Yamauchi30493242016-11-03 13:06:52 -070070}
71
Hiroshi Yamauchia2224042017-02-08 16:35:45 -080072inline void Thread::CheckEmptyCheckpointFromWeakRefAccess(BaseMutex* cond_var_mutex) {
73 Thread* self = Thread::Current();
74 DCHECK_EQ(self, this);
75 for (;;) {
Vladimir Markoddf4fd32021-11-22 16:31:57 +000076 if (ReadFlag(ThreadFlag::kEmptyCheckpointRequest)) {
Hiroshi Yamauchia2224042017-02-08 16:35:45 -080077 RunEmptyCheckpoint();
78 // Check we hold only an expected mutex when accessing weak ref.
79 if (kIsDebugBuild) {
80 for (int i = kLockLevelCount - 1; i >= 0; --i) {
81 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
82 if (held_mutex != nullptr &&
Vladimir Marko23cf32f2021-11-15 13:38:02 +000083 held_mutex != GetMutatorLock() &&
Hiroshi Yamauchia2224042017-02-08 16:35:45 -080084 held_mutex != cond_var_mutex) {
Hiroshi Yamauchi8a433242017-03-07 14:39:22 -080085 CHECK(Locks::IsExpectedOnWeakRefAccess(held_mutex))
Hiroshi Yamauchia2224042017-02-08 16:35:45 -080086 << "Holding unexpected mutex " << held_mutex->GetName()
87 << " when accessing weak ref";
88 }
89 }
90 }
91 } else {
92 break;
93 }
94 }
95}
96
97inline void Thread::CheckEmptyCheckpointFromMutex() {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -070098 DCHECK_EQ(Thread::Current(), this);
99 for (;;) {
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000100 if (ReadFlag(ThreadFlag::kEmptyCheckpointRequest)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700101 RunEmptyCheckpoint();
Ian Rogers7b078e82014-09-10 14:44:24 -0700102 } else {
103 break;
104 }
105 }
106}
107
Ian Rogersc0fa3ad2013-02-05 00:11:55 -0800108inline ThreadState Thread::SetState(ThreadState new_state) {
Yu Lieac44242015-06-29 10:50:03 +0800109 // Should only be used to change between suspended states.
110 // Cannot use this code to change into or from Runnable as changing to Runnable should
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000111 // fail if the `ThreadFlag::kSuspendRequest` is set and changing from Runnable might
Yu Lieac44242015-06-29 10:50:03 +0800112 // miss passing an active suspend barrier.
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000113 DCHECK_NE(new_state, ThreadState::kRunnable);
Andreas Gampeef048f62014-11-25 22:12:27 -0800114 if (kIsDebugBuild && this != Thread::Current()) {
115 std::string name;
116 GetThreadName(name);
117 LOG(FATAL) << "Thread \"" << name << "\"(" << this << " != Thread::Current()="
118 << Thread::Current() << ") changing state to " << new_state;
119 }
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000120
121 while (true) {
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000122 StateAndFlags old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000123 CHECK_NE(old_state_and_flags.GetState(), ThreadState::kRunnable)
124 << new_state << " " << *this << " " << *Thread::Current();
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000125 StateAndFlags new_state_and_flags = old_state_and_flags.WithState(new_state);
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000126 bool done =
127 tls32_.state_and_flags.CompareAndSetWeakRelaxed(old_state_and_flags.GetValue(),
128 new_state_and_flags.GetValue());
129 if (done) {
130 return static_cast<ThreadState>(old_state_and_flags.GetState());
131 }
132 }
Ian Rogersc0fa3ad2013-02-05 00:11:55 -0800133}
134
Mathieu Chartier10b218d2016-07-25 17:48:52 -0700135inline bool Thread::IsThreadSuspensionAllowable() const {
136 if (tls32_.no_thread_suspension != 0) {
137 return false;
138 }
139 for (int i = kLockLevelCount - 1; i >= 0; --i) {
Alex Light88fd7202017-06-30 08:31:59 -0700140 if (i != kMutatorLock &&
141 i != kUserCodeSuspensionLock &&
142 GetHeldMutex(static_cast<LockLevel>(i)) != nullptr) {
Mathieu Chartier10b218d2016-07-25 17:48:52 -0700143 return false;
144 }
145 }
Alex Light88fd7202017-06-30 08:31:59 -0700146 // Thread autoanalysis isn't able to understand that the GetHeldMutex(...) or AssertHeld means we
147 // have the mutex meaning we need to do this hack.
148 auto is_suspending_for_user_code = [this]() NO_THREAD_SAFETY_ANALYSIS {
149 return tls32_.user_code_suspend_count != 0;
150 };
151 if (GetHeldMutex(kUserCodeSuspensionLock) != nullptr && is_suspending_for_user_code()) {
152 return false;
153 }
Mathieu Chartier10b218d2016-07-25 17:48:52 -0700154 return true;
155}
156
Ian Rogers693ff612013-02-01 10:56:12 -0800157inline void Thread::AssertThreadSuspensionIsAllowable(bool check_locks) const {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700158 if (kIsDebugBuild) {
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000159 if (gAborting == 0) {
160 CHECK_EQ(0u, tls32_.no_thread_suspension) << tlsPtr_.last_no_thread_suspension_cause;
161 }
Ian Rogersf3d874c2014-07-17 18:52:42 -0700162 if (check_locks) {
163 bool bad_mutexes_held = false;
164 for (int i = kLockLevelCount - 1; i >= 0; --i) {
Vladimir Marko23cf32f2021-11-15 13:38:02 +0000165 // We expect no locks except the mutator lock. User code suspension lock is OK as long as
Alex Light88fd7202017-06-30 08:31:59 -0700166 // we aren't going to be held suspended due to SuspendReason::kForUserCode.
167 if (i != kMutatorLock && i != kUserCodeSuspensionLock) {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700168 BaseMutex* held_mutex = GetHeldMutex(static_cast<LockLevel>(i));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700169 if (held_mutex != nullptr) {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700170 LOG(ERROR) << "holding \"" << held_mutex->GetName()
171 << "\" at point where thread suspension is expected";
172 bad_mutexes_held = true;
173 }
Ian Rogers693ff612013-02-01 10:56:12 -0800174 }
175 }
Alex Light88fd7202017-06-30 08:31:59 -0700176 // Make sure that if we hold the user_code_suspension_lock_ we aren't suspending due to
177 // user_code_suspend_count which would prevent the thread from ever waking up. Thread
178 // autoanalysis isn't able to understand that the GetHeldMutex(...) or AssertHeld means we
179 // have the mutex meaning we need to do this hack.
180 auto is_suspending_for_user_code = [this]() NO_THREAD_SAFETY_ANALYSIS {
181 return tls32_.user_code_suspend_count != 0;
182 };
183 if (GetHeldMutex(kUserCodeSuspensionLock) != nullptr && is_suspending_for_user_code()) {
184 LOG(ERROR) << "suspending due to user-code while holding \""
185 << Locks::user_code_suspension_lock_->GetName() << "\"! Thread would never "
186 << "wake up.";
187 bad_mutexes_held = true;
188 }
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000189 if (gAborting == 0) {
190 CHECK(!bad_mutexes_held);
191 }
Ian Rogers693ff612013-02-01 10:56:12 -0800192 }
Ian Rogers693ff612013-02-01 10:56:12 -0800193 }
Ian Rogers693ff612013-02-01 10:56:12 -0800194}
195
Mathieu Chartier8ac9c912015-10-01 15:58:41 -0700196inline void Thread::TransitionToSuspendedAndRunCheckpoints(ThreadState new_state) {
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000197 DCHECK_NE(new_state, ThreadState::kRunnable);
Dave Allison0f5f6bb2013-11-22 17:39:19 -0800198 while (true) {
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000199 StateAndFlags old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000200 DCHECK_EQ(old_state_and_flags.GetState(), ThreadState::kRunnable);
201 if (UNLIKELY(old_state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest))) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700202 RunCheckpointFunction();
203 continue;
204 }
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000205 if (UNLIKELY(old_state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700206 RunEmptyCheckpoint();
207 continue;
208 }
Dave Allison0f5f6bb2013-11-22 17:39:19 -0800209 // Change the state but keep the current flags (kCheckpointRequest is clear).
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000210 DCHECK(!old_state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest));
211 DCHECK(!old_state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest));
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000212 StateAndFlags new_state_and_flags = old_state_and_flags.WithState(new_state);
Ian Rogersb8e087e2014-07-09 21:12:06 -0700213
Hans Boehm891cb882020-07-31 12:06:58 -0700214 // CAS the value, ensuring that prior memory operations are visible to any thread
215 // that observes that we are suspended.
Ian Rogersb8e087e2014-07-09 21:12:06 -0700216 bool done =
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000217 tls32_.state_and_flags.CompareAndSetWeakRelease(old_state_and_flags.GetValue(),
218 new_state_and_flags.GetValue());
Ian Rogersb8e087e2014-07-09 21:12:06 -0700219 if (LIKELY(done)) {
Dave Allison0f5f6bb2013-11-22 17:39:19 -0800220 break;
221 }
222 }
Mathieu Chartier8ac9c912015-10-01 15:58:41 -0700223}
Yu Lieac44242015-06-29 10:50:03 +0800224
Mathieu Chartier8ac9c912015-10-01 15:58:41 -0700225inline void Thread::PassActiveSuspendBarriers() {
Yu Lieac44242015-06-29 10:50:03 +0800226 while (true) {
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000227 StateAndFlags state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000228 if (LIKELY(!state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest) &&
229 !state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest) &&
230 !state_and_flags.IsFlagSet(ThreadFlag::kActiveSuspendBarrier))) {
Yu Lieac44242015-06-29 10:50:03 +0800231 break;
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000232 } else if (state_and_flags.IsFlagSet(ThreadFlag::kActiveSuspendBarrier)) {
Yu Lieac44242015-06-29 10:50:03 +0800233 PassActiveSuspendBarriers(this);
234 } else {
235 // Impossible
Mathieu Chartier8ac9c912015-10-01 15:58:41 -0700236 LOG(FATAL) << "Fatal, thread transitioned into suspended without running the checkpoint";
Yu Lieac44242015-06-29 10:50:03 +0800237 }
238 }
Ian Rogers693ff612013-02-01 10:56:12 -0800239}
240
Mathieu Chartier8ac9c912015-10-01 15:58:41 -0700241inline void Thread::TransitionFromRunnableToSuspended(ThreadState new_state) {
Vladimir Markoce2a3442021-11-24 15:10:26 +0000242 // Note: JNI stubs inline a fast path of this method that transitions to suspended if
243 // there are no flags set and then clears the `held_mutexes[kMutatorLock]` (this comes
244 // from a specialized `BaseMutex::RegisterAsLockedImpl(., kMutatorLock)` inlined from
245 // the `GetMutatorLock()->TransitionFromRunnableToSuspended(this)` below).
246 // Therefore any code added here (other than debug build assertions) should be gated
247 // on some flag being set, so that the JNI stub can take the slow path to get here.
Mathieu Chartier8ac9c912015-10-01 15:58:41 -0700248 AssertThreadSuspensionIsAllowable();
Mathieu Chartier3398c782016-09-30 10:27:43 -0700249 PoisonObjectPointersIfDebug();
Mathieu Chartier8ac9c912015-10-01 15:58:41 -0700250 DCHECK_EQ(this, Thread::Current());
251 // Change to non-runnable state, thereby appearing suspended to the system.
252 TransitionToSuspendedAndRunCheckpoints(new_state);
Vladimir Marko23cf32f2021-11-15 13:38:02 +0000253 // Mark the release of the share of the mutator lock.
254 GetMutatorLock()->TransitionFromRunnableToSuspended(this);
Mathieu Chartier8ac9c912015-10-01 15:58:41 -0700255 // Once suspended - check the active suspend barrier flag
256 PassActiveSuspendBarriers();
257}
258
Ian Rogers693ff612013-02-01 10:56:12 -0800259inline ThreadState Thread::TransitionFromSuspendedToRunnable() {
Vladimir Markoe74e0ce2021-12-08 14:16:21 +0000260 // Note: JNI stubs inline a fast path of this method that transitions to Runnable if
261 // there are no flags set and then stores the mutator lock to `held_mutexes[kMutatorLock]`
262 // (this comes from a specialized `BaseMutex::RegisterAsUnlockedImpl(., kMutatorLock)`
263 // inlined from the `GetMutatorLock()->TransitionFromSuspendedToRunnable(this)` below).
264 // Therefore any code added here (other than debug build assertions) should be gated
265 // on some flag being set, so that the JNI stub can take the slow path to get here.
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000266 StateAndFlags old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000267 ThreadState old_state = old_state_and_flags.GetState();
268 DCHECK_NE(old_state, ThreadState::kRunnable);
269 while (true) {
Vladimir Marko23cf32f2021-11-15 13:38:02 +0000270 GetMutatorLock()->AssertNotHeld(this); // Otherwise we starve GC.
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000271 // Optimize for the return from native code case - this is the fast path.
272 // Atomically change from suspended to runnable if no suspend request pending.
Vladimir Marko254a8582021-11-29 14:08:37 +0000273 constexpr uint32_t kCheckedFlags =
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000274 SuspendOrCheckpointRequestFlags() |
275 enum_cast<uint32_t>(ThreadFlag::kActiveSuspendBarrier) |
276 FlipFunctionFlags();
Vladimir Marko254a8582021-11-29 14:08:37 +0000277 if (LIKELY(!old_state_and_flags.IsAnyOfFlagsSet(kCheckedFlags))) {
Yu Lieac44242015-06-29 10:50:03 +0800278 // CAS the value with a memory barrier.
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000279 StateAndFlags new_state_and_flags = old_state_and_flags.WithState(ThreadState::kRunnable);
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000280 if (LIKELY(tls32_.state_and_flags.CompareAndSetWeakAcquire(old_state_and_flags.GetValue(),
281 new_state_and_flags.GetValue()))) {
Vladimir Marko23cf32f2021-11-15 13:38:02 +0000282 // Mark the acquisition of a share of the mutator lock.
283 GetMutatorLock()->TransitionFromSuspendedToRunnable(this);
Yu Lieac44242015-06-29 10:50:03 +0800284 break;
285 }
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000286 } else if (old_state_and_flags.IsFlagSet(ThreadFlag::kActiveSuspendBarrier)) {
Yu Lieac44242015-06-29 10:50:03 +0800287 PassActiveSuspendBarriers(this);
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000288 } else if (UNLIKELY(old_state_and_flags.IsFlagSet(ThreadFlag::kCheckpointRequest) ||
289 old_state_and_flags.IsFlagSet(ThreadFlag::kEmptyCheckpointRequest))) {
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000290 // Checkpoint flags should not be set while in suspended state.
Vladimir Marko254a8582021-11-29 14:08:37 +0000291 static_assert(static_cast<std::underlying_type_t<ThreadState>>(ThreadState::kRunnable) == 0u);
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000292 LOG(FATAL) << "Transitioning to Runnable with checkpoint flag,"
293 // Note: Keeping unused flags. If they are set, it points to memory corruption.
294 << " flags=" << old_state_and_flags.WithState(ThreadState::kRunnable).GetValue()
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000295 << " state=" << old_state_and_flags.GetState();
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000296 } else if (old_state_and_flags.IsFlagSet(ThreadFlag::kSuspendRequest)) {
Ian Rogers693ff612013-02-01 10:56:12 -0800297 // Wait while our suspend count is non-zero.
Nicolas Geoffray9f5f8ac2016-06-29 14:39:59 +0100298
299 // We pass null to the MutexLock as we may be in a situation where the
300 // runtime is shutting down. Guarding ourselves from that situation
301 // requires to take the shutdown lock, which is undesirable here.
302 Thread* thread_to_pass = nullptr;
303 if (kIsDebugBuild && !IsDaemon()) {
304 // We know we can make our debug locking checks on non-daemon threads,
305 // so re-enable them on debug builds.
306 thread_to_pass = this;
307 }
308 MutexLock mu(thread_to_pass, *Locks::thread_suspend_count_lock_);
Hiroshi Yamauchiee235822016-08-19 17:03:27 -0700309 ScopedTransitioningToRunnable scoped_transitioning_to_runnable(this);
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000310 // Reload state and flags after locking the mutex.
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000311 old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000312 DCHECK_EQ(old_state, old_state_and_flags.GetState());
313 while (old_state_and_flags.IsFlagSet(ThreadFlag::kSuspendRequest)) {
Ian Rogers693ff612013-02-01 10:56:12 -0800314 // Re-check when Thread::resume_cond_ is notified.
Nicolas Geoffray9f5f8ac2016-06-29 14:39:59 +0100315 Thread::resume_cond_->Wait(thread_to_pass);
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000316 // Reload state and flags after waiting.
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000317 old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000318 DCHECK_EQ(old_state, old_state_and_flags.GetState());
Ian Rogers693ff612013-02-01 10:56:12 -0800319 }
320 DCHECK_EQ(GetSuspendCount(), 0);
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000321 } else if (UNLIKELY(old_state_and_flags.IsFlagSet(ThreadFlag::kRunningFlipFunction)) ||
322 UNLIKELY(old_state_and_flags.IsFlagSet(ThreadFlag::kWaitingForFlipFunction))) {
323 // The thread should be suspended while another thread is running the flip function.
324 static_assert(static_cast<std::underlying_type_t<ThreadState>>(ThreadState::kRunnable) == 0u);
325 LOG(FATAL) << "Transitioning to Runnable while another thread is running the flip function,"
326 // Note: Keeping unused flags. If they are set, it points to memory corruption.
327 << " flags=" << old_state_and_flags.WithState(ThreadState::kRunnable).GetValue()
328 << " state=" << old_state_and_flags.GetState();
329 } else {
330 DCHECK(old_state_and_flags.IsFlagSet(ThreadFlag::kPendingFlipFunction));
331 // CAS the value with a memory barrier.
332 // Do not set `ThreadFlag::kRunningFlipFunction` as no other thread can run
333 // the flip function for a thread that is not suspended.
334 StateAndFlags new_state_and_flags = old_state_and_flags.WithState(ThreadState::kRunnable)
335 .WithoutFlag(ThreadFlag::kPendingFlipFunction);
336 if (LIKELY(tls32_.state_and_flags.CompareAndSetWeakAcquire(old_state_and_flags.GetValue(),
337 new_state_and_flags.GetValue()))) {
338 // Mark the acquisition of a share of the mutator lock.
339 GetMutatorLock()->TransitionFromSuspendedToRunnable(this);
340 // Run the flip function.
341 RunFlipFunction(this, /*notify=*/ false);
342 break;
343 }
Ian Rogers693ff612013-02-01 10:56:12 -0800344 }
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000345 // Reload state and flags.
Vladimir Marko9c0f7642021-12-06 16:17:52 +0000346 old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000347 DCHECK_EQ(old_state, old_state_and_flags.GetState());
348 }
Yu Lieac44242015-06-29 10:50:03 +0800349 return static_cast<ThreadState>(old_state);
Ian Rogers693ff612013-02-01 10:56:12 -0800350}
351
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800352inline mirror::Object* Thread::AllocTlab(size_t bytes) {
353 DCHECK_GE(TlabSize(), bytes);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700354 ++tlsPtr_.thread_local_objects;
355 mirror::Object* ret = reinterpret_cast<mirror::Object*>(tlsPtr_.thread_local_pos);
356 tlsPtr_.thread_local_pos += bytes;
Mathieu Chartier692fafd2013-11-29 17:24:40 -0800357 return ret;
358}
359
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800360inline bool Thread::PushOnThreadLocalAllocationStack(mirror::Object* obj) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700361 DCHECK_LE(tlsPtr_.thread_local_alloc_stack_top, tlsPtr_.thread_local_alloc_stack_end);
362 if (tlsPtr_.thread_local_alloc_stack_top < tlsPtr_.thread_local_alloc_stack_end) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800363 // There's room.
Ian Rogers13735952014-10-08 12:43:28 -0700364 DCHECK_LE(reinterpret_cast<uint8_t*>(tlsPtr_.thread_local_alloc_stack_top) +
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800365 sizeof(StackReference<mirror::Object>),
Ian Rogers13735952014-10-08 12:43:28 -0700366 reinterpret_cast<uint8_t*>(tlsPtr_.thread_local_alloc_stack_end));
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800367 DCHECK(tlsPtr_.thread_local_alloc_stack_top->AsMirrorPtr() == nullptr);
368 tlsPtr_.thread_local_alloc_stack_top->Assign(obj);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700369 ++tlsPtr_.thread_local_alloc_stack_top;
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800370 return true;
371 }
372 return false;
373}
374
Hans Boehm1b3ec0f2022-01-26 16:53:07 +0000375inline bool Thread::GetWeakRefAccessEnabled() const {
376 CHECK(kUseReadBarrier);
377 DCHECK(this == Thread::Current());
David Srbecky7134a712022-02-19 23:44:49 +0000378 WeakRefAccessState s = tls32_.weak_ref_access_enabled.load(std::memory_order_relaxed);
379 if (LIKELY(s == WeakRefAccessState::kVisiblyEnabled)) {
380 return true;
381 }
382 s = tls32_.weak_ref_access_enabled.load(std::memory_order_acquire);
Hans Boehm1b3ec0f2022-01-26 16:53:07 +0000383 if (s == WeakRefAccessState::kVisiblyEnabled) {
384 return true;
385 } else if (s == WeakRefAccessState::kDisabled) {
386 return false;
387 }
388 DCHECK(s == WeakRefAccessState::kEnabled)
389 << "state = " << static_cast<std::underlying_type_t<WeakRefAccessState>>(s);
390 // The state is only changed back to DISABLED during a checkpoint. Thus no other thread can
391 // change the value concurrently here. No other thread reads the value we store here, so there
392 // is no need for a release store.
393 tls32_.weak_ref_access_enabled.store(WeakRefAccessState::kVisiblyEnabled,
394 std::memory_order_relaxed);
395 return true;
396}
397
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800398inline void Thread::SetThreadLocalAllocationStack(StackReference<mirror::Object>* start,
399 StackReference<mirror::Object>* end) {
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800400 DCHECK(Thread::Current() == this) << "Should be called by self";
401 DCHECK(start != nullptr);
402 DCHECK(end != nullptr);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800403 DCHECK_ALIGNED(start, sizeof(StackReference<mirror::Object>));
404 DCHECK_ALIGNED(end, sizeof(StackReference<mirror::Object>));
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800405 DCHECK_LT(start, end);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700406 tlsPtr_.thread_local_alloc_stack_end = end;
407 tlsPtr_.thread_local_alloc_stack_top = start;
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800408}
409
410inline void Thread::RevokeThreadLocalAllocationStack() {
411 if (kIsDebugBuild) {
412 // Note: self is not necessarily equal to this thread since thread may be suspended.
413 Thread* self = Thread::Current();
Vladimir Markoddf4fd32021-11-22 16:31:57 +0000414 DCHECK(this == self || IsSuspended() || GetState() == ThreadState::kWaitingPerformingGc)
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800415 << GetState() << " thread " << this << " self " << self;
416 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700417 tlsPtr_.thread_local_alloc_stack_end = nullptr;
418 tlsPtr_.thread_local_alloc_stack_top = nullptr;
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800419}
420
Mathieu Chartiera59d9b22016-09-26 18:13:17 -0700421inline void Thread::PoisonObjectPointersIfDebug() {
Andreas Gampec73cb642017-02-22 10:11:30 -0800422 if (kObjPtrPoisoning) {
Mathieu Chartiera59d9b22016-09-26 18:13:17 -0700423 Thread::Current()->PoisonObjectPointers();
424 }
425}
426
Hiroshi Yamauchi02e7f1a2016-10-03 15:32:01 -0700427inline bool Thread::ModifySuspendCount(Thread* self,
428 int delta,
429 AtomicInteger* suspend_barrier,
Alex Light46f93402017-06-29 11:59:50 -0700430 SuspendReason reason) {
Hiroshi Yamauchi02e7f1a2016-10-03 15:32:01 -0700431 if (delta > 0 && ((kUseReadBarrier && this != self) || suspend_barrier != nullptr)) {
432 // When delta > 0 (requesting a suspend), ModifySuspendCountInternal() may fail either if
433 // active_suspend_barriers is full or we are in the middle of a thread flip. Retry in a loop.
434 while (true) {
Alex Light46f93402017-06-29 11:59:50 -0700435 if (LIKELY(ModifySuspendCountInternal(self, delta, suspend_barrier, reason))) {
Hiroshi Yamauchi02e7f1a2016-10-03 15:32:01 -0700436 return true;
437 } else {
438 // Failure means the list of active_suspend_barriers is full or we are in the middle of a
439 // thread flip, we should release the thread_suspend_count_lock_ (to avoid deadlock) and
440 // wait till the target thread has executed or Thread::PassActiveSuspendBarriers() or the
441 // flip function. Note that we could not simply wait for the thread to change to a suspended
442 // state, because it might need to run checkpoint function before the state change or
443 // resumes from the resume_cond_, which also needs thread_suspend_count_lock_.
444 //
445 // The list of active_suspend_barriers is very unlikely to be full since more than
446 // kMaxSuspendBarriers threads need to execute SuspendAllInternal() simultaneously, and
447 // target thread stays in kRunnable in the mean time.
448 Locks::thread_suspend_count_lock_->ExclusiveUnlock(self);
449 NanoSleep(100000);
450 Locks::thread_suspend_count_lock_->ExclusiveLock(self);
451 }
452 }
453 } else {
Alex Light46f93402017-06-29 11:59:50 -0700454 return ModifySuspendCountInternal(self, delta, suspend_barrier, reason);
Hiroshi Yamauchi02e7f1a2016-10-03 15:32:01 -0700455 }
456}
457
Andreas Gampe513061a2017-06-01 09:17:34 -0700458inline ShadowFrame* Thread::PushShadowFrame(ShadowFrame* new_top_frame) {
Nicolas Geoffray893147c2018-10-29 14:49:30 +0000459 new_top_frame->CheckConsistentVRegs();
Andreas Gampe513061a2017-06-01 09:17:34 -0700460 return tlsPtr_.managed_stack.PushShadowFrame(new_top_frame);
461}
462
463inline ShadowFrame* Thread::PopShadowFrame() {
464 return tlsPtr_.managed_stack.PopShadowFrame();
465}
466
Andreas Gampe639b2b12019-01-08 10:32:50 -0800467inline uint8_t* Thread::GetStackEndForInterpreter(bool implicit_overflow_check) const {
468 uint8_t* end = tlsPtr_.stack_end + (implicit_overflow_check
469 ? GetStackOverflowReservedBytes(kRuntimeISA)
470 : 0);
471 if (kIsDebugBuild) {
472 // In a debuggable build, but especially under ASAN, the access-checks interpreter has a
473 // potentially humongous stack size. We don't want to take too much of the stack regularly,
474 // so do not increase the regular reserved size (for compiled code etc) and only report the
475 // virtually smaller stack to the interpreter here.
476 end += GetStackOverflowReservedBytes(kRuntimeISA);
477 }
478 return end;
479}
480
481inline void Thread::ResetDefaultStackEnd() {
482 // Our stacks grow down, so we want stack_end_ to be near there, but reserving enough room
483 // to throw a StackOverflowError.
484 tlsPtr_.stack_end = tlsPtr_.stack_begin + GetStackOverflowReservedBytes(kRuntimeISA);
485}
486
Ian Rogers693ff612013-02-01 10:56:12 -0800487} // namespace art
488
Brian Carlstromfc0e3212013-07-17 14:40:12 -0700489#endif // ART_RUNTIME_THREAD_INL_H_