blob: 49d54fda0069457c48cd381b3bc7b1cb089493ab [file] [log] [blame]
Elliott Hughes8daa0922011-09-11 13:46:25 -07001/*
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#include "thread_list.h"
18
Mathieu Chartier6f365cc2014-04-23 12:42:27 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20
Christopher Ferris6cff48f2014-01-26 21:36:13 -080021#include <backtrace/BacktraceMap.h>
Mathieu Chartier6f365cc2014-04-23 12:42:27 -070022#include <cutils/trace.h>
Elliott Hughesabbe07d2012-06-05 17:42:23 -070023#include <dirent.h>
Ian Rogersd9c4fc92013-10-01 19:45:43 -070024#include <ScopedLocalRef.h>
25#include <ScopedUtfChars.h>
Elliott Hughesabbe07d2012-06-05 17:42:23 -070026#include <sys/types.h>
Elliott Hughes038a8062011-09-18 14:12:41 -070027#include <unistd.h>
28
Ian Rogersc7dd2952014-10-21 23:31:19 -070029#include <sstream>
30
Mathieu Chartier70a596d2014-12-17 14:56:47 -080031#include "base/histogram-inl.h"
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -070032#include "base/mutex-inl.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010033#include "base/time_utils.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080034#include "base/timing_logger.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070035#include "debugger.h"
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -070036#include "gc/collector/concurrent_copying.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070037#include "jni_internal.h"
38#include "lock_word.h"
39#include "monitor.h"
40#include "scoped_thread_state_change.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080041#include "thread.h"
Jeff Haoe094b872014-10-14 13:12:01 -070042#include "trace.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070043#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070044
Yu Lieac44242015-06-29 10:50:03 +080045#if ART_USE_FUTEXES
46#include "linux/futex.h"
47#include "sys/syscall.h"
48#ifndef SYS_futex
49#define SYS_futex __NR_futex
50#endif
51#endif // ART_USE_FUTEXES
52
Elliott Hughes8daa0922011-09-11 13:46:25 -070053namespace art {
54
Mathieu Chartier251755c2014-07-15 18:10:25 -070055static constexpr uint64_t kLongThreadSuspendThreshold = MsToNs(5);
Mathieu Chartier99143862015-02-03 14:26:46 -080056static constexpr uint64_t kThreadSuspendTimeoutMs = 30 * 1000; // 30s.
57// Use 0 since we want to yield to prevent blocking for an unpredictable amount of time.
58static constexpr useconds_t kThreadSuspendInitialSleepUs = 0;
59static constexpr useconds_t kThreadSuspendMaxYieldUs = 3000;
60static constexpr useconds_t kThreadSuspendMaxSleepUs = 5000;
Mathieu Chartier251755c2014-07-15 18:10:25 -070061
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080062ThreadList::ThreadList()
Mathieu Chartierb56200b2015-10-29 10:41:51 -070063 : suspend_all_count_(0),
64 debug_suspend_all_count_(0),
65 unregistering_count_(0),
66 suspend_all_historam_("suspend all histogram", 16, 64),
67 long_suspend_(false) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -080068 CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1, 0U)));
Elliott Hughes8daa0922011-09-11 13:46:25 -070069}
70
71ThreadList::~ThreadList() {
Mathieu Chartierfb6db4c2016-01-06 17:23:25 -080072 ATRACE_BEGIN(__FUNCTION__);
Elliott Hughese52e49b2012-04-02 16:05:44 -070073 // Detach the current thread if necessary. If we failed to start, there might not be any threads.
Elliott Hughes6a144332012-04-03 13:07:11 -070074 // We need to detach the current thread here in case there's another thread waiting to join with
75 // us.
Mathieu Chartierfec72f42014-10-09 12:57:58 -070076 bool contains = false;
77 {
78 Thread* self = Thread::Current();
79 MutexLock mu(self, *Locks::thread_list_lock_);
80 contains = Contains(self);
81 }
82 if (contains) {
Mathieu Chartierfb6db4c2016-01-06 17:23:25 -080083 ATRACE_BEGIN("DetachCurrentThread");
Elliott Hughes8daa0922011-09-11 13:46:25 -070084 Runtime::Current()->DetachCurrentThread();
Mathieu Chartierfb6db4c2016-01-06 17:23:25 -080085 ATRACE_END();
Elliott Hughes8daa0922011-09-11 13:46:25 -070086 }
Mathieu Chartierfb6db4c2016-01-06 17:23:25 -080087 ATRACE_BEGIN("WaitForOtherNonDaemonThreadsToExit");
Elliott Hughes6a144332012-04-03 13:07:11 -070088 WaitForOtherNonDaemonThreadsToExit();
Mathieu Chartierfb6db4c2016-01-06 17:23:25 -080089 ATRACE_END();
Mathieu Chartier51168372015-08-12 16:40:32 -070090 // Disable GC and wait for GC to complete in case there are still daemon threads doing
91 // allocations.
92 gc::Heap* const heap = Runtime::Current()->GetHeap();
93 heap->DisableGCForShutdown();
94 // In case a GC is in progress, wait for it to finish.
Mathieu Chartierfb6db4c2016-01-06 17:23:25 -080095 ATRACE_BEGIN("WaitForGcToComplete");
Mathieu Chartier51168372015-08-12 16:40:32 -070096 heap->WaitForGcToComplete(gc::kGcCauseBackground, Thread::Current());
Mathieu Chartierfb6db4c2016-01-06 17:23:25 -080097 ATRACE_END();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070098 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
99 // Thread::Init.
Mathieu Chartier4d87df62016-01-07 15:14:19 -0800100 ATRACE_BEGIN("SuspendAllDaemonThreadsForShutdown");
101 SuspendAllDaemonThreadsForShutdown();
Mathieu Chartierfb6db4c2016-01-06 17:23:25 -0800102 ATRACE_END();
103 ATRACE_END();
Elliott Hughes8daa0922011-09-11 13:46:25 -0700104}
105
106bool ThreadList::Contains(Thread* thread) {
107 return find(list_.begin(), list_.end(), thread) != list_.end();
108}
109
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700110bool ThreadList::Contains(pid_t tid) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700111 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700112 if (thread->GetTid() == tid) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700113 return true;
114 }
115 }
116 return false;
117}
118
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700119pid_t ThreadList::GetLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700120 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
Elliott Hughesaccd83d2011-10-17 14:25:58 -0700121}
122
Mathieu Chartier590fee92013-09-13 13:46:47 -0700123void ThreadList::DumpNativeStacks(std::ostream& os) {
124 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Christopher Ferris6cff48f2014-01-26 21:36:13 -0800125 std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(getpid()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700126 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700127 os << "DUMPING THREAD " << thread->GetTid() << "\n";
Christopher Ferris6cff48f2014-01-26 21:36:13 -0800128 DumpNativeStack(os, thread->GetTid(), map.get(), "\t");
Mathieu Chartier590fee92013-09-13 13:46:47 -0700129 os << "\n";
130 }
131}
132
Elliott Hughesc967f782012-04-16 10:23:15 -0700133void ThreadList::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800134 {
135 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier23f6e692014-12-18 18:24:39 -0800136 // Only print if we have samples.
137 if (suspend_all_historam_.SampleSize() > 0) {
138 Histogram<uint64_t>::CumulativeData data;
139 suspend_all_historam_.CreateHistogram(&data);
140 suspend_all_historam_.PrintConfidenceIntervals(os, 0.99, data); // Dump time to suspend.
141 }
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800142 }
Nicolas Geoffraya73280d2016-02-15 13:05:16 +0000143 Dump(os, Runtime::Current()->GetDumpNativeStackOnSigQuit());
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700144 DumpUnattachedThreads(os);
145}
146
Ian Rogerscfaa4552012-11-26 21:00:08 -0800147static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700148 // TODO: No thread safety analysis as DumpState with a null thread won't access fields, should
Ian Rogerscfaa4552012-11-26 21:00:08 -0800149 // refactor DumpState to avoid skipping analysis.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700150 Thread::DumpState(os, nullptr, tid);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700151 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -0700152 // TODO: Reenable this when the native code in system_server can handle it.
153 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
154 if (false) {
Christopher Ferris6cff48f2014-01-26 21:36:13 -0800155 DumpNativeStack(os, tid, nullptr, " native: ");
Brian Carlstromed8b7232012-06-27 17:54:47 -0700156 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700157 os << "\n";
158}
159
160void ThreadList::DumpUnattachedThreads(std::ostream& os) {
161 DIR* d = opendir("/proc/self/task");
162 if (!d) {
163 return;
164 }
165
Ian Rogers50b35e22012-10-04 10:09:15 -0700166 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700167 dirent* e;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700168 while ((e = readdir(d)) != nullptr) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700169 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700170 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700171 if (!*end) {
172 bool contains;
173 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700174 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700175 contains = Contains(tid);
176 }
177 if (!contains) {
178 DumpUnattachedThread(os, tid);
179 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700180 }
181 }
182 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800183}
184
Andreas Gampe4a3d19b2015-01-09 17:54:51 -0800185// Dump checkpoint timeout in milliseconds. Larger amount on the host, as dumping will invoke
186// addr2line when available.
Andreas Gampe1e4b0ca2015-01-14 09:06:32 -0800187static constexpr uint32_t kDumpWaitTimeout = kIsTargetBuild ? 10000 : 20000;
Andreas Gampe4a3d19b2015-01-09 17:54:51 -0800188
Ian Rogers7b078e82014-09-10 14:44:24 -0700189// A closure used by Thread::Dump.
190class DumpCheckpoint FINAL : public Closure {
191 public:
Nicolas Geoffraya73280d2016-02-15 13:05:16 +0000192 DumpCheckpoint(std::ostream* os, bool dump_native_stack)
193 : os_(os),
194 barrier_(0),
195 backtrace_map_(dump_native_stack ? BacktraceMap::Create(getpid()) : nullptr),
196 dump_native_stack_(dump_native_stack) {}
Ian Rogers7b078e82014-09-10 14:44:24 -0700197
198 void Run(Thread* thread) OVERRIDE {
199 // Note thread and self may not be equal if thread was already suspended at the point of the
200 // request.
201 Thread* self = Thread::Current();
202 std::ostringstream local_os;
203 {
204 ScopedObjectAccess soa(self);
Nicolas Geoffraya73280d2016-02-15 13:05:16 +0000205 thread->Dump(local_os, dump_native_stack_, backtrace_map_.get());
Ian Rogers7b078e82014-09-10 14:44:24 -0700206 }
207 local_os << "\n";
208 {
209 // Use the logging lock to ensure serialization when writing to the common ostream.
210 MutexLock mu(self, *Locks::logging_lock_);
211 *os_ << local_os.str();
212 }
Mathieu Chartier10d25082015-10-28 18:36:09 -0700213 barrier_.Pass(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700214 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700215
216 void WaitForThreadsToRunThroughCheckpoint(size_t threads_running_checkpoint) {
217 Thread* self = Thread::Current();
218 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
Andreas Gampe1e4b0ca2015-01-14 09:06:32 -0800219 bool timed_out = barrier_.Increment(self, threads_running_checkpoint, kDumpWaitTimeout);
Ian Rogers2156ff12014-09-13 19:20:54 -0700220 if (timed_out) {
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000221 // Avoid a recursive abort.
222 LOG((kIsDebugBuild && (gAborting == 0)) ? FATAL : ERROR)
223 << "Unexpected time out during dump checkpoint.";
Ian Rogers2156ff12014-09-13 19:20:54 -0700224 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700225 }
226
227 private:
228 // The common stream that will accumulate all the dumps.
229 std::ostream* const os_;
230 // The barrier to be passed through and for the requestor to wait upon.
231 Barrier barrier_;
Christopher Ferris6cff48f2014-01-26 21:36:13 -0800232 // A backtrace map, so that all threads use a shared info and don't reacquire/parse separately.
233 std::unique_ptr<BacktraceMap> backtrace_map_;
Nicolas Geoffraya73280d2016-02-15 13:05:16 +0000234 // Whether we should dump the native stack.
235 const bool dump_native_stack_;
Ian Rogers7b078e82014-09-10 14:44:24 -0700236};
237
Nicolas Geoffraya73280d2016-02-15 13:05:16 +0000238void ThreadList::Dump(std::ostream& os, bool dump_native_stack) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700239 {
240 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
241 os << "DALVIK THREADS (" << list_.size() << "):\n";
242 }
Nicolas Geoffraya73280d2016-02-15 13:05:16 +0000243 DumpCheckpoint checkpoint(&os, dump_native_stack);
Ian Rogers7b078e82014-09-10 14:44:24 -0700244 size_t threads_running_checkpoint = RunCheckpoint(&checkpoint);
Lei Lidd9943d2015-02-02 14:24:44 +0800245 if (threads_running_checkpoint != 0) {
246 checkpoint.WaitForThreadsToRunThroughCheckpoint(threads_running_checkpoint);
247 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700248}
249
Ian Rogers50b35e22012-10-04 10:09:15 -0700250void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
251 MutexLock mu(self, *Locks::thread_list_lock_);
252 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700253 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800254 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700255 CHECK(thread->IsSuspended())
256 << "\nUnsuspended thread: <<" << *thread << "\n"
257 << "self: <<" << *Thread::Current();
258 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700259 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700260}
261
Ian Rogers66aee5c2012-08-15 17:17:47 -0700262#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700263// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Andreas Gampe794ad762015-02-23 08:12:24 -0800264NO_RETURN static void UnsafeLogFatalForThreadSuspendAllTimeout() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700265 Runtime* runtime = Runtime::Current();
266 std::ostringstream ss;
267 ss << "Thread suspend timeout\n";
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700268 Locks::mutator_lock_->Dump(ss);
269 ss << "\n";
Ian Rogers7b078e82014-09-10 14:44:24 -0700270 runtime->GetThreadList()->Dump(ss);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700271 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800272 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700273}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700274#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700275
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800276// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
Mathieu Chartier99143862015-02-03 14:26:46 -0800277// individual thread requires polling. delay_us is the requested sleep wait. If delay_us is 0 then
278// we use sched_yield instead of calling usleep.
279static void ThreadSuspendSleep(useconds_t delay_us) {
280 if (delay_us == 0) {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800281 sched_yield();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800282 } else {
Mathieu Chartier99143862015-02-03 14:26:46 -0800283 usleep(delay_us);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800284 }
285}
286
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700287size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700288 Thread* self = Thread::Current();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800289 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
290 Locks::thread_list_lock_->AssertNotHeld(self);
291 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700292
293 std::vector<Thread*> suspended_count_modified_threads;
294 size_t count = 0;
295 {
296 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
297 // manually called.
298 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700299 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier10d25082015-10-28 18:36:09 -0700300 count = list_.size();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700301 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700302 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700303 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700304 if (thread->RequestCheckpoint(checkpoint_function)) {
Dave Allison0aded082013-11-07 13:15:11 -0800305 // This thread will run its checkpoint some time in the near future.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700306 break;
307 } else {
308 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700309 // The thread switched back to runnable.
310 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700311 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700312 continue;
313 }
Yu Lieac44242015-06-29 10:50:03 +0800314 thread->ModifySuspendCount(self, +1, nullptr, false);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700315 suspended_count_modified_threads.push_back(thread);
316 break;
317 }
318 }
319 }
320 }
321 }
322
323 // Run the checkpoint on ourself while we wait for threads to suspend.
324 checkpoint_function->Run(self);
325
326 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700327 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700328 if (!thread->IsSuspended()) {
Mathieu Chartier99143862015-02-03 14:26:46 -0800329 if (ATRACE_ENABLED()) {
330 std::ostringstream oss;
331 thread->ShortDump(oss);
332 ATRACE_BEGIN((std::string("Waiting for suspension of thread ") + oss.str()).c_str());
333 }
334 // Busy wait until the thread is suspended.
335 const uint64_t start_time = NanoTime();
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700336 do {
Mathieu Chartier99143862015-02-03 14:26:46 -0800337 ThreadSuspendSleep(kThreadSuspendInitialSleepUs);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700338 } while (!thread->IsSuspended());
Mathieu Chartier99143862015-02-03 14:26:46 -0800339 const uint64_t total_delay = NanoTime() - start_time;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800340 // Shouldn't need to wait for longer than 1000 microseconds.
Mathieu Chartier99143862015-02-03 14:26:46 -0800341 constexpr uint64_t kLongWaitThreshold = MsToNs(1);
342 ATRACE_END();
343 if (UNLIKELY(total_delay > kLongWaitThreshold)) {
344 LOG(WARNING) << "Long wait of " << PrettyDuration(total_delay) << " for "
345 << *thread << " suspension!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700346 }
347 }
348 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700349 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700350 {
351 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Yu Lieac44242015-06-29 10:50:03 +0800352 thread->ModifySuspendCount(self, -1, nullptr, false);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700353 }
354 }
355
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800356 {
357 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
358 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
359 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
360 Thread::resume_cond_->Broadcast(self);
361 }
362
Lei Lidd9943d2015-02-02 14:24:44 +0800363 return count;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700364}
365
Dave Allison39c3bfb2014-01-28 18:33:52 -0800366// Request that a checkpoint function be run on all active (non-suspended)
367// threads. Returns the number of successful requests.
368size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
369 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700370 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
371 Locks::thread_list_lock_->AssertNotHeld(self);
372 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
373 CHECK_NE(self->GetState(), kRunnable);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800374
375 size_t count = 0;
376 {
377 // Call a checkpoint function for each non-suspended thread.
378 MutexLock mu(self, *Locks::thread_list_lock_);
379 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
380 for (const auto& thread : list_) {
381 if (thread != self) {
382 if (thread->RequestCheckpoint(checkpoint_function)) {
383 // This thread will run its checkpoint some time in the near future.
384 count++;
385 }
386 }
387 }
388 }
389
390 // Return the number of threads that will run the checkpoint function.
391 return count;
392}
393
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800394// A checkpoint/suspend-all hybrid to switch thread roots from
395// from-space to to-space refs. Used to synchronize threads at a point
396// to mark the initiation of marking while maintaining the to-space
397// invariant.
Mathieu Chartierb56200b2015-10-29 10:41:51 -0700398size_t ThreadList::FlipThreadRoots(Closure* thread_flip_visitor,
399 Closure* flip_callback,
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800400 gc::collector::GarbageCollector* collector) {
401 TimingLogger::ScopedTiming split("ThreadListFlip", collector->GetTimings());
402 const uint64_t start_time = NanoTime();
403 Thread* self = Thread::Current();
404 Locks::mutator_lock_->AssertNotHeld(self);
405 Locks::thread_list_lock_->AssertNotHeld(self);
406 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
407 CHECK_NE(self->GetState(), kRunnable);
408
Mathieu Chartierb19ccb12015-07-15 10:24:16 -0700409 SuspendAllInternal(self, self, nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800410
411 // Run the flip callback for the collector.
412 Locks::mutator_lock_->ExclusiveLock(self);
413 flip_callback->Run(self);
414 Locks::mutator_lock_->ExclusiveUnlock(self);
415 collector->RegisterPause(NanoTime() - start_time);
416
417 // Resume runnable threads.
Mathieu Chartierb19ccb12015-07-15 10:24:16 -0700418 std::vector<Thread*> runnable_threads;
419 std::vector<Thread*> other_threads;
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800420 {
421 MutexLock mu(self, *Locks::thread_list_lock_);
422 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
423 --suspend_all_count_;
424 for (const auto& thread : list_) {
425 if (thread == self) {
426 continue;
427 }
428 // Set the flip function for both runnable and suspended threads
429 // because Thread::DumpState/DumpJavaStack() (invoked by a
430 // checkpoint) may cause the flip function to be run for a
431 // runnable/suspended thread before a runnable threads runs it
432 // for itself or we run it for a suspended thread below.
433 thread->SetFlipFunction(thread_flip_visitor);
434 if (thread->IsSuspendedAtSuspendCheck()) {
435 // The thread will resume right after the broadcast.
Yu Lieac44242015-06-29 10:50:03 +0800436 thread->ModifySuspendCount(self, -1, nullptr, false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800437 runnable_threads.push_back(thread);
438 } else {
439 other_threads.push_back(thread);
440 }
441 }
442 Thread::resume_cond_->Broadcast(self);
443 }
444
445 // Run the closure on the other threads and let them resume.
446 {
447 ReaderMutexLock mu(self, *Locks::mutator_lock_);
448 for (const auto& thread : other_threads) {
449 Closure* flip_func = thread->GetFlipFunction();
450 if (flip_func != nullptr) {
451 flip_func->Run(thread);
452 }
453 }
454 // Run it for self.
455 thread_flip_visitor->Run(self);
456 }
457
458 // Resume other threads.
459 {
460 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
461 for (const auto& thread : other_threads) {
Yu Lieac44242015-06-29 10:50:03 +0800462 thread->ModifySuspendCount(self, -1, nullptr, false);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800463 }
464 Thread::resume_cond_->Broadcast(self);
465 }
466
467 return runnable_threads.size() + other_threads.size() + 1; // +1 for self.
468}
469
Mathieu Chartierbf44d422015-06-02 11:42:18 -0700470void ThreadList::SuspendAll(const char* cause, bool long_suspend) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700471 Thread* self = Thread::Current();
472
Jeff Haoc5d824a2014-07-28 18:35:38 -0700473 if (self != nullptr) {
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700474 VLOG(threads) << *self << " SuspendAll for " << cause << " starting...";
Jeff Haoc5d824a2014-07-28 18:35:38 -0700475 } else {
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700476 VLOG(threads) << "Thread[null] SuspendAll for " << cause << " starting...";
Jeff Haoc5d824a2014-07-28 18:35:38 -0700477 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700478 ATRACE_BEGIN("Suspending mutator threads");
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800479 const uint64_t start_time = NanoTime();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700480
Yu Lieac44242015-06-29 10:50:03 +0800481 SuspendAllInternal(self, self);
482 // All threads are known to have suspended (but a thread may still own the mutator lock)
483 // Make sure this thread grabs exclusive access to the mutator lock and its protected data.
Ian Rogers66aee5c2012-08-15 17:17:47 -0700484#if HAVE_TIMED_RWLOCK
Mathieu Chartierbf44d422015-06-02 11:42:18 -0700485 while (true) {
486 if (Locks::mutator_lock_->ExclusiveLockWithTimeout(self, kThreadSuspendTimeoutMs, 0)) {
487 break;
488 } else if (!long_suspend_) {
489 // Reading long_suspend without the mutator lock is slightly racy, in some rare cases, this
490 // could result in a thread suspend timeout.
491 // Timeout if we wait more than kThreadSuspendTimeoutMs seconds.
492 UnsafeLogFatalForThreadSuspendAllTimeout();
493 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700494 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700495#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700496 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700497#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700498
Mathieu Chartierbf44d422015-06-02 11:42:18 -0700499 long_suspend_ = long_suspend;
500
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800501 const uint64_t end_time = NanoTime();
502 const uint64_t suspend_time = end_time - start_time;
503 suspend_all_historam_.AdjustAndAddValue(suspend_time);
504 if (suspend_time > kLongThreadSuspendThreshold) {
505 LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(suspend_time);
Mathieu Chartier251755c2014-07-15 18:10:25 -0700506 }
507
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800508 if (kDebugLocking) {
509 // Debug check that all threads are suspended.
510 AssertThreadsAreSuspended(self, self);
511 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700512
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700513 ATRACE_END();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700514 ATRACE_BEGIN((std::string("Mutator threads suspended for ") + cause).c_str());
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700515
Jeff Haoc5d824a2014-07-28 18:35:38 -0700516 if (self != nullptr) {
517 VLOG(threads) << *self << " SuspendAll complete";
518 } else {
519 VLOG(threads) << "Thread[null] SuspendAll complete";
520 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700521}
522
Yu Lieac44242015-06-29 10:50:03 +0800523// Ensures all threads running Java suspend and that those not running Java don't start.
524// Debugger thread might be set to kRunnable for a short period of time after the
525// SuspendAllInternal. This is safe because it will be set back to suspended state before
526// the SuspendAll returns.
Mathieu Chartierb56200b2015-10-29 10:41:51 -0700527void ThreadList::SuspendAllInternal(Thread* self,
528 Thread* ignore1,
529 Thread* ignore2,
Yu Lieac44242015-06-29 10:50:03 +0800530 bool debug_suspend) {
531 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
532 Locks::thread_list_lock_->AssertNotHeld(self);
533 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
534 if (kDebugLocking && self != nullptr) {
535 CHECK_NE(self->GetState(), kRunnable);
536 }
537
538 // First request that all threads suspend, then wait for them to suspend before
539 // returning. This suspension scheme also relies on other behaviour:
540 // 1. Threads cannot be deleted while they are suspended or have a suspend-
541 // request flag set - (see Unregister() below).
542 // 2. When threads are created, they are created in a suspended state (actually
543 // kNative) and will never begin executing Java code without first checking
544 // the suspend-request flag.
545
546 // The atomic counter for number of threads that need to pass the barrier.
547 AtomicInteger pending_threads;
548 uint32_t num_ignored = 0;
549 if (ignore1 != nullptr) {
550 ++num_ignored;
551 }
552 if (ignore2 != nullptr && ignore1 != ignore2) {
553 ++num_ignored;
554 }
555 {
556 MutexLock mu(self, *Locks::thread_list_lock_);
557 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
558 // Update global suspend all state for attaching threads.
559 ++suspend_all_count_;
560 if (debug_suspend)
561 ++debug_suspend_all_count_;
562 pending_threads.StoreRelaxed(list_.size() - num_ignored);
563 // Increment everybody's suspend count (except those that should be ignored).
564 for (const auto& thread : list_) {
565 if (thread == ignore1 || thread == ignore2) {
566 continue;
567 }
568 VLOG(threads) << "requesting thread suspend: " << *thread;
569 while (true) {
570 if (LIKELY(thread->ModifySuspendCount(self, +1, &pending_threads, debug_suspend))) {
571 break;
572 } else {
573 // Failure means the list of active_suspend_barriers is full, we should release the
574 // thread_suspend_count_lock_ (to avoid deadlock) and wait till the target thread has
575 // executed Thread::PassActiveSuspendBarriers(). Note that we could not simply wait for
576 // the thread to change to a suspended state, because it might need to run checkpoint
577 // function before the state change, which also needs thread_suspend_count_lock_.
578
579 // This is very unlikely to happen since more than kMaxSuspendBarriers threads need to
580 // execute SuspendAllInternal() simultaneously, and target thread stays in kRunnable
581 // in the mean time.
582 Locks::thread_suspend_count_lock_->ExclusiveUnlock(self);
583 NanoSleep(100000);
584 Locks::thread_suspend_count_lock_->ExclusiveLock(self);
585 }
586 }
587
588 // Must install the pending_threads counter first, then check thread->IsSuspend() and clear
589 // the counter. Otherwise there's a race with Thread::TransitionFromRunnableToSuspended()
590 // that can lead a thread to miss a call to PassActiveSuspendBarriers().
591 if (thread->IsSuspended()) {
592 // Only clear the counter for the current thread.
593 thread->ClearSuspendBarrier(&pending_threads);
594 pending_threads.FetchAndSubSequentiallyConsistent(1);
595 }
596 }
597 }
598
599 // Wait for the barrier to be passed by all runnable threads. This wait
600 // is done with a timeout so that we can detect problems.
Mathieu Chartier19af1172015-07-14 10:05:45 -0700601#if ART_USE_FUTEXES
Yu Lieac44242015-06-29 10:50:03 +0800602 timespec wait_timeout;
603 InitTimeSpec(true, CLOCK_MONOTONIC, 10000, 0, &wait_timeout);
Mathieu Chartier19af1172015-07-14 10:05:45 -0700604#endif
Yu Lieac44242015-06-29 10:50:03 +0800605 while (true) {
606 int32_t cur_val = pending_threads.LoadRelaxed();
607 if (LIKELY(cur_val > 0)) {
608#if ART_USE_FUTEXES
609 if (futex(pending_threads.Address(), FUTEX_WAIT, cur_val, &wait_timeout, nullptr, 0) != 0) {
610 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
611 if ((errno != EAGAIN) && (errno != EINTR)) {
612 if (errno == ETIMEDOUT) {
613 LOG(kIsDebugBuild ? FATAL : ERROR) << "Unexpected time out during suspend all.";
614 } else {
615 PLOG(FATAL) << "futex wait failed for SuspendAllInternal()";
616 }
617 }
618 } else {
619 cur_val = pending_threads.LoadRelaxed();
620 CHECK_EQ(cur_val, 0);
621 break;
622 }
623#else
624 // Spin wait. This is likely to be slow, but on most architecture ART_USE_FUTEXES is set.
625#endif
626 } else {
627 CHECK_EQ(cur_val, 0);
628 break;
629 }
630 }
631}
632
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700633void ThreadList::ResumeAll() {
634 Thread* self = Thread::Current();
635
Jeff Haoc5d824a2014-07-28 18:35:38 -0700636 if (self != nullptr) {
637 VLOG(threads) << *self << " ResumeAll starting";
638 } else {
639 VLOG(threads) << "Thread[null] ResumeAll starting";
640 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700641
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700642 ATRACE_END();
643 ATRACE_BEGIN("Resuming mutator threads");
644
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800645 if (kDebugLocking) {
646 // Debug check that all threads are suspended.
647 AssertThreadsAreSuspended(self, self);
648 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700649
Mathieu Chartierbf44d422015-06-02 11:42:18 -0700650 long_suspend_ = false;
651
Ian Rogers81d425b2012-09-27 16:03:43 -0700652 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700653 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700654 MutexLock mu(self, *Locks::thread_list_lock_);
655 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700656 // Update global suspend all state for attaching threads.
657 --suspend_all_count_;
658 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700659 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700660 if (thread == self) {
661 continue;
662 }
Yu Lieac44242015-06-29 10:50:03 +0800663 thread->ModifySuspendCount(self, -1, nullptr, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700664 }
665
666 // Broadcast a notification to all suspended threads, some or all of
667 // which may choose to wake up. No need to wait for them.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700668 if (self != nullptr) {
669 VLOG(threads) << *self << " ResumeAll waking others";
670 } else {
671 VLOG(threads) << "Thread[null] ResumeAll waking others";
672 }
Ian Rogersc604d732012-10-14 16:09:54 -0700673 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700674 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700675 ATRACE_END();
Jeff Haoc5d824a2014-07-28 18:35:38 -0700676
677 if (self != nullptr) {
678 VLOG(threads) << *self << " ResumeAll complete";
679 } else {
680 VLOG(threads) << "Thread[null] ResumeAll complete";
681 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700682}
683
684void ThreadList::Resume(Thread* thread, bool for_debugger) {
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800685 // This assumes there was an ATRACE_BEGIN when we suspended the thread.
686 ATRACE_END();
687
Ian Rogers81d425b2012-09-27 16:03:43 -0700688 Thread* self = Thread::Current();
689 DCHECK_NE(thread, self);
Brian Carlstromba32de42014-08-27 23:43:46 -0700690 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..."
691 << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700692
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700693 {
694 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700695 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700696 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700697 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
698 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700699 if (!Contains(thread)) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700700 // We only expect threads within the thread-list to have been suspended otherwise we can't
701 // stop such threads from delete-ing themselves.
702 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
703 << ") thread not within thread list";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700704 return;
705 }
Yu Lieac44242015-06-29 10:50:03 +0800706 thread->ModifySuspendCount(self, -1, nullptr, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700707 }
708
709 {
Brian Carlstromba32de42014-08-27 23:43:46 -0700710 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700711 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700712 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700713 }
714
Brian Carlstromba32de42014-08-27 23:43:46 -0700715 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700716}
Elliott Hughes01158d72011-09-19 19:47:10 -0700717
Mathieu Chartierb56200b2015-10-29 10:41:51 -0700718static void ThreadSuspendByPeerWarning(Thread* self,
719 LogSeverity severity,
720 const char* message,
Ian Rogersc7dd2952014-10-21 23:31:19 -0700721 jobject peer) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700722 JNIEnvExt* env = self->GetJniEnv();
723 ScopedLocalRef<jstring>
Mathieu Chartierb56200b2015-10-29 10:41:51 -0700724 scoped_name_string(env, static_cast<jstring>(env->GetObjectField(
725 peer, WellKnownClasses::java_lang_Thread_name)));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700726 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700727 if (scoped_name_chars.c_str() == nullptr) {
Ian Rogersc7dd2952014-10-21 23:31:19 -0700728 LOG(severity) << message << ": " << peer;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700729 env->ExceptionClear();
730 } else {
Ian Rogersc7dd2952014-10-21 23:31:19 -0700731 LOG(severity) << message << ": " << peer << ":" << scoped_name_chars.c_str();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700732 }
733}
734
Mathieu Chartierb56200b2015-10-29 10:41:51 -0700735Thread* ThreadList::SuspendThreadByPeer(jobject peer,
736 bool request_suspension,
737 bool debug_suspension,
738 bool* timed_out) {
Mathieu Chartier3a958aa2015-02-04 12:52:34 -0800739 const uint64_t start_time = NanoTime();
Mathieu Chartier99143862015-02-03 14:26:46 -0800740 useconds_t sleep_us = kThreadSuspendInitialSleepUs;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700741 *timed_out = false;
Mathieu Chartier99143862015-02-03 14:26:46 -0800742 Thread* const self = Thread::Current();
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800743 Thread* suspended_thread = nullptr;
Brian Carlstromba32de42014-08-27 23:43:46 -0700744 VLOG(threads) << "SuspendThreadByPeer starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700745 while (true) {
746 Thread* thread;
747 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700748 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
749 // is requesting another suspend, to avoid deadlock, by requiring this function be called
750 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
751 // than request thread suspension, to avoid potential cycles in threads requesting each other
752 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700753 ScopedObjectAccess soa(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800754 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700755 thread = Thread::FromManagedThread(soa, peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700756 if (thread == nullptr) {
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800757 if (suspended_thread != nullptr) {
758 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
759 // If we incremented the suspend count but the thread reset its peer, we need to
760 // re-decrement it since it is shutting down and may deadlock the runtime in
761 // ThreadList::WaitForOtherNonDaemonThreadsToExit.
Yu Lieac44242015-06-29 10:50:03 +0800762 suspended_thread->ModifySuspendCount(soa.Self(), -1, nullptr, debug_suspension);
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800763 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700764 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700765 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700766 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700767 if (!Contains(thread)) {
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800768 CHECK(suspended_thread == nullptr);
Brian Carlstromba32de42014-08-27 23:43:46 -0700769 VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
770 << reinterpret_cast<void*>(thread);
771 return nullptr;
772 }
773 VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700774 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800775 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700776 if (request_suspension) {
Ian Rogers4ad5cd32014-11-11 23:08:07 -0800777 if (self->GetSuspendCount() > 0) {
778 // We hold the suspend count lock but another thread is trying to suspend us. Its not
779 // safe to try to suspend another thread in case we get a cycle. Start the loop again
780 // which will allow this thread to be suspended.
781 continue;
782 }
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800783 CHECK(suspended_thread == nullptr);
784 suspended_thread = thread;
Yu Lieac44242015-06-29 10:50:03 +0800785 suspended_thread->ModifySuspendCount(self, +1, nullptr, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700786 request_suspension = false;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700787 } else {
788 // If the caller isn't requesting suspension, a suspension should have already occurred.
789 CHECK_GT(thread->GetSuspendCount(), 0);
790 }
791 // IsSuspended on the current thread will fail as the current thread is changed into
792 // Runnable above. As the suspend count is now raised if this is the current thread
793 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
794 // to just explicitly handle the current thread in the callers to this code.
795 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
796 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
797 // count, or else we've waited and it has self suspended) or is the current thread, we're
798 // done.
799 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700800 VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800801 if (ATRACE_ENABLED()) {
802 std::string name;
803 thread->GetThreadName(name);
804 ATRACE_BEGIN(StringPrintf("SuspendThreadByPeer suspended %s for peer=%p", name.c_str(),
805 peer).c_str());
806 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700807 return thread;
808 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800809 const uint64_t total_delay = NanoTime() - start_time;
810 if (total_delay >= MsToNs(kThreadSuspendTimeoutMs)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700811 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800812 if (suspended_thread != nullptr) {
813 CHECK_EQ(suspended_thread, thread);
Yu Lieac44242015-06-29 10:50:03 +0800814 suspended_thread->ModifySuspendCount(soa.Self(), -1, nullptr, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700815 }
816 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700817 return nullptr;
Mathieu Chartier99143862015-02-03 14:26:46 -0800818 } else if (sleep_us == 0 &&
819 total_delay > static_cast<uint64_t>(kThreadSuspendMaxYieldUs) * 1000) {
820 // We have spun for kThreadSuspendMaxYieldUs time, switch to sleeps to prevent
821 // excessive CPU usage.
822 sleep_us = kThreadSuspendMaxYieldUs / 2;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700823 }
824 }
825 // Release locks and come out of runnable state.
826 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800827 VLOG(threads) << "SuspendThreadByPeer waiting to allow thread chance to suspend";
828 ThreadSuspendSleep(sleep_us);
829 // This may stay at 0 if sleep_us == 0, but this is WAI since we want to avoid using usleep at
830 // all if possible. This shouldn't be an issue since time to suspend should always be small.
831 sleep_us = std::min(sleep_us * 2, kThreadSuspendMaxSleepUs);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700832 }
833}
834
Mathieu Chartierb56200b2015-10-29 10:41:51 -0700835static void ThreadSuspendByThreadIdWarning(LogSeverity severity,
836 const char* message,
Ian Rogersc7dd2952014-10-21 23:31:19 -0700837 uint32_t thread_id) {
838 LOG(severity) << StringPrintf("%s: %d", message, thread_id);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700839}
840
Mathieu Chartierb56200b2015-10-29 10:41:51 -0700841Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id,
842 bool debug_suspension,
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700843 bool* timed_out) {
Mathieu Chartier3a958aa2015-02-04 12:52:34 -0800844 const uint64_t start_time = NanoTime();
Mathieu Chartier99143862015-02-03 14:26:46 -0800845 useconds_t sleep_us = kThreadSuspendInitialSleepUs;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700846 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800847 Thread* suspended_thread = nullptr;
Mathieu Chartier99143862015-02-03 14:26:46 -0800848 Thread* const self = Thread::Current();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700849 CHECK_NE(thread_id, kInvalidThreadId);
Brian Carlstromba32de42014-08-27 23:43:46 -0700850 VLOG(threads) << "SuspendThreadByThreadId starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700851 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700852 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700853 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
854 // is requesting another suspend, to avoid deadlock, by requiring this function be called
855 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
856 // than request thread suspension, to avoid potential cycles in threads requesting each other
857 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700858 ScopedObjectAccess soa(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800859 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700860 Thread* thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700861 for (const auto& it : list_) {
862 if (it->GetThreadId() == thread_id) {
863 thread = it;
864 break;
865 }
866 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800867 if (thread == nullptr) {
868 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
869 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700870 // There's a race in inflating a lock and the owner giving up ownership and then dying.
871 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
Brian Carlstromba32de42014-08-27 23:43:46 -0700872 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700873 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700874 VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
875 DCHECK(Contains(thread));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700876 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800877 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800878 if (suspended_thread == nullptr) {
Ian Rogers4ad5cd32014-11-11 23:08:07 -0800879 if (self->GetSuspendCount() > 0) {
880 // We hold the suspend count lock but another thread is trying to suspend us. Its not
881 // safe to try to suspend another thread in case we get a cycle. Start the loop again
882 // which will allow this thread to be suspended.
883 continue;
884 }
Yu Lieac44242015-06-29 10:50:03 +0800885 thread->ModifySuspendCount(self, +1, nullptr, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800886 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700887 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800888 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700889 // If the caller isn't requesting suspension, a suspension should have already occurred.
890 CHECK_GT(thread->GetSuspendCount(), 0);
891 }
892 // IsSuspended on the current thread will fail as the current thread is changed into
893 // Runnable above. As the suspend count is now raised if this is the current thread
894 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
895 // to just explicitly handle the current thread in the callers to this code.
896 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
897 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
898 // count, or else we've waited and it has self suspended) or is the current thread, we're
899 // done.
900 if (thread->IsSuspended()) {
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800901 if (ATRACE_ENABLED()) {
902 std::string name;
903 thread->GetThreadName(name);
904 ATRACE_BEGIN(StringPrintf("SuspendThreadByThreadId suspended %s id=%d",
905 name.c_str(), thread_id).c_str());
906 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700907 VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700908 return thread;
909 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800910 const uint64_t total_delay = NanoTime() - start_time;
911 if (total_delay >= MsToNs(kThreadSuspendTimeoutMs)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700912 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800913 if (suspended_thread != nullptr) {
Yu Lieac44242015-06-29 10:50:03 +0800914 thread->ModifySuspendCount(soa.Self(), -1, nullptr, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700915 }
916 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700917 return nullptr;
Mathieu Chartier99143862015-02-03 14:26:46 -0800918 } else if (sleep_us == 0 &&
919 total_delay > static_cast<uint64_t>(kThreadSuspendMaxYieldUs) * 1000) {
920 // We have spun for kThreadSuspendMaxYieldUs time, switch to sleeps to prevent
921 // excessive CPU usage.
922 sleep_us = kThreadSuspendMaxYieldUs / 2;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700923 }
924 }
925 // Release locks and come out of runnable state.
926 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800927 VLOG(threads) << "SuspendThreadByThreadId waiting to allow thread chance to suspend";
928 ThreadSuspendSleep(sleep_us);
929 sleep_us = std::min(sleep_us * 2, kThreadSuspendMaxSleepUs);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700930 }
931}
932
933Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
934 Thread* self = Thread::Current();
935 MutexLock mu(self, *Locks::thread_list_lock_);
936 for (const auto& thread : list_) {
937 if (thread->GetThreadId() == thin_lock_id) {
938 CHECK(thread == self || thread->IsSuspended());
939 return thread;
940 }
941 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700942 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700943}
944
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700945void ThreadList::SuspendAllForDebugger() {
946 Thread* self = Thread::Current();
947 Thread* debug_thread = Dbg::GetDebugThread();
948
949 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
950
Yu Lieac44242015-06-29 10:50:03 +0800951 SuspendAllInternal(self, self, debug_thread, true);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700952 // Block on the mutator lock until all Runnable threads release their share of access then
953 // immediately unlock again.
954#if HAVE_TIMED_RWLOCK
955 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700956 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100957 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700958 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700959 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700960 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700961#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700962 Locks::mutator_lock_->ExclusiveLock(self);
963 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700964#endif
Mathieu Chartier9450c6c2015-11-07 11:55:23 -0800965 // Disabled for the following race condition:
966 // Thread 1 calls SuspendAllForDebugger, gets preempted after pulsing the mutator lock.
967 // Thread 2 calls SuspendAll and SetStateUnsafe (perhaps from Dbg::Disconnected).
968 // Thread 1 fails assertion that all threads are suspended due to thread 2 being in a runnable
969 // state (from SetStateUnsafe).
970 // AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700971
Sebastien Hertzed2be172014-08-19 15:33:43 +0200972 VLOG(threads) << *self << " SuspendAllForDebugger complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700973}
974
Elliott Hughes475fc232011-10-25 15:00:35 -0700975void ThreadList::SuspendSelfForDebugger() {
Sebastien Hertz1558b572015-02-25 15:05:59 +0100976 Thread* const self = Thread::Current();
977 self->SetReadyForDebugInvoke(true);
Elliott Hughes01158d72011-09-19 19:47:10 -0700978
Elliott Hughes475fc232011-10-25 15:00:35 -0700979 // The debugger thread must not suspend itself due to debugger activity!
980 Thread* debug_thread = Dbg::GetDebugThread();
Elliott Hughes475fc232011-10-25 15:00:35 -0700981 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800982 CHECK_NE(self->GetState(), kRunnable);
983 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700984
Sebastien Hertzcbc50642015-06-01 17:33:12 +0200985 // The debugger may have detached while we were executing an invoke request. In that case, we
986 // must not suspend ourself.
987 DebugInvokeReq* pReq = self->GetInvokeReq();
988 const bool skip_thread_suspension = (pReq != nullptr && !Dbg::IsDebuggerActive());
989 if (!skip_thread_suspension) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800990 // Collisions with other suspends aren't really interesting. We want
991 // to ensure that we're the only one fiddling with the suspend count
992 // though.
993 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Yu Lieac44242015-06-29 10:50:03 +0800994 self->ModifySuspendCount(self, +1, nullptr, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700995 CHECK_GT(self->GetSuspendCount(), 0);
Sebastien Hertzcbc50642015-06-01 17:33:12 +0200996
997 VLOG(threads) << *self << " self-suspending (debugger)";
998 } else {
999 // We must no longer be subject to debugger suspension.
1000 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
1001 CHECK_EQ(self->GetDebugSuspendCount(), 0) << "Debugger detached without resuming us";
1002
1003 VLOG(threads) << *self << " not self-suspending because debugger detached during invoke";
jeffhaoa77f0f62012-12-05 17:19:31 -08001004 }
Elliott Hughes475fc232011-10-25 15:00:35 -07001005
Sebastien Hertzcbc50642015-06-01 17:33:12 +02001006 // If the debugger requested an invoke, we need to send the reply and clear the request.
Sebastien Hertz1558b572015-02-25 15:05:59 +01001007 if (pReq != nullptr) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +02001008 Dbg::FinishInvokeMethod(pReq);
Sebastien Hertz1558b572015-02-25 15:05:59 +01001009 self->ClearDebugInvokeReq();
Sebastien Hertzcbc50642015-06-01 17:33:12 +02001010 pReq = nullptr; // object has been deleted, clear it for safety.
Sebastien Hertz21e729c2014-02-18 14:16:00 +01001011 }
1012
Elliott Hughes475fc232011-10-25 15:00:35 -07001013 // Tell JDWP that we've completed suspension. The JDWP thread can't
1014 // tell us to resume before we're fully asleep because we hold the
1015 // suspend count lock.
1016 Dbg::ClearWaitForEventThread();
1017
jeffhaoa77f0f62012-12-05 17:19:31 -08001018 {
1019 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001020 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001021 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001022 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -08001023 // The condition was signaled but we're still suspended. This
Sebastien Hertzf272af42014-09-18 10:20:42 +02001024 // can happen when we suspend then resume all threads to
1025 // update instrumentation or compute monitor info. This can
1026 // also happen if the debugger lets go while a SIGQUIT thread
jeffhaoa77f0f62012-12-05 17:19:31 -08001027 // dump event is pending (assuming SignalCatcher was resumed for
1028 // just long enough to try to grab the thread-suspend lock).
Sebastien Hertzf272af42014-09-18 10:20:42 +02001029 VLOG(jdwp) << *self << " still suspended after undo "
1030 << "(suspend count=" << self->GetSuspendCount() << ", "
1031 << "debug suspend count=" << self->GetDebugSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -08001032 }
Elliott Hughes475fc232011-10-25 15:00:35 -07001033 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001034 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -07001035 }
jeffhaoa77f0f62012-12-05 17:19:31 -08001036
Sebastien Hertz1558b572015-02-25 15:05:59 +01001037 self->SetReadyForDebugInvoke(false);
Elliott Hughes1f729aa2012-03-02 13:55:41 -08001038 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -07001039}
1040
Sebastien Hertz253fa552014-10-14 17:27:15 +02001041void ThreadList::ResumeAllForDebugger() {
1042 Thread* self = Thread::Current();
1043 Thread* debug_thread = Dbg::GetDebugThread();
Sebastien Hertz253fa552014-10-14 17:27:15 +02001044
1045 VLOG(threads) << *self << " ResumeAllForDebugger starting...";
1046
1047 // Threads can't resume if we exclusively hold the mutator lock.
1048 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
1049
1050 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001051 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Sebastien Hertz253fa552014-10-14 17:27:15 +02001052 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001053 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Sebastien Hertz253fa552014-10-14 17:27:15 +02001054 // Update global suspend all state for attaching threads.
1055 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Sebastien Hertzf9d233d2015-01-09 14:51:41 +01001056 if (debug_suspend_all_count_ > 0) {
Sebastien Hertz253fa552014-10-14 17:27:15 +02001057 --suspend_all_count_;
1058 --debug_suspend_all_count_;
Sebastien Hertz253fa552014-10-14 17:27:15 +02001059 } else {
1060 // We've been asked to resume all threads without being asked to
Sebastien Hertzf9d233d2015-01-09 14:51:41 +01001061 // suspend them all before. That may happen if a debugger tries
1062 // to resume some suspended threads (with suspend count == 1)
1063 // at once with a VirtualMachine.Resume command. Let's print a
1064 // warning.
Sebastien Hertz253fa552014-10-14 17:27:15 +02001065 LOG(WARNING) << "Debugger attempted to resume all threads without "
1066 << "having suspended them all before.";
1067 }
Sebastien Hertzf9d233d2015-01-09 14:51:41 +01001068 // Decrement everybody's suspend count (except our own).
1069 for (const auto& thread : list_) {
1070 if (thread == self || thread == debug_thread) {
1071 continue;
1072 }
1073 if (thread->GetDebugSuspendCount() == 0) {
1074 // This thread may have been individually resumed with ThreadReference.Resume.
1075 continue;
1076 }
1077 VLOG(threads) << "requesting thread resume: " << *thread;
Yu Lieac44242015-06-29 10:50:03 +08001078 thread->ModifySuspendCount(self, -1, nullptr, true);
Sebastien Hertzf9d233d2015-01-09 14:51:41 +01001079 }
Sebastien Hertz253fa552014-10-14 17:27:15 +02001080 }
1081 }
1082
Sebastien Hertzf9d233d2015-01-09 14:51:41 +01001083 {
Sebastien Hertz253fa552014-10-14 17:27:15 +02001084 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
1085 Thread::resume_cond_->Broadcast(self);
1086 }
1087
1088 VLOG(threads) << *self << " ResumeAllForDebugger complete";
1089}
1090
Elliott Hughes234ab152011-10-26 14:02:26 -07001091void ThreadList::UndoDebuggerSuspensions() {
1092 Thread* self = Thread::Current();
1093
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001094 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -07001095
1096 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001097 MutexLock mu(self, *Locks::thread_list_lock_);
1098 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001099 // Update global suspend all state for attaching threads.
1100 suspend_all_count_ -= debug_suspend_all_count_;
1101 debug_suspend_all_count_ = 0;
1102 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001103 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001104 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -07001105 continue;
1106 }
Yu Lieac44242015-06-29 10:50:03 +08001107 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), nullptr, true);
Elliott Hughes234ab152011-10-26 14:02:26 -07001108 }
1109 }
1110
1111 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001112 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -07001113 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -07001114 }
1115
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001116 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -07001117}
1118
Elliott Hughese52e49b2012-04-02 16:05:44 -07001119void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001120 Thread* self = Thread::Current();
1121 Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartier91e56692015-03-03 13:51:04 -08001122 while (true) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001123 {
1124 // No more threads can be born after we start to shutdown.
1125 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001126 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -07001127 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
1128 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001129 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier91e56692015-03-03 13:51:04 -08001130 // Also wait for any threads that are unregistering to finish. This is required so that no
1131 // threads access the thread list after it is deleted. TODO: This may not work for user daemon
1132 // threads since they could unregister at the wrong time.
1133 bool done = unregistering_count_ == 0;
1134 if (done) {
1135 for (const auto& thread : list_) {
1136 if (thread != self && !thread->IsDaemon()) {
1137 done = false;
1138 break;
1139 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001140 }
1141 }
Mathieu Chartier91e56692015-03-03 13:51:04 -08001142 if (done) {
1143 break;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001144 }
Mathieu Chartier91e56692015-03-03 13:51:04 -08001145 // Wait for another thread to exit before re-checking.
1146 Locks::thread_exit_cond_->Wait(self);
1147 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001148}
1149
Mathieu Chartier4d87df62016-01-07 15:14:19 -08001150void ThreadList::SuspendAllDaemonThreadsForShutdown() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001151 Thread* self = Thread::Current();
1152 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier62597d12016-01-11 10:19:06 -08001153 size_t daemons_left = 0;
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001154 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -07001155 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001156 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001157 // This is only run after all non-daemon threads have exited, so the remainder should all be
1158 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -07001159 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -07001160 if (thread != self) {
Yu Lieac44242015-06-29 10:50:03 +08001161 thread->ModifySuspendCount(self, +1, nullptr, false);
Mathieu Chartier62597d12016-01-11 10:19:06 -08001162 ++daemons_left;
Elliott Hughese52e49b2012-04-02 16:05:44 -07001163 }
Mathieu Chartier4d87df62016-01-07 15:14:19 -08001164 // We are shutting down the runtime, set the JNI functions of all the JNIEnvs to be
1165 // the sleep forever one.
1166 thread->GetJniEnv()->SetFunctionsToRuntimeShutdownFunctions();
Elliott Hughes038a8062011-09-18 14:12:41 -07001167 }
1168 }
Mathieu Chartier62597d12016-01-11 10:19:06 -08001169 // If we have any daemons left, wait 200ms to ensure they are not stuck in a place where they
1170 // are about to access runtime state and are not in a runnable state. Examples: Monitor code
1171 // or waking up from a condition variable. TODO: Try and see if there is a better way to wait
1172 // for daemon threads to be in a blocked state.
1173 if (daemons_left > 0) {
1174 static constexpr size_t kDaemonSleepTime = 200 * 1000;
1175 usleep(kDaemonSleepTime);
1176 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001177 // Give the threads a chance to suspend, complaining if they're slow.
1178 bool have_complained = false;
Mathieu Chartierba098ba2016-01-07 09:31:33 -08001179 static constexpr size_t kTimeoutMicroseconds = 2000 * 1000;
1180 static constexpr size_t kSleepMicroseconds = 1000;
1181 for (size_t i = 0; i < kTimeoutMicroseconds / kSleepMicroseconds; ++i) {
Elliott Hughes038a8062011-09-18 14:12:41 -07001182 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -07001183 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001184 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -07001185 if (!have_complained) {
1186 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
1187 have_complained = true;
1188 }
1189 all_suspended = false;
1190 }
1191 }
1192 if (all_suspended) {
1193 return;
1194 }
Mathieu Chartierba098ba2016-01-07 09:31:33 -08001195 usleep(kSleepMicroseconds);
Elliott Hughes038a8062011-09-18 14:12:41 -07001196 }
Mathieu Chartierba098ba2016-01-07 09:31:33 -08001197 LOG(WARNING) << "timed out suspending all daemon threads";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001198}
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001199
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001200void ThreadList::Register(Thread* self) {
1201 DCHECK_EQ(self, Thread::Current());
1202
1203 if (VLOG_IS_ON(threads)) {
1204 std::ostringstream oss;
1205 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
Ian Rogers5a9ba012014-05-19 13:28:52 -07001206 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001207 }
1208
1209 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
1210 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -07001211 MutexLock mu(self, *Locks::thread_list_lock_);
1212 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001213 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -07001214 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
1215 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
1216 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
Yu Lieac44242015-06-29 10:50:03 +08001217 self->ModifySuspendCount(self, +1, nullptr, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001218 }
Ian Rogers2966e132014-04-02 08:34:36 -07001219 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
Yu Lieac44242015-06-29 10:50:03 +08001220 self->ModifySuspendCount(self, +1, nullptr, false);
Ian Rogers01ae5802012-09-28 16:14:01 -07001221 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001222 CHECK(!Contains(self));
1223 list_.push_back(self);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001224 if (kUseReadBarrier) {
Hiroshi Yamauchi00370822015-08-18 14:47:25 -07001225 // Initialize according to the state of the CC collector.
1226 bool is_gc_marking =
1227 Runtime::Current()->GetHeap()->ConcurrentCopyingCollector()->IsMarking();
1228 self->SetIsGcMarking(is_gc_marking);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001229 bool weak_ref_access_enabled =
1230 Runtime::Current()->GetHeap()->ConcurrentCopyingCollector()->IsWeakRefAccessEnabled();
1231 self->SetWeakRefAccessEnabled(weak_ref_access_enabled);
1232 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001233}
1234
1235void ThreadList::Unregister(Thread* self) {
1236 DCHECK_EQ(self, Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -07001237 CHECK_NE(self->GetState(), kRunnable);
1238 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001239
1240 VLOG(threads) << "ThreadList::Unregister() " << *self;
1241
Mathieu Chartier91e56692015-03-03 13:51:04 -08001242 {
1243 MutexLock mu(self, *Locks::thread_list_lock_);
1244 ++unregistering_count_;
1245 }
1246
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001247 // Any time-consuming destruction, plus anything that can call back into managed code or
Mathieu Chartier91e56692015-03-03 13:51:04 -08001248 // suspend and so on, must happen at this point, and not in ~Thread. The self->Destroy is what
1249 // causes the threads to join. It is important to do this after incrementing unregistering_count_
1250 // since we want the runtime to wait for the daemon threads to exit before deleting the thread
1251 // list.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001252 self->Destroy();
1253
Jeff Haoe094b872014-10-14 13:12:01 -07001254 // If tracing, remember thread id and name before thread exits.
1255 Trace::StoreExitingThreadInfo(self);
1256
Ian Rogersdd7624d2014-03-14 17:43:00 -07001257 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier91e56692015-03-03 13:51:04 -08001258 while (true) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001259 // Remove and delete the Thread* while holding the thread_list_lock_ and
1260 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -07001261 // Note: deliberately not using MutexLock that could hold a stale self pointer.
Mathieu Chartier91e56692015-03-03 13:51:04 -08001262 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersa2af5c72014-09-15 15:17:07 -07001263 if (!Contains(self)) {
Mathieu Chartier9db831a2015-02-24 17:20:30 -08001264 std::string thread_name;
1265 self->GetThreadName(thread_name);
Ian Rogersa2af5c72014-09-15 15:17:07 -07001266 std::ostringstream os;
Christopher Ferris6cff48f2014-01-26 21:36:13 -08001267 DumpNativeStack(os, GetTid(), nullptr, " native: ", nullptr);
Mathieu Chartier9db831a2015-02-24 17:20:30 -08001268 LOG(ERROR) << "Request to unregister unattached thread " << thread_name << "\n" << os.str();
Mathieu Chartier91e56692015-03-03 13:51:04 -08001269 break;
Ian Rogersa2af5c72014-09-15 15:17:07 -07001270 } else {
Mathieu Chartier91e56692015-03-03 13:51:04 -08001271 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersa2af5c72014-09-15 15:17:07 -07001272 if (!self->IsSuspended()) {
1273 list_.remove(self);
Mathieu Chartier91e56692015-03-03 13:51:04 -08001274 break;
Ian Rogersa2af5c72014-09-15 15:17:07 -07001275 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001276 }
Mathieu Chartier91e56692015-03-03 13:51:04 -08001277 // We failed to remove the thread due to a suspend request, loop and try again.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001278 }
Mathieu Chartier91e56692015-03-03 13:51:04 -08001279 delete self;
1280
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -08001281 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
1282 // temporarily have multiple threads with the same thread id. When this occurs, it causes
1283 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
1284 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001285
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001286 // Clear the TLS data, so that the underlying native thread is recognizably detached.
1287 // (It may wish to reattach later.)
Andreas Gampe4382f1e2015-08-05 01:08:53 +00001288#ifdef __ANDROID__
1289 __get_tls()[TLS_SLOT_ART_THREAD_SELF] = nullptr;
1290#else
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001291 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, nullptr), "detach self");
Andreas Gampe4382f1e2015-08-05 01:08:53 +00001292#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001293
1294 // Signal that a thread just detached.
Mathieu Chartier91e56692015-03-03 13:51:04 -08001295 MutexLock mu(nullptr, *Locks::thread_list_lock_);
1296 --unregistering_count_;
1297 Locks::thread_exit_cond_->Broadcast(nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001298}
1299
1300void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001301 for (const auto& thread : list_) {
1302 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001303 }
1304}
1305
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001306void ThreadList::VisitRoots(RootVisitor* visitor) const {
Ian Rogers81d425b2012-09-27 16:03:43 -07001307 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001308 for (const auto& thread : list_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001309 thread->VisitRoots(visitor);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001310 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001311}
1312
Ian Rogerscfaa4552012-11-26 21:00:08 -08001313uint32_t ThreadList::AllocThreadId(Thread* self) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001314 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -07001315 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
1316 if (!allocated_ids_[i]) {
1317 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001318 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -07001319 }
1320 }
1321 LOG(FATAL) << "Out of internal thread ids";
1322 return 0;
1323}
1324
Ian Rogerscfaa4552012-11-26 21:00:08 -08001325void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001326 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001327 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -07001328 DCHECK(allocated_ids_[id]) << id;
1329 allocated_ids_.reset(id);
1330}
1331
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001332ScopedSuspendAll::ScopedSuspendAll(const char* cause, bool long_suspend) {
1333 Runtime::Current()->GetThreadList()->SuspendAll(cause, long_suspend);
1334}
1335
1336ScopedSuspendAll::~ScopedSuspendAll() {
1337 Runtime::Current()->GetThreadList()->ResumeAll();
1338}
1339
Elliott Hughes8daa0922011-09-11 13:46:25 -07001340} // namespace art