1 /*
2  * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #include "precompiled.hpp"
26 #include "classfile/classLoaderDataGraph.inline.hpp"
27 #include "classfile/javaClasses.hpp"
28 #include "classfile/protectionDomainCache.hpp"
29 #include "classfile/stringTable.hpp"
30 #include "classfile/symbolTable.hpp"
31 #include "classfile/systemDictionary.hpp"
32 #include "classfile/vmClasses.hpp"
33 #include "gc/shared/oopStorage.hpp"
34 #include "gc/shared/oopStorageSet.hpp"
35 #include "memory/universe.hpp"
36 #include "oops/oopHandle.inline.hpp"
37 #include "runtime/handles.inline.hpp"
38 #include "runtime/interfaceSupport.inline.hpp"
39 #include "runtime/java.hpp"
40 #include "runtime/javaCalls.hpp"
41 #include "runtime/jniHandles.hpp"
42 #include "runtime/serviceThread.hpp"
43 #include "runtime/mutexLocker.hpp"
44 #include "runtime/os.hpp"
45 #include "prims/jvmtiImpl.hpp"
46 #include "prims/jvmtiTagMap.hpp"
47 #include "prims/resolvedMethodTable.hpp"
48 #include "services/diagnosticArgument.hpp"
49 #include "services/diagnosticFramework.hpp"
50 #include "services/gcNotifier.hpp"
51 #include "services/lowMemoryDetector.hpp"
52 #include "services/threadIdTable.hpp"
53 
54 ServiceThread* ServiceThread::_instance = NULL;
55 JvmtiDeferredEvent* ServiceThread::_jvmti_event = NULL;
56 // The service thread has it's own static deferred event queue.
57 // Events can be posted before JVMTI vm_start, so it's too early to call JvmtiThreadState::state_for
58 // to add this field to the per-JavaThread event queue.  TODO: fix this sometime later
59 JvmtiDeferredEventQueue ServiceThread::_jvmti_service_queue;
60 
61 // Defer releasing JavaThread OopHandle to the ServiceThread
62 class OopHandleList : public CHeapObj<mtInternal> {
63   OopHandle      _handle;
64   OopHandleList* _next;
65  public:
OopHandleList(OopHandle h,OopHandleList * next)66    OopHandleList(OopHandle h, OopHandleList* next) : _handle(h), _next(next) {}
~OopHandleList()67    ~OopHandleList() {
68      _handle.release(JavaThread::thread_oop_storage());
69    }
next() const70    OopHandleList* next() const { return _next; }
71 };
72 
73 static OopHandleList* _oop_handle_list = NULL;
74 
release_oop_handles()75 static void release_oop_handles() {
76   OopHandleList* list;
77   {
78     MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
79     list = _oop_handle_list;
80     _oop_handle_list = NULL;
81   }
82   assert(!SafepointSynchronize::is_at_safepoint(), "cannot be called at a safepoint");
83 
84   while (list != NULL) {
85     OopHandleList* l = list;
86     list = l->next();
87     delete l;
88   }
89 }
90 
initialize()91 void ServiceThread::initialize() {
92   EXCEPTION_MARK;
93 
94   const char* name = "Service Thread";
95   Handle string = java_lang_String::create_from_str(name, CHECK);
96 
97   // Initialize thread_oop to put it into the system threadGroup
98   Handle thread_group (THREAD, Universe::system_thread_group());
99   Handle thread_oop = JavaCalls::construct_new_instance(
100                           vmClasses::Thread_klass(),
101                           vmSymbols::threadgroup_string_void_signature(),
102                           thread_group,
103                           string,
104                           CHECK);
105 
106   {
107     MutexLocker mu(THREAD, Threads_lock);
108     ServiceThread* thread =  new ServiceThread(&service_thread_entry);
109 
110     // At this point it may be possible that no osthread was created for the
111     // JavaThread due to lack of memory. We would have to throw an exception
112     // in that case. However, since this must work and we do not allow
113     // exceptions anyway, check and abort if this fails.
114     if (thread == NULL || thread->osthread() == NULL) {
115       vm_exit_during_initialization("java.lang.OutOfMemoryError",
116                                     os::native_thread_creation_failed_msg());
117     }
118 
119     java_lang_Thread::set_thread(thread_oop(), thread);
120     java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
121     java_lang_Thread::set_daemon(thread_oop());
122     thread->set_threadObj(thread_oop());
123     _instance = thread;
124 
125     Threads::add(thread);
126     Thread::start(thread);
127   }
128 }
129 
cleanup_oopstorages()130 static void cleanup_oopstorages() {
131   for (OopStorage* storage : OopStorageSet::Range<OopStorageSet::Id>()) {
132     storage->delete_empty_blocks();
133   }
134 }
135 
service_thread_entry(JavaThread * jt,TRAPS)136 void ServiceThread::service_thread_entry(JavaThread* jt, TRAPS) {
137   while (true) {
138     bool sensors_changed = false;
139     bool has_jvmti_events = false;
140     bool has_gc_notification_event = false;
141     bool has_dcmd_notification_event = false;
142     bool stringtable_work = false;
143     bool symboltable_work = false;
144     bool resolved_method_table_work = false;
145     bool thread_id_table_work = false;
146     bool protection_domain_table_work = false;
147     bool oopstorage_work = false;
148     JvmtiDeferredEvent jvmti_event;
149     bool oop_handles_to_release = false;
150     bool cldg_cleanup_work = false;
151     bool jvmti_tagmap_work = false;
152     {
153       // Need state transition ThreadBlockInVM so that this thread
154       // will be handled by safepoint correctly when this thread is
155       // notified at a safepoint.
156 
157       // This ThreadBlockInVM object is not also considered to be
158       // suspend-equivalent because ServiceThread is not visible to
159       // external suspension.
160 
161       ThreadBlockInVM tbivm(jt);
162 
163       MonitorLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
164       // Process all available work on each (outer) iteration, rather than
165       // only the first recognized bit of work, to avoid frequently true early
166       // tests from potentially starving later work.  Hence the use of
167       // arithmetic-or to combine results; we don't want short-circuiting.
168       while (((sensors_changed = (!UseNotificationThread && LowMemoryDetector::has_pending_requests())) |
169               (has_jvmti_events = _jvmti_service_queue.has_events()) |
170               (has_gc_notification_event = (!UseNotificationThread && GCNotifier::has_event())) |
171               (has_dcmd_notification_event = (!UseNotificationThread && DCmdFactory::has_pending_jmx_notification())) |
172               (stringtable_work = StringTable::has_work()) |
173               (symboltable_work = SymbolTable::has_work()) |
174               (resolved_method_table_work = ResolvedMethodTable::has_work()) |
175               (thread_id_table_work = ThreadIdTable::has_work()) |
176               (protection_domain_table_work = SystemDictionary::pd_cache_table()->has_work()) |
177               (oopstorage_work = OopStorage::has_cleanup_work_and_reset()) |
178               (oop_handles_to_release = (_oop_handle_list != NULL)) |
179               (cldg_cleanup_work = ClassLoaderDataGraph::should_clean_metaspaces_and_reset()) |
180               (jvmti_tagmap_work = JvmtiTagMap::has_object_free_events_and_reset())
181              ) == 0) {
182         // Wait until notified that there is some work to do.
183         ml.wait();
184       }
185 
186       if (has_jvmti_events) {
187         // Get the event under the Service_lock
188         jvmti_event = _jvmti_service_queue.dequeue();
189         _jvmti_event = &jvmti_event;
190       }
191     }
192 
193     if (stringtable_work) {
194       StringTable::do_concurrent_work(jt);
195     }
196 
197     if (symboltable_work) {
198       SymbolTable::do_concurrent_work(jt);
199     }
200 
201     if (has_jvmti_events) {
202       _jvmti_event->post();
203       _jvmti_event = NULL;  // reset
204     }
205 
206     if (!UseNotificationThread) {
207       if (sensors_changed) {
208         LowMemoryDetector::process_sensor_changes(jt);
209       }
210 
211       if(has_gc_notification_event) {
212         GCNotifier::sendNotification(CHECK);
213       }
214 
215       if(has_dcmd_notification_event) {
216         DCmdFactory::send_notification(CHECK);
217       }
218     }
219 
220     if (resolved_method_table_work) {
221       ResolvedMethodTable::do_concurrent_work(jt);
222     }
223 
224     if (thread_id_table_work) {
225       ThreadIdTable::do_concurrent_work(jt);
226     }
227 
228     if (protection_domain_table_work) {
229       SystemDictionary::pd_cache_table()->unlink();
230     }
231 
232     if (oopstorage_work) {
233       cleanup_oopstorages();
234     }
235 
236     if (oop_handles_to_release) {
237       release_oop_handles();
238     }
239 
240     if (cldg_cleanup_work) {
241       ClassLoaderDataGraph::safepoint_and_clean_metaspaces();
242     }
243 
244     if (jvmti_tagmap_work) {
245       JvmtiTagMap::flush_all_object_free_events();
246     }
247   }
248 }
249 
enqueue_deferred_event(JvmtiDeferredEvent * event)250 void ServiceThread::enqueue_deferred_event(JvmtiDeferredEvent* event) {
251   MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
252   // If you enqueue events before the service thread runs, gc and the sweeper
253   // cannot keep the nmethod alive.  This could be restricted to compiled method
254   // load and unload events, if we wanted to be picky.
255   assert(_instance != NULL, "cannot enqueue events before the service thread runs");
256   _jvmti_service_queue.enqueue(*event);
257   Service_lock->notify_all();
258  }
259 
oops_do_no_frames(OopClosure * f,CodeBlobClosure * cf)260 void ServiceThread::oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf) {
261   JavaThread::oops_do_no_frames(f, cf);
262   // The ServiceThread "owns" the JVMTI Deferred events, scan them here
263   // to keep them alive until they are processed.
264   if (_jvmti_event != NULL) {
265     _jvmti_event->oops_do(f, cf);
266   }
267   // Requires a lock, because threads can be adding to this queue.
268   MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
269   _jvmti_service_queue.oops_do(f, cf);
270 }
271 
nmethods_do(CodeBlobClosure * cf)272 void ServiceThread::nmethods_do(CodeBlobClosure* cf) {
273   JavaThread::nmethods_do(cf);
274   if (cf != NULL) {
275     if (_jvmti_event != NULL) {
276       _jvmti_event->nmethods_do(cf);
277     }
278     // Requires a lock, because threads can be adding to this queue.
279     MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
280     _jvmti_service_queue.nmethods_do(cf);
281   }
282 }
283 
add_oop_handle_release(OopHandle handle)284 void ServiceThread::add_oop_handle_release(OopHandle handle) {
285   MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
286   OopHandleList* new_head = new OopHandleList(handle, _oop_handle_list);
287   _oop_handle_list = new_head;
288   Service_lock->notify_all();
289 }
290