blob: 05a0bff13537d4a79287a76c0ef6b41b8e25c012 [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.
Ian Rogers7b078e82014-09-10 14:44:24 -0700231static void UnsafeLogFatalForThreadSuspendAllTimeout() __attribute__((noreturn));
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100232static void UnsafeLogFatalForThreadSuspendAllTimeout() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700233 Runtime* runtime = Runtime::Current();
234 std::ostringstream ss;
235 ss << "Thread suspend timeout\n";
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700236 Locks::mutator_lock_->Dump(ss);
237 ss << "\n";
Ian Rogers7b078e82014-09-10 14:44:24 -0700238 runtime->GetThreadList()->Dump(ss);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700239 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800240 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700241}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700242#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700243
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800244// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
Mathieu Chartier99143862015-02-03 14:26:46 -0800245// individual thread requires polling. delay_us is the requested sleep wait. If delay_us is 0 then
246// we use sched_yield instead of calling usleep.
247static void ThreadSuspendSleep(useconds_t delay_us) {
248 if (delay_us == 0) {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800249 sched_yield();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800250 } else {
Mathieu Chartier99143862015-02-03 14:26:46 -0800251 usleep(delay_us);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800252 }
253}
254
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700255size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700256 Thread* self = Thread::Current();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800257 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
258 Locks::thread_list_lock_->AssertNotHeld(self);
259 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000260 if (kDebugLocking && gAborting == 0) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700261 CHECK_NE(self->GetState(), kRunnable);
262 }
263
264 std::vector<Thread*> suspended_count_modified_threads;
265 size_t count = 0;
266 {
267 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
268 // manually called.
269 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700270 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700271 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700272 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700273 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700274 if (thread->RequestCheckpoint(checkpoint_function)) {
Dave Allison0aded082013-11-07 13:15:11 -0800275 // This thread will run its checkpoint some time in the near future.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700276 count++;
277 break;
278 } else {
279 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700280 // The thread switched back to runnable.
281 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700282 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700283 continue;
284 }
285 thread->ModifySuspendCount(self, +1, false);
286 suspended_count_modified_threads.push_back(thread);
287 break;
288 }
289 }
290 }
291 }
292 }
293
294 // Run the checkpoint on ourself while we wait for threads to suspend.
295 checkpoint_function->Run(self);
296
297 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700298 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700299 if (!thread->IsSuspended()) {
Mathieu Chartier99143862015-02-03 14:26:46 -0800300 if (ATRACE_ENABLED()) {
301 std::ostringstream oss;
302 thread->ShortDump(oss);
303 ATRACE_BEGIN((std::string("Waiting for suspension of thread ") + oss.str()).c_str());
304 }
305 // Busy wait until the thread is suspended.
306 const uint64_t start_time = NanoTime();
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700307 do {
Mathieu Chartier99143862015-02-03 14:26:46 -0800308 ThreadSuspendSleep(kThreadSuspendInitialSleepUs);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700309 } while (!thread->IsSuspended());
Mathieu Chartier99143862015-02-03 14:26:46 -0800310 const uint64_t total_delay = NanoTime() - start_time;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800311 // Shouldn't need to wait for longer than 1000 microseconds.
Mathieu Chartier99143862015-02-03 14:26:46 -0800312 constexpr uint64_t kLongWaitThreshold = MsToNs(1);
313 ATRACE_END();
314 if (UNLIKELY(total_delay > kLongWaitThreshold)) {
315 LOG(WARNING) << "Long wait of " << PrettyDuration(total_delay) << " for "
316 << *thread << " suspension!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700317 }
318 }
319 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700320 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700321 {
322 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
323 thread->ModifySuspendCount(self, -1, false);
324 }
325 }
326
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800327 {
328 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
329 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
330 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
331 Thread::resume_cond_->Broadcast(self);
332 }
333
Lei Lidd9943d2015-02-02 14:24:44 +0800334 return count;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700335}
336
Dave Allison39c3bfb2014-01-28 18:33:52 -0800337// Request that a checkpoint function be run on all active (non-suspended)
338// threads. Returns the number of successful requests.
339size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
340 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700341 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
342 Locks::thread_list_lock_->AssertNotHeld(self);
343 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
344 CHECK_NE(self->GetState(), kRunnable);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800345
346 size_t count = 0;
347 {
348 // Call a checkpoint function for each non-suspended thread.
349 MutexLock mu(self, *Locks::thread_list_lock_);
350 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
351 for (const auto& thread : list_) {
352 if (thread != self) {
353 if (thread->RequestCheckpoint(checkpoint_function)) {
354 // This thread will run its checkpoint some time in the near future.
355 count++;
356 }
357 }
358 }
359 }
360
361 // Return the number of threads that will run the checkpoint function.
362 return count;
363}
364
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800365// A checkpoint/suspend-all hybrid to switch thread roots from
366// from-space to to-space refs. Used to synchronize threads at a point
367// to mark the initiation of marking while maintaining the to-space
368// invariant.
369size_t ThreadList::FlipThreadRoots(Closure* thread_flip_visitor, Closure* flip_callback,
370 gc::collector::GarbageCollector* collector) {
371 TimingLogger::ScopedTiming split("ThreadListFlip", collector->GetTimings());
372 const uint64_t start_time = NanoTime();
373 Thread* self = Thread::Current();
374 Locks::mutator_lock_->AssertNotHeld(self);
375 Locks::thread_list_lock_->AssertNotHeld(self);
376 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
377 CHECK_NE(self->GetState(), kRunnable);
378
379 std::vector<Thread*> runnable_threads;
380 std::vector<Thread*> other_threads;
381
382 // Suspend all threads once.
383 {
384 MutexLock mu(self, *Locks::thread_list_lock_);
385 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
386 // Update global suspend all state for attaching threads.
387 ++suspend_all_count_;
388 // Increment everybody's suspend count (except our own).
389 for (const auto& thread : list_) {
390 if (thread == self) {
391 continue;
392 }
393 thread->ModifySuspendCount(self, +1, false);
394 }
395 }
396
397 // Run the flip callback for the collector.
398 Locks::mutator_lock_->ExclusiveLock(self);
399 flip_callback->Run(self);
400 Locks::mutator_lock_->ExclusiveUnlock(self);
401 collector->RegisterPause(NanoTime() - start_time);
402
403 // Resume runnable threads.
404 {
405 MutexLock mu(self, *Locks::thread_list_lock_);
406 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
407 --suspend_all_count_;
408 for (const auto& thread : list_) {
409 if (thread == self) {
410 continue;
411 }
412 // Set the flip function for both runnable and suspended threads
413 // because Thread::DumpState/DumpJavaStack() (invoked by a
414 // checkpoint) may cause the flip function to be run for a
415 // runnable/suspended thread before a runnable threads runs it
416 // for itself or we run it for a suspended thread below.
417 thread->SetFlipFunction(thread_flip_visitor);
418 if (thread->IsSuspendedAtSuspendCheck()) {
419 // The thread will resume right after the broadcast.
420 thread->ModifySuspendCount(self, -1, false);
421 runnable_threads.push_back(thread);
422 } else {
423 other_threads.push_back(thread);
424 }
425 }
426 Thread::resume_cond_->Broadcast(self);
427 }
428
429 // Run the closure on the other threads and let them resume.
430 {
431 ReaderMutexLock mu(self, *Locks::mutator_lock_);
432 for (const auto& thread : other_threads) {
433 Closure* flip_func = thread->GetFlipFunction();
434 if (flip_func != nullptr) {
435 flip_func->Run(thread);
436 }
437 }
438 // Run it for self.
439 thread_flip_visitor->Run(self);
440 }
441
442 // Resume other threads.
443 {
444 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
445 for (const auto& thread : other_threads) {
446 thread->ModifySuspendCount(self, -1, false);
447 }
448 Thread::resume_cond_->Broadcast(self);
449 }
450
451 return runnable_threads.size() + other_threads.size() + 1; // +1 for self.
452}
453
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700454void ThreadList::SuspendAll() {
455 Thread* self = Thread::Current();
456
Jeff Haoc5d824a2014-07-28 18:35:38 -0700457 if (self != nullptr) {
458 VLOG(threads) << *self << " SuspendAll starting...";
459 } else {
460 VLOG(threads) << "Thread[null] SuspendAll starting...";
461 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700462 ATRACE_BEGIN("Suspending mutator threads");
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800463 const uint64_t start_time = NanoTime();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700464
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800465 Locks::mutator_lock_->AssertNotHeld(self);
466 Locks::thread_list_lock_->AssertNotHeld(self);
467 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Jeff Haoc5d824a2014-07-28 18:35:38 -0700468 if (kDebugLocking && self != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469 CHECK_NE(self->GetState(), kRunnable);
470 }
471 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700472 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800473 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
474 // Update global suspend all state for attaching threads.
475 ++suspend_all_count_;
476 // Increment everybody's suspend count (except our own).
477 for (const auto& thread : list_) {
478 if (thread == self) {
479 continue;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700480 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800481 VLOG(threads) << "requesting thread suspend: " << *thread;
482 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700483 }
484 }
485
Ian Rogers66aee5c2012-08-15 17:17:47 -0700486 // Block on the mutator lock until all Runnable threads release their share of access.
487#if HAVE_TIMED_RWLOCK
488 // Timeout if we wait more than 30 seconds.
Mathieu Chartier99143862015-02-03 14:26:46 -0800489 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, kThreadSuspendTimeoutMs, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100490 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700491 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700492#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700493 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700494#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700495
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800496 const uint64_t end_time = NanoTime();
497 const uint64_t suspend_time = end_time - start_time;
498 suspend_all_historam_.AdjustAndAddValue(suspend_time);
499 if (suspend_time > kLongThreadSuspendThreshold) {
500 LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(suspend_time);
Mathieu Chartier251755c2014-07-15 18:10:25 -0700501 }
502
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800503 if (kDebugLocking) {
504 // Debug check that all threads are suspended.
505 AssertThreadsAreSuspended(self, self);
506 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700507
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700508 ATRACE_END();
509 ATRACE_BEGIN("Mutator threads suspended");
510
Jeff Haoc5d824a2014-07-28 18:35:38 -0700511 if (self != nullptr) {
512 VLOG(threads) << *self << " SuspendAll complete";
513 } else {
514 VLOG(threads) << "Thread[null] SuspendAll complete";
515 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700516}
517
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700518void ThreadList::ResumeAll() {
519 Thread* self = Thread::Current();
520
Jeff Haoc5d824a2014-07-28 18:35:38 -0700521 if (self != nullptr) {
522 VLOG(threads) << *self << " ResumeAll starting";
523 } else {
524 VLOG(threads) << "Thread[null] ResumeAll starting";
525 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700526
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700527 ATRACE_END();
528 ATRACE_BEGIN("Resuming mutator threads");
529
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800530 if (kDebugLocking) {
531 // Debug check that all threads are suspended.
532 AssertThreadsAreSuspended(self, self);
533 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700534
Ian Rogers81d425b2012-09-27 16:03:43 -0700535 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700536 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700537 MutexLock mu(self, *Locks::thread_list_lock_);
538 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700539 // Update global suspend all state for attaching threads.
540 --suspend_all_count_;
541 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700542 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700543 if (thread == self) {
544 continue;
545 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700546 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700547 }
548
549 // Broadcast a notification to all suspended threads, some or all of
550 // which may choose to wake up. No need to wait for them.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700551 if (self != nullptr) {
552 VLOG(threads) << *self << " ResumeAll waking others";
553 } else {
554 VLOG(threads) << "Thread[null] ResumeAll waking others";
555 }
Ian Rogersc604d732012-10-14 16:09:54 -0700556 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700557 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700558 ATRACE_END();
Jeff Haoc5d824a2014-07-28 18:35:38 -0700559
560 if (self != nullptr) {
561 VLOG(threads) << *self << " ResumeAll complete";
562 } else {
563 VLOG(threads) << "Thread[null] ResumeAll complete";
564 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700565}
566
567void ThreadList::Resume(Thread* thread, bool for_debugger) {
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800568 // This assumes there was an ATRACE_BEGIN when we suspended the thread.
569 ATRACE_END();
570
Ian Rogers81d425b2012-09-27 16:03:43 -0700571 Thread* self = Thread::Current();
572 DCHECK_NE(thread, self);
Brian Carlstromba32de42014-08-27 23:43:46 -0700573 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..."
574 << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700575
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700576 {
577 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700578 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700579 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700580 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
581 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700582 if (!Contains(thread)) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700583 // We only expect threads within the thread-list to have been suspended otherwise we can't
584 // stop such threads from delete-ing themselves.
585 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
586 << ") thread not within thread list";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700587 return;
588 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700589 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700590 }
591
592 {
Brian Carlstromba32de42014-08-27 23:43:46 -0700593 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700594 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700595 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700596 }
597
Brian Carlstromba32de42014-08-27 23:43:46 -0700598 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700599}
Elliott Hughes01158d72011-09-19 19:47:10 -0700600
Ian Rogersc7dd2952014-10-21 23:31:19 -0700601static void ThreadSuspendByPeerWarning(Thread* self, LogSeverity severity, const char* message,
602 jobject peer) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700603 JNIEnvExt* env = self->GetJniEnv();
604 ScopedLocalRef<jstring>
605 scoped_name_string(env, (jstring)env->GetObjectField(peer,
606 WellKnownClasses::java_lang_Thread_name));
607 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
608 if (scoped_name_chars.c_str() == NULL) {
Ian Rogersc7dd2952014-10-21 23:31:19 -0700609 LOG(severity) << message << ": " << peer;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700610 env->ExceptionClear();
611 } else {
Ian Rogersc7dd2952014-10-21 23:31:19 -0700612 LOG(severity) << message << ": " << peer << ":" << scoped_name_chars.c_str();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700613 }
614}
615
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700616Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
617 bool debug_suspension, bool* timed_out) {
Mathieu Chartier3a958aa2015-02-04 12:52:34 -0800618 const uint64_t start_time = NanoTime();
Mathieu Chartier99143862015-02-03 14:26:46 -0800619 useconds_t sleep_us = kThreadSuspendInitialSleepUs;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700620 *timed_out = false;
Mathieu Chartier99143862015-02-03 14:26:46 -0800621 Thread* const self = Thread::Current();
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800622 Thread* suspended_thread = nullptr;
Brian Carlstromba32de42014-08-27 23:43:46 -0700623 VLOG(threads) << "SuspendThreadByPeer starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700624 while (true) {
625 Thread* thread;
626 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700627 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
628 // is requesting another suspend, to avoid deadlock, by requiring this function be called
629 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
630 // than request thread suspension, to avoid potential cycles in threads requesting each other
631 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700632 ScopedObjectAccess soa(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800633 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700634 thread = Thread::FromManagedThread(soa, peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700635 if (thread == nullptr) {
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800636 if (suspended_thread != nullptr) {
637 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
638 // If we incremented the suspend count but the thread reset its peer, we need to
639 // re-decrement it since it is shutting down and may deadlock the runtime in
640 // ThreadList::WaitForOtherNonDaemonThreadsToExit.
641 suspended_thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
642 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700643 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700644 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700645 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700646 if (!Contains(thread)) {
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800647 CHECK(suspended_thread == nullptr);
Brian Carlstromba32de42014-08-27 23:43:46 -0700648 VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
649 << reinterpret_cast<void*>(thread);
650 return nullptr;
651 }
652 VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700653 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800654 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700655 if (request_suspension) {
Ian Rogers4ad5cd32014-11-11 23:08:07 -0800656 if (self->GetSuspendCount() > 0) {
657 // We hold the suspend count lock but another thread is trying to suspend us. Its not
658 // safe to try to suspend another thread in case we get a cycle. Start the loop again
659 // which will allow this thread to be suspended.
660 continue;
661 }
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800662 CHECK(suspended_thread == nullptr);
663 suspended_thread = thread;
664 suspended_thread->ModifySuspendCount(self, +1, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700665 request_suspension = false;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700666 } else {
667 // If the caller isn't requesting suspension, a suspension should have already occurred.
668 CHECK_GT(thread->GetSuspendCount(), 0);
669 }
670 // IsSuspended on the current thread will fail as the current thread is changed into
671 // Runnable above. As the suspend count is now raised if this is the current thread
672 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
673 // to just explicitly handle the current thread in the callers to this code.
674 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
675 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
676 // count, or else we've waited and it has self suspended) or is the current thread, we're
677 // done.
678 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700679 VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800680 if (ATRACE_ENABLED()) {
681 std::string name;
682 thread->GetThreadName(name);
683 ATRACE_BEGIN(StringPrintf("SuspendThreadByPeer suspended %s for peer=%p", name.c_str(),
684 peer).c_str());
685 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700686 return thread;
687 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800688 const uint64_t total_delay = NanoTime() - start_time;
689 if (total_delay >= MsToNs(kThreadSuspendTimeoutMs)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700690 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800691 if (suspended_thread != nullptr) {
692 CHECK_EQ(suspended_thread, thread);
693 suspended_thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700694 }
695 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700696 return nullptr;
Mathieu Chartier99143862015-02-03 14:26:46 -0800697 } else if (sleep_us == 0 &&
698 total_delay > static_cast<uint64_t>(kThreadSuspendMaxYieldUs) * 1000) {
699 // We have spun for kThreadSuspendMaxYieldUs time, switch to sleeps to prevent
700 // excessive CPU usage.
701 sleep_us = kThreadSuspendMaxYieldUs / 2;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700702 }
703 }
704 // Release locks and come out of runnable state.
705 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800706 VLOG(threads) << "SuspendThreadByPeer waiting to allow thread chance to suspend";
707 ThreadSuspendSleep(sleep_us);
708 // This may stay at 0 if sleep_us == 0, but this is WAI since we want to avoid using usleep at
709 // all if possible. This shouldn't be an issue since time to suspend should always be small.
710 sleep_us = std::min(sleep_us * 2, kThreadSuspendMaxSleepUs);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700711 }
712}
713
Ian Rogersc7dd2952014-10-21 23:31:19 -0700714static void ThreadSuspendByThreadIdWarning(LogSeverity severity, const char* message,
715 uint32_t thread_id) {
716 LOG(severity) << StringPrintf("%s: %d", message, thread_id);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700717}
718
719Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
720 bool* timed_out) {
Mathieu Chartier3a958aa2015-02-04 12:52:34 -0800721 const uint64_t start_time = NanoTime();
Mathieu Chartier99143862015-02-03 14:26:46 -0800722 useconds_t sleep_us = kThreadSuspendInitialSleepUs;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700723 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800724 Thread* suspended_thread = nullptr;
Mathieu Chartier99143862015-02-03 14:26:46 -0800725 Thread* const self = Thread::Current();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700726 CHECK_NE(thread_id, kInvalidThreadId);
Brian Carlstromba32de42014-08-27 23:43:46 -0700727 VLOG(threads) << "SuspendThreadByThreadId starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700728 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700729 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700730 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
731 // is requesting another suspend, to avoid deadlock, by requiring this function be called
732 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
733 // than request thread suspension, to avoid potential cycles in threads requesting each other
734 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700735 ScopedObjectAccess soa(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800736 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700737 Thread* thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700738 for (const auto& it : list_) {
739 if (it->GetThreadId() == thread_id) {
740 thread = it;
741 break;
742 }
743 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800744 if (thread == nullptr) {
745 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
746 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700747 // There's a race in inflating a lock and the owner giving up ownership and then dying.
748 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
Brian Carlstromba32de42014-08-27 23:43:46 -0700749 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700750 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700751 VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
752 DCHECK(Contains(thread));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700753 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800754 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800755 if (suspended_thread == nullptr) {
Ian Rogers4ad5cd32014-11-11 23:08:07 -0800756 if (self->GetSuspendCount() > 0) {
757 // We hold the suspend count lock but another thread is trying to suspend us. Its not
758 // safe to try to suspend another thread in case we get a cycle. Start the loop again
759 // which will allow this thread to be suspended.
760 continue;
761 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700762 thread->ModifySuspendCount(self, +1, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800763 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700764 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800765 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700766 // If the caller isn't requesting suspension, a suspension should have already occurred.
767 CHECK_GT(thread->GetSuspendCount(), 0);
768 }
769 // IsSuspended on the current thread will fail as the current thread is changed into
770 // Runnable above. As the suspend count is now raised if this is the current thread
771 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
772 // to just explicitly handle the current thread in the callers to this code.
773 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
774 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
775 // count, or else we've waited and it has self suspended) or is the current thread, we're
776 // done.
777 if (thread->IsSuspended()) {
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800778 if (ATRACE_ENABLED()) {
779 std::string name;
780 thread->GetThreadName(name);
781 ATRACE_BEGIN(StringPrintf("SuspendThreadByThreadId suspended %s id=%d",
782 name.c_str(), thread_id).c_str());
783 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700784 VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700785 return thread;
786 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800787 const uint64_t total_delay = NanoTime() - start_time;
788 if (total_delay >= MsToNs(kThreadSuspendTimeoutMs)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700789 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800790 if (suspended_thread != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700791 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
792 }
793 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700794 return nullptr;
Mathieu Chartier99143862015-02-03 14:26:46 -0800795 } else if (sleep_us == 0 &&
796 total_delay > static_cast<uint64_t>(kThreadSuspendMaxYieldUs) * 1000) {
797 // We have spun for kThreadSuspendMaxYieldUs time, switch to sleeps to prevent
798 // excessive CPU usage.
799 sleep_us = kThreadSuspendMaxYieldUs / 2;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700800 }
801 }
802 // Release locks and come out of runnable state.
803 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800804 VLOG(threads) << "SuspendThreadByThreadId waiting to allow thread chance to suspend";
805 ThreadSuspendSleep(sleep_us);
806 sleep_us = std::min(sleep_us * 2, kThreadSuspendMaxSleepUs);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700807 }
808}
809
810Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
811 Thread* self = Thread::Current();
812 MutexLock mu(self, *Locks::thread_list_lock_);
813 for (const auto& thread : list_) {
814 if (thread->GetThreadId() == thin_lock_id) {
815 CHECK(thread == self || thread->IsSuspended());
816 return thread;
817 }
818 }
819 return NULL;
820}
821
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700822void ThreadList::SuspendAllForDebugger() {
823 Thread* self = Thread::Current();
824 Thread* debug_thread = Dbg::GetDebugThread();
825
826 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
827
828 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800829 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700830 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800831 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700832 // Update global suspend all state for attaching threads.
Sebastien Hertz253fa552014-10-14 17:27:15 +0200833 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700834 ++suspend_all_count_;
835 ++debug_suspend_all_count_;
836 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700837 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700838 if (thread == self || thread == debug_thread) {
839 continue;
840 }
841 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700842 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700843 }
844 }
845 }
846
Ian Rogers66aee5c2012-08-15 17:17:47 -0700847 // Block on the mutator lock until all Runnable threads release their share of access then
848 // immediately unlock again.
849#if HAVE_TIMED_RWLOCK
850 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700851 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100852 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700853 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700854 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700855 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700856#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700857 Locks::mutator_lock_->ExclusiveLock(self);
858 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700859#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700860 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700861
Sebastien Hertzed2be172014-08-19 15:33:43 +0200862 VLOG(threads) << *self << " SuspendAllForDebugger complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700863}
864
Elliott Hughes475fc232011-10-25 15:00:35 -0700865void ThreadList::SuspendSelfForDebugger() {
866 Thread* self = Thread::Current();
Elliott Hughes01158d72011-09-19 19:47:10 -0700867
Elliott Hughes475fc232011-10-25 15:00:35 -0700868 // The debugger thread must not suspend itself due to debugger activity!
869 Thread* debug_thread = Dbg::GetDebugThread();
870 CHECK(debug_thread != NULL);
871 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800872 CHECK_NE(self->GetState(), kRunnable);
873 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700874
jeffhaoa77f0f62012-12-05 17:19:31 -0800875 {
876 // Collisions with other suspends aren't really interesting. We want
877 // to ensure that we're the only one fiddling with the suspend count
878 // though.
879 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
880 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700881 CHECK_GT(self->GetSuspendCount(), 0);
jeffhaoa77f0f62012-12-05 17:19:31 -0800882 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700883
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800884 VLOG(threads) << *self << " self-suspending (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700885
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100886 // Tell JDWP we've completed invocation and are ready to suspend.
887 DebugInvokeReq* pReq = self->GetInvokeReq();
888 DCHECK(pReq != NULL);
889 if (pReq->invoke_needed) {
890 // Clear this before signaling.
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200891 pReq->Clear();
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100892
893 VLOG(jdwp) << "invoke complete, signaling";
894 MutexLock mu(self, pReq->lock);
895 pReq->cond.Signal(self);
896 }
897
Elliott Hughes475fc232011-10-25 15:00:35 -0700898 // Tell JDWP that we've completed suspension. The JDWP thread can't
899 // tell us to resume before we're fully asleep because we hold the
900 // suspend count lock.
901 Dbg::ClearWaitForEventThread();
902
jeffhaoa77f0f62012-12-05 17:19:31 -0800903 {
904 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700905 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800906 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700907 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800908 // The condition was signaled but we're still suspended. This
Sebastien Hertzf272af42014-09-18 10:20:42 +0200909 // can happen when we suspend then resume all threads to
910 // update instrumentation or compute monitor info. This can
911 // also happen if the debugger lets go while a SIGQUIT thread
jeffhaoa77f0f62012-12-05 17:19:31 -0800912 // dump event is pending (assuming SignalCatcher was resumed for
913 // just long enough to try to grab the thread-suspend lock).
Sebastien Hertzf272af42014-09-18 10:20:42 +0200914 VLOG(jdwp) << *self << " still suspended after undo "
915 << "(suspend count=" << self->GetSuspendCount() << ", "
916 << "debug suspend count=" << self->GetDebugSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -0800917 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700918 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700919 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700920 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800921
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800922 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700923}
924
Sebastien Hertz253fa552014-10-14 17:27:15 +0200925void ThreadList::ResumeAllForDebugger() {
926 Thread* self = Thread::Current();
927 Thread* debug_thread = Dbg::GetDebugThread();
Sebastien Hertz253fa552014-10-14 17:27:15 +0200928
929 VLOG(threads) << *self << " ResumeAllForDebugger starting...";
930
931 // Threads can't resume if we exclusively hold the mutator lock.
932 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
933
934 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800935 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Sebastien Hertz253fa552014-10-14 17:27:15 +0200936 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800937 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Sebastien Hertz253fa552014-10-14 17:27:15 +0200938 // Update global suspend all state for attaching threads.
939 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100940 if (debug_suspend_all_count_ > 0) {
Sebastien Hertz253fa552014-10-14 17:27:15 +0200941 --suspend_all_count_;
942 --debug_suspend_all_count_;
Sebastien Hertz253fa552014-10-14 17:27:15 +0200943 } else {
944 // We've been asked to resume all threads without being asked to
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100945 // suspend them all before. That may happen if a debugger tries
946 // to resume some suspended threads (with suspend count == 1)
947 // at once with a VirtualMachine.Resume command. Let's print a
948 // warning.
Sebastien Hertz253fa552014-10-14 17:27:15 +0200949 LOG(WARNING) << "Debugger attempted to resume all threads without "
950 << "having suspended them all before.";
951 }
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100952 // Decrement everybody's suspend count (except our own).
953 for (const auto& thread : list_) {
954 if (thread == self || thread == debug_thread) {
955 continue;
956 }
957 if (thread->GetDebugSuspendCount() == 0) {
958 // This thread may have been individually resumed with ThreadReference.Resume.
959 continue;
960 }
961 VLOG(threads) << "requesting thread resume: " << *thread;
962 thread->ModifySuspendCount(self, -1, true);
963 }
Sebastien Hertz253fa552014-10-14 17:27:15 +0200964 }
965 }
966
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100967 {
Sebastien Hertz253fa552014-10-14 17:27:15 +0200968 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
969 Thread::resume_cond_->Broadcast(self);
970 }
971
972 VLOG(threads) << *self << " ResumeAllForDebugger complete";
973}
974
Elliott Hughes234ab152011-10-26 14:02:26 -0700975void ThreadList::UndoDebuggerSuspensions() {
976 Thread* self = Thread::Current();
977
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800978 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700979
980 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700981 MutexLock mu(self, *Locks::thread_list_lock_);
982 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700983 // Update global suspend all state for attaching threads.
984 suspend_all_count_ -= debug_suspend_all_count_;
985 debug_suspend_all_count_ = 0;
986 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700987 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700988 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -0700989 continue;
990 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700991 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
Elliott Hughes234ab152011-10-26 14:02:26 -0700992 }
993 }
994
995 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700996 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700997 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -0700998 }
999
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001000 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -07001001}
1002
Elliott Hughese52e49b2012-04-02 16:05:44 -07001003void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001004 Thread* self = Thread::Current();
1005 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001006 bool all_threads_are_daemons;
1007 do {
Ian Rogers120f1c72012-09-28 17:17:10 -07001008 {
1009 // No more threads can be born after we start to shutdown.
1010 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001011 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -07001012 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
1013 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001014 all_threads_are_daemons = true;
Ian Rogers120f1c72012-09-28 17:17:10 -07001015 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001016 for (const auto& thread : list_) {
Anwar Ghuloum97543682013-06-14 12:58:16 -07001017 if (thread != self && !thread->IsDaemon()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001018 all_threads_are_daemons = false;
1019 break;
1020 }
1021 }
1022 if (!all_threads_are_daemons) {
1023 // Wait for another thread to exit before re-checking.
Ian Rogersc604d732012-10-14 16:09:54 -07001024 thread_exit_cond_.Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001025 }
Brian Carlstromdf629502013-07-17 22:39:56 -07001026 } while (!all_threads_are_daemons);
Elliott Hughes038a8062011-09-18 14:12:41 -07001027}
1028
1029void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001030 Thread* self = Thread::Current();
1031 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001032 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -07001033 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001034 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001035 // This is only run after all non-daemon threads have exited, so the remainder should all be
1036 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -07001037 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -07001038 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -07001039 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -07001040 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001041 }
1042 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001043 // Give the threads a chance to suspend, complaining if they're slow.
1044 bool have_complained = false;
1045 for (int i = 0; i < 10; ++i) {
1046 usleep(200 * 1000);
1047 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -07001048 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001049 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -07001050 if (!have_complained) {
1051 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
1052 have_complained = true;
1053 }
1054 all_suspended = false;
1055 }
1056 }
1057 if (all_suspended) {
1058 return;
1059 }
1060 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001061 LOG(ERROR) << "suspend all daemons failed";
1062}
1063void ThreadList::Register(Thread* self) {
1064 DCHECK_EQ(self, Thread::Current());
1065
1066 if (VLOG_IS_ON(threads)) {
1067 std::ostringstream oss;
1068 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
Ian Rogers5a9ba012014-05-19 13:28:52 -07001069 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001070 }
1071
1072 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
1073 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -07001074 MutexLock mu(self, *Locks::thread_list_lock_);
1075 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001076 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -07001077 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
1078 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
1079 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
1080 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001081 }
Ian Rogers2966e132014-04-02 08:34:36 -07001082 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
1083 self->ModifySuspendCount(self, +1, false);
Ian Rogers01ae5802012-09-28 16:14:01 -07001084 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001085 CHECK(!Contains(self));
1086 list_.push_back(self);
1087}
1088
1089void ThreadList::Unregister(Thread* self) {
1090 DCHECK_EQ(self, Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -07001091 CHECK_NE(self->GetState(), kRunnable);
1092 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001093
1094 VLOG(threads) << "ThreadList::Unregister() " << *self;
1095
1096 // Any time-consuming destruction, plus anything that can call back into managed code or
1097 // suspend and so on, must happen at this point, and not in ~Thread.
1098 self->Destroy();
1099
Jeff Haoe094b872014-10-14 13:12:01 -07001100 // If tracing, remember thread id and name before thread exits.
1101 Trace::StoreExitingThreadInfo(self);
1102
Ian Rogersdd7624d2014-03-14 17:43:00 -07001103 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -08001104 while (self != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001105 // Remove and delete the Thread* while holding the thread_list_lock_ and
1106 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -07001107 // Note: deliberately not using MutexLock that could hold a stale self pointer.
1108 Locks::thread_list_lock_->ExclusiveLock(self);
Ian Rogersa2af5c72014-09-15 15:17:07 -07001109 bool removed = true;
1110 if (!Contains(self)) {
1111 std::ostringstream os;
1112 DumpNativeStack(os, GetTid(), " native: ", nullptr);
1113 LOG(ERROR) << "Request to unregister unattached thread\n" << os.str();
1114 } else {
1115 Locks::thread_suspend_count_lock_->ExclusiveLock(self);
1116 if (!self->IsSuspended()) {
1117 list_.remove(self);
1118 } else {
1119 // We failed to remove the thread due to a suspend request, loop and try again.
1120 removed = false;
1121 }
1122 Locks::thread_suspend_count_lock_->ExclusiveUnlock(self);
Ian Rogers68d8b422014-07-17 11:09:10 -07001123 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001124 Locks::thread_list_lock_->ExclusiveUnlock(self);
1125 if (removed) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001126 delete self;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -08001127 self = nullptr;
Ian Rogerscfaa4552012-11-26 21:00:08 -08001128 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001129 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -08001130 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
1131 // temporarily have multiple threads with the same thread id. When this occurs, it causes
1132 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
1133 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001134
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001135 // Clear the TLS data, so that the underlying native thread is recognizably detached.
1136 // (It may wish to reattach later.)
1137 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");
1138
1139 // Signal that a thread just detached.
Ian Rogers81d425b2012-09-27 16:03:43 -07001140 MutexLock mu(NULL, *Locks::thread_list_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -07001141 thread_exit_cond_.Signal(NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001142}
1143
1144void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001145 for (const auto& thread : list_) {
1146 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001147 }
1148}
1149
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001150void ThreadList::VisitRoots(RootCallback* callback, void* arg) const {
Ian Rogers81d425b2012-09-27 16:03:43 -07001151 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001152 for (const auto& thread : list_) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001153 thread->VisitRoots(callback, arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001154 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001155}
1156
Ian Rogerscfaa4552012-11-26 21:00:08 -08001157uint32_t ThreadList::AllocThreadId(Thread* self) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001158 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -07001159 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
1160 if (!allocated_ids_[i]) {
1161 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001162 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -07001163 }
1164 }
1165 LOG(FATAL) << "Out of internal thread ids";
1166 return 0;
1167}
1168
Ian Rogerscfaa4552012-11-26 21:00:08 -08001169void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001170 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001171 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -07001172 DCHECK(allocated_ids_[id]) << id;
1173 allocated_ids_.reset(id);
1174}
1175
Elliott Hughes8daa0922011-09-11 13:46:25 -07001176} // namespace art