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