1 /*
  2  * Copyright (c) 1997, 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 "memory/universe.hpp"
 27 #include "runtime/mutexLocker.hpp"
 28 #include "runtime/os.inline.hpp"
 29 #include "runtime/safepoint.hpp"
 30 #include "runtime/thread.inline.hpp"
 31 #include "runtime/vmThread.hpp"
 32 
 33 // Mutexes used in the VM (see comment in mutexLocker.hpp):
 34 //
 35 // Note that the following pointers are effectively final -- after having been
 36 // set at JVM startup-time, they should never be subsequently mutated.
 37 // Instead of using pointers to malloc()ed monitors and mutexes we should consider
 38 // eliminating the indirection and using instances instead.
 39 // Consider using GCC's __read_mostly.
 40 
 41 Mutex*   Patching_lock                = NULL;
 42 Mutex*   CompiledMethod_lock          = NULL;
 43 Monitor* SystemDictionary_lock        = NULL;
 44 Mutex*   ProtectionDomainSet_lock     = NULL;
 45 Mutex*   SharedDictionary_lock        = NULL;
 46 Mutex*   Module_lock                  = NULL;
 47 Mutex*   CompiledIC_lock              = NULL;
 48 Mutex*   InlineCacheBuffer_lock       = NULL;
 49 Mutex*   VMStatistic_lock             = NULL;
 50 Mutex*   JNIHandleBlockFreeList_lock  = NULL;
 51 Mutex*   JmethodIdCreation_lock       = NULL;
 52 Mutex*   JfieldIdCreation_lock        = NULL;
 53 Monitor* JNICritical_lock             = NULL;
 54 Mutex*   JvmtiThreadState_lock        = NULL;
 55 Monitor* Heap_lock                    = NULL;
 56 Mutex*   ExpandHeap_lock              = NULL;
 57 Mutex*   AdapterHandlerLibrary_lock   = NULL;
 58 Mutex*   SignatureHandlerLibrary_lock = NULL;
 59 Mutex*   VtableStubs_lock             = NULL;
 60 Mutex*   SymbolArena_lock             = NULL;
 61 Monitor* StringDedupQueue_lock        = NULL;
 62 Mutex*   StringDedupTable_lock        = NULL;
 63 Monitor* CodeCache_lock               = NULL;
 64 Mutex*   MethodData_lock              = NULL;
 65 Mutex*   TouchedMethodLog_lock        = NULL;
 66 Mutex*   RetData_lock                 = NULL;
 67 Monitor* VMOperationQueue_lock        = NULL;
 68 Monitor* VMOperationRequest_lock      = NULL;
 69 Monitor* Threads_lock                 = NULL;
 70 Mutex*   NonJavaThreadsList_lock      = NULL;
 71 Mutex*   NonJavaThreadsListSync_lock  = NULL;
 72 Monitor* CGC_lock                     = NULL;
 73 Monitor* STS_lock                     = NULL;
 74 Monitor* FullGCCount_lock             = NULL;
 75 Monitor* G1OldGCCount_lock            = NULL;
 76 Mutex*   Shared_DirtyCardQ_lock       = NULL;
 77 Mutex*   MarkStackFreeList_lock       = NULL;
 78 Mutex*   MarkStackChunkList_lock      = NULL;
 79 Mutex*   MonitoringSupport_lock       = NULL;
 80 Mutex*   ParGCRareEvent_lock          = NULL;
 81 Monitor* CGCPhaseManager_lock         = NULL;
 82 Mutex*   Compile_lock                 = NULL;
 83 Monitor* MethodCompileQueue_lock      = NULL;
 84 Monitor* CompileThread_lock           = NULL;
 85 Monitor* Compilation_lock             = NULL;
 86 Mutex*   CompileTaskAlloc_lock        = NULL;
 87 Mutex*   CompileStatistics_lock       = NULL;
 88 Mutex*   DirectivesStack_lock         = NULL;
 89 Mutex*   MultiArray_lock              = NULL;
 90 Monitor* Terminator_lock              = NULL;
 91 Monitor* InitCompleted_lock           = NULL;
 92 Monitor* BeforeExit_lock              = NULL;
 93 Monitor* Notify_lock                  = NULL;
 94 Mutex*   ProfilePrint_lock            = NULL;
 95 Mutex*   ExceptionCache_lock          = NULL;
 96 Mutex*   NMethodSweeperStats_lock     = NULL;
 97 #ifndef PRODUCT
 98 Mutex*   FullGCALot_lock              = NULL;
 99 #endif
100 
101 Mutex*   Debug1_lock                  = NULL;
102 Mutex*   Debug2_lock                  = NULL;
103 Mutex*   Debug3_lock                  = NULL;
104 
105 Mutex*   tty_lock                     = NULL;
106 
107 Mutex*   RawMonitor_lock              = NULL;
108 Mutex*   PerfDataMemAlloc_lock        = NULL;
109 Mutex*   PerfDataManager_lock         = NULL;
110 Mutex*   OopMapCacheAlloc_lock        = NULL;
111 
112 Mutex*   FreeList_lock                = NULL;
113 Mutex*   OldSets_lock                 = NULL;
114 Monitor* RootRegionScan_lock          = NULL;
115 
116 Mutex*   Management_lock              = NULL;
117 Monitor* Service_lock                 = NULL;
118 Monitor* Notification_lock            = NULL;
119 Monitor* PeriodicTask_lock            = NULL;
120 Monitor* RedefineClasses_lock         = NULL;
121 Mutex*   Verify_lock                  = NULL;
122 
123 #if INCLUDE_JFR
124 Mutex*   JfrStacktrace_lock           = NULL;
125 Monitor* JfrMsg_lock                  = NULL;
126 Mutex*   JfrBuffer_lock               = NULL;
127 Mutex*   JfrStream_lock               = NULL;
128 Monitor* JfrThreadSampler_lock        = NULL;
129 #endif
130 
131 #ifndef SUPPORTS_NATIVE_CX8
132 Mutex*   UnsafeJlong_lock             = NULL;
133 #endif
134 Mutex*   CodeHeapStateAnalytics_lock  = NULL;
135 
136 Mutex*   MetaspaceExpand_lock         = NULL;
137 Mutex*   ClassLoaderDataGraph_lock    = NULL;
138 Monitor* ThreadsSMRDelete_lock        = NULL;
139 Mutex*   ThreadIdTableCreate_lock     = NULL;
140 Mutex*   SharedDecoder_lock           = NULL;
141 Mutex*   DCmdFactory_lock             = NULL;
142 #if INCLUDE_NMT
143 Mutex*   NMTQuery_lock                = NULL;
144 #endif
145 #if INCLUDE_CDS
146 #if INCLUDE_JVMTI
147 Mutex*   CDSClassFileStream_lock      = NULL;
148 #endif
149 Mutex*   DumpTimeTable_lock           = NULL;
150 #endif // INCLUDE_CDS
151 
152 #if INCLUDE_JVMCI
153 Monitor* JVMCI_lock                   = NULL;
154 #endif
155 
156 
157 #define MAX_NUM_MUTEX 128
158 static Mutex* _mutex_array[MAX_NUM_MUTEX];
159 static int _num_mutex;
160 
161 #ifdef ASSERT
162 void assert_locked_or_safepoint(const Mutex* lock) {
163   // check if this thread owns the lock (common case)
164   assert(lock != NULL, "Need non-NULL lock");
165   if (lock->owned_by_self()) return;
166   if (SafepointSynchronize::is_at_safepoint()) return;
167   if (!Universe::is_fully_initialized()) return;
168   // see if invoker of VM operation owns it
169   VM_Operation* op = VMThread::vm_operation();
170   if (op != NULL && op->calling_thread() == lock->owner()) return;
171   fatal("must own lock %s", lock->name());
172 }
173 
174 // a weaker assertion than the above
175 void assert_locked_or_safepoint_weak(const Mutex* lock) {
176   assert(lock != NULL, "Need non-NULL lock");
177   if (lock->is_locked()) return;
178   if (SafepointSynchronize::is_at_safepoint()) return;
179   if (!Universe::is_fully_initialized()) return;
180   fatal("must own lock %s", lock->name());
181 }
182 
183 // a stronger assertion than the above
184 void assert_lock_strong(const Mutex* lock) {
185   assert(lock != NULL, "Need non-NULL lock");
186   if (lock->owned_by_self()) return;
187   fatal("must own lock %s", lock->name());
188 }
189 
190 void assert_locked_or_safepoint_or_handshake(const Mutex* lock, const JavaThread* thread) {
191   if (Thread::current()->is_VM_thread() && thread->is_vmthread_processing_handshake()) return;
192   assert_locked_or_safepoint(lock);
193 }
194 #endif
195 
196 #define def(var, type, pri, vm_block, safepoint_check_allowed ) {      \
197   var = new type(Mutex::pri, #var, vm_block, Mutex::safepoint_check_allowed); \
198   assert(_num_mutex < MAX_NUM_MUTEX, "increase MAX_NUM_MUTEX");        \
199   _mutex_array[_num_mutex++] = var;                                      \
200 }
201 
202 // Using Padded subclasses to prevent false sharing of these global monitors and mutexes.
203 void mutex_init() {
204   def(tty_lock                     , PaddedMutex  , tty,         true,  _safepoint_check_never);      // allow to lock in VM
205 
206   def(CGC_lock                     , PaddedMonitor, special,     true,  _safepoint_check_never);      // coordinate between fore- and background GC
207   def(STS_lock                     , PaddedMonitor, leaf,        true,  _safepoint_check_never);
208 
209   def(FullGCCount_lock             , PaddedMonitor, leaf,        true,  _safepoint_check_never);      // in support of ExplicitGCInvokesConcurrent
210   if (UseG1GC) {
211     def(G1OldGCCount_lock          , PaddedMonitor, leaf,        true,  _safepoint_check_always);
212 
213     def(Shared_DirtyCardQ_lock     , PaddedMutex  , access + 1,  true,  _safepoint_check_never);
214 
215     def(FreeList_lock              , PaddedMutex  , leaf     ,   true,  _safepoint_check_never);
216     def(OldSets_lock               , PaddedMutex  , leaf     ,   true,  _safepoint_check_never);
217     def(RootRegionScan_lock        , PaddedMonitor, leaf     ,   true,  _safepoint_check_never);
218 
219     def(StringDedupQueue_lock      , PaddedMonitor, leaf,        true,  _safepoint_check_never);
220     def(StringDedupTable_lock      , PaddedMutex  , leaf,        true,  _safepoint_check_never);
221 
222     def(MarkStackFreeList_lock     , PaddedMutex  , leaf     ,   true,  _safepoint_check_never);
223     def(MarkStackChunkList_lock    , PaddedMutex  , leaf     ,   true,  _safepoint_check_never);
224 
225     def(MonitoringSupport_lock     , PaddedMutex  , native   ,   true,  _safepoint_check_never);      // used for serviceability monitoring support
226   }
227   if (UseShenandoahGC) {
228     def(StringDedupQueue_lock      , PaddedMonitor, leaf,        true,  _safepoint_check_never);
229     def(StringDedupTable_lock      , PaddedMutex  , leaf + 1,    true,  _safepoint_check_never);
230   }
231   def(ParGCRareEvent_lock          , PaddedMutex  , leaf     ,   true,  _safepoint_check_always);
232   def(CGCPhaseManager_lock         , PaddedMonitor, leaf,        false, _safepoint_check_always);
233   def(CodeCache_lock               , PaddedMonitor, special,     true,  _safepoint_check_never);
234   def(RawMonitor_lock              , PaddedMutex  , special,     true,  _safepoint_check_never);
235   def(OopMapCacheAlloc_lock        , PaddedMutex  , leaf,        true,  _safepoint_check_always); // used for oop_map_cache allocation.
236 
237   def(MetaspaceExpand_lock         , PaddedMutex  , leaf-1,      true,  _safepoint_check_never);
238   def(ClassLoaderDataGraph_lock    , PaddedMutex  , nonleaf,     false, _safepoint_check_always);
239 
240   def(Patching_lock                , PaddedMutex  , special,     true,  _safepoint_check_never);      // used for safepointing and code patching.
241   def(CompiledMethod_lock          , PaddedMutex  , special-1,   true,  _safepoint_check_never);
242   def(Service_lock                 , PaddedMonitor, special,     true,  _safepoint_check_never);      // used for service thread operations
243 
244   if (UseNotificationThread) {
245     def(Notification_lock            , PaddedMonitor, special,     true,  _safepoint_check_never);  // used for notification thread operations
246   } else {
247     Notification_lock = Service_lock;
248   }
249 
250   def(JmethodIdCreation_lock       , PaddedMutex  , leaf,        true,  _safepoint_check_never); // used for creating jmethodIDs.
251 
252   def(SystemDictionary_lock        , PaddedMonitor, leaf,        true,  _safepoint_check_always);
253   def(ProtectionDomainSet_lock     , PaddedMutex  , leaf-1,      true,  _safepoint_check_never);
254   def(SharedDictionary_lock        , PaddedMutex  , leaf,        true,  _safepoint_check_always);
255   def(Module_lock                  , PaddedMutex  , leaf+2,      false, _safepoint_check_always);
256   def(InlineCacheBuffer_lock       , PaddedMutex  , leaf,        true,  _safepoint_check_never);
257   def(VMStatistic_lock             , PaddedMutex  , leaf,        false, _safepoint_check_always);
258   def(ExpandHeap_lock              , PaddedMutex  , leaf,        true,  _safepoint_check_always); // Used during compilation by VM thread
259   def(JNIHandleBlockFreeList_lock  , PaddedMutex  , leaf-1,      true,  _safepoint_check_never);      // handles are used by VM thread
260   def(SignatureHandlerLibrary_lock , PaddedMutex  , leaf,        false, _safepoint_check_always);
261   def(SymbolArena_lock             , PaddedMutex  , leaf+2,      true,  _safepoint_check_never);
262   def(ProfilePrint_lock            , PaddedMutex  , leaf,        false, _safepoint_check_always); // serial profile printing
263   def(ExceptionCache_lock          , PaddedMutex  , leaf,        false, _safepoint_check_always); // serial profile printing
264   def(Debug1_lock                  , PaddedMutex  , leaf,        true,  _safepoint_check_never);
265 #ifndef PRODUCT
266   def(FullGCALot_lock              , PaddedMutex  , leaf,        false, _safepoint_check_always); // a lock to make FullGCALot MT safe
267 #endif
268   def(BeforeExit_lock              , PaddedMonitor, leaf,        true,  _safepoint_check_always);
269   def(PerfDataMemAlloc_lock        , PaddedMutex  , leaf,        true,  _safepoint_check_always); // used for allocating PerfData memory for performance data
270   def(PerfDataManager_lock         , PaddedMutex  , leaf,        true,  _safepoint_check_always); // used for synchronized access to PerfDataManager resources
271 
272   def(Threads_lock                 , PaddedMonitor, barrier,     true,  _safepoint_check_always);  // Used for safepoint protocol.
273   def(NonJavaThreadsList_lock      , PaddedMutex,   leaf,        true,  _safepoint_check_never);
274   def(NonJavaThreadsListSync_lock  , PaddedMutex,   leaf,        true,  _safepoint_check_never);
275 
276   def(VMOperationQueue_lock        , PaddedMonitor, nonleaf,     true,  _safepoint_check_never);  // VM_thread allowed to block on these
277   def(VMOperationRequest_lock      , PaddedMonitor, nonleaf,     true,  _safepoint_check_always);
278   def(RetData_lock                 , PaddedMutex  , nonleaf,     false, _safepoint_check_always);
279   def(Terminator_lock              , PaddedMonitor, nonleaf,     true,  _safepoint_check_always);
280   def(InitCompleted_lock           , PaddedMonitor, leaf,        true,  _safepoint_check_never);
281   def(VtableStubs_lock             , PaddedMutex  , nonleaf,     true,  _safepoint_check_never);
282   def(Notify_lock                  , PaddedMonitor, nonleaf,     true,  _safepoint_check_always);
283   def(JNICritical_lock             , PaddedMonitor, nonleaf,     true,  _safepoint_check_always); // used for JNI critical regions
284   def(AdapterHandlerLibrary_lock   , PaddedMutex  , nonleaf,     true,  _safepoint_check_always);
285 
286   def(Heap_lock                    , PaddedMonitor, nonleaf+1,   false, _safepoint_check_sometimes);  // Doesn't safepoint check during termination.
287   def(JfieldIdCreation_lock        , PaddedMutex  , nonleaf+1,   true,  _safepoint_check_always); // jfieldID, Used in VM_Operation
288 
289   def(CompiledIC_lock              , PaddedMutex  , nonleaf+2,   false, _safepoint_check_never);      // locks VtableStubs_lock, InlineCacheBuffer_lock
290   def(CompileTaskAlloc_lock        , PaddedMutex  , nonleaf+2,   true,  _safepoint_check_always);
291   def(CompileStatistics_lock       , PaddedMutex  , nonleaf+2,   false, _safepoint_check_always);
292   def(DirectivesStack_lock         , PaddedMutex  , special,     true,  _safepoint_check_never);
293   def(MultiArray_lock              , PaddedMutex  , nonleaf+2,   false, _safepoint_check_always);
294 
295   def(JvmtiThreadState_lock        , PaddedMutex  , nonleaf+2,   false, _safepoint_check_always); // Used by JvmtiThreadState/JvmtiEventController
296   def(Management_lock              , PaddedMutex  , nonleaf+2,   false, _safepoint_check_always); // used for JVM management
297 
298   def(Compile_lock                 , PaddedMutex  , nonleaf+3,   false, _safepoint_check_always);
299   def(MethodData_lock              , PaddedMutex  , nonleaf+3,   false, _safepoint_check_always);
300   def(TouchedMethodLog_lock        , PaddedMutex  , nonleaf+3,   false, _safepoint_check_always);
301 
302   def(MethodCompileQueue_lock      , PaddedMonitor, nonleaf+4,   false, _safepoint_check_always);
303   def(Debug2_lock                  , PaddedMutex  , nonleaf+4,   true,  _safepoint_check_never);
304   def(Debug3_lock                  , PaddedMutex  , nonleaf+4,   true,  _safepoint_check_never);
305   def(CompileThread_lock           , PaddedMonitor, nonleaf+5,   false, _safepoint_check_always);
306   def(PeriodicTask_lock            , PaddedMonitor, nonleaf+5,   true,  _safepoint_check_always);
307   def(RedefineClasses_lock         , PaddedMonitor, nonleaf+5,   true,  _safepoint_check_always);
308   def(Verify_lock                  , PaddedMutex,   nonleaf+5,   true,  _safepoint_check_always);
309 
310   if (WhiteBoxAPI) {
311     def(Compilation_lock           , PaddedMonitor, leaf,        false, _safepoint_check_never);
312   }
313 
314 #if INCLUDE_JFR
315   def(JfrMsg_lock                  , PaddedMonitor, leaf,        true,  _safepoint_check_always);
316   def(JfrBuffer_lock               , PaddedMutex  , leaf,        true,  _safepoint_check_never);
317   def(JfrStream_lock               , PaddedMutex  , nonleaf + 1, false, _safepoint_check_never);
318   def(JfrStacktrace_lock           , PaddedMutex  , special,     true,  _safepoint_check_never);
319   def(JfrThreadSampler_lock        , PaddedMonitor, leaf,        true,  _safepoint_check_never);
320 #endif
321 
322 #ifndef SUPPORTS_NATIVE_CX8
323   def(UnsafeJlong_lock             , PaddedMutex  , special,     false, _safepoint_check_never);
324 #endif
325 
326   def(CodeHeapStateAnalytics_lock  , PaddedMutex  , leaf,        true,  _safepoint_check_never);
327   def(NMethodSweeperStats_lock     , PaddedMutex  , special,     true,  _safepoint_check_never);
328   def(ThreadsSMRDelete_lock        , PaddedMonitor, special,     true,  _safepoint_check_never);
329   def(ThreadIdTableCreate_lock     , PaddedMutex  , leaf,        false, _safepoint_check_always);
330   def(SharedDecoder_lock           , PaddedMutex  , native,      true,  _safepoint_check_never);
331   def(DCmdFactory_lock             , PaddedMutex  , leaf,        true,  _safepoint_check_never);
332 #if INCLUDE_NMT
333   def(NMTQuery_lock                , PaddedMutex  , max_nonleaf, false, _safepoint_check_always);
334 #endif
335 #if INCLUDE_CDS
336 #if INCLUDE_JVMTI
337   def(CDSClassFileStream_lock      , PaddedMutex  , max_nonleaf, false, _safepoint_check_always);
338 #endif
339   def(DumpTimeTable_lock           , PaddedMutex  , leaf,        true,  _safepoint_check_never);
340 #endif // INCLUDE_CDS
341 
342 #if INCLUDE_JVMCI
343   def(JVMCI_lock                   , PaddedMonitor, nonleaf+2,   true,  _safepoint_check_always);
344 #endif
345 }
346 
347 GCMutexLocker::GCMutexLocker(Mutex* mutex) {
348   if (SafepointSynchronize::is_at_safepoint()) {
349     _locked = false;
350   } else {
351     _mutex = mutex;
352     _locked = true;
353     _mutex->lock();
354   }
355 }
356 
357 // Print all mutexes/monitors that are currently owned by a thread; called
358 // by fatal error handler.
359 void print_owned_locks_on_error(outputStream* st) {
360   st->print("VM Mutex/Monitor currently owned by a thread: ");
361   bool none = true;
362   for (int i = 0; i < _num_mutex; i++) {
363      // see if it has an owner
364      if (_mutex_array[i]->owner() != NULL) {
365        if (none) {
366           // print format used by Mutex::print_on_error()
367           st->print_cr(" ([mutex/lock_event])");
368           none = false;
369        }
370        _mutex_array[i]->print_on_error(st);
371        st->cr();
372      }
373   }
374   if (none) st->print_cr("None");
375 }