1 /*
  2  * Copyright (c) 1998, 2023, 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 
144   // Used only to handle jni locks or other unmatched monitor enter/exit
145   // Internally they will use heavy weight monitor.
146   static void jni_enter(Handle obj, JavaThread* current);
147   static void jni_exit(oop obj, TRAPS);
148 
149   // Handle all interpreter, compiler and jni cases
150   static int  wait(Handle obj, jlong millis, TRAPS);
151   static void notify(Handle obj, TRAPS);
152   static void notifyall(Handle obj, TRAPS);
153 
154   static bool quick_notify(oopDesc* obj, JavaThread* current, bool All);
155   static bool quick_enter(oop obj, JavaThread* current, BasicLock* Lock);
156 
157   // Inflate light weight monitor to heavy weight monitor
158   static ObjectMonitor* inflate(Thread* current, oop obj, const InflateCause cause);
159   // This version is only for internal use
160   static void inflate_helper(oop obj);
161   static const char* inflate_cause_name(const InflateCause cause);
162 
163   // Returns the identity hash value for an oop
164   // NOTE: It may cause monitor inflation
165   static intptr_t FastHashCode(Thread* current, oop obj);
166 
167   // java.lang.Thread support
168   static bool current_thread_holds_lock(JavaThread* current, Handle h_obj);
169 
170   static JavaThread* get_lock_owner(ThreadsList * t_list, Handle h_obj);
171 
172   // JNI detach support
173   static void release_monitors_owned_by_thread(JavaThread* current);
174 
175   // Iterate ObjectMonitors where the owner == thread; this does NOT include
176   // ObjectMonitors where owner is set to a stack lock address in thread:
177   //
178   // This version of monitors_iterate() works with the in-use monitor list.
179   static void monitors_iterate(MonitorClosure* m, JavaThread* thread);
180   // This version of monitors_iterate() works with the specified linked list.
181   static void monitors_iterate(MonitorClosure* closure,
182                                ObjectMonitorsHashtable::PtrList* list,
183                                JavaThread* thread);
184 
185   // Initialize the gInflationLocks
186   static void initialize();
187 
188   // GC: we currently use aggressive monitor deflation policy
189   // Basically we try to deflate all monitors that are not busy.
190   static size_t deflate_idle_monitors(ObjectMonitorsHashtable* table);
191 
192   // Deflate idle monitors:
193   static void chk_for_block_req(JavaThread* current, const char* op_name,
194                                 const char* cnt_name, size_t cnt, LogStream* ls,
195                                 elapsedTimer* timer_p);
196   static size_t deflate_monitor_list(Thread* current, LogStream* ls, elapsedTimer* timer_p,
197                                      ObjectMonitorsHashtable* table);
198   static size_t in_use_list_ceiling();
199   static void dec_in_use_list_ceiling();
200   static void inc_in_use_list_ceiling();
201   static void set_in_use_list_ceiling(size_t new_value);
202   static bool is_async_deflation_needed();
203   static bool is_async_deflation_requested() { return _is_async_deflation_requested; }
204   static bool is_final_audit() { return _is_final_audit; }
205   static void set_is_final_audit() { _is_final_audit = true; }
206   static jlong last_async_deflation_time_ns() { return _last_async_deflation_time_ns; }
207   static bool request_deflate_idle_monitors();  // for whitebox test support
208   static void set_is_async_deflation_requested(bool new_value) { _is_async_deflation_requested = new_value; }
209   static jlong time_since_last_async_deflation_ms();
210 
211   // debugging
212   static void audit_and_print_stats(bool on_exit);
213   static void chk_in_use_list(outputStream* out, int* error_cnt_p);
214   static void chk_in_use_entry(ObjectMonitor* n, outputStream* out,
215                                int* error_cnt_p);
216   static void do_final_audit_and_print_stats();
217   static void log_in_use_monitor_details(outputStream* out);
218 
219  private:
220   friend class SynchronizerTest;
221 
222   static MonitorList _in_use_list;
223   static volatile bool _is_async_deflation_requested;
224   static volatile bool _is_final_audit;
225   static jlong         _last_async_deflation_time_ns;
226 
227   // Support for SynchronizerTest access to GVars fields:
228   static u_char* get_gvars_addr();
229   static u_char* get_gvars_hc_sequence_addr();
230   static size_t get_gvars_size();
231   static u_char* get_gvars_stw_random_addr();
232 
233   static void handle_sync_on_value_based_class(Handle obj, JavaThread* current);
234 };
235 
236 // ObjectLocker enforces balanced locking and can never throw an
237 // IllegalMonitorStateException. However, a pending exception may
238 // have to pass through, and we must also be able to deal with
239 // asynchronous exceptions. The caller is responsible for checking
240 // the thread's pending exception if needed.
241 class ObjectLocker : public StackObj {
242  private:
243   JavaThread* _thread;
244   Handle      _obj;
245   BasicLock   _lock;
246  public:
247   ObjectLocker(Handle obj, JavaThread* current);
248   ~ObjectLocker();
249 
250   // Monitor behavior
251   void wait(TRAPS)  { ObjectSynchronizer::wait(_obj, 0, CHECK); } // wait forever
252   void notify_all(TRAPS)  { ObjectSynchronizer::notifyall(_obj, CHECK); }
253 };
254 
255 #endif // SHARE_RUNTIME_SYNCHRONIZER_HPP