blob: 83c5ffb135cdff0777a918d0966f4fc8158a4a35 [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
21#include <cutils/trace.h>
Elliott Hughesabbe07d2012-06-05 17:42:23 -070022#include <dirent.h>
Ian Rogersd9c4fc92013-10-01 19:45:43 -070023#include <ScopedLocalRef.h>
24#include <ScopedUtfChars.h>
Elliott Hughesabbe07d2012-06-05 17:42:23 -070025#include <sys/types.h>
Elliott Hughes038a8062011-09-18 14:12:41 -070026#include <unistd.h>
27
Ian Rogersc7dd2952014-10-21 23:31:19 -070028#include <sstream>
29
Mathieu Chartier70a596d2014-12-17 14:56:47 -080030#include "base/histogram-inl.h"
Elliott Hughes76b61672012-12-12 17:47:30 -080031#include "base/mutex.h"
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -070032#include "base/mutex-inl.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080033#include "base/timing_logger.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070034#include "debugger.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070035#include "jni_internal.h"
36#include "lock_word.h"
37#include "monitor.h"
38#include "scoped_thread_state_change.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080039#include "thread.h"
Jeff Haoe094b872014-10-14 13:12:01 -070040#include "trace.h"
Elliott Hughesabbe07d2012-06-05 17:42:23 -070041#include "utils.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070042#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070043
Elliott Hughes8daa0922011-09-11 13:46:25 -070044namespace art {
45
Mathieu Chartier251755c2014-07-15 18:10:25 -070046static constexpr uint64_t kLongThreadSuspendThreshold = MsToNs(5);
Mathieu Chartier99143862015-02-03 14:26:46 -080047static constexpr uint64_t kThreadSuspendTimeoutMs = 30 * 1000; // 30s.
48// Use 0 since we want to yield to prevent blocking for an unpredictable amount of time.
49static constexpr useconds_t kThreadSuspendInitialSleepUs = 0;
50static constexpr useconds_t kThreadSuspendMaxYieldUs = 3000;
51static constexpr useconds_t kThreadSuspendMaxSleepUs = 5000;
Mathieu Chartier251755c2014-07-15 18:10:25 -070052
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080053ThreadList::ThreadList()
Chao-ying Fu9e369312014-05-21 11:20:52 -070054 : suspend_all_count_(0), debug_suspend_all_count_(0),
Mathieu Chartier70a596d2014-12-17 14:56:47 -080055 thread_exit_cond_("thread exit condition variable", *Locks::thread_list_lock_),
56 suspend_all_historam_("suspend all histogram", 16, 64) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070057 CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1)));
Elliott Hughes8daa0922011-09-11 13:46:25 -070058}
59
60ThreadList::~ThreadList() {
Elliott Hughese52e49b2012-04-02 16:05:44 -070061 // Detach the current thread if necessary. If we failed to start, there might not be any threads.
Elliott Hughes6a144332012-04-03 13:07:11 -070062 // We need to detach the current thread here in case there's another thread waiting to join with
63 // us.
Mathieu Chartierfec72f42014-10-09 12:57:58 -070064 bool contains = false;
65 {
66 Thread* self = Thread::Current();
67 MutexLock mu(self, *Locks::thread_list_lock_);
68 contains = Contains(self);
69 }
70 if (contains) {
Elliott Hughes8daa0922011-09-11 13:46:25 -070071 Runtime::Current()->DetachCurrentThread();
72 }
Elliott Hughes6a144332012-04-03 13:07:11 -070073
74 WaitForOtherNonDaemonThreadsToExit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070075 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
76 // Thread::Init.
Elliott Hughes6a144332012-04-03 13:07:11 -070077 SuspendAllDaemonThreads();
Elliott Hughes8daa0922011-09-11 13:46:25 -070078}
79
80bool ThreadList::Contains(Thread* thread) {
81 return find(list_.begin(), list_.end(), thread) != list_.end();
82}
83
Elliott Hughesabbe07d2012-06-05 17:42:23 -070084bool ThreadList::Contains(pid_t tid) {
Mathieu Chartier02e25112013-08-14 16:14:24 -070085 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070086 if (thread->GetTid() == tid) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -070087 return true;
88 }
89 }
90 return false;
91}
92
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070093pid_t ThreadList::GetLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -070094 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
Elliott Hughesaccd83d2011-10-17 14:25:58 -070095}
96
Mathieu Chartier590fee92013-09-13 13:46:47 -070097void ThreadList::DumpNativeStacks(std::ostream& os) {
98 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
99 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700100 os << "DUMPING THREAD " << thread->GetTid() << "\n";
Christopher Ferrisa2cee182014-04-16 19:13:59 -0700101 DumpNativeStack(os, thread->GetTid(), "\t");
Mathieu Chartier590fee92013-09-13 13:46:47 -0700102 os << "\n";
103 }
104}
105
Elliott Hughesc967f782012-04-16 10:23:15 -0700106void ThreadList::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800107 {
108 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier23f6e692014-12-18 18:24:39 -0800109 // Only print if we have samples.
110 if (suspend_all_historam_.SampleSize() > 0) {
111 Histogram<uint64_t>::CumulativeData data;
112 suspend_all_historam_.CreateHistogram(&data);
113 suspend_all_historam_.PrintConfidenceIntervals(os, 0.99, data); // Dump time to suspend.
114 }
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800115 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700116 Dump(os);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700117 DumpUnattachedThreads(os);
118}
119
Ian Rogerscfaa4552012-11-26 21:00:08 -0800120static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
121 // TODO: No thread safety analysis as DumpState with a NULL thread won't access fields, should
122 // refactor DumpState to avoid skipping analysis.
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700123 Thread::DumpState(os, NULL, tid);
124 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -0700125 // TODO: Reenable this when the native code in system_server can handle it.
126 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
127 if (false) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -0700128 DumpNativeStack(os, tid, " native: ");
Brian Carlstromed8b7232012-06-27 17:54:47 -0700129 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700130 os << "\n";
131}
132
133void ThreadList::DumpUnattachedThreads(std::ostream& os) {
134 DIR* d = opendir("/proc/self/task");
135 if (!d) {
136 return;
137 }
138
Ian Rogers50b35e22012-10-04 10:09:15 -0700139 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700140 dirent* e;
141 while ((e = readdir(d)) != NULL) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700142 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700143 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700144 if (!*end) {
145 bool contains;
146 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700147 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700148 contains = Contains(tid);
149 }
150 if (!contains) {
151 DumpUnattachedThread(os, tid);
152 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700153 }
154 }
155 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800156}
157
Andreas Gampe4a3d19b2015-01-09 17:54:51 -0800158// Dump checkpoint timeout in milliseconds. Larger amount on the host, as dumping will invoke
159// addr2line when available.
Andreas Gampe1e4b0ca2015-01-14 09:06:32 -0800160static constexpr uint32_t kDumpWaitTimeout = kIsTargetBuild ? 10000 : 20000;
Andreas Gampe4a3d19b2015-01-09 17:54:51 -0800161
Ian Rogers7b078e82014-09-10 14:44:24 -0700162// A closure used by Thread::Dump.
163class DumpCheckpoint FINAL : public Closure {
164 public:
165 explicit DumpCheckpoint(std::ostream* os) : os_(os), barrier_(0) {}
166
167 void Run(Thread* thread) OVERRIDE {
168 // Note thread and self may not be equal if thread was already suspended at the point of the
169 // request.
170 Thread* self = Thread::Current();
171 std::ostringstream local_os;
172 {
173 ScopedObjectAccess soa(self);
174 thread->Dump(local_os);
175 }
176 local_os << "\n";
177 {
178 // Use the logging lock to ensure serialization when writing to the common ostream.
179 MutexLock mu(self, *Locks::logging_lock_);
180 *os_ << local_os.str();
181 }
Lei Lidd9943d2015-02-02 14:24:44 +0800182 if (thread->GetState() == kRunnable) {
183 barrier_.Pass(self);
184 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700185 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700186
187 void WaitForThreadsToRunThroughCheckpoint(size_t threads_running_checkpoint) {
188 Thread* self = Thread::Current();
189 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
Andreas Gampe1e4b0ca2015-01-14 09:06:32 -0800190 bool timed_out = barrier_.Increment(self, threads_running_checkpoint, kDumpWaitTimeout);
Ian Rogers2156ff12014-09-13 19:20:54 -0700191 if (timed_out) {
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000192 // Avoid a recursive abort.
193 LOG((kIsDebugBuild && (gAborting == 0)) ? FATAL : ERROR)
194 << "Unexpected time out during dump checkpoint.";
Ian Rogers2156ff12014-09-13 19:20:54 -0700195 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700196 }
197
198 private:
199 // The common stream that will accumulate all the dumps.
200 std::ostream* const os_;
201 // The barrier to be passed through and for the requestor to wait upon.
202 Barrier barrier_;
203};
204
205void ThreadList::Dump(std::ostream& os) {
206 {
207 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
208 os << "DALVIK THREADS (" << list_.size() << "):\n";
209 }
210 DumpCheckpoint checkpoint(&os);
211 size_t threads_running_checkpoint = RunCheckpoint(&checkpoint);
Lei Lidd9943d2015-02-02 14:24:44 +0800212 if (threads_running_checkpoint != 0) {
213 checkpoint.WaitForThreadsToRunThroughCheckpoint(threads_running_checkpoint);
214 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700215}
216
Ian Rogers50b35e22012-10-04 10:09:15 -0700217void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
218 MutexLock mu(self, *Locks::thread_list_lock_);
219 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700220 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800221 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700222 CHECK(thread->IsSuspended())
223 << "\nUnsuspended thread: <<" << *thread << "\n"
224 << "self: <<" << *Thread::Current();
225 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700226 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700227}
228
Ian Rogers66aee5c2012-08-15 17:17:47 -0700229#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700230// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Andreas Gampe794ad762015-02-23 08:12:24 -0800231NO_RETURN static void UnsafeLogFatalForThreadSuspendAllTimeout() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700232 Runtime* runtime = Runtime::Current();
233 std::ostringstream ss;
234 ss << "Thread suspend timeout\n";
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700235 Locks::mutator_lock_->Dump(ss);
236 ss << "\n";
Ian Rogers7b078e82014-09-10 14:44:24 -0700237 runtime->GetThreadList()->Dump(ss);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700238 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800239 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700240}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700241#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700242
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800243// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
Mathieu Chartier99143862015-02-03 14:26:46 -0800244// individual thread requires polling. delay_us is the requested sleep wait. If delay_us is 0 then
245// we use sched_yield instead of calling usleep.
246static void ThreadSuspendSleep(useconds_t delay_us) {
247 if (delay_us == 0) {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800248 sched_yield();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800249 } else {
Mathieu Chartier99143862015-02-03 14:26:46 -0800250 usleep(delay_us);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800251 }
252}
253
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700254size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700255 Thread* self = Thread::Current();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800256 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
257 Locks::thread_list_lock_->AssertNotHeld(self);
258 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000259 if (kDebugLocking && gAborting == 0) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700260 CHECK_NE(self->GetState(), kRunnable);
261 }
262
263 std::vector<Thread*> suspended_count_modified_threads;
264 size_t count = 0;
265 {
266 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
267 // manually called.
268 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700269 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700270 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700271 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700272 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700273 if (thread->RequestCheckpoint(checkpoint_function)) {
Dave Allison0aded082013-11-07 13:15:11 -0800274 // This thread will run its checkpoint some time in the near future.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700275 count++;
276 break;
277 } else {
278 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700279 // The thread switched back to runnable.
280 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700281 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700282 continue;
283 }
284 thread->ModifySuspendCount(self, +1, false);
285 suspended_count_modified_threads.push_back(thread);
286 break;
287 }
288 }
289 }
290 }
291 }
292
293 // Run the checkpoint on ourself while we wait for threads to suspend.
294 checkpoint_function->Run(self);
295
296 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700297 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700298 if (!thread->IsSuspended()) {
Mathieu Chartier99143862015-02-03 14:26:46 -0800299 if (ATRACE_ENABLED()) {
300 std::ostringstream oss;
301 thread->ShortDump(oss);
302 ATRACE_BEGIN((std::string("Waiting for suspension of thread ") + oss.str()).c_str());
303 }
304 // Busy wait until the thread is suspended.
305 const uint64_t start_time = NanoTime();
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700306 do {
Mathieu Chartier99143862015-02-03 14:26:46 -0800307 ThreadSuspendSleep(kThreadSuspendInitialSleepUs);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700308 } while (!thread->IsSuspended());
Mathieu Chartier99143862015-02-03 14:26:46 -0800309 const uint64_t total_delay = NanoTime() - start_time;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800310 // Shouldn't need to wait for longer than 1000 microseconds.
Mathieu Chartier99143862015-02-03 14:26:46 -0800311 constexpr uint64_t kLongWaitThreshold = MsToNs(1);
312 ATRACE_END();
313 if (UNLIKELY(total_delay > kLongWaitThreshold)) {
314 LOG(WARNING) << "Long wait of " << PrettyDuration(total_delay) << " for "
315 << *thread << " suspension!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700316 }
317 }
318 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700319 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700320 {
321 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
322 thread->ModifySuspendCount(self, -1, false);
323 }
324 }
325
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800326 {
327 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
328 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
329 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
330 Thread::resume_cond_->Broadcast(self);
331 }
332
Lei Lidd9943d2015-02-02 14:24:44 +0800333 return count;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700334}
335
Dave Allison39c3bfb2014-01-28 18:33:52 -0800336// Request that a checkpoint function be run on all active (non-suspended)
337// threads. Returns the number of successful requests.
338size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
339 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700340 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
341 Locks::thread_list_lock_->AssertNotHeld(self);
342 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
343 CHECK_NE(self->GetState(), kRunnable);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800344
345 size_t count = 0;
346 {
347 // Call a checkpoint function for each non-suspended thread.
348 MutexLock mu(self, *Locks::thread_list_lock_);
349 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
350 for (const auto& thread : list_) {
351 if (thread != self) {
352 if (thread->RequestCheckpoint(checkpoint_function)) {
353 // This thread will run its checkpoint some time in the near future.
354 count++;
355 }
356 }
357 }
358 }
359
360 // Return the number of threads that will run the checkpoint function.
361 return count;
362}
363
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800364// A checkpoint/suspend-all hybrid to switch thread roots from
365// from-space to to-space refs. Used to synchronize threads at a point
366// to mark the initiation of marking while maintaining the to-space
367// invariant.
368size_t ThreadList::FlipThreadRoots(Closure* thread_flip_visitor, Closure* flip_callback,
369 gc::collector::GarbageCollector* collector) {
370 TimingLogger::ScopedTiming split("ThreadListFlip", collector->GetTimings());
371 const uint64_t start_time = NanoTime();
372 Thread* self = Thread::Current();
373 Locks::mutator_lock_->AssertNotHeld(self);
374 Locks::thread_list_lock_->AssertNotHeld(self);
375 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
376 CHECK_NE(self->GetState(), kRunnable);
377
378 std::vector<Thread*> runnable_threads;
379 std::vector<Thread*> other_threads;
380
381 // Suspend all threads once.
382 {
383 MutexLock mu(self, *Locks::thread_list_lock_);
384 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
385 // Update global suspend all state for attaching threads.
386 ++suspend_all_count_;
387 // Increment everybody's suspend count (except our own).
388 for (const auto& thread : list_) {
389 if (thread == self) {
390 continue;
391 }
392 thread->ModifySuspendCount(self, +1, false);
393 }
394 }
395
396 // Run the flip callback for the collector.
397 Locks::mutator_lock_->ExclusiveLock(self);
398 flip_callback->Run(self);
399 Locks::mutator_lock_->ExclusiveUnlock(self);
400 collector->RegisterPause(NanoTime() - start_time);
401
402 // Resume runnable threads.
403 {
404 MutexLock mu(self, *Locks::thread_list_lock_);
405 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
406 --suspend_all_count_;
407 for (const auto& thread : list_) {
408 if (thread == self) {
409 continue;
410 }
411 // Set the flip function for both runnable and suspended threads
412 // because Thread::DumpState/DumpJavaStack() (invoked by a
413 // checkpoint) may cause the flip function to be run for a
414 // runnable/suspended thread before a runnable threads runs it
415 // for itself or we run it for a suspended thread below.
416 thread->SetFlipFunction(thread_flip_visitor);
417 if (thread->IsSuspendedAtSuspendCheck()) {
418 // The thread will resume right after the broadcast.
419 thread->ModifySuspendCount(self, -1, false);
420 runnable_threads.push_back(thread);
421 } else {
422 other_threads.push_back(thread);
423 }
424 }
425 Thread::resume_cond_->Broadcast(self);
426 }
427
428 // Run the closure on the other threads and let them resume.
429 {
430 ReaderMutexLock mu(self, *Locks::mutator_lock_);
431 for (const auto& thread : other_threads) {
432 Closure* flip_func = thread->GetFlipFunction();
433 if (flip_func != nullptr) {
434 flip_func->Run(thread);
435 }
436 }
437 // Run it for self.
438 thread_flip_visitor->Run(self);
439 }
440
441 // Resume other threads.
442 {
443 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
444 for (const auto& thread : other_threads) {
445 thread->ModifySuspendCount(self, -1, false);
446 }
447 Thread::resume_cond_->Broadcast(self);
448 }
449
450 return runnable_threads.size() + other_threads.size() + 1; // +1 for self.
451}
452
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700453void ThreadList::SuspendAll() {
454 Thread* self = Thread::Current();
455
Jeff Haoc5d824a2014-07-28 18:35:38 -0700456 if (self != nullptr) {
457 VLOG(threads) << *self << " SuspendAll starting...";
458 } else {
459 VLOG(threads) << "Thread[null] SuspendAll starting...";
460 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700461 ATRACE_BEGIN("Suspending mutator threads");
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800462 const uint64_t start_time = NanoTime();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700463
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800464 Locks::mutator_lock_->AssertNotHeld(self);
465 Locks::thread_list_lock_->AssertNotHeld(self);
466 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Jeff Haoc5d824a2014-07-28 18:35:38 -0700467 if (kDebugLocking && self != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700468 CHECK_NE(self->GetState(), kRunnable);
469 }
470 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700471 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800472 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
473 // Update global suspend all state for attaching threads.
474 ++suspend_all_count_;
475 // Increment everybody's suspend count (except our own).
476 for (const auto& thread : list_) {
477 if (thread == self) {
478 continue;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700479 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800480 VLOG(threads) << "requesting thread suspend: " << *thread;
481 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700482 }
483 }
484
Ian Rogers66aee5c2012-08-15 17:17:47 -0700485 // Block on the mutator lock until all Runnable threads release their share of access.
486#if HAVE_TIMED_RWLOCK
487 // Timeout if we wait more than 30 seconds.
Mathieu Chartier99143862015-02-03 14:26:46 -0800488 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, kThreadSuspendTimeoutMs, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100489 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700490 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700491#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700492 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700493#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700494
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800495 const uint64_t end_time = NanoTime();
496 const uint64_t suspend_time = end_time - start_time;
497 suspend_all_historam_.AdjustAndAddValue(suspend_time);
498 if (suspend_time > kLongThreadSuspendThreshold) {
499 LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(suspend_time);
Mathieu Chartier251755c2014-07-15 18:10:25 -0700500 }
501
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800502 if (kDebugLocking) {
503 // Debug check that all threads are suspended.
504 AssertThreadsAreSuspended(self, self);
505 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700506
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700507 ATRACE_END();
508 ATRACE_BEGIN("Mutator threads suspended");
509
Jeff Haoc5d824a2014-07-28 18:35:38 -0700510 if (self != nullptr) {
511 VLOG(threads) << *self << " SuspendAll complete";
512 } else {
513 VLOG(threads) << "Thread[null] SuspendAll complete";
514 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700515}
516
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700517void ThreadList::ResumeAll() {
518 Thread* self = Thread::Current();
519
Jeff Haoc5d824a2014-07-28 18:35:38 -0700520 if (self != nullptr) {
521 VLOG(threads) << *self << " ResumeAll starting";
522 } else {
523 VLOG(threads) << "Thread[null] ResumeAll starting";
524 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700525
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700526 ATRACE_END();
527 ATRACE_BEGIN("Resuming mutator threads");
528
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800529 if (kDebugLocking) {
530 // Debug check that all threads are suspended.
531 AssertThreadsAreSuspended(self, self);
532 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700533
Ian Rogers81d425b2012-09-27 16:03:43 -0700534 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700535 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700536 MutexLock mu(self, *Locks::thread_list_lock_);
537 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700538 // Update global suspend all state for attaching threads.
539 --suspend_all_count_;
540 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700541 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700542 if (thread == self) {
543 continue;
544 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700545 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700546 }
547
548 // Broadcast a notification to all suspended threads, some or all of
549 // which may choose to wake up. No need to wait for them.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700550 if (self != nullptr) {
551 VLOG(threads) << *self << " ResumeAll waking others";
552 } else {
553 VLOG(threads) << "Thread[null] ResumeAll waking others";
554 }
Ian Rogersc604d732012-10-14 16:09:54 -0700555 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700556 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700557 ATRACE_END();
Jeff Haoc5d824a2014-07-28 18:35:38 -0700558
559 if (self != nullptr) {
560 VLOG(threads) << *self << " ResumeAll complete";
561 } else {
562 VLOG(threads) << "Thread[null] ResumeAll complete";
563 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700564}
565
566void ThreadList::Resume(Thread* thread, bool for_debugger) {
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800567 // This assumes there was an ATRACE_BEGIN when we suspended the thread.
568 ATRACE_END();
569
Ian Rogers81d425b2012-09-27 16:03:43 -0700570 Thread* self = Thread::Current();
571 DCHECK_NE(thread, self);
Brian Carlstromba32de42014-08-27 23:43:46 -0700572 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..."
573 << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700574
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700575 {
576 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700577 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700578 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700579 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
580 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700581 if (!Contains(thread)) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700582 // We only expect threads within the thread-list to have been suspended otherwise we can't
583 // stop such threads from delete-ing themselves.
584 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
585 << ") thread not within thread list";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700586 return;
587 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700588 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700589 }
590
591 {
Brian Carlstromba32de42014-08-27 23:43:46 -0700592 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700593 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700594 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700595 }
596
Brian Carlstromba32de42014-08-27 23:43:46 -0700597 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700598}
Elliott Hughes01158d72011-09-19 19:47:10 -0700599
Ian Rogersc7dd2952014-10-21 23:31:19 -0700600static void ThreadSuspendByPeerWarning(Thread* self, LogSeverity severity, const char* message,
601 jobject peer) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700602 JNIEnvExt* env = self->GetJniEnv();
603 ScopedLocalRef<jstring>
604 scoped_name_string(env, (jstring)env->GetObjectField(peer,
605 WellKnownClasses::java_lang_Thread_name));
606 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
607 if (scoped_name_chars.c_str() == NULL) {
Ian Rogersc7dd2952014-10-21 23:31:19 -0700608 LOG(severity) << message << ": " << peer;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700609 env->ExceptionClear();
610 } else {
Ian Rogersc7dd2952014-10-21 23:31:19 -0700611 LOG(severity) << message << ": " << peer << ":" << scoped_name_chars.c_str();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700612 }
613}
614
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700615Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
616 bool debug_suspension, bool* timed_out) {
Mathieu Chartier3a958aa2015-02-04 12:52:34 -0800617 const uint64_t start_time = NanoTime();
Mathieu Chartier99143862015-02-03 14:26:46 -0800618 useconds_t sleep_us = kThreadSuspendInitialSleepUs;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700619 *timed_out = false;
Mathieu Chartier99143862015-02-03 14:26:46 -0800620 Thread* const self = Thread::Current();
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800621 Thread* suspended_thread = nullptr;
Brian Carlstromba32de42014-08-27 23:43:46 -0700622 VLOG(threads) << "SuspendThreadByPeer starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700623 while (true) {
624 Thread* thread;
625 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700626 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
627 // is requesting another suspend, to avoid deadlock, by requiring this function be called
628 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
629 // than request thread suspension, to avoid potential cycles in threads requesting each other
630 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700631 ScopedObjectAccess soa(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800632 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700633 thread = Thread::FromManagedThread(soa, peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700634 if (thread == nullptr) {
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800635 if (suspended_thread != nullptr) {
636 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
637 // If we incremented the suspend count but the thread reset its peer, we need to
638 // re-decrement it since it is shutting down and may deadlock the runtime in
639 // ThreadList::WaitForOtherNonDaemonThreadsToExit.
640 suspended_thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
641 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700642 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700643 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700644 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700645 if (!Contains(thread)) {
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800646 CHECK(suspended_thread == nullptr);
Brian Carlstromba32de42014-08-27 23:43:46 -0700647 VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
648 << reinterpret_cast<void*>(thread);
649 return nullptr;
650 }
651 VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700652 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800653 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700654 if (request_suspension) {
Ian Rogers4ad5cd32014-11-11 23:08:07 -0800655 if (self->GetSuspendCount() > 0) {
656 // We hold the suspend count lock but another thread is trying to suspend us. Its not
657 // safe to try to suspend another thread in case we get a cycle. Start the loop again
658 // which will allow this thread to be suspended.
659 continue;
660 }
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800661 CHECK(suspended_thread == nullptr);
662 suspended_thread = thread;
663 suspended_thread->ModifySuspendCount(self, +1, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700664 request_suspension = false;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700665 } else {
666 // If the caller isn't requesting suspension, a suspension should have already occurred.
667 CHECK_GT(thread->GetSuspendCount(), 0);
668 }
669 // IsSuspended on the current thread will fail as the current thread is changed into
670 // Runnable above. As the suspend count is now raised if this is the current thread
671 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
672 // to just explicitly handle the current thread in the callers to this code.
673 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
674 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
675 // count, or else we've waited and it has self suspended) or is the current thread, we're
676 // done.
677 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700678 VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800679 if (ATRACE_ENABLED()) {
680 std::string name;
681 thread->GetThreadName(name);
682 ATRACE_BEGIN(StringPrintf("SuspendThreadByPeer suspended %s for peer=%p", name.c_str(),
683 peer).c_str());
684 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700685 return thread;
686 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800687 const uint64_t total_delay = NanoTime() - start_time;
688 if (total_delay >= MsToNs(kThreadSuspendTimeoutMs)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700689 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800690 if (suspended_thread != nullptr) {
691 CHECK_EQ(suspended_thread, thread);
692 suspended_thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700693 }
694 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700695 return nullptr;
Mathieu Chartier99143862015-02-03 14:26:46 -0800696 } else if (sleep_us == 0 &&
697 total_delay > static_cast<uint64_t>(kThreadSuspendMaxYieldUs) * 1000) {
698 // We have spun for kThreadSuspendMaxYieldUs time, switch to sleeps to prevent
699 // excessive CPU usage.
700 sleep_us = kThreadSuspendMaxYieldUs / 2;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700701 }
702 }
703 // Release locks and come out of runnable state.
704 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800705 VLOG(threads) << "SuspendThreadByPeer waiting to allow thread chance to suspend";
706 ThreadSuspendSleep(sleep_us);
707 // This may stay at 0 if sleep_us == 0, but this is WAI since we want to avoid using usleep at
708 // all if possible. This shouldn't be an issue since time to suspend should always be small.
709 sleep_us = std::min(sleep_us * 2, kThreadSuspendMaxSleepUs);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700710 }
711}
712
Ian Rogersc7dd2952014-10-21 23:31:19 -0700713static void ThreadSuspendByThreadIdWarning(LogSeverity severity, const char* message,
714 uint32_t thread_id) {
715 LOG(severity) << StringPrintf("%s: %d", message, thread_id);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700716}
717
718Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
719 bool* timed_out) {
Mathieu Chartier3a958aa2015-02-04 12:52:34 -0800720 const uint64_t start_time = NanoTime();
Mathieu Chartier99143862015-02-03 14:26:46 -0800721 useconds_t sleep_us = kThreadSuspendInitialSleepUs;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700722 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800723 Thread* suspended_thread = nullptr;
Mathieu Chartier99143862015-02-03 14:26:46 -0800724 Thread* const self = Thread::Current();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700725 CHECK_NE(thread_id, kInvalidThreadId);
Brian Carlstromba32de42014-08-27 23:43:46 -0700726 VLOG(threads) << "SuspendThreadByThreadId starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700727 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700728 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700729 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
730 // is requesting another suspend, to avoid deadlock, by requiring this function be called
731 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
732 // than request thread suspension, to avoid potential cycles in threads requesting each other
733 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700734 ScopedObjectAccess soa(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800735 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700736 Thread* thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700737 for (const auto& it : list_) {
738 if (it->GetThreadId() == thread_id) {
739 thread = it;
740 break;
741 }
742 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800743 if (thread == nullptr) {
744 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
745 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700746 // There's a race in inflating a lock and the owner giving up ownership and then dying.
747 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
Brian Carlstromba32de42014-08-27 23:43:46 -0700748 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700749 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700750 VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
751 DCHECK(Contains(thread));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700752 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800753 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800754 if (suspended_thread == nullptr) {
Ian Rogers4ad5cd32014-11-11 23:08:07 -0800755 if (self->GetSuspendCount() > 0) {
756 // We hold the suspend count lock but another thread is trying to suspend us. Its not
757 // safe to try to suspend another thread in case we get a cycle. Start the loop again
758 // which will allow this thread to be suspended.
759 continue;
760 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700761 thread->ModifySuspendCount(self, +1, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800762 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700763 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800764 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700765 // If the caller isn't requesting suspension, a suspension should have already occurred.
766 CHECK_GT(thread->GetSuspendCount(), 0);
767 }
768 // IsSuspended on the current thread will fail as the current thread is changed into
769 // Runnable above. As the suspend count is now raised if this is the current thread
770 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
771 // to just explicitly handle the current thread in the callers to this code.
772 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
773 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
774 // count, or else we've waited and it has self suspended) or is the current thread, we're
775 // done.
776 if (thread->IsSuspended()) {
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800777 if (ATRACE_ENABLED()) {
778 std::string name;
779 thread->GetThreadName(name);
780 ATRACE_BEGIN(StringPrintf("SuspendThreadByThreadId suspended %s id=%d",
781 name.c_str(), thread_id).c_str());
782 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700783 VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700784 return thread;
785 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800786 const uint64_t total_delay = NanoTime() - start_time;
787 if (total_delay >= MsToNs(kThreadSuspendTimeoutMs)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700788 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800789 if (suspended_thread != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700790 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
791 }
792 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700793 return nullptr;
Mathieu Chartier99143862015-02-03 14:26:46 -0800794 } else if (sleep_us == 0 &&
795 total_delay > static_cast<uint64_t>(kThreadSuspendMaxYieldUs) * 1000) {
796 // We have spun for kThreadSuspendMaxYieldUs time, switch to sleeps to prevent
797 // excessive CPU usage.
798 sleep_us = kThreadSuspendMaxYieldUs / 2;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700799 }
800 }
801 // Release locks and come out of runnable state.
802 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800803 VLOG(threads) << "SuspendThreadByThreadId waiting to allow thread chance to suspend";
804 ThreadSuspendSleep(sleep_us);
805 sleep_us = std::min(sleep_us * 2, kThreadSuspendMaxSleepUs);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700806 }
807}
808
809Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
810 Thread* self = Thread::Current();
811 MutexLock mu(self, *Locks::thread_list_lock_);
812 for (const auto& thread : list_) {
813 if (thread->GetThreadId() == thin_lock_id) {
814 CHECK(thread == self || thread->IsSuspended());
815 return thread;
816 }
817 }
818 return NULL;
819}
820
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700821void ThreadList::SuspendAllForDebugger() {
822 Thread* self = Thread::Current();
823 Thread* debug_thread = Dbg::GetDebugThread();
824
825 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
826
827 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800828 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700829 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800830 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700831 // Update global suspend all state for attaching threads.
Sebastien Hertz253fa552014-10-14 17:27:15 +0200832 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700833 ++suspend_all_count_;
834 ++debug_suspend_all_count_;
835 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700836 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700837 if (thread == self || thread == debug_thread) {
838 continue;
839 }
840 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700841 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700842 }
843 }
844 }
845
Ian Rogers66aee5c2012-08-15 17:17:47 -0700846 // Block on the mutator lock until all Runnable threads release their share of access then
847 // immediately unlock again.
848#if HAVE_TIMED_RWLOCK
849 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700850 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100851 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700852 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700853 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700854 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700855#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700856 Locks::mutator_lock_->ExclusiveLock(self);
857 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700858#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700859 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700860
Sebastien Hertzed2be172014-08-19 15:33:43 +0200861 VLOG(threads) << *self << " SuspendAllForDebugger complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700862}
863
Elliott Hughes475fc232011-10-25 15:00:35 -0700864void ThreadList::SuspendSelfForDebugger() {
865 Thread* self = Thread::Current();
Elliott Hughes01158d72011-09-19 19:47:10 -0700866
Elliott Hughes475fc232011-10-25 15:00:35 -0700867 // The debugger thread must not suspend itself due to debugger activity!
868 Thread* debug_thread = Dbg::GetDebugThread();
869 CHECK(debug_thread != NULL);
870 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800871 CHECK_NE(self->GetState(), kRunnable);
872 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700873
jeffhaoa77f0f62012-12-05 17:19:31 -0800874 {
875 // Collisions with other suspends aren't really interesting. We want
876 // to ensure that we're the only one fiddling with the suspend count
877 // though.
878 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
879 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700880 CHECK_GT(self->GetSuspendCount(), 0);
jeffhaoa77f0f62012-12-05 17:19:31 -0800881 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700882
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800883 VLOG(threads) << *self << " self-suspending (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700884
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100885 // Tell JDWP we've completed invocation and are ready to suspend.
886 DebugInvokeReq* pReq = self->GetInvokeReq();
887 DCHECK(pReq != NULL);
888 if (pReq->invoke_needed) {
889 // Clear this before signaling.
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200890 pReq->Clear();
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100891
892 VLOG(jdwp) << "invoke complete, signaling";
893 MutexLock mu(self, pReq->lock);
894 pReq->cond.Signal(self);
895 }
896
Elliott Hughes475fc232011-10-25 15:00:35 -0700897 // Tell JDWP that we've completed suspension. The JDWP thread can't
898 // tell us to resume before we're fully asleep because we hold the
899 // suspend count lock.
900 Dbg::ClearWaitForEventThread();
901
jeffhaoa77f0f62012-12-05 17:19:31 -0800902 {
903 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700904 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800905 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700906 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800907 // The condition was signaled but we're still suspended. This
Sebastien Hertzf272af42014-09-18 10:20:42 +0200908 // can happen when we suspend then resume all threads to
909 // update instrumentation or compute monitor info. This can
910 // also happen if the debugger lets go while a SIGQUIT thread
jeffhaoa77f0f62012-12-05 17:19:31 -0800911 // dump event is pending (assuming SignalCatcher was resumed for
912 // just long enough to try to grab the thread-suspend lock).
Sebastien Hertzf272af42014-09-18 10:20:42 +0200913 VLOG(jdwp) << *self << " still suspended after undo "
914 << "(suspend count=" << self->GetSuspendCount() << ", "
915 << "debug suspend count=" << self->GetDebugSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -0800916 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700917 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700918 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700919 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800920
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800921 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700922}
923
Sebastien Hertz253fa552014-10-14 17:27:15 +0200924void ThreadList::ResumeAllForDebugger() {
925 Thread* self = Thread::Current();
926 Thread* debug_thread = Dbg::GetDebugThread();
Sebastien Hertz253fa552014-10-14 17:27:15 +0200927
928 VLOG(threads) << *self << " ResumeAllForDebugger starting...";
929
930 // Threads can't resume if we exclusively hold the mutator lock.
931 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
932
933 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800934 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Sebastien Hertz253fa552014-10-14 17:27:15 +0200935 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800936 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Sebastien Hertz253fa552014-10-14 17:27:15 +0200937 // Update global suspend all state for attaching threads.
938 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100939 if (debug_suspend_all_count_ > 0) {
Sebastien Hertz253fa552014-10-14 17:27:15 +0200940 --suspend_all_count_;
941 --debug_suspend_all_count_;
Sebastien Hertz253fa552014-10-14 17:27:15 +0200942 } else {
943 // We've been asked to resume all threads without being asked to
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100944 // suspend them all before. That may happen if a debugger tries
945 // to resume some suspended threads (with suspend count == 1)
946 // at once with a VirtualMachine.Resume command. Let's print a
947 // warning.
Sebastien Hertz253fa552014-10-14 17:27:15 +0200948 LOG(WARNING) << "Debugger attempted to resume all threads without "
949 << "having suspended them all before.";
950 }
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100951 // Decrement everybody's suspend count (except our own).
952 for (const auto& thread : list_) {
953 if (thread == self || thread == debug_thread) {
954 continue;
955 }
956 if (thread->GetDebugSuspendCount() == 0) {
957 // This thread may have been individually resumed with ThreadReference.Resume.
958 continue;
959 }
960 VLOG(threads) << "requesting thread resume: " << *thread;
961 thread->ModifySuspendCount(self, -1, true);
962 }
Sebastien Hertz253fa552014-10-14 17:27:15 +0200963 }
964 }
965
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100966 {
Sebastien Hertz253fa552014-10-14 17:27:15 +0200967 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
968 Thread::resume_cond_->Broadcast(self);
969 }
970
971 VLOG(threads) << *self << " ResumeAllForDebugger complete";
972}
973
Elliott Hughes234ab152011-10-26 14:02:26 -0700974void ThreadList::UndoDebuggerSuspensions() {
975 Thread* self = Thread::Current();
976
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800977 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700978
979 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700980 MutexLock mu(self, *Locks::thread_list_lock_);
981 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700982 // Update global suspend all state for attaching threads.
983 suspend_all_count_ -= debug_suspend_all_count_;
984 debug_suspend_all_count_ = 0;
985 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700986 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700987 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -0700988 continue;
989 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700990 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
Elliott Hughes234ab152011-10-26 14:02:26 -0700991 }
992 }
993
994 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700995 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700996 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -0700997 }
998
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800999 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -07001000}
1001
Elliott Hughese52e49b2012-04-02 16:05:44 -07001002void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001003 Thread* self = Thread::Current();
1004 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001005 bool all_threads_are_daemons;
1006 do {
Ian Rogers120f1c72012-09-28 17:17:10 -07001007 {
1008 // No more threads can be born after we start to shutdown.
1009 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001010 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -07001011 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
1012 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001013 all_threads_are_daemons = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07001014 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001015 for (const auto& thread : list_) {
Anwar Ghuloum97543682013-06-14 12:58:16 -07001016 if (thread != self && !thread->IsDaemon()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001017 all_threads_are_daemons = false;
1018 break;
1019 }
1020 }
1021 if (!all_threads_are_daemons) {
1022 // Wait for another thread to exit before re-checking.
Ian Rogersc604d732012-10-14 16:09:54 -07001023 thread_exit_cond_.Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001024 }
Brian Carlstromdf629502013-07-17 22:39:56 -07001025 } while (!all_threads_are_daemons);
Elliott Hughes038a8062011-09-18 14:12:41 -07001026}
1027
1028void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001029 Thread* self = Thread::Current();
1030 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001031 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -07001032 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001033 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001034 // This is only run after all non-daemon threads have exited, so the remainder should all be
1035 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -07001036 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -07001037 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -07001038 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -07001039 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001040 }
1041 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001042 // Give the threads a chance to suspend, complaining if they're slow.
1043 bool have_complained = false;
1044 for (int i = 0; i < 10; ++i) {
1045 usleep(200 * 1000);
1046 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -07001047 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001048 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -07001049 if (!have_complained) {
1050 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
1051 have_complained = true;
1052 }
1053 all_suspended = false;
1054 }
1055 }
1056 if (all_suspended) {
1057 return;
1058 }
1059 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001060 LOG(ERROR) << "suspend all daemons failed";
1061}
1062void ThreadList::Register(Thread* self) {
1063 DCHECK_EQ(self, Thread::Current());
1064
1065 if (VLOG_IS_ON(threads)) {
1066 std::ostringstream oss;
1067 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
Ian Rogers5a9ba012014-05-19 13:28:52 -07001068 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001069 }
1070
1071 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
1072 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -07001073 MutexLock mu(self, *Locks::thread_list_lock_);
1074 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001075 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -07001076 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
1077 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
1078 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
1079 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001080 }
Ian Rogers2966e132014-04-02 08:34:36 -07001081 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
1082 self->ModifySuspendCount(self, +1, false);
Ian Rogers01ae5802012-09-28 16:14:01 -07001083 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001084 CHECK(!Contains(self));
1085 list_.push_back(self);
1086}
1087
1088void ThreadList::Unregister(Thread* self) {
1089 DCHECK_EQ(self, Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -07001090 CHECK_NE(self->GetState(), kRunnable);
1091 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001092
1093 VLOG(threads) << "ThreadList::Unregister() " << *self;
1094
1095 // Any time-consuming destruction, plus anything that can call back into managed code or
1096 // suspend and so on, must happen at this point, and not in ~Thread.
1097 self->Destroy();
1098
Jeff Haoe094b872014-10-14 13:12:01 -07001099 // If tracing, remember thread id and name before thread exits.
1100 Trace::StoreExitingThreadInfo(self);
1101
Ian Rogersdd7624d2014-03-14 17:43:00 -07001102 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -08001103 while (self != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001104 // Remove and delete the Thread* while holding the thread_list_lock_ and
1105 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -07001106 // Note: deliberately not using MutexLock that could hold a stale self pointer.
1107 Locks::thread_list_lock_->ExclusiveLock(self);
Ian Rogersa2af5c72014-09-15 15:17:07 -07001108 bool removed = true;
1109 if (!Contains(self)) {
Mathieu Chartier9db831a2015-02-24 17:20:30 -08001110 std::string thread_name;
1111 self->GetThreadName(thread_name);
Ian Rogersa2af5c72014-09-15 15:17:07 -07001112 std::ostringstream os;
1113 DumpNativeStack(os, GetTid(), " native: ", nullptr);
Mathieu Chartier9db831a2015-02-24 17:20:30 -08001114 LOG(ERROR) << "Request to unregister unattached thread " << thread_name << "\n" << os.str();
Ian Rogersa2af5c72014-09-15 15:17:07 -07001115 } else {
1116 Locks::thread_suspend_count_lock_->ExclusiveLock(self);
1117 if (!self->IsSuspended()) {
1118 list_.remove(self);
1119 } else {
1120 // We failed to remove the thread due to a suspend request, loop and try again.
1121 removed = false;
1122 }
1123 Locks::thread_suspend_count_lock_->ExclusiveUnlock(self);
Ian Rogers68d8b422014-07-17 11:09:10 -07001124 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001125 Locks::thread_list_lock_->ExclusiveUnlock(self);
1126 if (removed) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001127 delete self;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -08001128 self = nullptr;
Ian Rogerscfaa4552012-11-26 21:00:08 -08001129 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001130 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -08001131 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
1132 // temporarily have multiple threads with the same thread id. When this occurs, it causes
1133 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
1134 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001135
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001136 // Clear the TLS data, so that the underlying native thread is recognizably detached.
1137 // (It may wish to reattach later.)
1138 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");
1139
1140 // Signal that a thread just detached.
Ian Rogers81d425b2012-09-27 16:03:43 -07001141 MutexLock mu(NULL, *Locks::thread_list_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -07001142 thread_exit_cond_.Signal(NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001143}
1144
1145void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001146 for (const auto& thread : list_) {
1147 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001148 }
1149}
1150
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001151void ThreadList::VisitRoots(RootCallback* callback, void* arg) const {
Ian Rogers81d425b2012-09-27 16:03:43 -07001152 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001153 for (const auto& thread : list_) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001154 thread->VisitRoots(callback, arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001155 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001156}
1157
Ian Rogerscfaa4552012-11-26 21:00:08 -08001158uint32_t ThreadList::AllocThreadId(Thread* self) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001159 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -07001160 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
1161 if (!allocated_ids_[i]) {
1162 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001163 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -07001164 }
1165 }
1166 LOG(FATAL) << "Out of internal thread ids";
1167 return 0;
1168}
1169
Ian Rogerscfaa4552012-11-26 21:00:08 -08001170void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001171 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001172 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -07001173 DCHECK(allocated_ids_[id]) << id;
1174 allocated_ids_.reset(id);
1175}
1176
Elliott Hughes8daa0922011-09-11 13:46:25 -07001177} // namespace art