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