1 /*
  2  * Copyright (c) 1998, 2024, 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_SYNCHRONIZER_HPP
 26 #define SHARE_RUNTIME_SYNCHRONIZER_HPP
 27 
 28 #include "memory/padded.hpp"
 29 #include "oops/markWord.hpp"
 30 #include "runtime/basicLock.hpp"
 31 #include "runtime/handles.hpp"
 32 #include "utilities/resourceHash.hpp"
 33 
 34 template <typename T> class GrowableArray;
 35 class LogStream;
 36 class ObjectMonitor;
 37 class ObjectMonitorDeflationSafepointer;
 38 class ThreadsList;
 39 
 40 class MonitorList {
 41   friend class VMStructs;
 42 
 43 private:
 44   ObjectMonitor* volatile _head;
 45   volatile size_t _count;
 46   volatile size_t _max;
 47 
 48 public:
 49   void add(ObjectMonitor* monitor);
 50   size_t unlink_deflated(size_t deflated_count,
 51                          GrowableArray<ObjectMonitor*>* unlinked_list,
 52                          ObjectMonitorDeflationSafepointer* safepointer);
 53   size_t count() const;
 54   size_t max() const;
 55 
 56   class Iterator;
 57   Iterator iterator() const;
 58 };
 59 
 60 class MonitorList::Iterator {
 61   ObjectMonitor* _current;
 62 
 63 public:
 64   Iterator(ObjectMonitor* head) : _current(head) {}
 65   bool has_next() const { return _current != nullptr; }
 66   ObjectMonitor* next();
 67 };
 68 
 69 class ObjectSynchronizer : AllStatic {
 70   friend class VMStructs;
 71   friend class ObjectMonitorDeflationLogging;
 72   friend class WhiteBox;
 73 
 74  public:
 75   typedef enum {
 76     inflate_cause_vm_internal = 0,
 77     inflate_cause_monitor_enter = 1,
 78     inflate_cause_wait = 2,
 79     inflate_cause_notify = 3,
 80     inflate_cause_hash_code = 4,
 81     inflate_cause_jni_enter = 5,
 82     inflate_cause_jni_exit = 6,
 83     inflate_cause_nof = 7 // Number of causes
 84   } InflateCause;
 85 
 86   typedef enum {
 87     NOT_ENABLED    = 0,
 88     FATAL_EXIT     = 1,
 89     LOG_WARNING    = 2
 90   } SyncDiagnosticOption;
 91 
 92   // exit must be implemented non-blocking, since the compiler cannot easily handle
 93   // deoptimization at monitor exit. Hence, it does not take a Handle argument.
 94 
 95   // This is the "slow path" version of monitor enter and exit.
 96   static void enter(Handle obj, BasicLock* lock, JavaThread* current);
 97   static void exit(oop obj, BasicLock* lock, JavaThread* current);
 98   // Used to enter a monitor for another thread. This requires that the
 99   // locking_thread is suspended, and that entering on a potential
100   // inflated monitor may only contend with deflation. That is the obj being
101   // locked on is either already locked by the locking_thread or cannot
102   // escape the locking_thread.
103   static void enter_for(Handle obj, BasicLock* lock, JavaThread* locking_thread);
104 private:
105   // Shared implementation for enter and enter_for. Performs all but
106   // inflated monitor enter.
107   static bool enter_fast_impl(Handle obj, BasicLock* lock, JavaThread* locking_thread);
108 
109 public:
110   // Used only to handle jni locks or other unmatched monitor enter/exit
111   // Internally they will use heavy weight monitor.
112   static void jni_enter(Handle obj, JavaThread* current);
113   static void jni_exit(oop obj, TRAPS);
114 
115   // Handle all interpreter, compiler and jni cases
116   static int  wait(Handle obj, jlong millis, TRAPS);
117   static void notify(Handle obj, TRAPS);
118   static void notifyall(Handle obj, TRAPS);
119 
120   static bool quick_notify(oopDesc* obj, JavaThread* current, bool All);
121   static bool quick_enter(oop obj, JavaThread* current, BasicLock* Lock);
122 
123   // Special internal-use-only method for use by JVM infrastructure
124   // that needs to wait() on a java-level object but that can't risk
125   // throwing unexpected InterruptedExecutionExceptions.
126   static void waitUninterruptibly(Handle obj, jlong Millis, TRAPS);
127 
128   // Inflate light weight monitor to heavy weight monitor
129   static ObjectMonitor* inflate(Thread* current, oop obj, const InflateCause cause);
130   // Used to inflate a monitor as if it was done from the thread JavaThread.
131   static ObjectMonitor* inflate_for(JavaThread* thread, oop obj, const InflateCause cause);
132 
133 private:
134   // Shared implementation between the different LockingMode.
135   static ObjectMonitor* inflate_impl(JavaThread* thread, oop obj, const InflateCause cause);
136 
137 public:
138   // This version is only for internal use
139   static void inflate_helper(oop obj);
140   static const char* inflate_cause_name(const InflateCause cause);
141 
142   // Returns the identity hash value for an oop
143   // NOTE: It may cause monitor inflation
144   static intptr_t FastHashCode(Thread* current, oop obj);
145 
146   // java.lang.Thread support
147   static bool current_thread_holds_lock(JavaThread* current, Handle h_obj);
148 
149   static JavaThread* get_lock_owner(ThreadsList * t_list, Handle h_obj);
150 
151   // JNI detach support
152   static void release_monitors_owned_by_thread(JavaThread* current);
153 
154   // Iterate over all ObjectMonitors.
155   template <typename Function>
156   static void monitors_iterate(Function function);
157 
158   // Iterate ObjectMonitors owned by any thread and where the owner `filter`
159   // returns true.
160   template <typename OwnerFilter>
161   static void owned_monitors_iterate_filtered(MonitorClosure* closure, OwnerFilter filter);
162 
163   // Iterate ObjectMonitors where the owner == thread; this does NOT include
164   // ObjectMonitors where owner is set to a stack lock address in thread.
165   static void owned_monitors_iterate(MonitorClosure* m, JavaThread* thread);
166 
167   // Iterate ObjectMonitors owned by any thread.
168   static void owned_monitors_iterate(MonitorClosure* closure);
169 
170   // Initialize the gInflationLocks
171   static void initialize();
172 
173   // We currently use aggressive monitor deflation policy;
174   // basically we try to deflate all monitors that are not busy.
175   static size_t deflate_idle_monitors();
176 
177   // Deflate idle monitors:
178   static size_t deflate_monitor_list(ObjectMonitorDeflationSafepointer* safepointer);
179   static size_t in_use_list_ceiling();
180   static void dec_in_use_list_ceiling();
181   static void inc_in_use_list_ceiling();
182   static void set_in_use_list_ceiling(size_t new_value);
183   static bool is_async_deflation_needed();
184   static bool is_async_deflation_requested() { return _is_async_deflation_requested; }
185   static bool is_final_audit() { return _is_final_audit; }
186   static void set_is_final_audit() { _is_final_audit = true; }
187   static jlong last_async_deflation_time_ns() { return _last_async_deflation_time_ns; }
188   static void request_deflate_idle_monitors();
189   static bool request_deflate_idle_monitors_from_wb();  // for whitebox test support
190   static void set_is_async_deflation_requested(bool new_value) { _is_async_deflation_requested = new_value; }
191   static jlong time_since_last_async_deflation_ms();
192 
193   // debugging
194   static void audit_and_print_stats(outputStream* out, bool on_exit);
195   static void chk_in_use_list(outputStream* out, int* error_cnt_p);
196   static void chk_in_use_entry(ObjectMonitor* n, outputStream* out,
197                                int* error_cnt_p);
198   static void do_final_audit_and_print_stats();
199   static void log_in_use_monitor_details(outputStream* out, bool log_all);
200 
201  private:
202   friend class SynchronizerTest;
203 
204   static MonitorList _in_use_list;
205   static volatile bool _is_async_deflation_requested;
206   static volatile bool _is_final_audit;
207   static jlong         _last_async_deflation_time_ns;
208 
209   // Support for SynchronizerTest access to GVars fields:
210   static u_char* get_gvars_addr();
211   static u_char* get_gvars_hc_sequence_addr();
212   static size_t get_gvars_size();
213   static u_char* get_gvars_stw_random_addr();
214 
215   static void handle_sync_on_value_based_class(Handle obj, JavaThread* locking_thread);
216 };
217 
218 // ObjectLocker enforces balanced locking and can never throw an
219 // IllegalMonitorStateException. However, a pending exception may
220 // have to pass through, and we must also be able to deal with
221 // asynchronous exceptions. The caller is responsible for checking
222 // the thread's pending exception if needed.
223 class ObjectLocker : public StackObj {
224  private:
225   JavaThread* _thread;
226   Handle      _obj;
227   BasicLock   _lock;
228  public:
229   ObjectLocker(Handle obj, JavaThread* current);
230   ~ObjectLocker();
231 
232   // Monitor behavior
233   void wait(TRAPS)  { ObjectSynchronizer::wait(_obj, 0, CHECK); } // wait forever
234   void wait_uninterruptibly(TRAPS)  { ObjectSynchronizer::waitUninterruptibly(_obj, 0, CHECK); } // wait forever
235   void notify_all(TRAPS)  { ObjectSynchronizer::notifyall(_obj, CHECK); }
236 };
237 
238 // Interface to visit monitors
239 class ObjectMonitorsView {
240 public:
241   // Visit monitors that belong to the given thread
242   virtual void visit(MonitorClosure* closure, JavaThread* thread) = 0;
243 };
244 
245 #endif // SHARE_RUNTIME_SYNCHRONIZER_HPP