1 /*
   2  * Copyright (c) 2012, 2020, 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/protectionDomainCache.hpp"
  27 #include "classfile/stringTable.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "gc/shared/oopStorage.hpp"
  31 #include "gc/shared/oopStorageSet.hpp"
  32 #include "memory/universe.hpp"
  33 #include "runtime/handles.inline.hpp"
  34 #include "runtime/interfaceSupport.inline.hpp"
  35 #include "runtime/javaCalls.hpp"
  36 #include "runtime/jniHandles.hpp"
  37 #include "runtime/serviceThread.hpp"
  38 #include "runtime/mutexLocker.hpp"
  39 #include "runtime/os.hpp"
  40 #include "prims/jvmtiImpl.hpp"
  41 #include "prims/resolvedMethodTable.hpp"
  42 #include "services/diagnosticArgument.hpp"
  43 #include "services/diagnosticFramework.hpp"
  44 #include "services/gcNotifier.hpp"
  45 #include "services/lowMemoryDetector.hpp"
  46 #include "services/threadIdTable.hpp"
  47 
  48 ServiceThread* ServiceThread::_instance = NULL;
  49 JvmtiDeferredEvent* ServiceThread::_jvmti_event = NULL;
  50 // The service thread has it's own static deferred event queue.
  51 // Events can be posted before JVMTI vm_start, so it's too early to call JvmtiThreadState::state_for
  52 // to add this field to the per-JavaThread event queue.  TODO: fix this sometime later
  53 JvmtiDeferredEventQueue ServiceThread::_jvmti_service_queue;
  54 
  55 void ServiceThread::initialize() {
  56   EXCEPTION_MARK;
  57 
  58   const char* name = "Service Thread";
  59   Handle string = java_lang_String::create_from_str(name, CHECK);
  60 
  61   // Initialize thread_oop to put it into the system threadGroup
  62   Handle thread_group (THREAD, Universe::system_thread_group());
  63   Handle thread_oop = JavaCalls::construct_new_instance(
  64                           SystemDictionary::Thread_klass(),
  65                           vmSymbols::threadgroup_string_void_signature(),
  66                           thread_group,
  67                           string,
  68                           CHECK);
  69 
  70   {
  71     MutexLocker mu(THREAD, Threads_lock);
  72     ServiceThread* thread =  new ServiceThread(&service_thread_entry);
  73 
  74     // At this point it may be possible that no osthread was created for the
  75     // JavaThread due to lack of memory. We would have to throw an exception
  76     // in that case. However, since this must work and we do not allow
  77     // exceptions anyway, check and abort if this fails.
  78     if (thread == NULL || thread->osthread() == NULL) {
  79       vm_exit_during_initialization("java.lang.OutOfMemoryError",
  80                                     os::native_thread_creation_failed_msg());
  81     }
  82 
  83     java_lang_Thread::set_thread(thread_oop(), thread);
  84     java_lang_Thread::set_priority(thread_oop(), NearMaxPriority);
  85     java_lang_Thread::set_daemon(thread_oop());
  86     thread->set_threadObj(thread_oop());
  87     _instance = thread;
  88 
  89     Threads::add(thread);
  90     Thread::start(thread);
  91   }
  92 }
  93 
  94 static void cleanup_oopstorages() {
  95   OopStorageSet::Iterator it = OopStorageSet::all_iterator();
  96   for ( ; !it.is_end(); ++it) {
  97     it->delete_empty_blocks();
  98   }
  99 }
 100 
 101 void ServiceThread::service_thread_entry(JavaThread* jt, TRAPS) {
 102   while (true) {
 103     bool sensors_changed = false;
 104     bool has_jvmti_events = false;
 105     bool has_gc_notification_event = false;
 106     bool has_dcmd_notification_event = false;
 107     bool stringtable_work = false;
 108     bool symboltable_work = false;
 109     bool resolved_method_table_work = false;
 110     bool thread_id_table_work = false;
 111     bool protection_domain_table_work = false;
 112     bool oopstorage_work = false;
 113     bool deflate_idle_monitors = false;
 114     JvmtiDeferredEvent jvmti_event;
 115     {
 116       // Need state transition ThreadBlockInVM so that this thread
 117       // will be handled by safepoint correctly when this thread is
 118       // notified at a safepoint.
 119 
 120       // This ThreadBlockInVM object is not also considered to be
 121       // suspend-equivalent because ServiceThread is not visible to
 122       // external suspension.
 123 
 124       ThreadBlockInVM tbivm(jt);
 125 
 126       MonitorLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
 127       // Process all available work on each (outer) iteration, rather than
 128       // only the first recognized bit of work, to avoid frequently true early
 129       // tests from potentially starving later work.  Hence the use of
 130       // arithmetic-or to combine results; we don't want short-circuiting.
 131       while (((sensors_changed = (!UseNotificationThread && LowMemoryDetector::has_pending_requests())) |
 132               (has_jvmti_events = _jvmti_service_queue.has_events()) |
 133               (has_gc_notification_event = (!UseNotificationThread && GCNotifier::has_event())) |
 134               (has_dcmd_notification_event = (!UseNotificationThread && DCmdFactory::has_pending_jmx_notification())) |
 135               (stringtable_work = StringTable::has_work()) |
 136               (symboltable_work = SymbolTable::has_work()) |
 137               (resolved_method_table_work = ResolvedMethodTable::has_work()) |
 138               (thread_id_table_work = ThreadIdTable::has_work()) |
 139               (protection_domain_table_work = SystemDictionary::pd_cache_table()->has_work()) |
 140               (oopstorage_work = OopStorage::has_cleanup_work_and_reset()) |
 141               (deflate_idle_monitors = ObjectSynchronizer::is_async_deflation_needed())
 142              ) == 0) {
 143         // Wait until notified that there is some work to do.
 144         // If AsyncDeflateIdleMonitors, then we wait for
 145         // GuaranteedSafepointInterval so that is_async_deflation_needed()
 146         // is checked at the same interval.
 147         ml.wait(AsyncDeflateIdleMonitors ? GuaranteedSafepointInterval : 0);
 148       }
 149 
 150       if (has_jvmti_events) {
 151         // Get the event under the Service_lock
 152         jvmti_event = _jvmti_service_queue.dequeue();
 153         _jvmti_event = &jvmti_event;
 154       }
 155     }
 156 
 157     if (stringtable_work) {
 158       StringTable::do_concurrent_work(jt);
 159     }
 160 
 161     if (symboltable_work) {
 162       SymbolTable::do_concurrent_work(jt);
 163     }
 164 
 165     if (has_jvmti_events) {
 166       _jvmti_event->post();
 167       _jvmti_event = NULL;  // reset
 168     }
 169 
 170     if (!UseNotificationThread) {
 171       if (sensors_changed) {
 172         LowMemoryDetector::process_sensor_changes(jt);
 173       }
 174 
 175       if(has_gc_notification_event) {
 176         GCNotifier::sendNotification(CHECK);
 177       }
 178 
 179       if(has_dcmd_notification_event) {
 180         DCmdFactory::send_notification(CHECK);
 181       }
 182     }
 183 
 184     if (resolved_method_table_work) {
 185       ResolvedMethodTable::do_concurrent_work(jt);
 186     }
 187 
 188     if (thread_id_table_work) {
 189       ThreadIdTable::do_concurrent_work(jt);
 190     }
 191 
 192     if (protection_domain_table_work) {
 193       SystemDictionary::pd_cache_table()->unlink();
 194     }
 195 
 196     if (oopstorage_work) {
 197       cleanup_oopstorages();
 198     }
 199 
 200     if (deflate_idle_monitors) {
 201       ObjectSynchronizer::deflate_idle_monitors_using_JT();
 202     }
 203   }
 204 }
 205 
 206 void ServiceThread::enqueue_deferred_event(JvmtiDeferredEvent* event) {
 207   MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
 208   // If you enqueue events before the service thread runs, gc and the sweeper
 209   // cannot keep the nmethod alive.  This could be restricted to compiled method
 210   // load and unload events, if we wanted to be picky.
 211   assert(_instance != NULL, "cannot enqueue events before the service thread runs");
 212   _jvmti_service_queue.enqueue(*event);
 213   Service_lock->notify_all();
 214  }
 215 
 216 void ServiceThread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
 217   JavaThread::oops_do(f, cf);
 218   // The ServiceThread "owns" the JVMTI Deferred events, scan them here
 219   // to keep them alive until they are processed.
 220   if (cf != NULL) {
 221     if (_jvmti_event != NULL) {
 222       _jvmti_event->oops_do(f, cf);
 223     }
 224     // Requires a lock, because threads can be adding to this queue.
 225     MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
 226     _jvmti_service_queue.oops_do(f, cf);
 227   }
 228 }
 229 
 230 void ServiceThread::nmethods_do(CodeBlobClosure* cf) {
 231   JavaThread::nmethods_do(cf);
 232   if (cf != NULL) {
 233     if (_jvmti_event != NULL) {
 234       _jvmti_event->nmethods_do(cf);
 235     }
 236     // Requires a lock, because threads can be adding to this queue.
 237     MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
 238     _jvmti_service_queue.nmethods_do(cf);
 239   }
 240 }