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*   JmethodIdCreation_lock       = NULL;
 52 Mutex*   JfieldIdCreation_lock        = NULL;
 53 Monitor* JNICritical_lock             = NULL;
 54 Mutex*   JvmtiThreadState_lock        = NULL;
 55 Monitor* EscapeBarrier_lock           = NULL;
 56 Monitor* Heap_lock                    = NULL;
 57 Mutex*   ExpandHeap_lock              = NULL;
 58 Mutex*   AdapterHandlerLibrary_lock   = NULL;
 59 Mutex*   SignatureHandlerLibrary_lock = NULL;
 60 Mutex*   VtableStubs_lock             = NULL;
 61 Mutex*   SymbolArena_lock             = NULL;
 62 Monitor* StringDedup_lock             = NULL;
 63 Mutex*   StringDedupIntern_lock       = NULL;
 64 Monitor* CodeCache_lock               = NULL;
 65 Monitor* CodeSweeper_lock             = NULL;
 66 Mutex*   MethodData_lock              = NULL;
 67 Mutex*   TouchedMethodLog_lock        = NULL;
 68 Mutex*   RetData_lock                 = NULL;
 69 Monitor* VMOperation_lock             = NULL;
 70 Monitor* Threads_lock                 = NULL;
 71 Mutex*   NonJavaThreadsList_lock      = NULL;
 72 Mutex*   NonJavaThreadsListSync_lock  = NULL;
 73 Monitor* CGC_lock                     = NULL;
 74 Monitor* STS_lock                     = NULL;
 75 Monitor* G1OldGCCount_lock            = NULL;
 76 Mutex*   G1DetachedRefinementStats_lock = NULL;
 77 Mutex*   MarkStackFreeList_lock       = NULL;
 78 Mutex*   MarkStackChunkList_lock      = NULL;
 79 Mutex*   MonitoringSupport_lock       = NULL;
 80 Mutex*   ParGCRareEvent_lock          = NULL;
 81 Monitor* ConcurrentGCBreakpoints_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*   ExceptionCache_lock          = NULL;
 95 Mutex*   NMethodSweeperStats_lock     = NULL;
 96 #ifndef PRODUCT
 97 Mutex*   FullGCALot_lock              = NULL;
 98 #endif
 99 
