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 ThreadsList;
 38 
 39 // Hash table of void* to a list of ObjectMonitor* owned by the JavaThread.
 40 // The JavaThread's owner key is either a JavaThread* or a stack lock
 41 // address in the JavaThread so we use "void*".
 42 //
 43 class ObjectMonitorsHashtable {
 44  private:
 45   static unsigned int ptr_hash(void* const& s1) {
 46     // 2654435761 = 2^32 * Phi (golden ratio)
 47     return (unsigned int)(((uint32_t)(uintptr_t)s1) * 2654435761u);
 48   }
 49 
 50  public:
 51   class PtrList;
 52 
 53  private:
 54   // ResourceHashtable SIZE is specified at compile time so we
 55   // use 1031 which is the first prime after 1024.
 56   typedef ResourceHashtable<void*, PtrList*, 1031, AnyObj::C_HEAP, mtThread,
 57                             &ObjectMonitorsHashtable::ptr_hash> PtrTable;
 58   PtrTable* _ptrs;
 59   size_t _key_count;
 60   size_t _om_count;
 61 
 62  public:
 63   // ResourceHashtable is passed to various functions and populated in
 64   // different places so we allocate it using C_HEAP to make it immune
 65   // from any ResourceMarks that happen to be in the code paths.
 66   ObjectMonitorsHashtable() : _ptrs(new (mtThread) PtrTable), _key_count(0), _om_count(0) {}
 67 
 68   ~ObjectMonitorsHashtable();
 69 
 70   void add_entry(void* key, ObjectMonitor* om);
 71 
 72   void add_entry(void* key, PtrList* list) {
 73     _ptrs->put(key, list);
 74     _key_count++;
 75   }
 76 
 77   PtrList* get_entry(void* key) {
 78     PtrList** listpp = _ptrs->get(key);
 79     return (listpp == nullptr) ? nullptr : *listpp;
 80   }
 81 
 82   bool has_entry(void* key, ObjectMonitor* om);
 83 
 84   size_t key_count() { return _key_count; }
 85   size_t om_count() { return _om_count; }
 86 };
 87 
 88 class MonitorList {
 89   friend class VMStructs;
 90 
 91 private:
 92   ObjectMonitor* volatile _head;
 93   volatile size_t _count;
 94   volatile size_t _max;
 95 
 96 public:
 97   void add(ObjectMonitor* monitor);
 98   size_t unlink_deflated(Thread* current, LogStream* ls, elapsedTimer* timer_p,
 99                          GrowableArray<ObjectMonitor*>* unlinked_list);
100   size_t count() const;
101   size_t max() const;
102 
103   class Iterator;
104   Iterator iterator() const;
105 };
106 
107 class MonitorList::Iterator {
108   ObjectMonitor* _current;
109 
110 public:
111   Iterator(ObjectMonitor* head) : _current(head) {}
112   bool has_next() const { return _current != nullptr; }
113   ObjectMonitor* next();
114 };
115 
116 class ObjectSynchronizer : AllStatic {
117   friend class VMStructs;
118 
119  public:
120   typedef enum {
121     inflate_cause_vm_internal = 0,
122     inflate_cause_monitor_enter = 1,
123     inflate_cause_wait = 2,
124     inflate_cause_notify = 3,
125     inflate_cause_hash_code = 4,
126     inflate_cause_jni_enter = 5,
127     inflate_cause_jni_exit = 6,
128     inflate_cause_nof = 7 // Number of causes
129   } InflateCause;
130 
131   typedef enum {
132     NOT_ENABLED    = 0,
133     FATAL_EXIT     = 1,
134     LOG_WARNING    = 2
135   } SyncDiagnosticOption;
136 
137   // exit must be implemented non-blocking, since the compiler cannot easily handle
138   // deoptimization at monitor exit. Hence, it does not take a Handle argument.
139 
140   // This is the "slow path" version of monitor enter and exit.
141   static void enter(Handle obj, BasicLock* lock, JavaThread* current);
142   static void exit(oop obj, BasicLock* lock, JavaThread* current);
143   // Used to enter a monitor for another thread. This requires that the
144   // locking_thread is suspended, and that entering on a potential
145   // inflated monitor may only contend with deflation. That is the obj being
146   // locked on is either already locked by the locking_thread or cannot
147   // escape the locking_thread.
148   static void enter_for(Handle obj, BasicLock* lock, JavaThread* locking_thread);
149 private:
150   // Shared implementation for enter and enter_for. Performs all but
151   // inflated monitor enter.
152   static bool enter_fast_impl(Handle obj, BasicLock* lock, JavaThread* locking_thread);
153 
154 public:
155   // Used only to handle jni locks or other unmatched monitor enter/exit
156   // Internally they will use heavy weight monitor.
157   static void jni_enter(Handle obj, JavaThread* current);
158   static void jni_exit(oop obj, TRAPS);
159 
160   // Handle all interpreter, compiler and jni cases
161   static int  wait(Handle obj, jlong millis, TRAPS);
162   static void notify(Handle obj, TRAPS);
163   static void notifyall(Handle obj, TRAPS);
164 
165   static bool quick_notify(oopDesc* obj, JavaThread* current, bool All);
166   static bool quick_enter(oop obj, JavaThread* current, BasicLock* Lock);
167 
168   // Inflate light weight monitor to heavy weight monitor
169   static ObjectMonitor* inflate(Thread* current, oop obj, const InflateCause cause);
170   // Used to inflate a monitor as if it was done from the thread JavaThread.
171   static ObjectMonitor* inflate_for(JavaThread* thread, oop obj, const InflateCause cause);
172 
173 private:
174   // Shared implementation between the different LockingMode.
175   static ObjectMonitor* inflate_impl(JavaThread* thread, oop obj, const InflateCause cause);
176 
177 public:
178   // This version is only for internal use
179   static void inflate_helper(oop obj);
180   static const char* inflate_cause_name(const InflateCause cause);
181 
182   // Returns the identity hash value for an oop
183   // NOTE: It may cause monitor inflation
184   static intptr_t FastHashCode(Thread* current, oop obj);
185 
186   // java.lang.Thread support
187   static bool current_thread_holds_lock(JavaThread* current, Handle h_obj);
188 
189   static JavaThread* get_lock_owner(ThreadsList * t_list, Handle h_obj);
190 
191   // JNI detach support
192   static void release_monitors_owned_by_thread(JavaThread* current);
193 
194   // Iterate ObjectMonitors where the owner == thread; this does NOT include
195   // ObjectMonitors where owner is set to a stack lock address in thread:
196   //
197   // This version of monitors_iterate() works with the in-use monitor list.
198   static void monitors_iterate(MonitorClosure* m, JavaThread* thread);
199   // This version of monitors_iterate() works with the specified linked list.
200   static void monitors_iterate(MonitorClosure* closure,
201                                ObjectMonitorsHashtable::PtrList* list,
202                                JavaThread* thread);
203 
204   // Initialize the gInflationLocks
205   static void initialize();
206 
207   // GC: we currently use aggressive monitor deflation policy
208   // Basically we try to deflate all monitors that are not busy.
209   static size_t deflate_idle_monitors(ObjectMonitorsHashtable* table);
210 
211   // Deflate idle monitors:
212   static void chk_for_block_req(JavaThread* current, const char* op_name,
213                                 const char* cnt_name, size_t cnt, LogStream* ls,
214                                 elapsedTimer* timer_p);
215   static size_t deflate_monitor_list(Thread* current, LogStream* ls, elapsedTimer* timer_p,
216                                      ObjectMonitorsHashtable* table);
217   static size_t in_use_list_ceiling();
218   static void dec_in_use_list_ceiling();
219   static void inc_in_use_list_ceiling();
220   static void set_in_use_list_ceiling(size_t new_value);
221   static bool is_async_deflation_needed();
222   static bool is_async_deflation_requested() { return _is_async_deflation_requested; }
223   static bool is_final_audit() { return _is_final_audit; }
224   static void set_is_final_audit() { _is_final_audit = true; }
225   static jlong last_async_deflation_time_ns() { return _last_async_deflation_time_ns; }
226   static bool request_deflate_idle_monitors();  // for whitebox test support
227   static void set_is_async_deflation_requested(bool new_value) { _is_async_deflation_requested = new_value; }
228   static jlong time_since_last_async_deflation_ms();
229 
230   // debugging
231   static void audit_and_print_stats(bool on_exit);
232   static void chk_in_use_list(outputStream* out, int* error_cnt_p);
233   static void chk_in_use_entry(ObjectMonitor* n, outputStream* out,
234                                int* error_cnt_p);
235   static void do_final_audit_and_print_stats();
236   static void log_in_use_monitor_details(outputStream* out);
237 
238  private:
239   friend class SynchronizerTest;
240 
241   static MonitorList _in_use_list;
242   static volatile bool _is_async_deflation_requested;
243   static volatile bool _is_final_audit;
244   static jlong         _last_async_deflation_time_ns;
245 
246   // Support for SynchronizerTest access to GVars fields:
247   static u_char* get_gvars_addr();
248   static u_char* get_gvars_hc_sequence_addr();
249   static size_t get_gvars_size();
250   static u_char* get_gvars_stw_random_addr();
251 
252   static void handle_sync_on_value_based_class(Handle obj, JavaThread* locking_thread);
253 };
254 
255 // ObjectLocker enforces balanced locking and can never throw an
256 // IllegalMonitorStateException. However, a pending exception may
257 // have to pass through, and we must also be able to deal with
258 // asynchronous exceptions. The caller is responsible for checking
259 // the thread's pending exception if needed.
260 class ObjectLocker : public StackObj {
261  private:
262   JavaThread* _thread;
263   Handle      _obj;
264   BasicLock   _lock;
265  public:
266   ObjectLocker(Handle obj, JavaThread* current);
267   ~ObjectLocker();
268 
269   // Monitor behavior
270   void wait(TRAPS)  { ObjectSynchronizer::wait(_obj, 0, CHECK); } // wait forever
271   void notify_all(TRAPS)  { ObjectSynchronizer::notifyall(_obj, CHECK); }
272 };
273 
274 #endif // SHARE_RUNTIME_SYNCHRONIZER_HPP