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 #ifndef ART_RUNTIME_THREAD_LIST_H_
18 #define ART_RUNTIME_THREAD_LIST_H_
19 
20 #include "barrier.h"
21 #include "base/histogram.h"
22 #include "base/mutex.h"
23 #include "base/value_object.h"
24 #include "jni.h"
25 #include "reflective_handle_scope.h"
26 #include "suspend_reason.h"
27 
28 #include <bitset>
29 #include <list>
30 #include <vector>
31 
32 namespace art {
33 namespace gc {
34 namespace collector {
35 class GarbageCollector;
36 }  // namespace collector
37 class GcPauseListener;
38 }  // namespace gc
39 class Closure;
40 class IsMarkedVisitor;
41 class RootVisitor;
42 class Thread;
43 class TimingLogger;
44 enum VisitRootFlags : uint8_t;
45 
46 class ThreadList {
47  public:
48   static constexpr uint32_t kMaxThreadId = 0xFFFF;
49   static constexpr uint32_t kInvalidThreadId = 0;
50   static constexpr uint32_t kMainThreadId = 1;
51   static constexpr uint64_t kDefaultThreadSuspendTimeout =
52       kIsDebugBuild ? 50'000'000'000ull : 10'000'000'000ull;
53 
54   explicit ThreadList(uint64_t thread_suspend_timeout_ns);
55   ~ThreadList();
56 
57   void ShutDown();
58 
59   void DumpForSigQuit(std::ostream& os)
60       REQUIRES(!Locks::thread_list_lock_, !Locks::mutator_lock_);
61   // For thread suspend timeout dumps.
62   void Dump(std::ostream& os, bool dump_native_stack = true)
63       REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_);
64   pid_t GetLockOwner();  // For SignalCatcher.
65 
66   // Thread suspension support.
67   void ResumeAll()
68       REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_)
69       UNLOCK_FUNCTION(Locks::mutator_lock_);
70   bool Resume(Thread* thread, SuspendReason reason = SuspendReason::kInternal)
71       REQUIRES(!Locks::thread_suspend_count_lock_) WARN_UNUSED;
72 
73   // Suspends all threads and gets exclusive access to the mutator lock.
74   // If long_suspend is true, then other threads who try to suspend will never timeout.
75   // long_suspend is currenly used for hprof since large heaps take a long time.
76   void SuspendAll(const char* cause, bool long_suspend = false)
77       EXCLUSIVE_LOCK_FUNCTION(Locks::mutator_lock_)
78       REQUIRES(!Locks::thread_list_lock_,
79                !Locks::thread_suspend_count_lock_,
80                !Locks::mutator_lock_);
81 
82   // Suspend a thread using a peer, typically used by the debugger. Returns the thread on success,
83   // else null. The peer is used to identify the thread to avoid races with the thread terminating.
84   // If the suspension times out then *timeout is set to true.
85   Thread* SuspendThreadByPeer(jobject peer,
86                               SuspendReason reason,
87                               bool* timed_out)
88       REQUIRES(!Locks::mutator_lock_,
89                !Locks::thread_list_lock_,
90                !Locks::thread_suspend_count_lock_);
91 
92   // Suspend a thread using its thread id, typically used by lock/monitor inflation. Returns the
93   // thread on success else null. The thread id is used to identify the thread to avoid races with
94   // the thread terminating. Note that as thread ids are recycled this may not suspend the expected
95   // thread, that may be terminating. If the suspension times out then *timeout is set to true.
96   Thread* SuspendThreadByThreadId(uint32_t thread_id, SuspendReason reason, bool* timed_out)
97       REQUIRES(!Locks::mutator_lock_,
98                !Locks::thread_list_lock_,
99                !Locks::thread_suspend_count_lock_);
100 
101   // Find an existing thread (or self) by its thread id (not tid).
102   Thread* FindThreadByThreadId(uint32_t thread_id) REQUIRES(Locks::thread_list_lock_);
103 
104   // Find an existing thread (or self) by its tid (not thread id).
105   Thread* FindThreadByTid(int tid) REQUIRES(Locks::thread_list_lock_);
106 
107   // Does the thread list still contain the given thread, or one at the same address?
108   // Used by Monitor to provide (mostly accurate) debugging information.
109   bool Contains(Thread* thread) REQUIRES(Locks::thread_list_lock_);
110 
111   // Run a checkpoint on all threads. Return the total number of threads for which the checkpoint
112   // function has been or will be called.
113   // Running threads are not suspended but run the checkpoint inside of the suspend check. The
114   // return value includes already suspended threads for b/24191051. Runs or requests the
115   // callback, if non-null, inside the thread_list_lock critical section after determining the
116   // runnable/suspended states of the threads. Does not wait for completion of the callbacks in
117   // running threads.
118   size_t RunCheckpoint(Closure* checkpoint_function, Closure* callback = nullptr)
119       REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_);
120 
121   // Run an empty checkpoint on threads. Wait until threads pass the next suspend point or are
122   // suspended. This is used to ensure that the threads finish or aren't in the middle of an
123   // in-flight mutator heap access (eg. a read barrier.) Runnable threads will respond by
124   // decrementing the empty checkpoint barrier count. This works even when the weak ref access is
125   // disabled. Only one concurrent use is currently supported.
126   void RunEmptyCheckpoint()
127       REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_);
128 
129   // Flip thread roots from from-space refs to to-space refs. Used by
130   // the concurrent copying collector.
131   size_t FlipThreadRoots(Closure* thread_flip_visitor,
132                          Closure* flip_callback,
133                          gc::collector::GarbageCollector* collector,
134                          gc::GcPauseListener* pause_listener)
135       REQUIRES(!Locks::mutator_lock_,
136                !Locks::thread_list_lock_,
137                !Locks::thread_suspend_count_lock_);
138 
139   // Iterates over all the threads.
140   void ForEach(void (*callback)(Thread*, void*), void* context)
141       REQUIRES(Locks::thread_list_lock_);
142 
143   template<typename CallBack>
ForEach(CallBack cb)144   void ForEach(CallBack cb) REQUIRES(Locks::thread_list_lock_) {
145     ForEach([](Thread* t, void* ctx) REQUIRES(Locks::thread_list_lock_) {
146       (*reinterpret_cast<CallBack*>(ctx))(t);
147     }, &cb);
148   }
149 
150   // Add/remove current thread from list.
151   void Register(Thread* self)
152       REQUIRES(Locks::runtime_shutdown_lock_)
153       REQUIRES(!Locks::mutator_lock_,
154                !Locks::thread_list_lock_,
155                !Locks::thread_suspend_count_lock_);
156   void Unregister(Thread* self)
157       REQUIRES(!Locks::mutator_lock_,
158                !Locks::thread_list_lock_,
159                !Locks::thread_suspend_count_lock_);
160 
161   void VisitRoots(RootVisitor* visitor, VisitRootFlags flags) const
162       REQUIRES_SHARED(Locks::mutator_lock_);
163 
164   void VisitRootsForSuspendedThreads(RootVisitor* visitor)
165       REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_)
166       REQUIRES_SHARED(Locks::mutator_lock_);
167 
168   void VisitReflectiveTargets(ReflectiveValueVisitor* visitor) const REQUIRES(Locks::mutator_lock_);
169 
170   // Return a copy of the thread list.
GetList()171   std::list<Thread*> GetList() REQUIRES(Locks::thread_list_lock_) {
172     return list_;
173   }
174 
175   void DumpNativeStacks(std::ostream& os)
176       REQUIRES(!Locks::thread_list_lock_);
177 
EmptyCheckpointBarrier()178   Barrier* EmptyCheckpointBarrier() {
179     return empty_checkpoint_barrier_.get();
180   }
181 
182   void SweepInterpreterCaches(IsMarkedVisitor* visitor) const
183       REQUIRES(!Locks::thread_list_lock_)
184       REQUIRES_SHARED(Locks::mutator_lock_);
185 
186   void WaitForOtherNonDaemonThreadsToExit(bool check_no_birth = true)
187       REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_,
188                !Locks::mutator_lock_);
189 
190  private:
191   uint32_t AllocThreadId(Thread* self);
192   void ReleaseThreadId(Thread* self, uint32_t id) REQUIRES(!Locks::allocated_thread_ids_lock_);
193 
194   size_t RunCheckpoint(Closure* checkpoint_function, bool includeSuspended)
195       REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_);
196 
197   void DumpUnattachedThreads(std::ostream& os, bool dump_native_stack)
198       REQUIRES(!Locks::thread_list_lock_);
199 
200   void SuspendAllDaemonThreadsForShutdown()
201       REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_);
202 
203   void SuspendAllInternal(Thread* self,
204                           Thread* ignore1,
205                           Thread* ignore2 = nullptr,
206                           SuspendReason reason = SuspendReason::kInternal)
207       REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_);
208 
209   void AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2 = nullptr)
210       REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_);
211 
212   std::bitset<kMaxThreadId> allocated_ids_ GUARDED_BY(Locks::allocated_thread_ids_lock_);
213 
214   // The actual list of all threads.
215   std::list<Thread*> list_ GUARDED_BY(Locks::thread_list_lock_);
216 
217   // Ongoing suspend all requests, used to ensure threads added to list_ respect SuspendAll.
218   int suspend_all_count_ GUARDED_BY(Locks::thread_suspend_count_lock_);
219 
220   // Number of threads unregistering, ~ThreadList blocks until this hits 0.
221   int unregistering_count_ GUARDED_BY(Locks::thread_list_lock_);
222 
223   // Thread suspend time histogram. Only modified when all the threads are suspended, so guarding
224   // by mutator lock ensures no thread can read when another thread is modifying it.
225   Histogram<uint64_t> suspend_all_historam_ GUARDED_BY(Locks::mutator_lock_);
226 
227   // Whether or not the current thread suspension is long.
228   bool long_suspend_;
229 
230   // Whether the shutdown function has been called. This is checked in the destructor. It is an
231   // error to destroy a ThreadList instance without first calling ShutDown().
232   bool shut_down_;
233 
234   // Thread suspension timeout in nanoseconds.
235   const uint64_t thread_suspend_timeout_ns_;
236 
237   std::unique_ptr<Barrier> empty_checkpoint_barrier_;
238 
239   friend class Thread;
240 
241   DISALLOW_COPY_AND_ASSIGN(ThreadList);
242 };
243 
244 // Helper for suspending all threads and getting exclusive access to the mutator lock.
245 class ScopedSuspendAll : public ValueObject {
246  public:
247   explicit ScopedSuspendAll(const char* cause, bool long_suspend = false)
248      EXCLUSIVE_LOCK_FUNCTION(Locks::mutator_lock_)
249      REQUIRES(!Locks::thread_list_lock_,
250               !Locks::thread_suspend_count_lock_,
251               !Locks::mutator_lock_);
252   // No REQUIRES(mutator_lock_) since the unlock function already asserts this.
253   ~ScopedSuspendAll()
254       REQUIRES(!Locks::thread_list_lock_, !Locks::thread_suspend_count_lock_)
255       UNLOCK_FUNCTION(Locks::mutator_lock_);
256 };
257 
258 }  // namespace art
259 
260 #endif  // ART_RUNTIME_THREAD_LIST_H_
261