blob: b697b43a77afe875ca23cad613645435bd76ac03 [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"
Vladimir Marko80afd022015-05-19 18:08:00 +010033#include "base/time_utils.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080034#include "base/timing_logger.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070035#include "debugger.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070036#include "jni_internal.h"
37#include "lock_word.h"
38#include "monitor.h"
39#include "scoped_thread_state_change.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080040#include "thread.h"
Jeff Haoe094b872014-10-14 13:12:01 -070041#include "trace.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()
Mathieu Chartier91e56692015-03-03 13:51:04 -080054 : suspend_all_count_(0), debug_suspend_all_count_(0), unregistering_count_(0),
Mathieu Chartierbf44d422015-06-02 11:42:18 -070055 suspend_all_historam_("suspend all histogram", 16, 64), long_suspend_(false) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -080056 CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1, 0U)));
Elliott Hughes8daa0922011-09-11 13:46:25 -070057}
58
59ThreadList::~ThreadList() {
Elliott Hughese52e49b2012-04-02 16:05:44 -070060 // Detach the current thread if necessary. If we failed to start, there might not be any threads.
Elliott Hughes6a144332012-04-03 13:07:11 -070061 // We need to detach the current thread here in case there's another thread waiting to join with
62 // us.
Mathieu Chartierfec72f42014-10-09 12:57:58 -070063 bool contains = false;
64 {
65 Thread* self = Thread::Current();
66 MutexLock mu(self, *Locks::thread_list_lock_);
67 contains = Contains(self);
68 }
69 if (contains) {
Elliott Hughes8daa0922011-09-11 13:46:25 -070070 Runtime::Current()->DetachCurrentThread();
71 }
Elliott Hughes6a144332012-04-03 13:07:11 -070072 WaitForOtherNonDaemonThreadsToExit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070073 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
74 // Thread::Init.
Elliott Hughes6a144332012-04-03 13:07:11 -070075 SuspendAllDaemonThreads();
Elliott Hughes8daa0922011-09-11 13:46:25 -070076}
77
78bool ThreadList::Contains(Thread* thread) {
79 return find(list_.begin(), list_.end(), thread) != list_.end();
80}
81
Elliott Hughesabbe07d2012-06-05 17:42:23 -070082bool ThreadList::Contains(pid_t tid) {
Mathieu Chartier02e25112013-08-14 16:14:24 -070083 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070084 if (thread->GetTid() == tid) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -070085 return true;
86 }
87 }
88 return false;
89}
90
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070091pid_t ThreadList::GetLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -070092 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
Elliott Hughesaccd83d2011-10-17 14:25:58 -070093}
94
Mathieu Chartier590fee92013-09-13 13:46:47 -070095void ThreadList::DumpNativeStacks(std::ostream& os) {
96 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
97 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070098 os << "DUMPING THREAD " << thread->GetTid() << "\n";
Christopher Ferrisa2cee182014-04-16 19:13:59 -070099 DumpNativeStack(os, thread->GetTid(), "\t");
Mathieu Chartier590fee92013-09-13 13:46:47 -0700100 os << "\n";
101 }
102}
103
Elliott Hughesc967f782012-04-16 10:23:15 -0700104void ThreadList::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800105 {
106 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier23f6e692014-12-18 18:24:39 -0800107 // Only print if we have samples.
108 if (suspend_all_historam_.SampleSize() > 0) {
109 Histogram<uint64_t>::CumulativeData data;
110 suspend_all_historam_.CreateHistogram(&data);
111 suspend_all_historam_.PrintConfidenceIntervals(os, 0.99, data); // Dump time to suspend.
112 }
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800113 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700114 Dump(os);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700115 DumpUnattachedThreads(os);
116}
117
Ian Rogerscfaa4552012-11-26 21:00:08 -0800118static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700119 // TODO: No thread safety analysis as DumpState with a null thread won't access fields, should
Ian Rogerscfaa4552012-11-26 21:00:08 -0800120 // refactor DumpState to avoid skipping analysis.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700121 Thread::DumpState(os, nullptr, tid);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700122 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -0700123 // TODO: Reenable this when the native code in system_server can handle it.
124 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
125 if (false) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -0700126 DumpNativeStack(os, tid, " native: ");
Brian Carlstromed8b7232012-06-27 17:54:47 -0700127 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700128 os << "\n";
129}
130
131void ThreadList::DumpUnattachedThreads(std::ostream& os) {
132 DIR* d = opendir("/proc/self/task");
133 if (!d) {
134 return;
135 }
136
Ian Rogers50b35e22012-10-04 10:09:15 -0700137 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700138 dirent* e;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700139 while ((e = readdir(d)) != nullptr) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700140 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700141 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700142 if (!*end) {
143 bool contains;
144 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700145 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700146 contains = Contains(tid);
147 }
148 if (!contains) {
149 DumpUnattachedThread(os, tid);
150 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700151 }
152 }
153 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800154}
155
Andreas Gampe4a3d19b2015-01-09 17:54:51 -0800156// Dump checkpoint timeout in milliseconds. Larger amount on the host, as dumping will invoke
157// addr2line when available.
Andreas Gampe1e4b0ca2015-01-14 09:06:32 -0800158static constexpr uint32_t kDumpWaitTimeout = kIsTargetBuild ? 10000 : 20000;
Andreas Gampe4a3d19b2015-01-09 17:54:51 -0800159
Ian Rogers7b078e82014-09-10 14:44:24 -0700160// A closure used by Thread::Dump.
161class DumpCheckpoint FINAL : public Closure {
162 public:
163 explicit DumpCheckpoint(std::ostream* os) : os_(os), barrier_(0) {}
164
165 void Run(Thread* thread) OVERRIDE {
166 // Note thread and self may not be equal if thread was already suspended at the point of the
167 // request.
168 Thread* self = Thread::Current();
169 std::ostringstream local_os;
170 {
171 ScopedObjectAccess soa(self);
172 thread->Dump(local_os);
173 }
174 local_os << "\n";
175 {
176 // Use the logging lock to ensure serialization when writing to the common ostream.
177 MutexLock mu(self, *Locks::logging_lock_);
178 *os_ << local_os.str();
179 }
Lei Lidd9943d2015-02-02 14:24:44 +0800180 if (thread->GetState() == kRunnable) {
181 barrier_.Pass(self);
182 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700183 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700184
185 void WaitForThreadsToRunThroughCheckpoint(size_t threads_running_checkpoint) {
186 Thread* self = Thread::Current();
187 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
Andreas Gampe1e4b0ca2015-01-14 09:06:32 -0800188 bool timed_out = barrier_.Increment(self, threads_running_checkpoint, kDumpWaitTimeout);
Ian Rogers2156ff12014-09-13 19:20:54 -0700189 if (timed_out) {
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000190 // Avoid a recursive abort.
191 LOG((kIsDebugBuild && (gAborting == 0)) ? FATAL : ERROR)
192 << "Unexpected time out during dump checkpoint.";
Ian Rogers2156ff12014-09-13 19:20:54 -0700193 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700194 }
195
196 private:
197 // The common stream that will accumulate all the dumps.
198 std::ostream* const os_;
199 // The barrier to be passed through and for the requestor to wait upon.
200 Barrier barrier_;
201};
202
203void ThreadList::Dump(std::ostream& os) {
204 {
205 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
206 os << "DALVIK THREADS (" << list_.size() << "):\n";
207 }
208 DumpCheckpoint checkpoint(&os);
209 size_t threads_running_checkpoint = RunCheckpoint(&checkpoint);
Lei Lidd9943d2015-02-02 14:24:44 +0800210 if (threads_running_checkpoint != 0) {
211 checkpoint.WaitForThreadsToRunThroughCheckpoint(threads_running_checkpoint);
212 }
Elliott Hughes8daa0922011-09-11 13:46:25 -0700213}
214
Ian Rogers50b35e22012-10-04 10:09:15 -0700215void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
216 MutexLock mu(self, *Locks::thread_list_lock_);
217 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700218 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800219 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700220 CHECK(thread->IsSuspended())
221 << "\nUnsuspended thread: <<" << *thread << "\n"
222 << "self: <<" << *Thread::Current();
223 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700224 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700225}
226
Ian Rogers66aee5c2012-08-15 17:17:47 -0700227#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700228// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Andreas Gampe794ad762015-02-23 08:12:24 -0800229NO_RETURN static void UnsafeLogFatalForThreadSuspendAllTimeout() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700230 Runtime* runtime = Runtime::Current();
231 std::ostringstream ss;
232 ss << "Thread suspend timeout\n";
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700233 Locks::mutator_lock_->Dump(ss);
234 ss << "\n";
Ian Rogers7b078e82014-09-10 14:44:24 -0700235 runtime->GetThreadList()->Dump(ss);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700236 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800237 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700238}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700239#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700240
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800241// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
Mathieu Chartier99143862015-02-03 14:26:46 -0800242// individual thread requires polling. delay_us is the requested sleep wait. If delay_us is 0 then
243// we use sched_yield instead of calling usleep.
244static void ThreadSuspendSleep(useconds_t delay_us) {
245 if (delay_us == 0) {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800246 sched_yield();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800247 } else {
Mathieu Chartier99143862015-02-03 14:26:46 -0800248 usleep(delay_us);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800249 }
250}
251
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700252size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700253 Thread* self = Thread::Current();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800254 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
255 Locks::thread_list_lock_->AssertNotHeld(self);
256 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000257 if (kDebugLocking && gAborting == 0) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700258 CHECK_NE(self->GetState(), kRunnable);
259 }
260
261 std::vector<Thread*> suspended_count_modified_threads;
262 size_t count = 0;
263 {
264 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
265 // manually called.
266 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700267 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700268 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700269 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700270 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700271 if (thread->RequestCheckpoint(checkpoint_function)) {
Dave Allison0aded082013-11-07 13:15:11 -0800272 // This thread will run its checkpoint some time in the near future.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700273 count++;
274 break;
275 } else {
276 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700277 // The thread switched back to runnable.
278 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700279 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700280 continue;
281 }
282 thread->ModifySuspendCount(self, +1, false);
283 suspended_count_modified_threads.push_back(thread);
284 break;
285 }
286 }
287 }
288 }
289 }
290
291 // Run the checkpoint on ourself while we wait for threads to suspend.
292 checkpoint_function->Run(self);
293
294 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700295 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700296 if (!thread->IsSuspended()) {
Mathieu Chartier99143862015-02-03 14:26:46 -0800297 if (ATRACE_ENABLED()) {
298 std::ostringstream oss;
299 thread->ShortDump(oss);
300 ATRACE_BEGIN((std::string("Waiting for suspension of thread ") + oss.str()).c_str());
301 }
302 // Busy wait until the thread is suspended.
303 const uint64_t start_time = NanoTime();
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700304 do {
Mathieu Chartier99143862015-02-03 14:26:46 -0800305 ThreadSuspendSleep(kThreadSuspendInitialSleepUs);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700306 } while (!thread->IsSuspended());
Mathieu Chartier99143862015-02-03 14:26:46 -0800307 const uint64_t total_delay = NanoTime() - start_time;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800308 // Shouldn't need to wait for longer than 1000 microseconds.
Mathieu Chartier99143862015-02-03 14:26:46 -0800309 constexpr uint64_t kLongWaitThreshold = MsToNs(1);
310 ATRACE_END();
311 if (UNLIKELY(total_delay > kLongWaitThreshold)) {
312 LOG(WARNING) << "Long wait of " << PrettyDuration(total_delay) << " for "
313 << *thread << " suspension!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700314 }
315 }
316 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700317 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700318 {
319 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
320 thread->ModifySuspendCount(self, -1, false);
321 }
322 }
323
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800324 {
325 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
326 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
327 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
328 Thread::resume_cond_->Broadcast(self);
329 }
330
Lei Lidd9943d2015-02-02 14:24:44 +0800331 return count;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700332}
333
Dave Allison39c3bfb2014-01-28 18:33:52 -0800334// Request that a checkpoint function be run on all active (non-suspended)
335// threads. Returns the number of successful requests.
336size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
337 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700338 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
339 Locks::thread_list_lock_->AssertNotHeld(self);
340 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
341 CHECK_NE(self->GetState(), kRunnable);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800342
343 size_t count = 0;
344 {
345 // Call a checkpoint function for each non-suspended thread.
346 MutexLock mu(self, *Locks::thread_list_lock_);
347 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
348 for (const auto& thread : list_) {
349 if (thread != self) {
350 if (thread->RequestCheckpoint(checkpoint_function)) {
351 // This thread will run its checkpoint some time in the near future.
352 count++;
353 }
354 }
355 }
356 }
357
358 // Return the number of threads that will run the checkpoint function.
359 return count;
360}
361
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800362// A checkpoint/suspend-all hybrid to switch thread roots from
363// from-space to to-space refs. Used to synchronize threads at a point
364// to mark the initiation of marking while maintaining the to-space
365// invariant.
366size_t ThreadList::FlipThreadRoots(Closure* thread_flip_visitor, Closure* flip_callback,
367 gc::collector::GarbageCollector* collector) {
368 TimingLogger::ScopedTiming split("ThreadListFlip", collector->GetTimings());
369 const uint64_t start_time = NanoTime();
370 Thread* self = Thread::Current();
371 Locks::mutator_lock_->AssertNotHeld(self);
372 Locks::thread_list_lock_->AssertNotHeld(self);
373 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
374 CHECK_NE(self->GetState(), kRunnable);
375
376 std::vector<Thread*> runnable_threads;
377 std::vector<Thread*> other_threads;
378
379 // Suspend all threads once.
380 {
381 MutexLock mu(self, *Locks::thread_list_lock_);
382 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
383 // Update global suspend all state for attaching threads.
384 ++suspend_all_count_;
385 // Increment everybody's suspend count (except our own).
386 for (const auto& thread : list_) {
387 if (thread == self) {
388 continue;
389 }
390 thread->ModifySuspendCount(self, +1, false);
391 }
392 }
393
394 // Run the flip callback for the collector.
395 Locks::mutator_lock_->ExclusiveLock(self);
396 flip_callback->Run(self);
397 Locks::mutator_lock_->ExclusiveUnlock(self);
398 collector->RegisterPause(NanoTime() - start_time);
399
400 // Resume runnable threads.
401 {
402 MutexLock mu(self, *Locks::thread_list_lock_);
403 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
404 --suspend_all_count_;
405 for (const auto& thread : list_) {
406 if (thread == self) {
407 continue;
408 }
409 // Set the flip function for both runnable and suspended threads
410 // because Thread::DumpState/DumpJavaStack() (invoked by a
411 // checkpoint) may cause the flip function to be run for a
412 // runnable/suspended thread before a runnable threads runs it
413 // for itself or we run it for a suspended thread below.
414 thread->SetFlipFunction(thread_flip_visitor);
415 if (thread->IsSuspendedAtSuspendCheck()) {
416 // The thread will resume right after the broadcast.
417 thread->ModifySuspendCount(self, -1, false);
418 runnable_threads.push_back(thread);
419 } else {
420 other_threads.push_back(thread);
421 }
422 }
423 Thread::resume_cond_->Broadcast(self);
424 }
425
426 // Run the closure on the other threads and let them resume.
427 {
428 ReaderMutexLock mu(self, *Locks::mutator_lock_);
429 for (const auto& thread : other_threads) {
430 Closure* flip_func = thread->GetFlipFunction();
431 if (flip_func != nullptr) {
432 flip_func->Run(thread);
433 }
434 }
435 // Run it for self.
436 thread_flip_visitor->Run(self);
437 }
438
439 // Resume other threads.
440 {
441 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
442 for (const auto& thread : other_threads) {
443 thread->ModifySuspendCount(self, -1, false);
444 }
445 Thread::resume_cond_->Broadcast(self);
446 }
447
448 return runnable_threads.size() + other_threads.size() + 1; // +1 for self.
449}
450
Mathieu Chartierbf44d422015-06-02 11:42:18 -0700451void ThreadList::SuspendAll(const char* cause, bool long_suspend) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700452 Thread* self = Thread::Current();
453
Jeff Haoc5d824a2014-07-28 18:35:38 -0700454 if (self != nullptr) {
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700455 VLOG(threads) << *self << " SuspendAll for " << cause << " starting...";
Jeff Haoc5d824a2014-07-28 18:35:38 -0700456 } else {
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700457 VLOG(threads) << "Thread[null] SuspendAll for " << cause << " starting...";
Jeff Haoc5d824a2014-07-28 18:35:38 -0700458 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700459 ATRACE_BEGIN("Suspending mutator threads");
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800460 const uint64_t start_time = NanoTime();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700461
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800462 Locks::mutator_lock_->AssertNotHeld(self);
463 Locks::thread_list_lock_->AssertNotHeld(self);
464 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Jeff Haoc5d824a2014-07-28 18:35:38 -0700465 if (kDebugLocking && self != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700466 CHECK_NE(self->GetState(), kRunnable);
467 }
468 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700469 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800470 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
471 // Update global suspend all state for attaching threads.
472 ++suspend_all_count_;
473 // Increment everybody's suspend count (except our own).
474 for (const auto& thread : list_) {
475 if (thread == self) {
476 continue;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800478 VLOG(threads) << "requesting thread suspend: " << *thread;
479 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700480 }
481 }
482
Ian Rogers66aee5c2012-08-15 17:17:47 -0700483 // Block on the mutator lock until all Runnable threads release their share of access.
484#if HAVE_TIMED_RWLOCK
Mathieu Chartierbf44d422015-06-02 11:42:18 -0700485 while (true) {
486 if (Locks::mutator_lock_->ExclusiveLockWithTimeout(self, kThreadSuspendTimeoutMs, 0)) {
487 break;
488 } else if (!long_suspend_) {
489 // Reading long_suspend without the mutator lock is slightly racy, in some rare cases, this
490 // could result in a thread suspend timeout.
491 // Timeout if we wait more than kThreadSuspendTimeoutMs seconds.
492 UnsafeLogFatalForThreadSuspendAllTimeout();
493 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700494 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700495#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700496 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700497#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700498
Mathieu Chartierbf44d422015-06-02 11:42:18 -0700499 long_suspend_ = long_suspend;
500
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800501 const uint64_t end_time = NanoTime();
502 const uint64_t suspend_time = end_time - start_time;
503 suspend_all_historam_.AdjustAndAddValue(suspend_time);
504 if (suspend_time > kLongThreadSuspendThreshold) {
505 LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(suspend_time);
Mathieu Chartier251755c2014-07-15 18:10:25 -0700506 }
507
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800508 if (kDebugLocking) {
509 // Debug check that all threads are suspended.
510 AssertThreadsAreSuspended(self, self);
511 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700512
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700513 ATRACE_END();
Mathieu Chartierbf9fc582015-03-13 17:21:25 -0700514 ATRACE_BEGIN((std::string("Mutator threads suspended for ") + cause).c_str());
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700515
Jeff Haoc5d824a2014-07-28 18:35:38 -0700516 if (self != nullptr) {
517 VLOG(threads) << *self << " SuspendAll complete";
518 } else {
519 VLOG(threads) << "Thread[null] SuspendAll complete";
520 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700521}
522
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700523void ThreadList::ResumeAll() {
524 Thread* self = Thread::Current();
525
Jeff Haoc5d824a2014-07-28 18:35:38 -0700526 if (self != nullptr) {
527 VLOG(threads) << *self << " ResumeAll starting";
528 } else {
529 VLOG(threads) << "Thread[null] ResumeAll starting";
530 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700531
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700532 ATRACE_END();
533 ATRACE_BEGIN("Resuming mutator threads");
534
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800535 if (kDebugLocking) {
536 // Debug check that all threads are suspended.
537 AssertThreadsAreSuspended(self, self);
538 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700539
Mathieu Chartierbf44d422015-06-02 11:42:18 -0700540 long_suspend_ = false;
541
Ian Rogers81d425b2012-09-27 16:03:43 -0700542 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700543 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700544 MutexLock mu(self, *Locks::thread_list_lock_);
545 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700546 // Update global suspend all state for attaching threads.
547 --suspend_all_count_;
548 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700549 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700550 if (thread == self) {
551 continue;
552 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700553 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700554 }
555
556 // Broadcast a notification to all suspended threads, some or all of
557 // which may choose to wake up. No need to wait for them.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700558 if (self != nullptr) {
559 VLOG(threads) << *self << " ResumeAll waking others";
560 } else {
561 VLOG(threads) << "Thread[null] ResumeAll waking others";
562 }
Ian Rogersc604d732012-10-14 16:09:54 -0700563 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700564 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700565 ATRACE_END();
Jeff Haoc5d824a2014-07-28 18:35:38 -0700566
567 if (self != nullptr) {
568 VLOG(threads) << *self << " ResumeAll complete";
569 } else {
570 VLOG(threads) << "Thread[null] ResumeAll complete";
571 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700572}
573
574void ThreadList::Resume(Thread* thread, bool for_debugger) {
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800575 // This assumes there was an ATRACE_BEGIN when we suspended the thread.
576 ATRACE_END();
577
Ian Rogers81d425b2012-09-27 16:03:43 -0700578 Thread* self = Thread::Current();
579 DCHECK_NE(thread, self);
Brian Carlstromba32de42014-08-27 23:43:46 -0700580 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..."
581 << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700582
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700583 {
584 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700585 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700586 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700587 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
588 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700589 if (!Contains(thread)) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700590 // We only expect threads within the thread-list to have been suspended otherwise we can't
591 // stop such threads from delete-ing themselves.
592 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
593 << ") thread not within thread list";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700594 return;
595 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700596 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700597 }
598
599 {
Brian Carlstromba32de42014-08-27 23:43:46 -0700600 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700601 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700602 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700603 }
604
Brian Carlstromba32de42014-08-27 23:43:46 -0700605 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700606}
Elliott Hughes01158d72011-09-19 19:47:10 -0700607
Ian Rogersc7dd2952014-10-21 23:31:19 -0700608static void ThreadSuspendByPeerWarning(Thread* self, LogSeverity severity, const char* message,
609 jobject peer) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700610 JNIEnvExt* env = self->GetJniEnv();
611 ScopedLocalRef<jstring>
Mathieu Chartierbf44d422015-06-02 11:42:18 -0700612 scoped_name_string(env, (jstring)env->GetObjectField(
613 peer, WellKnownClasses::java_lang_Thread_name));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700614 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700615 if (scoped_name_chars.c_str() == nullptr) {
Ian Rogersc7dd2952014-10-21 23:31:19 -0700616 LOG(severity) << message << ": " << peer;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700617 env->ExceptionClear();
618 } else {
Ian Rogersc7dd2952014-10-21 23:31:19 -0700619 LOG(severity) << message << ": " << peer << ":" << scoped_name_chars.c_str();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700620 }
621}
622
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700623Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
624 bool debug_suspension, bool* timed_out) {
Mathieu Chartier3a958aa2015-02-04 12:52:34 -0800625 const uint64_t start_time = NanoTime();
Mathieu Chartier99143862015-02-03 14:26:46 -0800626 useconds_t sleep_us = kThreadSuspendInitialSleepUs;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700627 *timed_out = false;
Mathieu Chartier99143862015-02-03 14:26:46 -0800628 Thread* const self = Thread::Current();
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800629 Thread* suspended_thread = nullptr;
Brian Carlstromba32de42014-08-27 23:43:46 -0700630 VLOG(threads) << "SuspendThreadByPeer starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700631 while (true) {
632 Thread* thread;
633 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700634 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
635 // is requesting another suspend, to avoid deadlock, by requiring this function be called
636 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
637 // than request thread suspension, to avoid potential cycles in threads requesting each other
638 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700639 ScopedObjectAccess soa(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800640 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700641 thread = Thread::FromManagedThread(soa, peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700642 if (thread == nullptr) {
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800643 if (suspended_thread != nullptr) {
644 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
645 // If we incremented the suspend count but the thread reset its peer, we need to
646 // re-decrement it since it is shutting down and may deadlock the runtime in
647 // ThreadList::WaitForOtherNonDaemonThreadsToExit.
648 suspended_thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
649 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700650 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700651 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700652 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700653 if (!Contains(thread)) {
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800654 CHECK(suspended_thread == nullptr);
Brian Carlstromba32de42014-08-27 23:43:46 -0700655 VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
656 << reinterpret_cast<void*>(thread);
657 return nullptr;
658 }
659 VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700660 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800661 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700662 if (request_suspension) {
Ian Rogers4ad5cd32014-11-11 23:08:07 -0800663 if (self->GetSuspendCount() > 0) {
664 // We hold the suspend count lock but another thread is trying to suspend us. Its not
665 // safe to try to suspend another thread in case we get a cycle. Start the loop again
666 // which will allow this thread to be suspended.
667 continue;
668 }
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800669 CHECK(suspended_thread == nullptr);
670 suspended_thread = thread;
671 suspended_thread->ModifySuspendCount(self, +1, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700672 request_suspension = false;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700673 } else {
674 // If the caller isn't requesting suspension, a suspension should have already occurred.
675 CHECK_GT(thread->GetSuspendCount(), 0);
676 }
677 // IsSuspended on the current thread will fail as the current thread is changed into
678 // Runnable above. As the suspend count is now raised if this is the current thread
679 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
680 // to just explicitly handle the current thread in the callers to this code.
681 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
682 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
683 // count, or else we've waited and it has self suspended) or is the current thread, we're
684 // done.
685 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700686 VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800687 if (ATRACE_ENABLED()) {
688 std::string name;
689 thread->GetThreadName(name);
690 ATRACE_BEGIN(StringPrintf("SuspendThreadByPeer suspended %s for peer=%p", name.c_str(),
691 peer).c_str());
692 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700693 return thread;
694 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800695 const uint64_t total_delay = NanoTime() - start_time;
696 if (total_delay >= MsToNs(kThreadSuspendTimeoutMs)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700697 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800698 if (suspended_thread != nullptr) {
699 CHECK_EQ(suspended_thread, thread);
700 suspended_thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700701 }
702 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700703 return nullptr;
Mathieu Chartier99143862015-02-03 14:26:46 -0800704 } else if (sleep_us == 0 &&
705 total_delay > static_cast<uint64_t>(kThreadSuspendMaxYieldUs) * 1000) {
706 // We have spun for kThreadSuspendMaxYieldUs time, switch to sleeps to prevent
707 // excessive CPU usage.
708 sleep_us = kThreadSuspendMaxYieldUs / 2;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700709 }
710 }
711 // Release locks and come out of runnable state.
712 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800713 VLOG(threads) << "SuspendThreadByPeer waiting to allow thread chance to suspend";
714 ThreadSuspendSleep(sleep_us);
715 // This may stay at 0 if sleep_us == 0, but this is WAI since we want to avoid using usleep at
716 // all if possible. This shouldn't be an issue since time to suspend should always be small.
717 sleep_us = std::min(sleep_us * 2, kThreadSuspendMaxSleepUs);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700718 }
719}
720
Ian Rogersc7dd2952014-10-21 23:31:19 -0700721static void ThreadSuspendByThreadIdWarning(LogSeverity severity, const char* message,
722 uint32_t thread_id) {
723 LOG(severity) << StringPrintf("%s: %d", message, thread_id);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700724}
725
726Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
727 bool* timed_out) {
Mathieu Chartier3a958aa2015-02-04 12:52:34 -0800728 const uint64_t start_time = NanoTime();
Mathieu Chartier99143862015-02-03 14:26:46 -0800729 useconds_t sleep_us = kThreadSuspendInitialSleepUs;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700730 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800731 Thread* suspended_thread = nullptr;
Mathieu Chartier99143862015-02-03 14:26:46 -0800732 Thread* const self = Thread::Current();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700733 CHECK_NE(thread_id, kInvalidThreadId);
Brian Carlstromba32de42014-08-27 23:43:46 -0700734 VLOG(threads) << "SuspendThreadByThreadId starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700735 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700736 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700737 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
738 // is requesting another suspend, to avoid deadlock, by requiring this function be called
739 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
740 // than request thread suspension, to avoid potential cycles in threads requesting each other
741 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700742 ScopedObjectAccess soa(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800743 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700744 Thread* thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700745 for (const auto& it : list_) {
746 if (it->GetThreadId() == thread_id) {
747 thread = it;
748 break;
749 }
750 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800751 if (thread == nullptr) {
752 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
753 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700754 // There's a race in inflating a lock and the owner giving up ownership and then dying.
755 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
Brian Carlstromba32de42014-08-27 23:43:46 -0700756 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700757 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700758 VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
759 DCHECK(Contains(thread));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700760 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800761 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800762 if (suspended_thread == nullptr) {
Ian Rogers4ad5cd32014-11-11 23:08:07 -0800763 if (self->GetSuspendCount() > 0) {
764 // We hold the suspend count lock but another thread is trying to suspend us. Its not
765 // safe to try to suspend another thread in case we get a cycle. Start the loop again
766 // which will allow this thread to be suspended.
767 continue;
768 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700769 thread->ModifySuspendCount(self, +1, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800770 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700771 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800772 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700773 // If the caller isn't requesting suspension, a suspension should have already occurred.
774 CHECK_GT(thread->GetSuspendCount(), 0);
775 }
776 // IsSuspended on the current thread will fail as the current thread is changed into
777 // Runnable above. As the suspend count is now raised if this is the current thread
778 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
779 // to just explicitly handle the current thread in the callers to this code.
780 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
781 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
782 // count, or else we've waited and it has self suspended) or is the current thread, we're
783 // done.
784 if (thread->IsSuspended()) {
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800785 if (ATRACE_ENABLED()) {
786 std::string name;
787 thread->GetThreadName(name);
788 ATRACE_BEGIN(StringPrintf("SuspendThreadByThreadId suspended %s id=%d",
789 name.c_str(), thread_id).c_str());
790 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700791 VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700792 return thread;
793 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800794 const uint64_t total_delay = NanoTime() - start_time;
795 if (total_delay >= MsToNs(kThreadSuspendTimeoutMs)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700796 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800797 if (suspended_thread != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700798 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
799 }
800 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700801 return nullptr;
Mathieu Chartier99143862015-02-03 14:26:46 -0800802 } else if (sleep_us == 0 &&
803 total_delay > static_cast<uint64_t>(kThreadSuspendMaxYieldUs) * 1000) {
804 // We have spun for kThreadSuspendMaxYieldUs time, switch to sleeps to prevent
805 // excessive CPU usage.
806 sleep_us = kThreadSuspendMaxYieldUs / 2;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700807 }
808 }
809 // Release locks and come out of runnable state.
810 }
Mathieu Chartier99143862015-02-03 14:26:46 -0800811 VLOG(threads) << "SuspendThreadByThreadId waiting to allow thread chance to suspend";
812 ThreadSuspendSleep(sleep_us);
813 sleep_us = std::min(sleep_us * 2, kThreadSuspendMaxSleepUs);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700814 }
815}
816
817Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
818 Thread* self = Thread::Current();
819 MutexLock mu(self, *Locks::thread_list_lock_);
820 for (const auto& thread : list_) {
821 if (thread->GetThreadId() == thin_lock_id) {
822 CHECK(thread == self || thread->IsSuspended());
823 return thread;
824 }
825 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700826 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700827}
828
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700829void ThreadList::SuspendAllForDebugger() {
830 Thread* self = Thread::Current();
831 Thread* debug_thread = Dbg::GetDebugThread();
832
833 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
834
835 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800836 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700837 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800838 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700839 // Update global suspend all state for attaching threads.
Sebastien Hertz253fa552014-10-14 17:27:15 +0200840 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700841 ++suspend_all_count_;
842 ++debug_suspend_all_count_;
843 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700844 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700845 if (thread == self || thread == debug_thread) {
846 continue;
847 }
848 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700849 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700850 }
851 }
852 }
853
Ian Rogers66aee5c2012-08-15 17:17:47 -0700854 // Block on the mutator lock until all Runnable threads release their share of access then
855 // immediately unlock again.
856#if HAVE_TIMED_RWLOCK
857 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700858 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100859 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700860 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700861 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700862 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700863#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700864 Locks::mutator_lock_->ExclusiveLock(self);
865 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700866#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700867 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700868
Sebastien Hertzed2be172014-08-19 15:33:43 +0200869 VLOG(threads) << *self << " SuspendAllForDebugger complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700870}
871
Elliott Hughes475fc232011-10-25 15:00:35 -0700872void ThreadList::SuspendSelfForDebugger() {
Sebastien Hertz1558b572015-02-25 15:05:59 +0100873 Thread* const self = Thread::Current();
874 self->SetReadyForDebugInvoke(true);
Elliott Hughes01158d72011-09-19 19:47:10 -0700875
Elliott Hughes475fc232011-10-25 15:00:35 -0700876 // The debugger thread must not suspend itself due to debugger activity!
877 Thread* debug_thread = Dbg::GetDebugThread();
Elliott Hughes475fc232011-10-25 15:00:35 -0700878 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800879 CHECK_NE(self->GetState(), kRunnable);
880 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700881
Sebastien Hertzcbc50642015-06-01 17:33:12 +0200882 // The debugger may have detached while we were executing an invoke request. In that case, we
883 // must not suspend ourself.
884 DebugInvokeReq* pReq = self->GetInvokeReq();
885 const bool skip_thread_suspension = (pReq != nullptr && !Dbg::IsDebuggerActive());
886 if (!skip_thread_suspension) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800887 // Collisions with other suspends aren't really interesting. We want
888 // to ensure that we're the only one fiddling with the suspend count
889 // though.
890 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
891 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700892 CHECK_GT(self->GetSuspendCount(), 0);
Sebastien Hertzcbc50642015-06-01 17:33:12 +0200893
894 VLOG(threads) << *self << " self-suspending (debugger)";
895 } else {
896 // We must no longer be subject to debugger suspension.
897 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
898 CHECK_EQ(self->GetDebugSuspendCount(), 0) << "Debugger detached without resuming us";
899
900 VLOG(threads) << *self << " not self-suspending because debugger detached during invoke";
jeffhaoa77f0f62012-12-05 17:19:31 -0800901 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700902
Sebastien Hertzcbc50642015-06-01 17:33:12 +0200903 // If the debugger requested an invoke, we need to send the reply and clear the request.
Sebastien Hertz1558b572015-02-25 15:05:59 +0100904 if (pReq != nullptr) {
Sebastien Hertzcbc50642015-06-01 17:33:12 +0200905 Dbg::FinishInvokeMethod(pReq);
Sebastien Hertz1558b572015-02-25 15:05:59 +0100906 self->ClearDebugInvokeReq();
Sebastien Hertzcbc50642015-06-01 17:33:12 +0200907 pReq = nullptr; // object has been deleted, clear it for safety.
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100908 }
909
Elliott Hughes475fc232011-10-25 15:00:35 -0700910 // Tell JDWP that we've completed suspension. The JDWP thread can't
911 // tell us to resume before we're fully asleep because we hold the
912 // suspend count lock.
913 Dbg::ClearWaitForEventThread();
914
jeffhaoa77f0f62012-12-05 17:19:31 -0800915 {
916 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700917 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800918 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700919 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800920 // The condition was signaled but we're still suspended. This
Sebastien Hertzf272af42014-09-18 10:20:42 +0200921 // can happen when we suspend then resume all threads to
922 // update instrumentation or compute monitor info. This can
923 // also happen if the debugger lets go while a SIGQUIT thread
jeffhaoa77f0f62012-12-05 17:19:31 -0800924 // dump event is pending (assuming SignalCatcher was resumed for
925 // just long enough to try to grab the thread-suspend lock).
Sebastien Hertzf272af42014-09-18 10:20:42 +0200926 VLOG(jdwp) << *self << " still suspended after undo "
927 << "(suspend count=" << self->GetSuspendCount() << ", "
928 << "debug suspend count=" << self->GetDebugSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -0800929 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700930 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700931 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700932 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800933
Sebastien Hertz1558b572015-02-25 15:05:59 +0100934 self->SetReadyForDebugInvoke(false);
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800935 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700936}
937
Sebastien Hertz253fa552014-10-14 17:27:15 +0200938void ThreadList::ResumeAllForDebugger() {
939 Thread* self = Thread::Current();
940 Thread* debug_thread = Dbg::GetDebugThread();
Sebastien Hertz253fa552014-10-14 17:27:15 +0200941
942 VLOG(threads) << *self << " ResumeAllForDebugger starting...";
943
944 // Threads can't resume if we exclusively hold the mutator lock.
945 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
946
947 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800948 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Sebastien Hertz253fa552014-10-14 17:27:15 +0200949 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800950 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Sebastien Hertz253fa552014-10-14 17:27:15 +0200951 // Update global suspend all state for attaching threads.
952 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100953 if (debug_suspend_all_count_ > 0) {
Sebastien Hertz253fa552014-10-14 17:27:15 +0200954 --suspend_all_count_;
955 --debug_suspend_all_count_;
Sebastien Hertz253fa552014-10-14 17:27:15 +0200956 } else {
957 // We've been asked to resume all threads without being asked to
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100958 // suspend them all before. That may happen if a debugger tries
959 // to resume some suspended threads (with suspend count == 1)
960 // at once with a VirtualMachine.Resume command. Let's print a
961 // warning.
Sebastien Hertz253fa552014-10-14 17:27:15 +0200962 LOG(WARNING) << "Debugger attempted to resume all threads without "
963 << "having suspended them all before.";
964 }
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100965 // Decrement everybody's suspend count (except our own).
966 for (const auto& thread : list_) {
967 if (thread == self || thread == debug_thread) {
968 continue;
969 }
970 if (thread->GetDebugSuspendCount() == 0) {
971 // This thread may have been individually resumed with ThreadReference.Resume.
972 continue;
973 }
974 VLOG(threads) << "requesting thread resume: " << *thread;
975 thread->ModifySuspendCount(self, -1, true);
976 }
Sebastien Hertz253fa552014-10-14 17:27:15 +0200977 }
978 }
979
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100980 {
Sebastien Hertz253fa552014-10-14 17:27:15 +0200981 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
982 Thread::resume_cond_->Broadcast(self);
983 }
984
985 VLOG(threads) << *self << " ResumeAllForDebugger complete";
986}
987
Elliott Hughes234ab152011-10-26 14:02:26 -0700988void ThreadList::UndoDebuggerSuspensions() {
989 Thread* self = Thread::Current();
990
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800991 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700992
993 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700994 MutexLock mu(self, *Locks::thread_list_lock_);
995 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700996 // Update global suspend all state for attaching threads.
997 suspend_all_count_ -= debug_suspend_all_count_;
998 debug_suspend_all_count_ = 0;
999 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -07001000 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001001 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -07001002 continue;
1003 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001004 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
Elliott Hughes234ab152011-10-26 14:02:26 -07001005 }
1006 }
1007
1008 {
Ian Rogers81d425b2012-09-27 16:03:43 -07001009 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -07001010 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -07001011 }
1012
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001013 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -07001014}
1015
Elliott Hughese52e49b2012-04-02 16:05:44 -07001016void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001017 Thread* self = Thread::Current();
1018 Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartier91e56692015-03-03 13:51:04 -08001019 while (true) {
Ian Rogers120f1c72012-09-28 17:17:10 -07001020 {
1021 // No more threads can be born after we start to shutdown.
1022 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001023 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -07001024 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
1025 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001026 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier91e56692015-03-03 13:51:04 -08001027 // Also wait for any threads that are unregistering to finish. This is required so that no
1028 // threads access the thread list after it is deleted. TODO: This may not work for user daemon
1029 // threads since they could unregister at the wrong time.
1030 bool done = unregistering_count_ == 0;
1031 if (done) {
1032 for (const auto& thread : list_) {
1033 if (thread != self && !thread->IsDaemon()) {
1034 done = false;
1035 break;
1036 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001037 }
1038 }
Mathieu Chartier91e56692015-03-03 13:51:04 -08001039 if (done) {
1040 break;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001041 }
Mathieu Chartier91e56692015-03-03 13:51:04 -08001042 // Wait for another thread to exit before re-checking.
1043 Locks::thread_exit_cond_->Wait(self);
1044 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001045}
1046
1047void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -07001048 Thread* self = Thread::Current();
1049 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001050 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -07001051 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001052 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001053 // This is only run after all non-daemon threads have exited, so the remainder should all be
1054 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -07001055 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -07001056 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -07001057 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -07001058 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001059 }
1060 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001061 // Give the threads a chance to suspend, complaining if they're slow.
1062 bool have_complained = false;
1063 for (int i = 0; i < 10; ++i) {
1064 usleep(200 * 1000);
1065 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -07001066 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -07001067 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -07001068 if (!have_complained) {
1069 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
1070 have_complained = true;
1071 }
1072 all_suspended = false;
1073 }
1074 }
1075 if (all_suspended) {
1076 return;
1077 }
1078 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001079 LOG(ERROR) << "suspend all daemons failed";
1080}
1081void ThreadList::Register(Thread* self) {
1082 DCHECK_EQ(self, Thread::Current());
1083
1084 if (VLOG_IS_ON(threads)) {
1085 std::ostringstream oss;
1086 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
Ian Rogers5a9ba012014-05-19 13:28:52 -07001087 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001088 }
1089
1090 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
1091 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -07001092 MutexLock mu(self, *Locks::thread_list_lock_);
1093 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001094 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -07001095 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
1096 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
1097 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
1098 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001099 }
Ian Rogers2966e132014-04-02 08:34:36 -07001100 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
1101 self->ModifySuspendCount(self, +1, false);
Ian Rogers01ae5802012-09-28 16:14:01 -07001102 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001103 CHECK(!Contains(self));
1104 list_.push_back(self);
1105}
1106
1107void ThreadList::Unregister(Thread* self) {
1108 DCHECK_EQ(self, Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -07001109 CHECK_NE(self->GetState(), kRunnable);
1110 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001111
1112 VLOG(threads) << "ThreadList::Unregister() " << *self;
1113
Mathieu Chartier91e56692015-03-03 13:51:04 -08001114 {
1115 MutexLock mu(self, *Locks::thread_list_lock_);
1116 ++unregistering_count_;
1117 }
1118
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001119 // Any time-consuming destruction, plus anything that can call back into managed code or
Mathieu Chartier91e56692015-03-03 13:51:04 -08001120 // suspend and so on, must happen at this point, and not in ~Thread. The self->Destroy is what
1121 // causes the threads to join. It is important to do this after incrementing unregistering_count_
1122 // since we want the runtime to wait for the daemon threads to exit before deleting the thread
1123 // list.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001124 self->Destroy();
1125
Jeff Haoe094b872014-10-14 13:12:01 -07001126 // If tracing, remember thread id and name before thread exits.
1127 Trace::StoreExitingThreadInfo(self);
1128
Ian Rogersdd7624d2014-03-14 17:43:00 -07001129 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier91e56692015-03-03 13:51:04 -08001130 while (true) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001131 // Remove and delete the Thread* while holding the thread_list_lock_ and
1132 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -07001133 // Note: deliberately not using MutexLock that could hold a stale self pointer.
Mathieu Chartier91e56692015-03-03 13:51:04 -08001134 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersa2af5c72014-09-15 15:17:07 -07001135 if (!Contains(self)) {
Mathieu Chartier9db831a2015-02-24 17:20:30 -08001136 std::string thread_name;
1137 self->GetThreadName(thread_name);
Ian Rogersa2af5c72014-09-15 15:17:07 -07001138 std::ostringstream os;
1139 DumpNativeStack(os, GetTid(), " native: ", nullptr);
Mathieu Chartier9db831a2015-02-24 17:20:30 -08001140 LOG(ERROR) << "Request to unregister unattached thread " << thread_name << "\n" << os.str();
Mathieu Chartier91e56692015-03-03 13:51:04 -08001141 break;
Ian Rogersa2af5c72014-09-15 15:17:07 -07001142 } else {
Mathieu Chartier91e56692015-03-03 13:51:04 -08001143 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersa2af5c72014-09-15 15:17:07 -07001144 if (!self->IsSuspended()) {
1145 list_.remove(self);
Mathieu Chartier91e56692015-03-03 13:51:04 -08001146 break;
Ian Rogersa2af5c72014-09-15 15:17:07 -07001147 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001148 }
Mathieu Chartier91e56692015-03-03 13:51:04 -08001149 // We failed to remove the thread due to a suspend request, loop and try again.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001150 }
Mathieu Chartier91e56692015-03-03 13:51:04 -08001151 delete self;
1152
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -08001153 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
1154 // temporarily have multiple threads with the same thread id. When this occurs, it causes
1155 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
1156 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001157
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001158 // Clear the TLS data, so that the underlying native thread is recognizably detached.
1159 // (It may wish to reattach later.)
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001160 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, nullptr), "detach self");
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001161
1162 // Signal that a thread just detached.
Mathieu Chartier91e56692015-03-03 13:51:04 -08001163 MutexLock mu(nullptr, *Locks::thread_list_lock_);
1164 --unregistering_count_;
1165 Locks::thread_exit_cond_->Broadcast(nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001166}
1167
1168void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001169 for (const auto& thread : list_) {
1170 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001171 }
1172}
1173
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001174void ThreadList::VisitRoots(RootVisitor* visitor) const {
Ian Rogers81d425b2012-09-27 16:03:43 -07001175 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001176 for (const auto& thread : list_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001177 thread->VisitRoots(visitor);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001178 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001179}
1180
Ian Rogerscfaa4552012-11-26 21:00:08 -08001181uint32_t ThreadList::AllocThreadId(Thread* self) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001182 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -07001183 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
1184 if (!allocated_ids_[i]) {
1185 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001186 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -07001187 }
1188 }
1189 LOG(FATAL) << "Out of internal thread ids";
1190 return 0;
1191}
1192
Ian Rogerscfaa4552012-11-26 21:00:08 -08001193void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001194 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001195 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -07001196 DCHECK(allocated_ids_[id]) << id;
1197 allocated_ids_.reset(id);
1198}
1199
Elliott Hughes8daa0922011-09-11 13:46:25 -07001200} // namespace art