1 /*
  2  * Copyright (c) 1997, 2025, 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 #ifndef SHARE_RUNTIME_MUTEXLOCKER_HPP
 26 #define SHARE_RUNTIME_MUTEXLOCKER_HPP
 27 
 28 #include "logging/log.hpp"
 29 #include "memory/allocation.hpp"
 30 #include "runtime/flags/flagSetting.hpp"
 31 #include "runtime/mutex.hpp"
 32 #include "runtime/perfData.hpp"
 33 
 34 class Thread;
 35 
 36 // Mutexes used in the VM.
 37 
 38 extern Mutex*   NMethodState_lock;               // a lock used to guard a compiled method state
 39 extern Monitor* SystemDictionary_lock;           // a lock on the system dictionary
 40 extern Mutex*   InvokeMethodTypeTable_lock;
 41 extern Monitor* InvokeMethodIntrinsicTable_lock;
 42 extern Mutex*   SharedDictionary_lock;           // a lock on the CDS shared dictionary
 43 extern Monitor* ClassInitError_lock;             // a lock on the class initialization error table
 44 extern Mutex*   Module_lock;                     // a lock on module and package related data structures
 45 extern Mutex*   CompiledIC_lock;                 // a lock used to guard compiled IC patching and access
 46 extern Mutex*   VMStatistic_lock;                // a lock used to guard statistics count increment
 47 extern Mutex*   JmethodIdCreation_lock;          // a lock on creating JNI method identifiers
 48 extern Mutex*   JfieldIdCreation_lock;           // a lock on creating JNI static field identifiers
 49 extern Monitor* JNICritical_lock;                // a lock used while synchronizing with threads entering/leaving JNI critical regions
 50 extern Mutex*   JvmtiThreadState_lock;           // a lock on modification of JVMTI thread data
 51 extern Monitor* EscapeBarrier_lock;              // a lock to sync reallocating and relocking objects because of JVMTI access
 52 extern Monitor* JvmtiVTMSTransition_lock;        // a lock for Virtual Thread Mount State transition (VTMS transition) management
 53 extern Mutex*   JvmtiVThreadSuspend_lock;        // a lock for virtual threads suspension
 54 extern Monitor* Heap_lock;                       // a lock on the heap
 55 #if INCLUDE_PARALLELGC
 56 extern Mutex*   PSOldGenExpand_lock;         // a lock on expanding the heap
 57 #endif
 58 extern Mutex*   AdapterHandlerLibrary_lock;      // a lock on the AdapterHandlerLibrary
 59 extern Mutex*   SignatureHandlerLibrary_lock;    // a lock on the SignatureHandlerLibrary
 60 extern Mutex*   VtableStubs_lock;                // a lock on the VtableStubs
 61 extern Mutex*   SymbolArena_lock;                // a lock on the symbol table arena
 62 extern Monitor* StringDedup_lock;                // a lock on the string deduplication facility
 63 extern Mutex*   StringDedupIntern_lock;          // a lock on StringTable notification of StringDedup
 64 extern Monitor* CodeCache_lock;                  // a lock on the CodeCache
 65 extern Mutex*   TouchedMethodLog_lock;           // a lock on allocation of LogExecutedMethods info
 66 extern Mutex*   RetData_lock;                    // a lock on installation of RetData inside method data
 67 extern Monitor* VMOperation_lock;                // a lock on queue of vm_operations waiting to execute
 68 extern Monitor* ThreadsLockThrottle_lock;        // used by Thread start/exit to reduce competition for Threads_lock,
 69                                                  // so a VM thread calling a safepoint is prioritized
 70 extern Monitor* Threads_lock;                    // a lock on the Threads table of active Java threads
 71                                                  // (also used by Safepoints too to block threads creation/destruction)
 72 extern Mutex*   NonJavaThreadsList_lock;         // a lock on the NonJavaThreads list
 73 extern Mutex*   NonJavaThreadsListSync_lock;     // a lock for NonJavaThreads list synchronization
 74 extern Monitor* CGC_lock;                        // used for coordination between
 75                                                  // fore- & background GC threads.
 76 extern Monitor* STS_lock;                        // used for joining/leaving SuspendibleThreadSet.
 77 extern Monitor* G1OldGCCount_lock;               // in support of "concurrent" full gc
 78 extern Mutex*   G1RareEvent_lock;                // Synchronizes (rare) parallel GC operations.
 79 extern Mutex*   G1DetachedRefinementStats_lock;  // Lock protecting detached refinement stats
 80 extern Mutex*   MarkStackFreeList_lock;          // Protects access to the global mark stack free list.
 81 extern Mutex*   MarkStackChunkList_lock;         // Protects access to the global mark stack chunk list.
 82 extern Mutex*   MonitoringSupport_lock;          // Protects updates to the serviceability memory pools and allocated memory high water mark.
 83 extern Monitor* ConcurrentGCBreakpoints_lock;    // Protects concurrent GC breakpoint management
 84 extern Mutex*   Compile_lock;                    // a lock held when Compilation is updating code (used to block CodeCache traversal, CHA updates, etc)
 85 extern Monitor* MethodCompileQueue_lock;         // a lock held when method compilations are enqueued, dequeued
 86 extern Monitor* MethodCompileQueueC1_lock;       // a lock held when method compilations are enqueued, dequeued
 87 extern Monitor* MethodCompileQueueC2_lock;       // a lock held when method compilations are enqueued, dequeued
 88 extern Monitor* MethodCompileQueueC3_lock;       // a lock held when method compilations are enqueued, dequeued
 89 extern Monitor* MethodCompileQueueSC1_lock;      // a lock held when method compilations are enqueued, dequeued
 90 extern Monitor* MethodCompileQueueSC2_lock;      // a lock held when method compilations are enqueued, dequeued
 91 extern Monitor* CompileThread_lock;              // a lock held by compile threads during compilation system initialization
 92 extern Monitor* Compilation_lock;                // a lock used to pause compilation
 93 extern Mutex*   TrainingData_lock;               // a lock used when accessing training records
 94 extern Monitor* TrainingReplayQueue_lock;        // a lock held when class are added/removed to the training replay queue
 95 extern Monitor* CompileTaskAlloc_lock;           // a lock held when CompileTasks are allocated
 96 extern Mutex*   CompileStatistics_lock;          // a lock held when updating compilation statistics
 97 extern Mutex*   DirectivesStack_lock;            // a lock held when mutating the dirstack and ref counting directives
 98 extern Monitor* Terminator_lock;                 // a lock used to guard termination of the vm
 99 extern Monitor* InitCompleted_lock;              // a lock used to signal threads waiting on init completed
100 extern Monitor* BeforeExit_lock;                 // a lock used to guard cleanups and shutdown hooks
101 extern Monitor* Notify_lock;                     // a lock used to synchronize the start-up of the vm
102 extern Mutex*   ExceptionCache_lock;             // a lock used to synchronize exception cache updates
103 
104 #ifndef PRODUCT
105 extern Mutex*   FullGCALot_lock;                 // a lock to make FullGCALot MT safe
106 #endif // PRODUCT
107 
108 extern Mutex*   RawMonitor_lock;
109 extern Mutex*   PerfDataMemAlloc_lock;           // a lock on the allocator for PerfData memory for performance data
110 extern Mutex*   PerfDataManager_lock;            // a long on access to PerfDataManager resources
111 
112 extern Mutex*   FreeList_lock;                   // protects the free region list during safepoints
113 extern Mutex*   OldSets_lock;                    // protects the old region sets
114 extern Mutex*   Uncommit_lock;                   // protects the uncommit list when not at safepoints
115 extern Monitor* RootRegionScan_lock;             // used to notify that the CM threads have finished scanning the IM snapshot regions
116 
117 extern Mutex*   Management_lock;                 // a lock used to serialize JVM management
118 extern Monitor* MonitorDeflation_lock;           // a lock used for monitor deflation thread operation
119 extern Monitor* Service_lock;                    // a lock used for service thread operation
120 extern Monitor* Notification_lock;               // a lock used for notification thread operation
121 extern Monitor* PeriodicTask_lock;               // protects the periodic task structure
122 extern Monitor* RedefineClasses_lock;            // locks classes from parallel redefinition
123 extern Mutex*   Verify_lock;                     // synchronize initialization of verify library
124 extern Monitor* ThreadsSMRDelete_lock;           // Used by ThreadsSMRSupport to take pressure off the Threads_lock
125 extern Mutex*   ThreadIdTableCreate_lock;        // Used by ThreadIdTable to lazily create the thread id table
126 extern Mutex*   SharedDecoder_lock;              // serializes access to the decoder during normal (not error reporting) use
127 extern Mutex*   DCmdFactory_lock;                // serialize access to DCmdFactory information
128 extern Mutex*   NMTQuery_lock;                   // serialize NMT Dcmd queries
129 extern Mutex*   NMTCompilationCostHistory_lock;  // guards NMT compilation cost history
130 extern Mutex*   NmtVirtualMemory_lock;           // guards NMT virtual memory updates
131 #if INCLUDE_CDS
132 #if INCLUDE_JVMTI
133 extern Mutex*   CDSClassFileStream_lock;         // FileMapInfo::open_stream_for_jvmti
134 #endif
135 extern Mutex*   DumpTimeTable_lock;              // SystemDictionaryShared::_dumptime_table
136 extern Mutex*   CDSLambda_lock;                  // LambdaProxyClassDictionary::find_lambda_proxy_class
137 extern Mutex*   DumpRegion_lock;                 // Symbol::operator new(size_t sz, int len)
138 extern Mutex*   ClassListFile_lock;              // ClassListWriter()
139 extern Mutex*   UnregisteredClassesTable_lock;   // UnregisteredClassesTableTable
140 extern Mutex*   LambdaFormInvokers_lock;         // Protecting LambdaFormInvokers::_lambdaform_lines
141 extern Mutex*   ScratchObjects_lock;             // Protecting _scratch_xxx_table in heapShared.cpp
142 extern Mutex*   ArchivedObjectTables_lock;       // Protecting the table used by HeapShared::get_archived_object_permanent_index()
143 extern Mutex*   FinalImageRecipes_lock;          // Protecting the tables used by FinalImageRecipes.
144 #endif // INCLUDE_CDS
145 #if INCLUDE_JFR
146 extern Mutex*   JfrStacktrace_lock;              // used to guard access to the JFR stacktrace table
147 extern Monitor* JfrMsg_lock;                     // protects JFR messaging
148 extern Mutex*   JfrBuffer_lock;                  // protects JFR buffer operations
149 #endif
150 
151 extern Mutex*   Metaspace_lock;                  // protects Metaspace virtualspace and chunk expansions
152 extern Monitor* MetaspaceCritical_lock;          // synchronizes failed metaspace allocations that risk throwing metaspace OOM
153 extern Mutex*   ClassLoaderDataGraph_lock;       // protects CLDG list, needed for concurrent unloading
154 
155 
156 extern Mutex*   CodeHeapStateAnalytics_lock;     // lock print functions against concurrent analyze functions.
157                                                  // Only used locally in PrintCodeCacheLayout processing.
158 
159 extern Mutex*   ExternalsRecorder_lock;          // used to guard access to the external addresses table
160 
161 extern Mutex*   AOTCodeCStrings_lock;            // used to guard access to the AOT code C strings table
162 
163 extern Monitor* ContinuationRelativize_lock;
164 
165 #if INCLUDE_JVMCI
166 extern Monitor* JVMCI_lock;                      // protects global JVMCI critical sections
167 extern Monitor* JVMCIRuntime_lock;               // protects critical sections for a specific JVMCIRuntime object
168 #endif
169 
170 extern Mutex*   Bootclasspath_lock;
171 
172 extern Mutex*   tty_lock;                          // lock to synchronize output.
173 
174 // A MutexLocker provides mutual exclusion with respect to a given mutex
175 // for the scope which contains the locker.  The lock is an OS lock, not
176 // an object lock, and the two do not interoperate.  Do not use Mutex-based
177 // locks to lock on Java objects, because they will not be respected if a
178 // that object is locked using the Java locking mechanism.
179 //
180 //                NOTE WELL!!
181 //
182 // See orderAccess.hpp.  We assume throughout the VM that MutexLocker's
183 // and friends constructors do a fence, a lock and an acquire *in that
184 // order*.  And that their destructors do a release and unlock, in *that*
185 // order.  If their implementations change such that these assumptions
186 // are violated, a whole lot of code will break.
187 
188 // for debugging: check that we're already owning this lock (or are at a safepoint / handshake)
189 #ifdef ASSERT
190 void assert_locked_or_safepoint(const Mutex* lock);
191 void assert_lock_strong(const Mutex* lock);
192 #else
193 #define assert_locked_or_safepoint(lock)
194 #define assert_lock_strong(lock)
195 #endif
196 
197 // Internal implementation. Skips on null Mutex.
198 // Subclasses enforce stronger invariants.
199 class MutexLockerImpl: public StackObj {
200  protected:
201   Mutex* _mutex;
202   bool _prof;
203   elapsedTimer _before;
204   elapsedTimer _after;
205 
206 private:
207   static PerfCounter** _perf_lock_count;
208   static PerfCounter** _perf_lock_wait_time;
209   static PerfCounter** _perf_lock_hold_time;
210 
211 public:
212 
213   MutexLockerImpl(Mutex* mutex, Mutex::SafepointCheckFlag flag = Mutex::_safepoint_check_flag);
214 
215   MutexLockerImpl(Thread* thread, Mutex* mutex, Mutex::SafepointCheckFlag flag = Mutex::_safepoint_check_flag);
216 
217   ~MutexLockerImpl() {
218     if (_mutex != nullptr) {
219       assert_lock_strong(_mutex);
220       _mutex->unlock();
221 
222       if (_mutex->id() == -1) {
223         log_trace(init)("Unnamed unclassified lock: %s", _mutex->name());
224       }
225 
226       if (_prof) {
227         assert(UsePerfData, "required");
228         _after.stop();
229         _perf_lock_count    [_mutex->id() + 1]->inc();
230         _perf_lock_wait_time[_mutex->id() + 1]->inc(_before.ticks());
231         _perf_lock_hold_time[_mutex->id() + 1]->inc(_after.ticks());
232       }
233     }
234   }
235 
236  private:
237   static void print_counter_on(outputStream* st, const char* name, bool is_unique, int idx);
238 
239  public:
240   static int name2id(const char* name);
241 
242   static void post_initialize();
243   static void init_counters();
244   static void print_counters_on(outputStream* st);
245 };
246 
247 // Simplest mutex locker.
248 // Does not allow null mutexes.
249 class MutexLocker: public MutexLockerImpl {
250  public:
251    MutexLocker(Mutex* mutex, Mutex::SafepointCheckFlag flag = Mutex::_safepoint_check_flag) :
252      MutexLockerImpl(mutex, flag) {
253      assert(mutex != nullptr, "null mutex not allowed");
254    }
255 
256    MutexLocker(Thread* thread, Mutex* mutex, Mutex::SafepointCheckFlag flag = Mutex::_safepoint_check_flag) :
257      MutexLockerImpl(thread, mutex, flag) {
258      assert(mutex != nullptr, "null mutex not allowed");
259    }
260 };
261 
262 // Conditional mutex locker.
263 // Like MutexLocker above, but only locks when condition is true.
264 class ConditionalMutexLocker: public MutexLockerImpl {
265  public:
266    ConditionalMutexLocker(Mutex* mutex, bool condition, Mutex::SafepointCheckFlag flag = Mutex::_safepoint_check_flag) :
267      MutexLockerImpl(condition ? mutex : nullptr, flag) {
268      assert(!condition || mutex != nullptr, "null mutex not allowed when locking");
269    }
270 
271    ConditionalMutexLocker(Thread* thread, Mutex* mutex, bool condition, Mutex::SafepointCheckFlag flag = Mutex::_safepoint_check_flag) :
272      MutexLockerImpl(thread, condition ? mutex : nullptr, flag) {
273      assert(!condition || mutex != nullptr, "null mutex not allowed when locking");
274    }
275 };
276 
277 // A MonitorLocker is like a MutexLocker above, except it allows
278 // wait/notify as well which are delegated to the underlying Monitor.
279 // It also disallows null.
280 class MonitorLocker: public MutexLockerImpl {
281   Mutex::SafepointCheckFlag _flag;
282 
283  protected:
284   Monitor* as_monitor() const {
285     return static_cast<Monitor*>(_mutex);
286   }
287 
288  public:
289   MonitorLocker(Monitor* monitor, Mutex::SafepointCheckFlag flag = Mutex::_safepoint_check_flag) :
290     MutexLockerImpl(monitor, flag), _flag(flag) {
291     // Superclass constructor did locking
292     assert(monitor != nullptr, "null monitor not allowed");
293   }
294 
295   MonitorLocker(Thread* thread, Monitor* monitor, Mutex::SafepointCheckFlag flag = Mutex::_safepoint_check_flag) :
296     MutexLockerImpl(thread, monitor, flag), _flag(flag) {
297     // Superclass constructor did locking
298     assert(monitor != nullptr, "null monitor not allowed");
299   }
300 
301   bool wait(int64_t timeout = 0) {
302     return _flag == Mutex::_safepoint_check_flag ?
303       as_monitor()->wait(timeout) : as_monitor()->wait_without_safepoint_check(timeout);
304   }
305 
306   void notify_all() {
307     as_monitor()->notify_all();
308   }
309 
310   void notify() {
311     as_monitor()->notify();
312   }
313 };
314 
315 
316 // A GCMutexLocker is usually initialized with a mutex that is
317 // automatically acquired in order to do GC.  The function that
318 // synchronizes using a GCMutexLocker may be called both during and between
319 // GC's.  Thus, it must acquire the mutex if GC is not in progress, but not
320 // if GC is in progress (since the mutex is already held on its behalf.)
321 
322 class GCMutexLocker: public StackObj {
323 private:
324   Mutex* _mutex;
325   bool _locked;
326 public:
327   GCMutexLocker(Mutex* mutex);
328   ~GCMutexLocker() { if (_locked) _mutex->unlock(); }
329 };
330 
331 // A MutexUnlocker temporarily exits a previously
332 // entered mutex for the scope which contains the unlocker.
333 
334 class MutexUnlocker: StackObj {
335  private:
336   Mutex* _mutex;
337   bool _no_safepoint_check;
338 
339  public:
340   MutexUnlocker(Mutex* mutex, Mutex::SafepointCheckFlag flag = Mutex::_safepoint_check_flag) :
341     _mutex(mutex),
342     _no_safepoint_check(flag == Mutex::_no_safepoint_check_flag) {
343     _mutex->unlock();
344   }
345 
346   ~MutexUnlocker() {
347     if (_no_safepoint_check) {
348       _mutex->lock_without_safepoint_check();
349     } else {
350       _mutex->lock();
351     }
352   }
353 };
354 
355 // Instance of a RecursiveLock that may be held through Java heap allocation, which may include calls to Java,
356 // and JNI event notification for resource exhaustion for metaspace or heap.
357 extern RecursiveMutex* MultiArray_lock;
358 
359 // RAII locker for a RecursiveMutex.  See comments in mutex.hpp for more information.
360 class RecursiveLocker {
361   RecursiveMutex* _lock;
362   Thread*         _thread;
363  public:
364   RecursiveLocker(RecursiveMutex* lock, Thread* current) : _lock(lock), _thread(current) {
365     _lock->lock(_thread);
366   }
367   ~RecursiveLocker() {
368     _lock->unlock(_thread);
369   }
370 };
371 
372 #endif // SHARE_RUNTIME_MUTEXLOCKER_HPP