100 Mutex*   tty_lock                     = NULL;
101 
102 Mutex*   RawMonitor_lock              = NULL;
103 Mutex*   PerfDataMemAlloc_lock        = NULL;
104 Mutex*   PerfDataManager_lock         = NULL;
105 Mutex*   OopMapCacheAlloc_lock        = NULL;
106 
107 Mutex*   FreeList_lock                = NULL;
108 Mutex*   OldSets_lock                 = NULL;
109 Mutex*   Uncommit_lock                = NULL;
110 Monitor* RootRegionScan_lock          = NULL;
111 
112 Mutex*   Management_lock              = NULL;
113 Monitor* MonitorDeflation_lock        = NULL;
114 Monitor* Service_lock                 = NULL;
115 Monitor* Notification_lock            = NULL;
116 Monitor* PeriodicTask_lock            = NULL;
117 Monitor* RedefineClasses_lock         = NULL;
118 Mutex*   Verify_lock                  = NULL;
119 Monitor* Zip_lock                     = NULL;
120 
121 #if INCLUDE_JFR
122 Mutex*   JfrStacktrace_lock           = NULL;
123 Monitor* JfrMsg_lock                  = NULL;
124 Mutex*   JfrBuffer_lock               = NULL;
125 Monitor* JfrThreadSampler_lock        = NULL;
126 #endif
127 
128 #ifndef SUPPORTS_NATIVE_CX8
129 Mutex*   UnsafeJlong_lock             = NULL;
130 #endif
131 Mutex*   CodeHeapStateAnalytics_lock  = NULL;
132 
133 Mutex*   Metaspace_lock               = NULL;
134 Monitor* MetaspaceCritical_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, ...) {            \
203   var = new type(Mutex::pri, #var, ##__VA_ARGS__); \
204   add_mutex(var);                             \
205 }
206 
207 // Specify relative ranked lock
208 #ifdef ASSERT
209 #define defl(var, type, held_lock, ...) {         \
210   var = new type(held_lock->rank()-1, #var, ##__VA_ARGS__); \
211   add_mutex(var);                                      \
212 }
213 #else
214 #define defl(var, type, held_lock, ...) {         \
215   var = new type(Mutex::safepoint, #var, ##__VA_ARGS__); \
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);      // allow to lock in VM
223 
224   def(STS_lock                     , PaddedMonitor, nosafepoint);
225 
226   if (UseG1GC) {
227     def(CGC_lock                   , PaddedMonitor, nosafepoint);
228 
229     def(G1DetachedRefinementStats_lock, PaddedMutex, nosafepoint-2);
230 
231     def(FreeList_lock              , PaddedMutex  , service-1);
232     def(OldSets_lock               , PaddedMutex  , nosafepoint);
233     def(Uncommit_lock              , PaddedMutex  , service-2);
234     def(RootRegionScan_lock        , PaddedMonitor, nosafepoint-1);
235 
236     def(MarkStackFreeList_lock     , PaddedMutex  , nosafepoint);
237     def(MarkStackChunkList_lock    , PaddedMutex  , nosafepoint);
238 
239     def(MonitoringSupport_lock     , PaddedMutex  , service-1);      // used for serviceability monitoring support
240   }
241   def(StringDedup_lock             , PaddedMonitor, nosafepoint);
242   def(StringDedupIntern_lock       , PaddedMutex  , nosafepoint);
243   def(ParGCRareEvent_lock          , PaddedMutex  , safepoint, true);
244   def(RawMonitor_lock              , PaddedMutex  , nosafepoint-1);
245 
246   def(Metaspace_lock               , PaddedMutex  , nosafepoint-3);
247   def(MetaspaceCritical_lock       , PaddedMonitor, nosafepoint-1);
248 
249   def(Patching_lock                , PaddedMutex  , nosafepoint);      // used for safepointing and code patching.
250   def(MonitorDeflation_lock        , PaddedMonitor, nosafepoint);      // used for monitor deflation thread operations
251   def(Service_lock                 , PaddedMonitor, service);      // used for service thread operations
252 
253   if (UseNotificationThread) {
254     def(Notification_lock          , PaddedMonitor, service);  // used for notification thread operations
255   } else {
256     Notification_lock = Service_lock;
257   }
258 
259   def(JmethodIdCreation_lock       , PaddedMutex  , nosafepoint-2); // used for creating jmethodIDs.
260 
261   def(SharedDictionary_lock        , PaddedMutex  , safepoint);
262   def(VMStatistic_lock             , PaddedMutex  , safepoint);
263   def(SignatureHandlerLibrary_lock , PaddedMutex  , safepoint);
264   def(SymbolArena_lock             , PaddedMutex  , nosafepoint);
265   def(ExceptionCache_lock          , PaddedMutex  , safepoint);
266 #ifndef PRODUCT
267   def(FullGCALot_lock              , PaddedMutex  , safepoint); // a lock to make FullGCALot MT safe
268 #endif
269   def(BeforeExit_lock              , PaddedMonitor, safepoint);
270 
271   def(NonJavaThreadsList_lock      , PaddedMutex,   nosafepoint-1);
272   def(NonJavaThreadsListSync_lock  , PaddedMutex,   nosafepoint);
273 
274   def(RetData_lock                 , PaddedMutex  , safepoint);
275   def(Terminator_lock              , PaddedMonitor, safepoint, true);
276   def(InitCompleted_lock           , PaddedMonitor, nosafepoint);
277   def(Notify_lock                  , PaddedMonitor, safepoint, true);
278   def(AdapterHandlerLibrary_lock   , PaddedMutex  , safepoint);
279 
280   def(Heap_lock                    , PaddedMonitor, safepoint); // Doesn't safepoint check during termination.
281   def(JfieldIdCreation_lock        , PaddedMutex  , safepoint);
282 
283   def(CompiledIC_lock              , PaddedMutex  , nosafepoint);  // locks VtableStubs_lock, InlineCacheBuffer_lock
284   def(MethodCompileQueue_lock      , PaddedMonitor, safepoint);
285   def(CompileStatistics_lock       , PaddedMutex  , safepoint);
286   def(DirectivesStack_lock         , PaddedMutex  , nosafepoint);
287   def(MultiArray_lock              , PaddedMutex  , safepoint);
288 
289   def(JvmtiThreadState_lock        , PaddedMutex  , safepoint); // Used by JvmtiThreadState/JvmtiEventController
290   def(EscapeBarrier_lock           , PaddedMonitor, nosafepoint);  // Used to synchronize object reallocation/relocking triggered by JVMTI
291   def(Management_lock              , PaddedMutex  , safepoint); // used for JVM management
292 
293   def(ConcurrentGCBreakpoints_lock , PaddedMonitor, safepoint, true);
294   def(MethodData_lock              , PaddedMutex  , safepoint);
295   def(TouchedMethodLog_lock        , PaddedMutex  , safepoint);
296 
297   def(CompileThread_lock           , PaddedMonitor, safepoint);
298   def(PeriodicTask_lock            , PaddedMonitor, safepoint, true);
299   def(RedefineClasses_lock         , PaddedMonitor, safepoint);
300   def(Verify_lock                  , PaddedMutex,   safepoint);
301 
302   if (WhiteBoxAPI) {
303     def(Compilation_lock           , PaddedMonitor, nosafepoint);
304   }
305 
306 #if INCLUDE_JFR
307   def(JfrBuffer_lock               , PaddedMutex  , nosafepoint);
308   def(JfrMsg_lock                  , PaddedMonitor, nosafepoint-3);
309   def(JfrStacktrace_lock           , PaddedMutex  , stackwatermark-1);
310   def(JfrThreadSampler_lock        , PaddedMonitor, nosafepoint);
311 #endif
312 
313 #ifndef SUPPORTS_NATIVE_CX8
314   def(UnsafeJlong_lock             , PaddedMutex  , nosafepoint);
315 #endif
316 
317   def(CodeHeapStateAnalytics_lock  , PaddedMutex  , safepoint);
318   def(NMethodSweeperStats_lock     , PaddedMutex  , nosafepoint);
319   def(ThreadsSMRDelete_lock        , PaddedMonitor, nosafepoint-3); // Holds ConcurrentHashTableResize_lock
320   def(ThreadIdTableCreate_lock     , PaddedMutex  , safepoint);
321   def(SharedDecoder_lock           , PaddedMutex  , tty-1);
322   def(DCmdFactory_lock             , PaddedMutex  , nosafepoint);
323 #if INCLUDE_NMT
324   def(NMTQuery_lock                , PaddedMutex  , safepoint);
325 #endif
326 #if INCLUDE_CDS
327 #if INCLUDE_JVMTI
328   def(CDSClassFileStream_lock      , PaddedMutex  , safepoint);
329 #endif
330   def(DumpTimeTable_lock           , PaddedMutex  , nosafepoint);
331   def(CDSLambda_lock               , PaddedMutex  , nosafepoint);
332   def(DumpRegion_lock              , PaddedMutex  , nosafepoint);
333   def(ClassListFile_lock           , PaddedMutex  , nosafepoint);
334   def(LambdaFormInvokers_lock      , PaddedMutex  , safepoint);
335 #endif // INCLUDE_CDS
336   def(Bootclasspath_lock           , PaddedMutex  , nosafepoint);
337   def(Zip_lock                     , PaddedMonitor, nosafepoint-1); // Holds DumpTimeTable_lock
338 
339 #if INCLUDE_JVMCI
340   def(JVMCI_lock                   , PaddedMonitor, safepoint, true);
341 #endif
342 
343   // These locks have relative rankings, and inherit safepoint checking attributes from that rank.
344   defl(InlineCacheBuffer_lock      , PaddedMutex  , CompiledIC_lock);
345   defl(VtableStubs_lock            , PaddedMutex  , CompiledIC_lock);  // Also holds DumpTimeTable_lock
346   defl(CodeCache_lock              , PaddedMonitor, VtableStubs_lock);
347   defl(CompiledMethod_lock         , PaddedMutex  , CodeCache_lock);
348   defl(CodeSweeper_lock            , PaddedMonitor, CompiledMethod_lock);
349 
350   defl(Threads_lock                , PaddedMonitor, CompileThread_lock, true);
351   defl(Heap_lock                   , PaddedMonitor, MultiArray_lock);
352   defl(Compile_lock                , PaddedMutex ,  MethodCompileQueue_lock);
353 
354   defl(PerfDataMemAlloc_lock       , PaddedMutex  , Heap_lock);
355   defl(PerfDataManager_lock        , PaddedMutex  , Heap_lock);
356   defl(ClassLoaderDataGraph_lock   , PaddedMutex  , MultiArray_lock);
357   defl(VMOperation_lock            , PaddedMonitor, Compile_lock, true);
358   defl(ClassInitError_lock         , PaddedMonitor, Threads_lock);
359 
360   if (UseG1GC) {
361     defl(G1OldGCCount_lock         , PaddedMonitor, Threads_lock, true);
362   }
363   defl(CompileTaskAlloc_lock       , PaddedMutex ,  MethodCompileQueue_lock);
364   defl(ExpandHeap_lock             , PaddedMutex ,  Heap_lock, true);
365   defl(OopMapCacheAlloc_lock       , PaddedMutex ,  Threads_lock, true);
366   defl(Module_lock                 , PaddedMutex ,  ClassLoaderDataGraph_lock);
367   defl(SystemDictionary_lock       , PaddedMonitor, Module_lock);
368   defl(JNICritical_lock            , PaddedMonitor, MultiArray_lock); // used for JNI critical regions
369 }
370 
371 GCMutexLocker::GCMutexLocker(Mutex* mutex) {
372   if (SafepointSynchronize::is_at_safepoint()) {
373     _locked = false;
374   } else {
375     _mutex = mutex;
376     _locked = true;
377     _mutex->lock();
378   }
379 }
380 
381 // Print all mutexes/monitors that are currently owned by a thread; called
382 // by fatal error handler.
383 void print_owned_locks_on_error(outputStream* st) {
384   st->print("VM Mutex/Monitor currently owned by a thread: ");
385   bool none = true;
386   for (int i = 0; i < _num_mutex; i++) {
387      // see if it has an owner
388      if (_mutex_array[i]->owner() != NULL) {
389        if (none) {
390           // print format used by Mutex::print_on_error()
391           st->print_cr(" ([mutex/lock_event])");
392           none = false;
393        }
394        _mutex_array[i]->print_on_error(st);
395        st->cr();
396      }
397   }
398   if (none) st->print_cr("None");
399 }