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