1 /*
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
19 #include <dirent.h>
20 #include <sys/types.h>
21 #include <unistd.h>
22
23 #include <map>
24 #include <sstream>
25 #include <tuple>
26 #include <vector>
27
28 #include "android-base/stringprintf.h"
29 #include "nativehelper/scoped_local_ref.h"
30 #include "nativehelper/scoped_utf_chars.h"
31 #include "unwindstack/AndroidUnwinder.h"
32
33 #include "art_field-inl.h"
34 #include "base/aborting.h"
35 #include "base/histogram-inl.h"
36 #include "base/mutex-inl.h"
37 #include "base/systrace.h"
38 #include "base/time_utils.h"
39 #include "base/timing_logger.h"
40 #include "debugger.h"
41 #include "gc/collector/concurrent_copying.h"
42 #include "gc/gc_pause_listener.h"
43 #include "gc/heap.h"
44 #include "gc/reference_processor.h"
45 #include "gc_root.h"
46 #include "jni/jni_internal.h"
47 #include "lock_word.h"
48 #include "mirror/string.h"
49 #include "monitor.h"
50 #include "native_stack_dump.h"
51 #include "obj_ptr-inl.h"
52 #include "scoped_thread_state_change-inl.h"
53 #include "thread.h"
54 #include "trace.h"
55 #include "well_known_classes.h"
56
57 #if ART_USE_FUTEXES
58 #include "linux/futex.h"
59 #include "sys/syscall.h"
60 #ifndef SYS_futex
61 #define SYS_futex __NR_futex
62 #endif
63 #endif // ART_USE_FUTEXES
64
65 namespace art {
66
67 using android::base::StringPrintf;
68
69 static constexpr uint64_t kLongThreadSuspendThreshold = MsToNs(5);
70 // Use 0 since we want to yield to prevent blocking for an unpredictable amount of time.
71 static constexpr useconds_t kThreadSuspendInitialSleepUs = 0;
72 static constexpr useconds_t kThreadSuspendMaxYieldUs = 3000;
73 static constexpr useconds_t kThreadSuspendMaxSleepUs = 5000;
74
75 // Whether we should try to dump the native stack of unattached threads. See commit ed8b723 for
76 // some history.
77 static constexpr bool kDumpUnattachedThreadNativeStackForSigQuit = true;
78
ThreadList(uint64_t thread_suspend_timeout_ns)79 ThreadList::ThreadList(uint64_t thread_suspend_timeout_ns)
80 : suspend_all_count_(0),
81 unregistering_count_(0),
82 suspend_all_historam_("suspend all histogram", 16, 64),
83 long_suspend_(false),
84 shut_down_(false),
85 thread_suspend_timeout_ns_(thread_suspend_timeout_ns),
86 empty_checkpoint_barrier_(new Barrier(0)) {
87 CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1, 0U)));
88 }
89
~ThreadList()90 ThreadList::~ThreadList() {
91 CHECK(shut_down_);
92 }
93
ShutDown()94 void ThreadList::ShutDown() {
95 ScopedTrace trace(__PRETTY_FUNCTION__);
96 // Detach the current thread if necessary. If we failed to start, there might not be any threads.
97 // We need to detach the current thread here in case there's another thread waiting to join with
98 // us.
99 bool contains = false;
100 Thread* self = Thread::Current();
101 {
102 MutexLock mu(self, *Locks::thread_list_lock_);
103 contains = Contains(self);
104 }
105 if (contains) {
106 Runtime::Current()->DetachCurrentThread();
107 }
108 WaitForOtherNonDaemonThreadsToExit();
109 // The only caller of this function, ~Runtime, has already disabled GC and
110 // ensured that the last GC is finished.
111 gc::Heap* const heap = Runtime::Current()->GetHeap();
112 CHECK(heap->IsGCDisabledForShutdown());
113
114 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
115 // Thread::Init.
116 SuspendAllDaemonThreadsForShutdown();
117
118 shut_down_ = true;
119 }
120
Contains(Thread * thread)121 bool ThreadList::Contains(Thread* thread) {
122 return find(list_.begin(), list_.end(), thread) != list_.end();
123 }
124
GetLockOwner()125 pid_t ThreadList::GetLockOwner() {
126 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
127 }
128
DumpNativeStacks(std::ostream & os)129 void ThreadList::DumpNativeStacks(std::ostream& os) {
130 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
131 unwindstack::AndroidLocalUnwinder unwinder;
132 for (const auto& thread : list_) {
133 os << "DUMPING THREAD " << thread->GetTid() << "\n";
134 DumpNativeStack(os, unwinder, thread->GetTid(), "\t");
135 os << "\n";
136 }
137 }
138
DumpForSigQuit(std::ostream & os)139 void ThreadList::DumpForSigQuit(std::ostream& os) {
140 {
141 ScopedObjectAccess soa(Thread::Current());
142 // Only print if we have samples.
143 if (suspend_all_historam_.SampleSize() > 0) {
144 Histogram<uint64_t>::CumulativeData data;
145 suspend_all_historam_.CreateHistogram(&data);
146 suspend_all_historam_.PrintConfidenceIntervals(os, 0.99, data); // Dump time to suspend.
147 }
148 }
149 bool dump_native_stack = Runtime::Current()->GetDumpNativeStackOnSigQuit();
150 Dump(os, dump_native_stack);
151 DumpUnattachedThreads(os, dump_native_stack && kDumpUnattachedThreadNativeStackForSigQuit);
152 }
153
DumpUnattachedThread(std::ostream & os,pid_t tid,bool dump_native_stack)154 static void DumpUnattachedThread(std::ostream& os, pid_t tid, bool dump_native_stack)
155 NO_THREAD_SAFETY_ANALYSIS {
156 // TODO: No thread safety analysis as DumpState with a null thread won't access fields, should
157 // refactor DumpState to avoid skipping analysis.
158 Thread::DumpState(os, nullptr, tid);
159 if (dump_native_stack) {
160 DumpNativeStack(os, tid, " native: ");
161 }
162 os << std::endl;
163 }
164
DumpUnattachedThreads(std::ostream & os,bool dump_native_stack)165 void ThreadList::DumpUnattachedThreads(std::ostream& os, bool dump_native_stack) {
166 DIR* d = opendir("/proc/self/task");
167 if (!d) {
168 return;
169 }
170
171 Thread* self = Thread::Current();
172 dirent* e;
173 while ((e = readdir(d)) != nullptr) {
174 char* end;
175 pid_t tid = strtol(e->d_name, &end, 10);
176 if (!*end) {
177 Thread* thread;
178 {
179 MutexLock mu(self, *Locks::thread_list_lock_);
180 thread = FindThreadByTid(tid);
181 }
182 if (thread == nullptr) {
183 DumpUnattachedThread(os, tid, dump_native_stack);
184 }
185 }
186 }
187 closedir(d);
188 }
189
190 // Dump checkpoint timeout in milliseconds. Larger amount on the target, since the device could be
191 // overloaded with ANR dumps.
192 static constexpr uint32_t kDumpWaitTimeout = kIsTargetBuild ? 100000 : 20000;
193
194 // A closure used by Thread::Dump.
195 class DumpCheckpoint final : public Closure {
196 public:
DumpCheckpoint(bool dump_native_stack)197 DumpCheckpoint(bool dump_native_stack)
198 : lock_("Dump checkpoint lock", kGenericBottomLock),
199 os_(),
200 // Avoid verifying count in case a thread doesn't end up passing through the barrier.
201 // This avoids a SIGABRT that would otherwise happen in the destructor.
202 barrier_(0, /*verify_count_on_shutdown=*/false),
203 unwinder_(std::vector<std::string>{}, std::vector<std::string> {"oat", "odex"}),
204 dump_native_stack_(dump_native_stack) {
205 }
206
Run(Thread * thread)207 void Run(Thread* thread) override {
208 // Note thread and self may not be equal if thread was already suspended at the point of the
209 // request.
210 Thread* self = Thread::Current();
211 CHECK(self != nullptr);
212 std::ostringstream local_os;
213 Thread::DumpOrder dump_order;
214 {
215 ScopedObjectAccess soa(self);
216 dump_order = thread->Dump(local_os, unwinder_, dump_native_stack_);
217 }
218 {
219 MutexLock mu(self, lock_);
220 // Sort, so that the most interesting threads for ANR are printed first (ANRs can be trimmed).
221 std::pair<Thread::DumpOrder, uint32_t> sort_key(dump_order, thread->GetThreadId());
222 os_.emplace(sort_key, std::move(local_os));
223 }
224 barrier_.Pass(self);
225 }
226
227 // Called at the end to print all the dumps in sequential prioritized order.
Dump(Thread * self,std::ostream & os)228 void Dump(Thread* self, std::ostream& os) {
229 MutexLock mu(self, lock_);
230 for (const auto& it : os_) {
231 os << it.second.str() << std::endl;
232 }
233 }
234
WaitForThreadsToRunThroughCheckpoint(size_t threads_running_checkpoint)235 void WaitForThreadsToRunThroughCheckpoint(size_t threads_running_checkpoint) {
236 Thread* self = Thread::Current();
237 ScopedThreadStateChange tsc(self, ThreadState::kWaitingForCheckPointsToRun);
238 bool timed_out = barrier_.Increment(self, threads_running_checkpoint, kDumpWaitTimeout);
239 if (timed_out) {
240 // Avoid a recursive abort.
241 LOG((kIsDebugBuild && (gAborting == 0)) ? ::android::base::FATAL : ::android::base::ERROR)
242 << "Unexpected time out during dump checkpoint.";
243 }
244 }
245
246 private:
247 // Storage for the per-thread dumps (guarded by lock since they are generated in parallel).
248 // Map is used to obtain sorted order. The key is unique, but use multimap just in case.
249 Mutex lock_;
250 std::multimap<std::pair<Thread::DumpOrder, uint32_t>, std::ostringstream> os_ GUARDED_BY(lock_);
251 // The barrier to be passed through and for the requestor to wait upon.
252 Barrier barrier_;
253 // A backtrace map, so that all threads use a shared info and don't reacquire/parse separately.
254 unwindstack::AndroidLocalUnwinder unwinder_;
255 // Whether we should dump the native stack.
256 const bool dump_native_stack_;
257 };
258
Dump(std::ostream & os,bool dump_native_stack)259 void ThreadList::Dump(std::ostream& os, bool dump_native_stack) {
260 Thread* self = Thread::Current();
261 {
262 MutexLock mu(self, *Locks::thread_list_lock_);
263 os << "DALVIK THREADS (" << list_.size() << "):\n";
264 }
265 if (self != nullptr) {
266 DumpCheckpoint checkpoint(dump_native_stack);
267 size_t threads_running_checkpoint;
268 {
269 // Use SOA to prevent deadlocks if multiple threads are calling Dump() at the same time.
270 ScopedObjectAccess soa(self);
271 threads_running_checkpoint = RunCheckpoint(&checkpoint);
272 }
273 if (threads_running_checkpoint != 0) {
274 checkpoint.WaitForThreadsToRunThroughCheckpoint(threads_running_checkpoint);
275 }
276 checkpoint.Dump(self, os);
277 } else {
278 DumpUnattachedThreads(os, dump_native_stack);
279 }
280 }
281
AssertThreadsAreSuspended(Thread * self,Thread * ignore1,Thread * ignore2)282 void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
283 MutexLock mu(self, *Locks::thread_list_lock_);
284 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
285 for (const auto& thread : list_) {
286 if (thread != ignore1 && thread != ignore2) {
287 CHECK(thread->IsSuspended())
288 << "\nUnsuspended thread: <<" << *thread << "\n"
289 << "self: <<" << *Thread::Current();
290 }
291 }
292 }
293
294 #if HAVE_TIMED_RWLOCK
295 // Attempt to rectify locks so that we dump thread list with required locks before exiting.
UnsafeLogFatalForThreadSuspendAllTimeout()296 NO_RETURN static void UnsafeLogFatalForThreadSuspendAllTimeout() {
297 // Increment gAborting before doing the thread list dump since we don't want any failures from
298 // AssertThreadSuspensionIsAllowable in cases where thread suspension is not allowed.
299 // See b/69044468.
300 ++gAborting;
301 Runtime* runtime = Runtime::Current();
302 std::ostringstream ss;
303 ss << "Thread suspend timeout\n";
304 Locks::mutator_lock_->Dump(ss);
305 ss << "\n";
306 runtime->GetThreadList()->Dump(ss);
307 --gAborting;
308 LOG(FATAL) << ss.str();
309 exit(0);
310 }
311 #endif
312
313 // Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
314 // individual thread requires polling. delay_us is the requested sleep wait. If delay_us is 0 then
315 // we use sched_yield instead of calling usleep.
316 // Although there is the possibility, here and elsewhere, that usleep could return -1 and
317 // errno = EINTR, there should be no problem if interrupted, so we do not check.
ThreadSuspendSleep(useconds_t delay_us)318 static void ThreadSuspendSleep(useconds_t delay_us) {
319 if (delay_us == 0) {
320 sched_yield();
321 } else {
322 usleep(delay_us);
323 }
324 }
325
RunCheckpoint(Closure * checkpoint_function,Closure * callback)326 size_t ThreadList::RunCheckpoint(Closure* checkpoint_function, Closure* callback) {
327 Thread* self = Thread::Current();
328 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
329 Locks::thread_list_lock_->AssertNotHeld(self);
330 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
331
332 std::vector<Thread*> suspended_count_modified_threads;
333 size_t count = 0;
334 {
335 // Call a checkpoint function for each thread, threads which are suspended get their checkpoint
336 // manually called.
337 MutexLock mu(self, *Locks::thread_list_lock_);
338 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
339 count = list_.size();
340 for (const auto& thread : list_) {
341 if (thread != self) {
342 bool requested_suspend = false;
343 while (true) {
344 if (thread->RequestCheckpoint(checkpoint_function)) {
345 // This thread will run its checkpoint some time in the near future.
346 if (requested_suspend) {
347 // The suspend request is now unnecessary.
348 bool updated =
349 thread->ModifySuspendCount(self, -1, nullptr, SuspendReason::kInternal);
350 DCHECK(updated);
351 requested_suspend = false;
352 }
353 break;
354 } else {
355 // The thread is probably suspended, try to make sure that it stays suspended.
356 if (thread->GetState() == ThreadState::kRunnable) {
357 // Spurious fail, try again.
358 continue;
359 }
360 if (!requested_suspend) {
361 bool updated =
362 thread->ModifySuspendCount(self, +1, nullptr, SuspendReason::kInternal);
363 DCHECK(updated);
364 requested_suspend = true;
365 if (thread->IsSuspended()) {
366 break;
367 }
368 // The thread raced us to become Runnable. Try to RequestCheckpoint() again.
369 } else {
370 // The thread previously raced our suspend request to become Runnable but
371 // since it is suspended again, it must honor that suspend request now.
372 DCHECK(thread->IsSuspended());
373 break;
374 }
375 }
376 }
377 if (requested_suspend) {
378 suspended_count_modified_threads.push_back(thread);
379 }
380 }
381 }
382 // Run the callback to be called inside this critical section.
383 if (callback != nullptr) {
384 callback->Run(self);
385 }
386 }
387
388 // Run the checkpoint on ourself while we wait for threads to suspend.
389 checkpoint_function->Run(self);
390
391 // Run the checkpoint on the suspended threads.
392 for (const auto& thread : suspended_count_modified_threads) {
393 // We know for sure that the thread is suspended at this point.
394 DCHECK(thread->IsSuspended());
395 checkpoint_function->Run(thread);
396 {
397 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
398 bool updated = thread->ModifySuspendCount(self, -1, nullptr, SuspendReason::kInternal);
399 DCHECK(updated);
400 }
401 }
402
403 {
404 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
405 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
406 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
407 Thread::resume_cond_->Broadcast(self);
408 }
409
410 return count;
411 }
412
RunEmptyCheckpoint()413 void ThreadList::RunEmptyCheckpoint() {
414 Thread* self = Thread::Current();
415 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
416 Locks::thread_list_lock_->AssertNotHeld(self);
417 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
418 std::vector<uint32_t> runnable_thread_ids;
419 size_t count = 0;
420 Barrier* barrier = empty_checkpoint_barrier_.get();
421 barrier->Init(self, 0);
422 {
423 MutexLock mu(self, *Locks::thread_list_lock_);
424 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
425 for (Thread* thread : list_) {
426 if (thread != self) {
427 while (true) {
428 if (thread->RequestEmptyCheckpoint()) {
429 // This thread will run an empty checkpoint (decrement the empty checkpoint barrier)
430 // some time in the near future.
431 ++count;
432 if (kIsDebugBuild) {
433 runnable_thread_ids.push_back(thread->GetThreadId());
434 }
435 break;
436 }
437 if (thread->GetState() != ThreadState::kRunnable) {
438 // It's seen suspended, we are done because it must not be in the middle of a mutator
439 // heap access.
440 break;
441 }
442 }
443 }
444 }
445 }
446
447 // Wake up the threads blocking for weak ref access so that they will respond to the empty
448 // checkpoint request. Otherwise we will hang as they are blocking in the kRunnable state.
449 Runtime::Current()->GetHeap()->GetReferenceProcessor()->BroadcastForSlowPath(self);
450 Runtime::Current()->BroadcastForNewSystemWeaks(/*broadcast_for_checkpoint=*/true);
451 {
452 ScopedThreadStateChange tsc(self, ThreadState::kWaitingForCheckPointsToRun);
453 uint64_t total_wait_time = 0;
454 bool first_iter = true;
455 while (true) {
456 // Wake up the runnable threads blocked on the mutexes that another thread, which is blocked
457 // on a weak ref access, holds (indirectly blocking for weak ref access through another thread
458 // and a mutex.) This needs to be done periodically because the thread may be preempted
459 // between the CheckEmptyCheckpointFromMutex call and the subsequent futex wait in
460 // Mutex::ExclusiveLock, etc. when the wakeup via WakeupToRespondToEmptyCheckpoint
461 // arrives. This could cause a *very rare* deadlock, if not repeated. Most of the cases are
462 // handled in the first iteration.
463 for (BaseMutex* mutex : Locks::expected_mutexes_on_weak_ref_access_) {
464 mutex->WakeupToRespondToEmptyCheckpoint();
465 }
466 static constexpr uint64_t kEmptyCheckpointPeriodicTimeoutMs = 100; // 100ms
467 static constexpr uint64_t kEmptyCheckpointTotalTimeoutMs = 600 * 1000; // 10 minutes.
468 size_t barrier_count = first_iter ? count : 0;
469 first_iter = false; // Don't add to the barrier count from the second iteration on.
470 bool timed_out = barrier->Increment(self, barrier_count, kEmptyCheckpointPeriodicTimeoutMs);
471 if (!timed_out) {
472 break; // Success
473 }
474 // This is a very rare case.
475 total_wait_time += kEmptyCheckpointPeriodicTimeoutMs;
476 if (kIsDebugBuild && total_wait_time > kEmptyCheckpointTotalTimeoutMs) {
477 std::ostringstream ss;
478 ss << "Empty checkpoint timeout\n";
479 ss << "Barrier count " << barrier->GetCount(self) << "\n";
480 ss << "Runnable thread IDs";
481 for (uint32_t tid : runnable_thread_ids) {
482 ss << " " << tid;
483 }
484 ss << "\n";
485 Locks::mutator_lock_->Dump(ss);
486 ss << "\n";
487 LOG(FATAL_WITHOUT_ABORT) << ss.str();
488 // Some threads in 'runnable_thread_ids' are probably stuck. Try to dump their stacks.
489 // Avoid using ThreadList::Dump() initially because it is likely to get stuck as well.
490 {
491 ScopedObjectAccess soa(self);
492 MutexLock mu1(self, *Locks::thread_list_lock_);
493 for (Thread* thread : GetList()) {
494 uint32_t tid = thread->GetThreadId();
495 bool is_in_runnable_thread_ids =
496 std::find(runnable_thread_ids.begin(), runnable_thread_ids.end(), tid) !=
497 runnable_thread_ids.end();
498 if (is_in_runnable_thread_ids &&
499 thread->ReadFlag(ThreadFlag::kEmptyCheckpointRequest)) {
500 // Found a runnable thread that hasn't responded to the empty checkpoint request.
501 // Assume it's stuck and safe to dump its stack.
502 thread->Dump(LOG_STREAM(FATAL_WITHOUT_ABORT),
503 /*dump_native_stack=*/ true,
504 /*force_dump_stack=*/ true);
505 }
506 }
507 }
508 LOG(FATAL_WITHOUT_ABORT)
509 << "Dumped runnable threads that haven't responded to empty checkpoint.";
510 // Now use ThreadList::Dump() to dump more threads, noting it may get stuck.
511 Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
512 LOG(FATAL) << "Dumped all threads.";
513 }
514 }
515 }
516 }
517
518 // A checkpoint/suspend-all hybrid to switch thread roots from
519 // from-space to to-space refs. Used to synchronize threads at a point
520 // to mark the initiation of marking while maintaining the to-space
521 // invariant.
FlipThreadRoots(Closure * thread_flip_visitor,Closure * flip_callback,gc::collector::GarbageCollector * collector,gc::GcPauseListener * pause_listener)522 size_t ThreadList::FlipThreadRoots(Closure* thread_flip_visitor,
523 Closure* flip_callback,
524 gc::collector::GarbageCollector* collector,
525 gc::GcPauseListener* pause_listener) {
526 TimingLogger::ScopedTiming split("ThreadListFlip", collector->GetTimings());
527 Thread* self = Thread::Current();
528 Locks::mutator_lock_->AssertNotHeld(self);
529 Locks::thread_list_lock_->AssertNotHeld(self);
530 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
531 CHECK_NE(self->GetState(), ThreadState::kRunnable);
532 size_t runnable_thread_count = 0;
533 std::vector<Thread*> other_threads;
534
535 collector->GetHeap()->ThreadFlipBegin(self); // Sync with JNI critical calls.
536
537 // ThreadFlipBegin happens before we suspend all the threads, so it does not
538 // count towards the pause.
539 const uint64_t suspend_start_time = NanoTime();
540 SuspendAllInternal(self, self, nullptr);
541 if (pause_listener != nullptr) {
542 pause_listener->StartPause();
543 }
544
545 // Run the flip callback for the collector.
546 Locks::mutator_lock_->ExclusiveLock(self);
547 suspend_all_historam_.AdjustAndAddValue(NanoTime() - suspend_start_time);
548 flip_callback->Run(self);
549 // Releasing mutator-lock *before* setting up flip function in the threads
550 // leaves a gap for another thread trying to suspend all threads. That thread
551 // gets to run with mutator-lock, thereby accessing the heap, without running
552 // its flip function. It's not a problem with CC as the gc-thread hasn't
553 // started marking yet and the from-space is accessible. By delaying releasing
554 // mutator-lock until after the flip function are running on all threads we
555 // fix that without increasing pause time, except for any thread that might be
556 // trying to suspend all. Even though the change works irrespective of the GC,
557 // it has been limited to userfaultfd GC to keep the change behind the flag.
558 //
559 // TODO: It's a temporary change as aosp/2377951 is going to clean-up at a
560 // broad scale, including not allowing concurrent suspend-all.
561
562 // Resume runnable threads.
563 {
564 TimingLogger::ScopedTiming split2("ResumeRunnableThreads", collector->GetTimings());
565 MutexLock mu(self, *Locks::thread_list_lock_);
566 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
567 --suspend_all_count_;
568 for (Thread* thread : list_) {
569 // Set the flip function for all threads because once we start resuming any threads,
570 // they may need to run the flip function on behalf of other threads, even this one.
571 thread->SetFlipFunction(thread_flip_visitor);
572 if (thread == self) {
573 continue;
574 }
575 // Resume early the threads that were runnable but are suspended just for this thread flip or
576 // about to transition from non-runnable (eg. kNative at the SOA entry in a JNI function) to
577 // runnable (both cases waiting inside Thread::TransitionFromSuspendedToRunnable), or waiting
578 // for the thread flip to end at the JNI critical section entry (kWaitingForGcThreadFlip),
579 ThreadState state = thread->GetState();
580 if ((state == ThreadState::kWaitingForGcThreadFlip || thread->IsTransitioningToRunnable()) &&
581 thread->GetSuspendCount() == 1) {
582 // The thread will resume right after the broadcast.
583 bool updated = thread->ModifySuspendCount(self, -1, nullptr, SuspendReason::kInternal);
584 DCHECK(updated);
585 ++runnable_thread_count;
586 } else {
587 other_threads.push_back(thread);
588 }
589 }
590 Thread::resume_cond_->Broadcast(self);
591 }
592
593 collector->RegisterPause(NanoTime() - suspend_start_time);
594 if (pause_listener != nullptr) {
595 pause_listener->EndPause();
596 }
597 collector->GetHeap()->ThreadFlipEnd(self);
598
599 // Try to run the closure on the other threads.
600 {
601 TimingLogger::ScopedTiming split3("FlipOtherThreads", collector->GetTimings());
602 for (Thread* thread : other_threads) {
603 thread->EnsureFlipFunctionStarted(self);
604 DCHECK(!thread->ReadFlag(ThreadFlag::kPendingFlipFunction));
605 }
606 // Try to run the flip function for self.
607 self->EnsureFlipFunctionStarted(self);
608 DCHECK(!self->ReadFlag(ThreadFlag::kPendingFlipFunction));
609 }
610
611 Locks::mutator_lock_->ExclusiveUnlock(self);
612
613 // Resume other threads.
614 {
615 TimingLogger::ScopedTiming split4("ResumeOtherThreads", collector->GetTimings());
616 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
617 for (const auto& thread : other_threads) {
618 bool updated = thread->ModifySuspendCount(self, -1, nullptr, SuspendReason::kInternal);
619 DCHECK(updated);
620 }
621 Thread::resume_cond_->Broadcast(self);
622 }
623
624 return runnable_thread_count + other_threads.size() + 1; // +1 for self.
625 }
626
SuspendAll(const char * cause,bool long_suspend)627 void ThreadList::SuspendAll(const char* cause, bool long_suspend) {
628 Thread* self = Thread::Current();
629
630 if (self != nullptr) {
631 VLOG(threads) << *self << " SuspendAll for " << cause << " starting...";
632 } else {
633 VLOG(threads) << "Thread[null] SuspendAll for " << cause << " starting...";
634 }
635 {
636 ScopedTrace trace("Suspending mutator threads");
637 const uint64_t start_time = NanoTime();
638
639 SuspendAllInternal(self, self);
640 // All threads are known to have suspended (but a thread may still own the mutator lock)
641 // Make sure this thread grabs exclusive access to the mutator lock and its protected data.
642 #if HAVE_TIMED_RWLOCK
643 while (true) {
644 if (Locks::mutator_lock_->ExclusiveLockWithTimeout(self,
645 NsToMs(thread_suspend_timeout_ns_),
646 0)) {
647 break;
648 } else if (!long_suspend_) {
649 // Reading long_suspend without the mutator lock is slightly racy, in some rare cases, this
650 // could result in a thread suspend timeout.
651 // Timeout if we wait more than thread_suspend_timeout_ns_ nanoseconds.
652 UnsafeLogFatalForThreadSuspendAllTimeout();
653 }
654 }
655 #else
656 Locks::mutator_lock_->ExclusiveLock(self);
657 #endif
658
659 long_suspend_ = long_suspend;
660
661 const uint64_t end_time = NanoTime();
662 const uint64_t suspend_time = end_time - start_time;
663 suspend_all_historam_.AdjustAndAddValue(suspend_time);
664 if (suspend_time > kLongThreadSuspendThreshold) {
665 LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(suspend_time);
666 }
667
668 if (kDebugLocking) {
669 // Debug check that all threads are suspended.
670 AssertThreadsAreSuspended(self, self);
671 }
672 }
673 ATraceBegin((std::string("Mutator threads suspended for ") + cause).c_str());
674
675 if (self != nullptr) {
676 VLOG(threads) << *self << " SuspendAll complete";
677 } else {
678 VLOG(threads) << "Thread[null] SuspendAll complete";
679 }
680 }
681
682 // Ensures all threads running Java suspend and that those not running Java don't start.
SuspendAllInternal(Thread * self,Thread * ignore1,Thread * ignore2,SuspendReason reason)683 void ThreadList::SuspendAllInternal(Thread* self,
684 Thread* ignore1,
685 Thread* ignore2,
686 SuspendReason reason) {
687 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
688 Locks::thread_list_lock_->AssertNotHeld(self);
689 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
690 if (kDebugLocking && self != nullptr) {
691 CHECK_NE(self->GetState(), ThreadState::kRunnable);
692 }
693
694 // First request that all threads suspend, then wait for them to suspend before
695 // returning. This suspension scheme also relies on other behaviour:
696 // 1. Threads cannot be deleted while they are suspended or have a suspend-
697 // request flag set - (see Unregister() below).
698 // 2. When threads are created, they are created in a suspended state (actually
699 // kNative) and will never begin executing Java code without first checking
700 // the suspend-request flag.
701
702 // The atomic counter for number of threads that need to pass the barrier.
703 AtomicInteger pending_threads;
704 uint32_t num_ignored = 0;
705 if (ignore1 != nullptr) {
706 ++num_ignored;
707 }
708 if (ignore2 != nullptr && ignore1 != ignore2) {
709 ++num_ignored;
710 }
711 {
712 MutexLock mu(self, *Locks::thread_list_lock_);
713 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
714 // Update global suspend all state for attaching threads.
715 ++suspend_all_count_;
716 pending_threads.store(list_.size() - num_ignored, std::memory_order_relaxed);
717 // Increment everybody's suspend count (except those that should be ignored).
718 for (const auto& thread : list_) {
719 if (thread == ignore1 || thread == ignore2) {
720 continue;
721 }
722 VLOG(threads) << "requesting thread suspend: " << *thread;
723 bool updated = thread->ModifySuspendCount(self, +1, &pending_threads, reason);
724 DCHECK(updated);
725
726 // Must install the pending_threads counter first, then check thread->IsSuspend() and clear
727 // the counter. Otherwise there's a race with Thread::TransitionFromRunnableToSuspended()
728 // that can lead a thread to miss a call to PassActiveSuspendBarriers().
729 if (thread->IsSuspended()) {
730 // Only clear the counter for the current thread.
731 thread->ClearSuspendBarrier(&pending_threads);
732 pending_threads.fetch_sub(1, std::memory_order_seq_cst);
733 }
734 }
735 }
736
737 // Wait for the barrier to be passed by all runnable threads. This wait
738 // is done with a timeout so that we can detect problems.
739 #if ART_USE_FUTEXES
740 timespec wait_timeout;
741 InitTimeSpec(false, CLOCK_MONOTONIC, NsToMs(thread_suspend_timeout_ns_), 0, &wait_timeout);
742 #endif
743 const uint64_t start_time = NanoTime();
744 while (true) {
745 int32_t cur_val = pending_threads.load(std::memory_order_relaxed);
746 if (LIKELY(cur_val > 0)) {
747 #if ART_USE_FUTEXES
748 if (futex(pending_threads.Address(), FUTEX_WAIT_PRIVATE, cur_val, &wait_timeout, nullptr, 0)
749 != 0) {
750 if ((errno == EAGAIN) || (errno == EINTR)) {
751 // EAGAIN and EINTR both indicate a spurious failure, try again from the beginning.
752 continue;
753 }
754 if (errno == ETIMEDOUT) {
755 const uint64_t wait_time = NanoTime() - start_time;
756 MutexLock mu(self, *Locks::thread_list_lock_);
757 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
758 std::ostringstream oss;
759 for (const auto& thread : list_) {
760 if (thread == ignore1 || thread == ignore2) {
761 continue;
762 }
763 if (!thread->IsSuspended()) {
764 oss << std::endl << "Thread not suspended: " << *thread;
765 }
766 }
767 LOG(kIsDebugBuild ? ::android::base::FATAL : ::android::base::ERROR)
768 << "Timed out waiting for threads to suspend, waited for "
769 << PrettyDuration(wait_time)
770 << oss.str();
771 } else {
772 PLOG(FATAL) << "futex wait failed for SuspendAllInternal()";
773 }
774 } // else re-check pending_threads in the next iteration (this may be a spurious wake-up).
775 #else
776 // Spin wait. This is likely to be slow, but on most architecture ART_USE_FUTEXES is set.
777 UNUSED(start_time);
778 #endif
779 } else {
780 CHECK_EQ(cur_val, 0);
781 break;
782 }
783 }
784 }
785
ResumeAll()786 void ThreadList::ResumeAll() {
787 Thread* self = Thread::Current();
788
789 if (self != nullptr) {
790 VLOG(threads) << *self << " ResumeAll starting";
791 } else {
792 VLOG(threads) << "Thread[null] ResumeAll starting";
793 }
794
795 ATraceEnd();
796
797 ScopedTrace trace("Resuming mutator threads");
798
799 if (kDebugLocking) {
800 // Debug check that all threads are suspended.
801 AssertThreadsAreSuspended(self, self);
802 }
803
804 long_suspend_ = false;
805
806 Locks::mutator_lock_->ExclusiveUnlock(self);
807 {
808 MutexLock mu(self, *Locks::thread_list_lock_);
809 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
810 // Update global suspend all state for attaching threads.
811 --suspend_all_count_;
812 // Decrement the suspend counts for all threads.
813 for (const auto& thread : list_) {
814 if (thread == self) {
815 continue;
816 }
817 bool updated = thread->ModifySuspendCount(self, -1, nullptr, SuspendReason::kInternal);
818 DCHECK(updated);
819 }
820
821 // Broadcast a notification to all suspended threads, some or all of
822 // which may choose to wake up. No need to wait for them.
823 if (self != nullptr) {
824 VLOG(threads) << *self << " ResumeAll waking others";
825 } else {
826 VLOG(threads) << "Thread[null] ResumeAll waking others";
827 }
828 Thread::resume_cond_->Broadcast(self);
829 }
830
831 if (self != nullptr) {
832 VLOG(threads) << *self << " ResumeAll complete";
833 } else {
834 VLOG(threads) << "Thread[null] ResumeAll complete";
835 }
836 }
837
Resume(Thread * thread,SuspendReason reason)838 bool ThreadList::Resume(Thread* thread, SuspendReason reason) {
839 // This assumes there was an ATraceBegin when we suspended the thread.
840 ATraceEnd();
841
842 Thread* self = Thread::Current();
843 DCHECK_NE(thread, self);
844 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..." << reason;
845
846 {
847 // To check Contains.
848 MutexLock mu(self, *Locks::thread_list_lock_);
849 // To check IsSuspended.
850 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
851 if (UNLIKELY(!thread->IsSuspended())) {
852 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
853 << ") thread not suspended";
854 return false;
855 }
856 if (!Contains(thread)) {
857 // We only expect threads within the thread-list to have been suspended otherwise we can't
858 // stop such threads from delete-ing themselves.
859 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
860 << ") thread not within thread list";
861 return false;
862 }
863 if (UNLIKELY(!thread->ModifySuspendCount(self, -1, nullptr, reason))) {
864 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
865 << ") could not modify suspend count.";
866 return false;
867 }
868 }
869
870 {
871 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
872 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
873 Thread::resume_cond_->Broadcast(self);
874 }
875
876 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
877 return true;
878 }
879
ThreadSuspendByPeerWarning(ScopedObjectAccess & soa,LogSeverity severity,const char * message,jobject peer)880 static void ThreadSuspendByPeerWarning(ScopedObjectAccess& soa,
881 LogSeverity severity,
882 const char* message,
883 jobject peer) REQUIRES_SHARED(Locks::mutator_lock_) {
884 ObjPtr<mirror::Object> name =
885 WellKnownClasses::java_lang_Thread_name->GetObject(soa.Decode<mirror::Object>(peer));
886 if (name == nullptr) {
887 LOG(severity) << message << ": " << peer;
888 } else {
889 LOG(severity) << message << ": " << peer << ":" << name->AsString()->ToModifiedUtf8();
890 }
891 }
892
SuspendThreadByPeer(jobject peer,SuspendReason reason,bool * timed_out)893 Thread* ThreadList::SuspendThreadByPeer(jobject peer,
894 SuspendReason reason,
895 bool* timed_out) {
896 bool request_suspension = true;
897 const uint64_t start_time = NanoTime();
898 int self_suspend_count = 0;
899 useconds_t sleep_us = kThreadSuspendInitialSleepUs;
900 *timed_out = false;
901 Thread* const self = Thread::Current();
902 Thread* suspended_thread = nullptr;
903 VLOG(threads) << "SuspendThreadByPeer starting";
904 while (true) {
905 Thread* thread;
906 {
907 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
908 // is requesting another suspend, to avoid deadlock, by requiring this function be called
909 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
910 // than request thread suspension, to avoid potential cycles in threads requesting each other
911 // suspend.
912 ScopedObjectAccess soa(self);
913 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
914 thread = Thread::FromManagedThread(soa, peer);
915 if (thread == nullptr) {
916 if (suspended_thread != nullptr) {
917 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
918 // If we incremented the suspend count but the thread reset its peer, we need to
919 // re-decrement it since it is shutting down and may deadlock the runtime in
920 // ThreadList::WaitForOtherNonDaemonThreadsToExit.
921 bool updated = suspended_thread->ModifySuspendCount(soa.Self(),
922 -1,
923 nullptr,
924 reason);
925 DCHECK(updated);
926 }
927 ThreadSuspendByPeerWarning(soa,
928 ::android::base::WARNING,
929 "No such thread for suspend",
930 peer);
931 return nullptr;
932 }
933 if (!Contains(thread)) {
934 CHECK(suspended_thread == nullptr);
935 VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
936 << reinterpret_cast<void*>(thread);
937 return nullptr;
938 }
939 VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
940 {
941 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
942 if (request_suspension) {
943 if (self->GetSuspendCount() > 0) {
944 // We hold the suspend count lock but another thread is trying to suspend us. Its not
945 // safe to try to suspend another thread in case we get a cycle. Start the loop again
946 // which will allow this thread to be suspended.
947 ++self_suspend_count;
948 continue;
949 }
950 CHECK(suspended_thread == nullptr);
951 suspended_thread = thread;
952 bool updated = suspended_thread->ModifySuspendCount(self, +1, nullptr, reason);
953 DCHECK(updated);
954 request_suspension = false;
955 } else {
956 // If the caller isn't requesting suspension, a suspension should have already occurred.
957 CHECK_GT(thread->GetSuspendCount(), 0);
958 }
959 // IsSuspended on the current thread will fail as the current thread is changed into
960 // Runnable above. As the suspend count is now raised if this is the current thread
961 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
962 // to just explicitly handle the current thread in the callers to this code.
963 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
964 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
965 // count, or else we've waited and it has self suspended) or is the current thread, we're
966 // done.
967 if (thread->IsSuspended()) {
968 VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
969 if (ATraceEnabled()) {
970 std::string name;
971 thread->GetThreadName(name);
972 ATraceBegin(StringPrintf("SuspendThreadByPeer suspended %s for peer=%p", name.c_str(),
973 peer).c_str());
974 }
975 return thread;
976 }
977 const uint64_t total_delay = NanoTime() - start_time;
978 if (total_delay >= thread_suspend_timeout_ns_) {
979 if (suspended_thread == nullptr) {
980 ThreadSuspendByPeerWarning(soa,
981 ::android::base::FATAL,
982 "Failed to issue suspend request",
983 peer);
984 } else {
985 CHECK_EQ(suspended_thread, thread);
986 LOG(WARNING) << "Suspended thread state_and_flags: "
987 << suspended_thread->StateAndFlagsAsHexString()
988 << ", self_suspend_count = " << self_suspend_count;
989 // Explicitly release thread_suspend_count_lock_; we haven't held it for long, so
990 // seeing threads blocked on it is not informative.
991 Locks::thread_suspend_count_lock_->Unlock(self);
992 ThreadSuspendByPeerWarning(soa,
993 ::android::base::FATAL,
994 "Thread suspension timed out",
995 peer);
996 }
997 UNREACHABLE();
998 } else if (sleep_us == 0 &&
999 total_delay > static_cast<uint64_t>(kThreadSuspendMaxYieldUs) * 1000) {
1000 // We have spun for kThreadSuspendMaxYieldUs time, switch to sleeps to prevent
1001 // excessive CPU usage.
1002 sleep_us = kThreadSuspendMaxYieldUs / 2;
1003 }
1004 }
1005 // Release locks and come out of runnable state.
1006 }
1007 VLOG(threads) << "SuspendThreadByPeer waiting to allow thread chance to suspend";
1008 ThreadSuspendSleep(sleep_us);
1009 // This may stay at 0 if sleep_us == 0, but this is WAI since we want to avoid using usleep at
1010 // all if possible. This shouldn't be an issue since time to suspend should always be small.
1011 sleep_us = std::min(sleep_us * 2, kThreadSuspendMaxSleepUs);
1012 }
1013 }
1014
ThreadSuspendByThreadIdWarning(LogSeverity severity,const char * message,uint32_t thread_id)1015 static void ThreadSuspendByThreadIdWarning(LogSeverity severity,
1016 const char* message,
1017 uint32_t thread_id) {
1018 LOG(severity) << StringPrintf("%s: %d", message, thread_id);
1019 }
1020
SuspendThreadByThreadId(uint32_t thread_id,SuspendReason reason,bool * timed_out)1021 Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id,
1022 SuspendReason reason,
1023 bool* timed_out) {
1024 const uint64_t start_time = NanoTime();
1025 useconds_t sleep_us = kThreadSuspendInitialSleepUs;
1026 *timed_out = false;
1027 Thread* suspended_thread = nullptr;
1028 Thread* const self = Thread::Current();
1029 CHECK_NE(thread_id, kInvalidThreadId);
1030 VLOG(threads) << "SuspendThreadByThreadId starting";
1031 while (true) {
1032 {
1033 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
1034 // is requesting another suspend, to avoid deadlock, by requiring this function be called
1035 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
1036 // than request thread suspension, to avoid potential cycles in threads requesting each other
1037 // suspend.
1038 ScopedObjectAccess soa(self);
1039 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
1040 Thread* thread = nullptr;
1041 for (const auto& it : list_) {
1042 if (it->GetThreadId() == thread_id) {
1043 thread = it;
1044 break;
1045 }
1046 }
1047 if (thread == nullptr) {
1048 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
1049 << " no longer in thread list";
1050 // There's a race in inflating a lock and the owner giving up ownership and then dying.
1051 ThreadSuspendByThreadIdWarning(::android::base::WARNING,
1052 "No such thread id for suspend",
1053 thread_id);
1054 return nullptr;
1055 }
1056 VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
1057 DCHECK(Contains(thread));
1058 {
1059 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
1060 if (suspended_thread == nullptr) {
1061 if (self->GetSuspendCount() > 0) {
1062 // We hold the suspend count lock but another thread is trying to suspend us. Its not
1063 // safe to try to suspend another thread in case we get a cycle. Start the loop again
1064 // which will allow this thread to be suspended.
1065 continue;
1066 }
1067 bool updated = thread->ModifySuspendCount(self, +1, nullptr, reason);
1068 DCHECK(updated);
1069 suspended_thread = thread;
1070 } else {
1071 CHECK_EQ(suspended_thread, thread);
1072 // If the caller isn't requesting suspension, a suspension should have already occurred.
1073 CHECK_GT(thread->GetSuspendCount(), 0);
1074 }
1075 // IsSuspended on the current thread will fail as the current thread is changed into
1076 // Runnable above. As the suspend count is now raised if this is the current thread
1077 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
1078 // to just explicitly handle the current thread in the callers to this code.
1079 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
1080 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
1081 // count, or else we've waited and it has self suspended) or is the current thread, we're
1082 // done.
1083 if (thread->IsSuspended()) {
1084 if (ATraceEnabled()) {
1085 std::string name;
1086 thread->GetThreadName(name);
1087 ATraceBegin(StringPrintf("SuspendThreadByThreadId suspended %s id=%d",
1088 name.c_str(), thread_id).c_str());
1089 }
1090 VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
1091 return thread;
1092 }
1093 const uint64_t total_delay = NanoTime() - start_time;
1094 if (total_delay >= thread_suspend_timeout_ns_) {
1095 ThreadSuspendByThreadIdWarning(::android::base::WARNING,
1096 "Thread suspension timed out",
1097 thread_id);
1098 if (suspended_thread != nullptr) {
1099 bool updated = thread->ModifySuspendCount(soa.Self(), -1, nullptr, reason);
1100 DCHECK(updated);
1101 }
1102 *timed_out = true;
1103 return nullptr;
1104 } else if (sleep_us == 0 &&
1105 total_delay > static_cast<uint64_t>(kThreadSuspendMaxYieldUs) * 1000) {
1106 // We have spun for kThreadSuspendMaxYieldUs time, switch to sleeps to prevent
1107 // excessive CPU usage.
1108 sleep_us = kThreadSuspendMaxYieldUs / 2;
1109 }
1110 }
1111 // Release locks and come out of runnable state.
1112 }
1113 VLOG(threads) << "SuspendThreadByThreadId waiting to allow thread chance to suspend";
1114 ThreadSuspendSleep(sleep_us);
1115 sleep_us = std::min(sleep_us * 2, kThreadSuspendMaxSleepUs);
1116 }
1117 }
1118
FindThreadByThreadId(uint32_t thread_id)1119 Thread* ThreadList::FindThreadByThreadId(uint32_t thread_id) {
1120 for (const auto& thread : list_) {
1121 if (thread->GetThreadId() == thread_id) {
1122 return thread;
1123 }
1124 }
1125 return nullptr;
1126 }
1127
FindThreadByTid(int tid)1128 Thread* ThreadList::FindThreadByTid(int tid) {
1129 for (const auto& thread : list_) {
1130 if (thread->GetTid() == tid) {
1131 return thread;
1132 }
1133 }
1134 return nullptr;
1135 }
1136
WaitForOtherNonDaemonThreadsToExit(bool check_no_birth)1137 void ThreadList::WaitForOtherNonDaemonThreadsToExit(bool check_no_birth) {
1138 ScopedTrace trace(__PRETTY_FUNCTION__);
1139 Thread* self = Thread::Current();
1140 Locks::mutator_lock_->AssertNotHeld(self);
1141 while (true) {
1142 Locks::runtime_shutdown_lock_->Lock(self);
1143 if (check_no_birth) {
1144 // No more threads can be born after we start to shutdown.
1145 CHECK(Runtime::Current()->IsShuttingDownLocked());
1146 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
1147 } else {
1148 if (Runtime::Current()->NumberOfThreadsBeingBorn() != 0U) {
1149 // Awkward. Shutdown_cond_ is private, but the only live thread may not be registered yet.
1150 // Fortunately, this is used mostly for testing, and not performance-critical.
1151 Locks::runtime_shutdown_lock_->Unlock(self);
1152 usleep(1000);
1153 continue;
1154 }
1155 }
1156 MutexLock mu(self, *Locks::thread_list_lock_);
1157 Locks::runtime_shutdown_lock_->Unlock(self);
1158 // Also wait for any threads that are unregistering to finish. This is required so that no
1159 // threads access the thread list after it is deleted. TODO: This may not work for user daemon
1160 // threads since they could unregister at the wrong time.
1161 bool done = unregistering_count_ == 0;
1162 if (done) {
1163 for (const auto& thread : list_) {
1164 if (thread != self && !thread->IsDaemon()) {
1165 done = false;
1166 break;
1167 }
1168 }
1169 }
1170 if (done) {
1171 break;
1172 }
1173 // Wait for another thread to exit before re-checking.
1174 Locks::thread_exit_cond_->Wait(self);
1175 }
1176 }
1177
SuspendAllDaemonThreadsForShutdown()1178 void ThreadList::SuspendAllDaemonThreadsForShutdown() {
1179 ScopedTrace trace(__PRETTY_FUNCTION__);
1180 Thread* self = Thread::Current();
1181 size_t daemons_left = 0;
1182 {
1183 // Tell all the daemons it's time to suspend.
1184 MutexLock mu(self, *Locks::thread_list_lock_);
1185 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
1186 for (const auto& thread : list_) {
1187 // This is only run after all non-daemon threads have exited, so the remainder should all be
1188 // daemons.
1189 CHECK(thread->IsDaemon()) << *thread;
1190 if (thread != self) {
1191 bool updated = thread->ModifySuspendCount(self, +1, nullptr, SuspendReason::kInternal);
1192 DCHECK(updated);
1193 ++daemons_left;
1194 }
1195 // We are shutting down the runtime, set the JNI functions of all the JNIEnvs to be
1196 // the sleep forever one.
1197 thread->GetJniEnv()->SetFunctionsToRuntimeShutdownFunctions();
1198 }
1199 }
1200 if (daemons_left == 0) {
1201 // No threads left; safe to shut down.
1202 return;
1203 }
1204 // There is not a clean way to shut down if we have daemons left. We have no mechanism for
1205 // killing them and reclaiming thread stacks. We also have no mechanism for waiting until they
1206 // have truly finished touching the memory we are about to deallocate. We do the best we can with
1207 // timeouts.
1208 //
1209 // If we have any daemons left, wait until they are (a) suspended and (b) they are not stuck
1210 // in a place where they are about to access runtime state and are not in a runnable state.
1211 // We attempt to do the latter by just waiting long enough for things to
1212 // quiesce. Examples: Monitor code or waking up from a condition variable.
1213 //
1214 // Give the threads a chance to suspend, complaining if they're slow. (a)
1215 bool have_complained = false;
1216 static constexpr size_t kTimeoutMicroseconds = 2000 * 1000;
1217 static constexpr size_t kSleepMicroseconds = 1000;
1218 bool all_suspended = false;
1219 for (size_t i = 0; !all_suspended && i < kTimeoutMicroseconds / kSleepMicroseconds; ++i) {
1220 bool found_running = false;
1221 {
1222 MutexLock mu(self, *Locks::thread_list_lock_);
1223 for (const auto& thread : list_) {
1224 if (thread != self && thread->GetState() == ThreadState::kRunnable) {
1225 if (!have_complained) {
1226 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
1227 have_complained = true;
1228 }
1229 found_running = true;
1230 }
1231 }
1232 }
1233 if (found_running) {
1234 // Sleep briefly before checking again. Max total sleep time is kTimeoutMicroseconds.
1235 usleep(kSleepMicroseconds);
1236 } else {
1237 all_suspended = true;
1238 }
1239 }
1240 if (!all_suspended) {
1241 // We can get here if a daemon thread executed a fastnative native call, so that it
1242 // remained in runnable state, and then made a JNI call after we called
1243 // SetFunctionsToRuntimeShutdownFunctions(), causing it to permanently stay in a harmless
1244 // but runnable state. See b/147804269 .
1245 LOG(WARNING) << "timed out suspending all daemon threads";
1246 }
1247 // Assume all threads are either suspended or somehow wedged.
1248 // Wait again for all the now "suspended" threads to actually quiesce. (b)
1249 static constexpr size_t kDaemonSleepTime = 400'000;
1250 usleep(kDaemonSleepTime);
1251 std::list<Thread*> list_copy;
1252 {
1253 MutexLock mu(self, *Locks::thread_list_lock_);
1254 // Half-way through the wait, set the "runtime deleted" flag, causing any newly awoken
1255 // threads to immediately go back to sleep without touching memory. This prevents us from
1256 // touching deallocated memory, but it also prevents mutexes from getting released. Thus we
1257 // only do this once we're reasonably sure that no system mutexes are still held.
1258 for (const auto& thread : list_) {
1259 DCHECK(thread == self || !all_suspended || thread->GetState() != ThreadState::kRunnable);
1260 // In the !all_suspended case, the target is probably sleeping.
1261 thread->GetJniEnv()->SetRuntimeDeleted();
1262 // Possibly contended Mutex acquisitions are unsafe after this.
1263 // Releasing thread_list_lock_ is OK, since it can't block.
1264 }
1265 }
1266 // Finally wait for any threads woken before we set the "runtime deleted" flags to finish
1267 // touching memory.
1268 usleep(kDaemonSleepTime);
1269 #if defined(__has_feature)
1270 #if __has_feature(address_sanitizer) || __has_feature(hwaddress_sanitizer)
1271 // Sleep a bit longer with -fsanitize=address, since everything is slower.
1272 usleep(2 * kDaemonSleepTime);
1273 #endif
1274 #endif
1275 // At this point no threads should be touching our data structures anymore.
1276 }
1277
Register(Thread * self)1278 void ThreadList::Register(Thread* self) {
1279 DCHECK_EQ(self, Thread::Current());
1280 CHECK(!shut_down_);
1281
1282 if (VLOG_IS_ON(threads)) {
1283 std::ostringstream oss;
1284 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
1285 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
1286 }
1287
1288 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
1289 // SuspendAll requests.
1290 MutexLock mu(self, *Locks::thread_list_lock_);
1291 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
1292 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
1293 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
1294 for (int delta = suspend_all_count_; delta > 0; delta--) {
1295 bool updated = self->ModifySuspendCount(self, +1, nullptr, SuspendReason::kInternal);
1296 DCHECK(updated);
1297 }
1298 CHECK(!Contains(self));
1299 list_.push_back(self);
1300 if (gUseReadBarrier) {
1301 gc::collector::ConcurrentCopying* const cc =
1302 Runtime::Current()->GetHeap()->ConcurrentCopyingCollector();
1303 // Initialize according to the state of the CC collector.
1304 self->SetIsGcMarkingAndUpdateEntrypoints(cc->IsMarking());
1305 if (cc->IsUsingReadBarrierEntrypoints()) {
1306 self->SetReadBarrierEntrypoints();
1307 }
1308 self->SetWeakRefAccessEnabled(cc->IsWeakRefAccessEnabled());
1309 }
1310 }
1311
Unregister(Thread * self,bool should_run_callbacks)1312 void ThreadList::Unregister(Thread* self, bool should_run_callbacks) {
1313 DCHECK_EQ(self, Thread::Current());
1314 CHECK_NE(self->GetState(), ThreadState::kRunnable);
1315 Locks::mutator_lock_->AssertNotHeld(self);
1316 if (self->tls32_.disable_thread_flip_count != 0) {
1317 LOG(FATAL) << "Incomplete PrimitiveArrayCritical section at exit: " << *self << "count = "
1318 << self->tls32_.disable_thread_flip_count;
1319 }
1320
1321 VLOG(threads) << "ThreadList::Unregister() " << *self;
1322
1323 {
1324 MutexLock mu(self, *Locks::thread_list_lock_);
1325 ++unregistering_count_;
1326 }
1327
1328 // Any time-consuming destruction, plus anything that can call back into managed code or
1329 // suspend and so on, must happen at this point, and not in ~Thread. The self->Destroy is what
1330 // causes the threads to join. It is important to do this after incrementing unregistering_count_
1331 // since we want the runtime to wait for the daemon threads to exit before deleting the thread
1332 // list.
1333 self->Destroy(should_run_callbacks);
1334
1335 // If tracing, remember thread id and name before thread exits.
1336 Trace::StoreExitingThreadInfo(self);
1337
1338 uint32_t thin_lock_id = self->GetThreadId();
1339 while (true) {
1340 // Remove and delete the Thread* while holding the thread_list_lock_ and
1341 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
1342 // Note: deliberately not using MutexLock that could hold a stale self pointer.
1343 {
1344 MutexLock mu(self, *Locks::thread_list_lock_);
1345 if (!Contains(self)) {
1346 std::string thread_name;
1347 self->GetThreadName(thread_name);
1348 std::ostringstream os;
1349 DumpNativeStack(os, GetTid(), " native: ", nullptr);
1350 LOG(ERROR) << "Request to unregister unattached thread " << thread_name << "\n" << os.str();
1351 break;
1352 } else {
1353 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
1354 if (!self->IsSuspended()) {
1355 list_.remove(self);
1356 break;
1357 }
1358 }
1359 }
1360 // In the case where we are not suspended yet, sleep to leave other threads time to execute.
1361 // This is important if there are realtime threads. b/111277984
1362 usleep(1);
1363 // We failed to remove the thread due to a suspend request, loop and try again.
1364 }
1365 delete self;
1366
1367 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
1368 // temporarily have multiple threads with the same thread id. When this occurs, it causes
1369 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
1370 ReleaseThreadId(nullptr, thin_lock_id);
1371
1372 // Clear the TLS data, so that the underlying native thread is recognizably detached.
1373 // (It may wish to reattach later.)
1374 #ifdef __BIONIC__
1375 __get_tls()[TLS_SLOT_ART_THREAD_SELF] = nullptr;
1376 #else
1377 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, nullptr), "detach self");
1378 Thread::self_tls_ = nullptr;
1379 #endif
1380
1381 // Signal that a thread just detached.
1382 MutexLock mu(nullptr, *Locks::thread_list_lock_);
1383 --unregistering_count_;
1384 Locks::thread_exit_cond_->Broadcast(nullptr);
1385 }
1386
ForEach(void (* callback)(Thread *,void *),void * context)1387 void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
1388 for (const auto& thread : list_) {
1389 callback(thread, context);
1390 }
1391 }
1392
VisitRootsForSuspendedThreads(RootVisitor * visitor)1393 void ThreadList::VisitRootsForSuspendedThreads(RootVisitor* visitor) {
1394 Thread* const self = Thread::Current();
1395 std::vector<Thread*> threads_to_visit;
1396
1397 // Tell threads to suspend and copy them into list.
1398 {
1399 MutexLock mu(self, *Locks::thread_list_lock_);
1400 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
1401 for (Thread* thread : list_) {
1402 bool suspended = thread->ModifySuspendCount(self, +1, nullptr, SuspendReason::kInternal);
1403 DCHECK(suspended);
1404 if (thread == self || thread->IsSuspended()) {
1405 threads_to_visit.push_back(thread);
1406 } else {
1407 bool resumed = thread->ModifySuspendCount(self, -1, nullptr, SuspendReason::kInternal);
1408 DCHECK(resumed);
1409 }
1410 }
1411 }
1412
1413 // Visit roots without holding thread_list_lock_ and thread_suspend_count_lock_ to prevent lock
1414 // order violations.
1415 for (Thread* thread : threads_to_visit) {
1416 thread->VisitRoots(visitor, kVisitRootFlagAllRoots);
1417 }
1418
1419 // Restore suspend counts.
1420 {
1421 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
1422 for (Thread* thread : threads_to_visit) {
1423 bool updated = thread->ModifySuspendCount(self, -1, nullptr, SuspendReason::kInternal);
1424 DCHECK(updated);
1425 }
1426 }
1427 }
1428
VisitRoots(RootVisitor * visitor,VisitRootFlags flags) const1429 void ThreadList::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) const {
1430 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
1431 for (const auto& thread : list_) {
1432 thread->VisitRoots(visitor, flags);
1433 }
1434 }
1435
VisitReflectiveTargets(ReflectiveValueVisitor * visitor) const1436 void ThreadList::VisitReflectiveTargets(ReflectiveValueVisitor *visitor) const {
1437 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
1438 for (const auto& thread : list_) {
1439 thread->VisitReflectiveTargets(visitor);
1440 }
1441 }
1442
SweepInterpreterCaches(IsMarkedVisitor * visitor) const1443 void ThreadList::SweepInterpreterCaches(IsMarkedVisitor* visitor) const {
1444 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
1445 for (const auto& thread : list_) {
1446 thread->SweepInterpreterCache(visitor);
1447 }
1448 }
1449
AllocThreadId(Thread * self)1450 uint32_t ThreadList::AllocThreadId(Thread* self) {
1451 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
1452 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
1453 if (!allocated_ids_[i]) {
1454 allocated_ids_.set(i);
1455 return i + 1; // Zero is reserved to mean "invalid".
1456 }
1457 }
1458 LOG(FATAL) << "Out of internal thread ids";
1459 UNREACHABLE();
1460 }
1461
ReleaseThreadId(Thread * self,uint32_t id)1462 void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
1463 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
1464 --id; // Zero is reserved to mean "invalid".
1465 DCHECK(allocated_ids_[id]) << id;
1466 allocated_ids_.reset(id);
1467 }
1468
ScopedSuspendAll(const char * cause,bool long_suspend)1469 ScopedSuspendAll::ScopedSuspendAll(const char* cause, bool long_suspend) {
1470 Runtime::Current()->GetThreadList()->SuspendAll(cause, long_suspend);
1471 }
1472
~ScopedSuspendAll()1473 ScopedSuspendAll::~ScopedSuspendAll() {
1474 Runtime::Current()->GetThreadList()->ResumeAll();
1475 }
1476
1477 } // namespace art
1478