blob: 6ec40d46d7611255729e01806c01e164c57bee85 [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);
47
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080048ThreadList::ThreadList()
Chao-ying Fu9e369312014-05-21 11:20:52 -070049 : suspend_all_count_(0), debug_suspend_all_count_(0),
Mathieu Chartier70a596d2014-12-17 14:56:47 -080050 thread_exit_cond_("thread exit condition variable", *Locks::thread_list_lock_),
51 suspend_all_historam_("suspend all histogram", 16, 64) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070052 CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1)));
Elliott Hughes8daa0922011-09-11 13:46:25 -070053}
54
55ThreadList::~ThreadList() {
Elliott Hughese52e49b2012-04-02 16:05:44 -070056 // Detach the current thread if necessary. If we failed to start, there might not be any threads.
Elliott Hughes6a144332012-04-03 13:07:11 -070057 // We need to detach the current thread here in case there's another thread waiting to join with
58 // us.
Mathieu Chartierfec72f42014-10-09 12:57:58 -070059 bool contains = false;
60 {
61 Thread* self = Thread::Current();
62 MutexLock mu(self, *Locks::thread_list_lock_);
63 contains = Contains(self);
64 }
65 if (contains) {
Elliott Hughes8daa0922011-09-11 13:46:25 -070066 Runtime::Current()->DetachCurrentThread();
67 }
Elliott Hughes6a144332012-04-03 13:07:11 -070068
69 WaitForOtherNonDaemonThreadsToExit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070070 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
71 // Thread::Init.
Elliott Hughes6a144332012-04-03 13:07:11 -070072 SuspendAllDaemonThreads();
Elliott Hughes8daa0922011-09-11 13:46:25 -070073}
74
75bool ThreadList::Contains(Thread* thread) {
76 return find(list_.begin(), list_.end(), thread) != list_.end();
77}
78
Elliott Hughesabbe07d2012-06-05 17:42:23 -070079bool ThreadList::Contains(pid_t tid) {
Mathieu Chartier02e25112013-08-14 16:14:24 -070080 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070081 if (thread->GetTid() == tid) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -070082 return true;
83 }
84 }
85 return false;
86}
87
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070088pid_t ThreadList::GetLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -070089 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
Elliott Hughesaccd83d2011-10-17 14:25:58 -070090}
91
Mathieu Chartier590fee92013-09-13 13:46:47 -070092void ThreadList::DumpNativeStacks(std::ostream& os) {
93 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
94 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070095 os << "DUMPING THREAD " << thread->GetTid() << "\n";
Christopher Ferrisa2cee182014-04-16 19:13:59 -070096 DumpNativeStack(os, thread->GetTid(), "\t");
Mathieu Chartier590fee92013-09-13 13:46:47 -070097 os << "\n";
98 }
99}
100
Elliott Hughesc967f782012-04-16 10:23:15 -0700101void ThreadList::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800102 {
103 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier23f6e692014-12-18 18:24:39 -0800104 // Only print if we have samples.
105 if (suspend_all_historam_.SampleSize() > 0) {
106 Histogram<uint64_t>::CumulativeData data;
107 suspend_all_historam_.CreateHistogram(&data);
108 suspend_all_historam_.PrintConfidenceIntervals(os, 0.99, data); // Dump time to suspend.
109 }
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800110 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700111 Dump(os);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700112 DumpUnattachedThreads(os);
113}
114
Ian Rogerscfaa4552012-11-26 21:00:08 -0800115static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
116 // TODO: No thread safety analysis as DumpState with a NULL thread won't access fields, should
117 // refactor DumpState to avoid skipping analysis.
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700118 Thread::DumpState(os, NULL, tid);
119 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -0700120 // TODO: Reenable this when the native code in system_server can handle it.
121 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
122 if (false) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -0700123 DumpNativeStack(os, tid, " native: ");
Brian Carlstromed8b7232012-06-27 17:54:47 -0700124 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700125 os << "\n";
126}
127
128void ThreadList::DumpUnattachedThreads(std::ostream& os) {
129 DIR* d = opendir("/proc/self/task");
130 if (!d) {
131 return;
132 }
133
Ian Rogers50b35e22012-10-04 10:09:15 -0700134 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700135 dirent* e;
136 while ((e = readdir(d)) != NULL) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700137 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700138 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700139 if (!*end) {
140 bool contains;
141 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700142 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700143 contains = Contains(tid);
144 }
145 if (!contains) {
146 DumpUnattachedThread(os, tid);
147 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700148 }
149 }
150 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800151}
152
Andreas Gampe4a3d19b2015-01-09 17:54:51 -0800153// Dump checkpoint timeout in milliseconds. Larger amount on the host, as dumping will invoke
154// addr2line when available.
Andreas Gampe1e4b0ca2015-01-14 09:06:32 -0800155static constexpr uint32_t kDumpWaitTimeout = kIsTargetBuild ? 10000 : 20000;
Andreas Gampe4a3d19b2015-01-09 17:54:51 -0800156
Ian Rogers7b078e82014-09-10 14:44:24 -0700157// A closure used by Thread::Dump.
158class DumpCheckpoint FINAL : public Closure {
159 public:
160 explicit DumpCheckpoint(std::ostream* os) : os_(os), barrier_(0) {}
161
162 void Run(Thread* thread) OVERRIDE {
163 // Note thread and self may not be equal if thread was already suspended at the point of the
164 // request.
165 Thread* self = Thread::Current();
166 std::ostringstream local_os;
167 {
168 ScopedObjectAccess soa(self);
169 thread->Dump(local_os);
170 }
171 local_os << "\n";
172 {
173 // Use the logging lock to ensure serialization when writing to the common ostream.
174 MutexLock mu(self, *Locks::logging_lock_);
175 *os_ << local_os.str();
176 }
177 barrier_.Pass(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700178 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700179
180 void WaitForThreadsToRunThroughCheckpoint(size_t threads_running_checkpoint) {
181 Thread* self = Thread::Current();
182 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
Andreas Gampe1e4b0ca2015-01-14 09:06:32 -0800183 bool timed_out = barrier_.Increment(self, threads_running_checkpoint, kDumpWaitTimeout);
Ian Rogers2156ff12014-09-13 19:20:54 -0700184 if (timed_out) {
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000185 // Avoid a recursive abort.
186 LOG((kIsDebugBuild && (gAborting == 0)) ? FATAL : ERROR)
187 << "Unexpected time out during dump checkpoint.";
Ian Rogers2156ff12014-09-13 19:20:54 -0700188 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700189 }
190
191 private:
192 // The common stream that will accumulate all the dumps.
193 std::ostream* const os_;
194 // The barrier to be passed through and for the requestor to wait upon.
195 Barrier barrier_;
196};
197
198void ThreadList::Dump(std::ostream& os) {
199 {
200 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
201 os << "DALVIK THREADS (" << list_.size() << "):\n";
202 }
203 DumpCheckpoint checkpoint(&os);
204 size_t threads_running_checkpoint = RunCheckpoint(&checkpoint);
205 checkpoint.WaitForThreadsToRunThroughCheckpoint(threads_running_checkpoint);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700206}
207
Ian Rogers50b35e22012-10-04 10:09:15 -0700208void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
209 MutexLock mu(self, *Locks::thread_list_lock_);
210 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700211 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800212 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700213 CHECK(thread->IsSuspended())
214 << "\nUnsuspended thread: <<" << *thread << "\n"
215 << "self: <<" << *Thread::Current();
216 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700217 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700218}
219
Ian Rogers66aee5c2012-08-15 17:17:47 -0700220#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700221// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Ian Rogers7b078e82014-09-10 14:44:24 -0700222static void UnsafeLogFatalForThreadSuspendAllTimeout() __attribute__((noreturn));
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100223static void UnsafeLogFatalForThreadSuspendAllTimeout() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700224 Runtime* runtime = Runtime::Current();
225 std::ostringstream ss;
226 ss << "Thread suspend timeout\n";
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700227 Locks::mutator_lock_->Dump(ss);
228 ss << "\n";
Ian Rogers7b078e82014-09-10 14:44:24 -0700229 runtime->GetThreadList()->Dump(ss);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700230 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800231 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700232}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700233#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700234
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800235// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
236// individual thread requires polling. delay_us is the requested sleep and total_delay_us
237// accumulates the total time spent sleeping for timeouts. The first sleep is just a yield,
238// subsequently sleeps increase delay_us from 1ms to 500ms by doubling.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700239static void ThreadSuspendSleep(useconds_t* delay_us, useconds_t* total_delay_us) {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800240 useconds_t new_delay_us = (*delay_us) * 2;
241 CHECK_GE(new_delay_us, *delay_us);
242 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
243 *delay_us = new_delay_us;
244 }
245 if (*delay_us == 0) {
246 sched_yield();
247 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
248 *delay_us = 500;
249 } else {
250 usleep(*delay_us);
251 *total_delay_us += *delay_us;
252 }
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()) {
300 // Wait until the thread is suspended.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800301 useconds_t total_delay_us = 0;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700302 do {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800303 useconds_t delay_us = 100;
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700304 ThreadSuspendSleep(&delay_us, &total_delay_us);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700305 } while (!thread->IsSuspended());
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800306 // Shouldn't need to wait for longer than 1000 microseconds.
307 constexpr useconds_t kLongWaitThresholdUS = 1000;
308 if (UNLIKELY(total_delay_us > kLongWaitThresholdUS)) {
309 LOG(WARNING) << "Waited " << total_delay_us << " us for thread suspend!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700310 }
311 }
312 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700313 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700314 {
315 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
316 thread->ModifySuspendCount(self, -1, false);
317 }
318 }
319
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800320 {
321 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
322 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
323 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
324 Thread::resume_cond_->Broadcast(self);
325 }
326
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700327 // Add one for self.
328 return count + suspended_count_modified_threads.size() + 1;
329}
330
Dave Allison39c3bfb2014-01-28 18:33:52 -0800331// Request that a checkpoint function be run on all active (non-suspended)
332// threads. Returns the number of successful requests.
333size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
334 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700335 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
336 Locks::thread_list_lock_->AssertNotHeld(self);
337 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
338 CHECK_NE(self->GetState(), kRunnable);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800339
340 size_t count = 0;
341 {
342 // Call a checkpoint function for each non-suspended thread.
343 MutexLock mu(self, *Locks::thread_list_lock_);
344 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
345 for (const auto& thread : list_) {
346 if (thread != self) {
347 if (thread->RequestCheckpoint(checkpoint_function)) {
348 // This thread will run its checkpoint some time in the near future.
349 count++;
350 }
351 }
352 }
353 }
354
355 // Return the number of threads that will run the checkpoint function.
356 return count;
357}
358
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700359void ThreadList::SuspendAll() {
360 Thread* self = Thread::Current();
361
Jeff Haoc5d824a2014-07-28 18:35:38 -0700362 if (self != nullptr) {
363 VLOG(threads) << *self << " SuspendAll starting...";
364 } else {
365 VLOG(threads) << "Thread[null] SuspendAll starting...";
366 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700367 ATRACE_BEGIN("Suspending mutator threads");
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800368 const uint64_t start_time = NanoTime();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700369
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800370 Locks::mutator_lock_->AssertNotHeld(self);
371 Locks::thread_list_lock_->AssertNotHeld(self);
372 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Jeff Haoc5d824a2014-07-28 18:35:38 -0700373 if (kDebugLocking && self != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700374 CHECK_NE(self->GetState(), kRunnable);
375 }
376 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700377 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800378 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
379 // Update global suspend all state for attaching threads.
380 ++suspend_all_count_;
381 // Increment everybody's suspend count (except our own).
382 for (const auto& thread : list_) {
383 if (thread == self) {
384 continue;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700385 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800386 VLOG(threads) << "requesting thread suspend: " << *thread;
387 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700388 }
389 }
390
Ian Rogers66aee5c2012-08-15 17:17:47 -0700391 // Block on the mutator lock until all Runnable threads release their share of access.
392#if HAVE_TIMED_RWLOCK
393 // Timeout if we wait more than 30 seconds.
Ian Rogers719d1a32014-03-06 12:13:39 -0800394 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100395 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700396 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700397#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700398 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700399#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700400
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800401 const uint64_t end_time = NanoTime();
402 const uint64_t suspend_time = end_time - start_time;
403 suspend_all_historam_.AdjustAndAddValue(suspend_time);
404 if (suspend_time > kLongThreadSuspendThreshold) {
405 LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(suspend_time);
Mathieu Chartier251755c2014-07-15 18:10:25 -0700406 }
407
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800408 if (kDebugLocking) {
409 // Debug check that all threads are suspended.
410 AssertThreadsAreSuspended(self, self);
411 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700412
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700413 ATRACE_END();
414 ATRACE_BEGIN("Mutator threads suspended");
415
Jeff Haoc5d824a2014-07-28 18:35:38 -0700416 if (self != nullptr) {
417 VLOG(threads) << *self << " SuspendAll complete";
418 } else {
419 VLOG(threads) << "Thread[null] SuspendAll complete";
420 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700421}
422
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700423void ThreadList::ResumeAll() {
424 Thread* self = Thread::Current();
425
Jeff Haoc5d824a2014-07-28 18:35:38 -0700426 if (self != nullptr) {
427 VLOG(threads) << *self << " ResumeAll starting";
428 } else {
429 VLOG(threads) << "Thread[null] ResumeAll starting";
430 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700431
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700432 ATRACE_END();
433 ATRACE_BEGIN("Resuming mutator threads");
434
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800435 if (kDebugLocking) {
436 // Debug check that all threads are suspended.
437 AssertThreadsAreSuspended(self, self);
438 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700439
Ian Rogers81d425b2012-09-27 16:03:43 -0700440 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700441 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700442 MutexLock mu(self, *Locks::thread_list_lock_);
443 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700444 // Update global suspend all state for attaching threads.
445 --suspend_all_count_;
446 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700447 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700448 if (thread == self) {
449 continue;
450 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700451 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700452 }
453
454 // Broadcast a notification to all suspended threads, some or all of
455 // which may choose to wake up. No need to wait for them.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700456 if (self != nullptr) {
457 VLOG(threads) << *self << " ResumeAll waking others";
458 } else {
459 VLOG(threads) << "Thread[null] ResumeAll waking others";
460 }
Ian Rogersc604d732012-10-14 16:09:54 -0700461 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700462 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700463 ATRACE_END();
Jeff Haoc5d824a2014-07-28 18:35:38 -0700464
465 if (self != nullptr) {
466 VLOG(threads) << *self << " ResumeAll complete";
467 } else {
468 VLOG(threads) << "Thread[null] ResumeAll complete";
469 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700470}
471
472void ThreadList::Resume(Thread* thread, bool for_debugger) {
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800473 // This assumes there was an ATRACE_BEGIN when we suspended the thread.
474 ATRACE_END();
475
Ian Rogers81d425b2012-09-27 16:03:43 -0700476 Thread* self = Thread::Current();
477 DCHECK_NE(thread, self);
Brian Carlstromba32de42014-08-27 23:43:46 -0700478 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..."
479 << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700480
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481 {
482 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700483 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700484 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700485 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
486 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700487 if (!Contains(thread)) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700488 // We only expect threads within the thread-list to have been suspended otherwise we can't
489 // stop such threads from delete-ing themselves.
490 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
491 << ") thread not within thread list";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700492 return;
493 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700494 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700495 }
496
497 {
Brian Carlstromba32de42014-08-27 23:43:46 -0700498 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700499 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700500 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700501 }
502
Brian Carlstromba32de42014-08-27 23:43:46 -0700503 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700504}
Elliott Hughes01158d72011-09-19 19:47:10 -0700505
Ian Rogersc7dd2952014-10-21 23:31:19 -0700506static void ThreadSuspendByPeerWarning(Thread* self, LogSeverity severity, const char* message,
507 jobject peer) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700508 JNIEnvExt* env = self->GetJniEnv();
509 ScopedLocalRef<jstring>
510 scoped_name_string(env, (jstring)env->GetObjectField(peer,
511 WellKnownClasses::java_lang_Thread_name));
512 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
513 if (scoped_name_chars.c_str() == NULL) {
Ian Rogersc7dd2952014-10-21 23:31:19 -0700514 LOG(severity) << message << ": " << peer;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700515 env->ExceptionClear();
516 } else {
Ian Rogersc7dd2952014-10-21 23:31:19 -0700517 LOG(severity) << message << ": " << peer << ":" << scoped_name_chars.c_str();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700518 }
519}
520
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700521Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
522 bool debug_suspension, bool* timed_out) {
523 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
524 useconds_t total_delay_us = 0;
525 useconds_t delay_us = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700526 *timed_out = false;
527 Thread* self = Thread::Current();
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800528 Thread* suspended_thread = nullptr;
Brian Carlstromba32de42014-08-27 23:43:46 -0700529 VLOG(threads) << "SuspendThreadByPeer starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700530 while (true) {
531 Thread* thread;
532 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700533 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
534 // is requesting another suspend, to avoid deadlock, by requiring this function be called
535 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
536 // than request thread suspension, to avoid potential cycles in threads requesting each other
537 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700538 ScopedObjectAccess soa(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800539 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700540 thread = Thread::FromManagedThread(soa, peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700541 if (thread == nullptr) {
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800542 if (suspended_thread != nullptr) {
543 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
544 // If we incremented the suspend count but the thread reset its peer, we need to
545 // re-decrement it since it is shutting down and may deadlock the runtime in
546 // ThreadList::WaitForOtherNonDaemonThreadsToExit.
547 suspended_thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
548 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700549 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700550 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700551 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700552 if (!Contains(thread)) {
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800553 CHECK(suspended_thread == nullptr);
Brian Carlstromba32de42014-08-27 23:43:46 -0700554 VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
555 << reinterpret_cast<void*>(thread);
556 return nullptr;
557 }
558 VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700559 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800560 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700561 if (request_suspension) {
Ian Rogers4ad5cd32014-11-11 23:08:07 -0800562 if (self->GetSuspendCount() > 0) {
563 // We hold the suspend count lock but another thread is trying to suspend us. Its not
564 // safe to try to suspend another thread in case we get a cycle. Start the loop again
565 // which will allow this thread to be suspended.
566 continue;
567 }
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800568 CHECK(suspended_thread == nullptr);
569 suspended_thread = thread;
570 suspended_thread->ModifySuspendCount(self, +1, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700571 request_suspension = false;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700572 } else {
573 // If the caller isn't requesting suspension, a suspension should have already occurred.
574 CHECK_GT(thread->GetSuspendCount(), 0);
575 }
576 // IsSuspended on the current thread will fail as the current thread is changed into
577 // Runnable above. As the suspend count is now raised if this is the current thread
578 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
579 // to just explicitly handle the current thread in the callers to this code.
580 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
581 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
582 // count, or else we've waited and it has self suspended) or is the current thread, we're
583 // done.
584 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700585 VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800586 if (ATRACE_ENABLED()) {
587 std::string name;
588 thread->GetThreadName(name);
589 ATRACE_BEGIN(StringPrintf("SuspendThreadByPeer suspended %s for peer=%p", name.c_str(),
590 peer).c_str());
591 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700592 return thread;
593 }
594 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700595 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800596 if (suspended_thread != nullptr) {
597 CHECK_EQ(suspended_thread, thread);
598 suspended_thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700599 }
600 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700601 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700602 }
603 }
604 // Release locks and come out of runnable state.
605 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700606 VLOG(threads) << "SuspendThreadByPeer sleeping to allow thread chance to suspend";
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700607 ThreadSuspendSleep(&delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700608 }
609}
610
Ian Rogersc7dd2952014-10-21 23:31:19 -0700611static void ThreadSuspendByThreadIdWarning(LogSeverity severity, const char* message,
612 uint32_t thread_id) {
613 LOG(severity) << StringPrintf("%s: %d", message, thread_id);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700614}
615
616Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
617 bool* timed_out) {
618 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
619 useconds_t total_delay_us = 0;
620 useconds_t delay_us = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700621 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800622 Thread* suspended_thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700623 Thread* self = Thread::Current();
624 CHECK_NE(thread_id, kInvalidThreadId);
Brian Carlstromba32de42014-08-27 23:43:46 -0700625 VLOG(threads) << "SuspendThreadByThreadId starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700626 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700627 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700628 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
629 // is requesting another suspend, to avoid deadlock, by requiring this function be called
630 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
631 // than request thread suspension, to avoid potential cycles in threads requesting each other
632 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700633 ScopedObjectAccess soa(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800634 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700635 Thread* thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700636 for (const auto& it : list_) {
637 if (it->GetThreadId() == thread_id) {
638 thread = it;
639 break;
640 }
641 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800642 if (thread == nullptr) {
643 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
644 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700645 // There's a race in inflating a lock and the owner giving up ownership and then dying.
646 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
Brian Carlstromba32de42014-08-27 23:43:46 -0700647 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700648 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700649 VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
650 DCHECK(Contains(thread));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700651 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800652 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800653 if (suspended_thread == nullptr) {
Ian Rogers4ad5cd32014-11-11 23:08:07 -0800654 if (self->GetSuspendCount() > 0) {
655 // We hold the suspend count lock but another thread is trying to suspend us. Its not
656 // safe to try to suspend another thread in case we get a cycle. Start the loop again
657 // which will allow this thread to be suspended.
658 continue;
659 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700660 thread->ModifySuspendCount(self, +1, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800661 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700662 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800663 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700664 // If the caller isn't requesting suspension, a suspension should have already occurred.
665 CHECK_GT(thread->GetSuspendCount(), 0);
666 }
667 // IsSuspended on the current thread will fail as the current thread is changed into
668 // Runnable above. As the suspend count is now raised if this is the current thread
669 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
670 // to just explicitly handle the current thread in the callers to this code.
671 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
672 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
673 // count, or else we've waited and it has self suspended) or is the current thread, we're
674 // done.
675 if (thread->IsSuspended()) {
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800676 if (ATRACE_ENABLED()) {
677 std::string name;
678 thread->GetThreadName(name);
679 ATRACE_BEGIN(StringPrintf("SuspendThreadByThreadId suspended %s id=%d",
680 name.c_str(), thread_id).c_str());
681 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700682 VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700683 return thread;
684 }
685 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700686 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800687 if (suspended_thread != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700688 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
689 }
690 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700691 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700692 }
693 }
694 // Release locks and come out of runnable state.
695 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700696 VLOG(threads) << "SuspendThreadByThreadId sleeping to allow thread chance to suspend";
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700697 ThreadSuspendSleep(&delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700698 }
699}
700
701Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
702 Thread* self = Thread::Current();
703 MutexLock mu(self, *Locks::thread_list_lock_);
704 for (const auto& thread : list_) {
705 if (thread->GetThreadId() == thin_lock_id) {
706 CHECK(thread == self || thread->IsSuspended());
707 return thread;
708 }
709 }
710 return NULL;
711}
712
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700713void ThreadList::SuspendAllForDebugger() {
714 Thread* self = Thread::Current();
715 Thread* debug_thread = Dbg::GetDebugThread();
716
717 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
718
719 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800720 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700721 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800722 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700723 // Update global suspend all state for attaching threads.
Sebastien Hertz253fa552014-10-14 17:27:15 +0200724 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700725 ++suspend_all_count_;
726 ++debug_suspend_all_count_;
727 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700728 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700729 if (thread == self || thread == debug_thread) {
730 continue;
731 }
732 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700733 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700734 }
735 }
736 }
737
Ian Rogers66aee5c2012-08-15 17:17:47 -0700738 // Block on the mutator lock until all Runnable threads release their share of access then
739 // immediately unlock again.
740#if HAVE_TIMED_RWLOCK
741 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700742 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100743 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700744 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700745 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700746 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700747#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700748 Locks::mutator_lock_->ExclusiveLock(self);
749 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700750#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700751 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700752
Sebastien Hertzed2be172014-08-19 15:33:43 +0200753 VLOG(threads) << *self << " SuspendAllForDebugger complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700754}
755
Elliott Hughes475fc232011-10-25 15:00:35 -0700756void ThreadList::SuspendSelfForDebugger() {
757 Thread* self = Thread::Current();
Elliott Hughes01158d72011-09-19 19:47:10 -0700758
Elliott Hughes475fc232011-10-25 15:00:35 -0700759 // The debugger thread must not suspend itself due to debugger activity!
760 Thread* debug_thread = Dbg::GetDebugThread();
761 CHECK(debug_thread != NULL);
762 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800763 CHECK_NE(self->GetState(), kRunnable);
764 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700765
jeffhaoa77f0f62012-12-05 17:19:31 -0800766 {
767 // Collisions with other suspends aren't really interesting. We want
768 // to ensure that we're the only one fiddling with the suspend count
769 // though.
770 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
771 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700772 CHECK_GT(self->GetSuspendCount(), 0);
jeffhaoa77f0f62012-12-05 17:19:31 -0800773 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700774
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800775 VLOG(threads) << *self << " self-suspending (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700776
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100777 // Tell JDWP we've completed invocation and are ready to suspend.
778 DebugInvokeReq* pReq = self->GetInvokeReq();
779 DCHECK(pReq != NULL);
780 if (pReq->invoke_needed) {
781 // Clear this before signaling.
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200782 pReq->Clear();
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100783
784 VLOG(jdwp) << "invoke complete, signaling";
785 MutexLock mu(self, pReq->lock);
786 pReq->cond.Signal(self);
787 }
788
Elliott Hughes475fc232011-10-25 15:00:35 -0700789 // Tell JDWP that we've completed suspension. The JDWP thread can't
790 // tell us to resume before we're fully asleep because we hold the
791 // suspend count lock.
792 Dbg::ClearWaitForEventThread();
793
jeffhaoa77f0f62012-12-05 17:19:31 -0800794 {
795 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700796 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800797 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700798 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800799 // The condition was signaled but we're still suspended. This
Sebastien Hertzf272af42014-09-18 10:20:42 +0200800 // can happen when we suspend then resume all threads to
801 // update instrumentation or compute monitor info. This can
802 // also happen if the debugger lets go while a SIGQUIT thread
jeffhaoa77f0f62012-12-05 17:19:31 -0800803 // dump event is pending (assuming SignalCatcher was resumed for
804 // just long enough to try to grab the thread-suspend lock).
Sebastien Hertzf272af42014-09-18 10:20:42 +0200805 VLOG(jdwp) << *self << " still suspended after undo "
806 << "(suspend count=" << self->GetSuspendCount() << ", "
807 << "debug suspend count=" << self->GetDebugSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -0800808 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700809 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700810 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700811 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800812
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800813 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700814}
815
Sebastien Hertz253fa552014-10-14 17:27:15 +0200816void ThreadList::ResumeAllForDebugger() {
817 Thread* self = Thread::Current();
818 Thread* debug_thread = Dbg::GetDebugThread();
Sebastien Hertz253fa552014-10-14 17:27:15 +0200819
820 VLOG(threads) << *self << " ResumeAllForDebugger starting...";
821
822 // Threads can't resume if we exclusively hold the mutator lock.
823 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
824
825 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800826 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Sebastien Hertz253fa552014-10-14 17:27:15 +0200827 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800828 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Sebastien Hertz253fa552014-10-14 17:27:15 +0200829 // Update global suspend all state for attaching threads.
830 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100831 if (debug_suspend_all_count_ > 0) {
Sebastien Hertz253fa552014-10-14 17:27:15 +0200832 --suspend_all_count_;
833 --debug_suspend_all_count_;
Sebastien Hertz253fa552014-10-14 17:27:15 +0200834 } else {
835 // We've been asked to resume all threads without being asked to
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100836 // suspend them all before. That may happen if a debugger tries
837 // to resume some suspended threads (with suspend count == 1)
838 // at once with a VirtualMachine.Resume command. Let's print a
839 // warning.
Sebastien Hertz253fa552014-10-14 17:27:15 +0200840 LOG(WARNING) << "Debugger attempted to resume all threads without "
841 << "having suspended them all before.";
842 }
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100843 // Decrement everybody's suspend count (except our own).
844 for (const auto& thread : list_) {
845 if (thread == self || thread == debug_thread) {
846 continue;
847 }
848 if (thread->GetDebugSuspendCount() == 0) {
849 // This thread may have been individually resumed with ThreadReference.Resume.
850 continue;
851 }
852 VLOG(threads) << "requesting thread resume: " << *thread;
853 thread->ModifySuspendCount(self, -1, true);
854 }
Sebastien Hertz253fa552014-10-14 17:27:15 +0200855 }
856 }
857
Sebastien Hertzf9d233d2015-01-09 14:51:41 +0100858 {
Sebastien Hertz253fa552014-10-14 17:27:15 +0200859 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
860 Thread::resume_cond_->Broadcast(self);
861 }
862
863 VLOG(threads) << *self << " ResumeAllForDebugger complete";
864}
865
Elliott Hughes234ab152011-10-26 14:02:26 -0700866void ThreadList::UndoDebuggerSuspensions() {
867 Thread* self = Thread::Current();
868
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800869 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700870
871 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700872 MutexLock mu(self, *Locks::thread_list_lock_);
873 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700874 // Update global suspend all state for attaching threads.
875 suspend_all_count_ -= debug_suspend_all_count_;
876 debug_suspend_all_count_ = 0;
877 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700878 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700879 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -0700880 continue;
881 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700882 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
Elliott Hughes234ab152011-10-26 14:02:26 -0700883 }
884 }
885
886 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700887 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700888 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -0700889 }
890
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800891 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -0700892}
893
Elliott Hughese52e49b2012-04-02 16:05:44 -0700894void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700895 Thread* self = Thread::Current();
896 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700897 bool all_threads_are_daemons;
898 do {
Ian Rogers120f1c72012-09-28 17:17:10 -0700899 {
900 // No more threads can be born after we start to shutdown.
901 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700902 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -0700903 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
904 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700905 all_threads_are_daemons = true;
Ian Rogers120f1c72012-09-28 17:17:10 -0700906 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700907 for (const auto& thread : list_) {
Anwar Ghuloum97543682013-06-14 12:58:16 -0700908 if (thread != self && !thread->IsDaemon()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700909 all_threads_are_daemons = false;
910 break;
911 }
912 }
913 if (!all_threads_are_daemons) {
914 // Wait for another thread to exit before re-checking.
Ian Rogersc604d732012-10-14 16:09:54 -0700915 thread_exit_cond_.Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700916 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700917 } while (!all_threads_are_daemons);
Elliott Hughes038a8062011-09-18 14:12:41 -0700918}
919
920void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700921 Thread* self = Thread::Current();
922 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700923 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -0700924 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700925 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700926 // This is only run after all non-daemon threads have exited, so the remainder should all be
927 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -0700928 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -0700929 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700930 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -0700931 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700932 }
933 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700934 // Give the threads a chance to suspend, complaining if they're slow.
935 bool have_complained = false;
936 for (int i = 0; i < 10; ++i) {
937 usleep(200 * 1000);
938 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700939 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700940 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700941 if (!have_complained) {
942 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
943 have_complained = true;
944 }
945 all_suspended = false;
946 }
947 }
948 if (all_suspended) {
949 return;
950 }
951 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700952 LOG(ERROR) << "suspend all daemons failed";
953}
954void ThreadList::Register(Thread* self) {
955 DCHECK_EQ(self, Thread::Current());
956
957 if (VLOG_IS_ON(threads)) {
958 std::ostringstream oss;
959 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
Ian Rogers5a9ba012014-05-19 13:28:52 -0700960 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700961 }
962
963 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
964 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -0700965 MutexLock mu(self, *Locks::thread_list_lock_);
966 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700967 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -0700968 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
969 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
970 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
971 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700972 }
Ian Rogers2966e132014-04-02 08:34:36 -0700973 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
974 self->ModifySuspendCount(self, +1, false);
Ian Rogers01ae5802012-09-28 16:14:01 -0700975 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700976 CHECK(!Contains(self));
977 list_.push_back(self);
978}
979
980void ThreadList::Unregister(Thread* self) {
981 DCHECK_EQ(self, Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700982 CHECK_NE(self->GetState(), kRunnable);
983 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700984
985 VLOG(threads) << "ThreadList::Unregister() " << *self;
986
987 // Any time-consuming destruction, plus anything that can call back into managed code or
988 // suspend and so on, must happen at this point, and not in ~Thread.
989 self->Destroy();
990
Jeff Haoe094b872014-10-14 13:12:01 -0700991 // If tracing, remember thread id and name before thread exits.
992 Trace::StoreExitingThreadInfo(self);
993
Ian Rogersdd7624d2014-03-14 17:43:00 -0700994 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800995 while (self != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800996 // Remove and delete the Thread* while holding the thread_list_lock_ and
997 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -0700998 // Note: deliberately not using MutexLock that could hold a stale self pointer.
999 Locks::thread_list_lock_->ExclusiveLock(self);
Ian Rogersa2af5c72014-09-15 15:17:07 -07001000 bool removed = true;
1001 if (!Contains(self)) {
1002 std::ostringstream os;
1003 DumpNativeStack(os, GetTid(), " native: ", nullptr);
1004 LOG(ERROR) << "Request to unregister unattached thread\n" << os.str();
1005 } else {
1006 Locks::thread_suspend_count_lock_->ExclusiveLock(self);
1007 if (!self->IsSuspended()) {
1008 list_.remove(self);
1009 } else {
1010 // We failed to remove the thread due to a suspend request, loop and try again.
1011 removed = false;
1012 }
1013 Locks::thread_suspend_count_lock_->ExclusiveUnlock(self);
Ian Rogers68d8b422014-07-17 11:09:10 -07001014 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001015 Locks::thread_list_lock_->ExclusiveUnlock(self);
1016 if (removed) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001017 delete self;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -08001018 self = nullptr;
Ian Rogerscfaa4552012-11-26 21:00:08 -08001019 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001020 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -08001021 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
1022 // temporarily have multiple threads with the same thread id. When this occurs, it causes
1023 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
1024 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001025
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001026 // Clear the TLS data, so that the underlying native thread is recognizably detached.
1027 // (It may wish to reattach later.)
1028 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");
1029
1030 // Signal that a thread just detached.
Ian Rogers81d425b2012-09-27 16:03:43 -07001031 MutexLock mu(NULL, *Locks::thread_list_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -07001032 thread_exit_cond_.Signal(NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001033}
1034
1035void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001036 for (const auto& thread : list_) {
1037 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001038 }
1039}
1040
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001041void ThreadList::VisitRoots(RootCallback* callback, void* arg) const {
Ian Rogers81d425b2012-09-27 16:03:43 -07001042 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001043 for (const auto& thread : list_) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001044 thread->VisitRoots(callback, arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001045 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001046}
1047
Ian Rogerscfaa4552012-11-26 21:00:08 -08001048uint32_t ThreadList::AllocThreadId(Thread* self) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001049 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -07001050 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
1051 if (!allocated_ids_[i]) {
1052 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001053 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -07001054 }
1055 }
1056 LOG(FATAL) << "Out of internal thread ids";
1057 return 0;
1058}
1059
Ian Rogerscfaa4552012-11-26 21:00:08 -08001060void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001061 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001062 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -07001063 DCHECK(allocated_ids_[id]) << id;
1064 allocated_ids_.reset(id);
1065}
1066
Elliott Hughes8daa0922011-09-11 13:46:25 -07001067} // namespace art