1 /*
  2  * Copyright (c) 1998, 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_OBJECTMONITOR_HPP
 26 #define SHARE_RUNTIME_OBJECTMONITOR_HPP
 27 
 28 #include "memory/allocation.hpp"
 29 #include "memory/padded.hpp"
 30 #include "oops/markWord.hpp"
 31 #include "oops/oopHandle.hpp"
 32 #include "oops/weakHandle.hpp"
 33 #include "runtime/javaThread.hpp"
 34 #include "utilities/checkedCast.hpp"
 35 #include "utilities/globalDefinitions.hpp"
 36 
 37 class ObjectMonitor;
 38 class ObjectMonitorContentionMark;
 39 class ParkEvent;
 40 class BasicLock;
 41 class ContinuationWrapper;
 42 
 43 
 44 class ObjectWaiter : public CHeapObj<mtThread> {
 45  public:
 46   enum TStates : uint8_t { TS_UNDEF, TS_READY, TS_RUN, TS_WAIT, TS_ENTER };
 47   ObjectWaiter* volatile _next;
 48   ObjectWaiter* volatile _prev;
 49   JavaThread*     _thread;
 50   OopHandle      _vthread;
 51   ObjectMonitor* _monitor;
 52   uint64_t  _notifier_tid;
 53   int         _recursions;
 54   volatile TStates TState;
 55   volatile bool _notified;
 56   bool           _is_wait;
 57   bool        _at_reenter;
 58   bool       _interrupted;
 59   bool     _interruptible;
 60   bool     _do_timed_park;
 61   bool            _active;    // Contention monitoring is enabled
 62  public:
 63   ObjectWaiter(JavaThread* current);
 64   ObjectWaiter(oop vthread, ObjectMonitor* mon);
 65   ~ObjectWaiter();
 66   JavaThread* thread()      const { return _thread; }
 67   bool is_vthread()         const { return _thread == nullptr; }
 68   uint8_t state()           const { return TState; }
 69   ObjectMonitor* monitor()  const { return _monitor; }
 70   bool is_wait()            const { return _is_wait; }
 71   bool notified()           const { return _notified; }
 72   bool at_reenter()         const { return _at_reenter; }
 73   bool at_monitorenter()    const { return !_is_wait || _at_reenter || _notified; }
 74   oop vthread() const;
 75   void wait_reenter_begin(ObjectMonitor *mon);
 76   void wait_reenter_end(ObjectMonitor *mon);
 77 
 78   void set_bad_pointers() {
 79 #ifdef ASSERT
 80     this->_prev  = (ObjectWaiter*) badAddressVal;
 81     this->_next  = (ObjectWaiter*) badAddressVal;
 82     this->TState = ObjectWaiter::TS_RUN;
 83 #endif
 84   }
 85   ObjectWaiter* next() {
 86     assert (_next != (ObjectWaiter*) badAddressVal, "corrupted list!");
 87     return _next;
 88   }
 89   ObjectWaiter* prev() {
 90     assert (_prev != (ObjectWaiter*) badAddressVal, "corrupted list!");
 91     return _prev;
 92   }
 93 };
 94 
 95 // The ObjectMonitor class implements the heavyweight version of a
 96 // JavaMonitor. The lightweight BasicLock/stack lock version has been
 97 // inflated into an ObjectMonitor. This inflation is typically due to
 98 // contention or use of Object.wait().
 99 //
100 // WARNING: This is a very sensitive and fragile class. DO NOT make any
101 // changes unless you are fully aware of the underlying semantics.
102 //
103 // ObjectMonitor Layout Overview/Highlights/Restrictions:
104 //
105 // - For performance reasons we ensure the _metadata field is located at offset 0,
106 //   which in turn means that ObjectMonitor can't inherit from any other class nor use
107 //   any virtual member functions.
108 // - The _metadata and _owner fields should be separated by enough space
109 //   to avoid false sharing due to parallel access by different threads.
110 //   This is an advisory recommendation.
111 // - The general layout of the fields in ObjectMonitor is:
112 //     _metadata
113 //     <lightly_used_fields>
114 //     <optional padding>
115 //     _owner
116 //     <optional padding>
117 //     <remaining_fields>
118 // - The VM assumes write ordering and machine word alignment with
119 //   respect to the _owner field and the <remaining_fields> that can
120 //   be read in parallel by other threads.
121 // - Generally fields that are accessed closely together in time should
122 //   be placed proximally in space to promote data cache locality. That
123 //   is, temporal locality should condition spatial locality.
124 // - We have to balance avoiding false sharing with excessive invalidation
125 //   from coherence traffic. As such, we try to cluster fields that tend
126 //   to be _written_ at approximately the same time onto the same data
127 //   cache line.
128 // - We also have to balance the natural tension between minimizing
129 //   single threaded capacity misses with excessive multi-threaded
130 //   coherency misses. There is no single optimal layout for both
131 //   single-threaded and multi-threaded environments.
132 //
133 // - See TEST_VM(ObjectMonitor, sanity) gtest for how critical restrictions are
134 //   enforced.
135 //
136 // - Separating _owner from the <remaining_fields> by enough space to
137 //   avoid false sharing might be profitable. Given that the CAS in
138 //   monitorenter will invalidate the line underlying _owner. We want
139 //   to avoid an L1 data cache miss on that same line for monitorexit.
140 //   Putting these <remaining_fields>:
141 //   _recursions, _entry_list and _succ, all of which may be
142 //   fetched in the inflated unlock path, on a different cache line
143 //   would make them immune to CAS-based invalidation from the _owner
144 //   field.
145 //
146 // - TODO: The _recursions field should be of type int, or int32_t but not
147 //   intptr_t. There's no reason to use a 64-bit type for this field
148 //   in a 64-bit JVM.
149 
150 #define OM_CACHE_LINE_SIZE DEFAULT_CACHE_LINE_SIZE
151 
152 class ObjectMonitor : public CHeapObj<mtObjectMonitor> {
153   friend class VMStructs;
154   JVMCI_ONLY(friend class JVMCIVMStructs;)
155 
156   static OopStorage* _oop_storage;
157 
158   // List of j.l.VirtualThread waiting to be unblocked by unblocker thread.
159   static OopHandle _vthread_list_head;
160   // ParkEvent of unblocker thread.
161   static ParkEvent* _vthread_unparker_ParkEvent;
162 
163   // Because of frequent access, the metadata field is at offset zero (0).
164   // Enforced by the assert() in metadata_addr().
165   // * Lightweight locking with UseObjectMonitorTable:
166   //   Contains the _object's hashCode.
167   // * * Lightweight locking without UseObjectMonitorTable:
168   // Contains the displaced object header word - mark
169   volatile uintptr_t _metadata;     // metadata
170   WeakHandle _object;               // backward object pointer
171   // Separate _metadata and _owner on different cache lines since both can
172   // have busy multi-threaded access. _metadata and _object are set at initial
173   // inflation. The _object does not change, so it is a good choice to share
174   // its cache line with _metadata.
175   DEFINE_PAD_MINUS_SIZE(0, OM_CACHE_LINE_SIZE, sizeof(_metadata) +
176                         sizeof(WeakHandle));
177 
178   static const int64_t NO_OWNER = 0;
179   static const int64_t ANONYMOUS_OWNER = 1;
180   static const int64_t DEFLATER_MARKER = 2;
181 
182   int64_t volatile _owner;  // Either owner_id of owner, NO_OWNER, ANONYMOUS_OWNER or DEFLATER_MARKER.
183   volatile uint64_t _previous_owner_tid;  // thread id of the previous owner of the monitor
184   // Separate _owner and _next_om on different cache lines since
185   // both can have busy multi-threaded access. _previous_owner_tid is only
186   // changed by ObjectMonitor::exit() so it is a good choice to share the
187   // cache line with _owner.
188   DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(void* volatile) +
189                         sizeof(volatile uint64_t));
190   ObjectMonitor* _next_om;          // Next ObjectMonitor* linkage
191   volatile intx _recursions;        // recursion count, 0 for first entry
192   ObjectWaiter* volatile _entry_list;  // Threads blocked on entry or reentry.
193                                        // The list is actually composed of wait-nodes,
194                                        // acting as proxies for Threads.
195   ObjectWaiter* volatile _entry_list_tail; // _entry_list is the head, this is the tail.
196   int64_t volatile _succ;           // Heir presumptive thread - used for futile wakeup throttling
197 
198   volatile int _SpinDuration;
199 
200   int _contentions;                 // Number of active contentions in enter(). It is used by is_busy()
201                                     // along with other fields to determine if an ObjectMonitor can be
202                                     // deflated. It is also used by the async deflation protocol. See
203                                     // ObjectMonitor::deflate_monitor().
204   int64_t _unmounted_vthreads;      // Number of nodes in the _entry_list associated with unmounted vthreads.
205                                     // It might be temporarily more than the actual number but never less.
206   OopHandle _object_strong;         // Used to protect object during preemption on class initialization
207 
208   ObjectWaiter* volatile _wait_set; // LL of threads waiting on the monitor - wait()
209   volatile int  _waiters;           // number of waiting threads
210   volatile int _wait_set_lock;      // protects wait set queue - simple spinlock
211   volatile int _object_strong_lock; // protects setting of _object_strong
212 
213  public:
214 
215   static void Initialize();
216   static void Initialize2();
217 
218   static OopHandle& vthread_list_head() { return _vthread_list_head; }
219   static ParkEvent* vthread_unparker_ParkEvent() { return _vthread_unparker_ParkEvent; }
220 
221   static int Knob_SpinLimit;
222 
223   static ByteSize metadata_offset()    { return byte_offset_of(ObjectMonitor, _metadata); }
224   static ByteSize owner_offset()       { return byte_offset_of(ObjectMonitor, _owner); }
225   static ByteSize recursions_offset()  { return byte_offset_of(ObjectMonitor, _recursions); }
226   static ByteSize succ_offset()        { return byte_offset_of(ObjectMonitor, _succ); }
227   static ByteSize entry_list_offset()  { return byte_offset_of(ObjectMonitor, _entry_list); }
228 
229   // ObjectMonitor references can be ORed with markWord::monitor_value
230   // as part of the ObjectMonitor tagging mechanism. When we combine an
231   // ObjectMonitor reference with an offset, we need to remove the tag
232   // value in order to generate the proper address.
233   //
234   // We can either adjust the ObjectMonitor reference and then add the
235   // offset or we can adjust the offset that is added to the ObjectMonitor
236   // reference. The latter avoids an AGI (Address Generation Interlock)
237   // stall so the helper macro adjusts the offset value that is returned
238   // to the ObjectMonitor reference manipulation code:
239   //
240   #define OM_OFFSET_NO_MONITOR_VALUE_TAG(f) \
241     ((in_bytes(ObjectMonitor::f ## _offset())) - checked_cast<int>(markWord::monitor_value))
242 
243   uintptr_t           metadata() const;
244   void                set_metadata(uintptr_t value);
245   volatile uintptr_t* metadata_addr();
246 
247   markWord            header() const;
248   void                set_header(markWord hdr);
249 
250   intptr_t            hash() const;
251   void                set_hash(intptr_t hash);
252 
253   bool is_busy() const {
254     // TODO-FIXME: assert _owner == NO_OWNER implies _recursions = 0
255     intptr_t ret_code = intptr_t(_waiters) | intptr_t(_entry_list);
256     int cnts = contentions(); // read once
257     if (cnts > 0) {
258       ret_code |= intptr_t(cnts);
259     }
260     if (!owner_is_DEFLATER_MARKER()) {
261       ret_code |= intptr_t(owner_raw());
262     }
263     return ret_code != 0;
264   }
265   const char* is_busy_to_string(stringStream* ss);
266 
267   bool is_entered(JavaThread* current) const;
268 
269   // Returns true if this OM has an owner, false otherwise.
270   bool      has_owner() const;
271   int64_t   owner() const;  // Returns NO_OWNER if DEFLATER_MARKER is observed.
272   int64_t   owner_raw() const;
273 
274   // These methods return the value we set in _owner when acquiring
275   // the monitor with the given thread/vthread, AKA owner_id.
276   static int64_t owner_id_from(JavaThread* thread);
277   static int64_t owner_id_from(oop vthread);
278 
279   // Returns true if owner field == DEFLATER_MARKER and false otherwise.
280   bool      owner_is_DEFLATER_MARKER() const;
281   // Returns true if 'this' is being async deflated and false otherwise.
282   bool      is_being_async_deflated();
283   // Clear _owner field; current value must match thread's owner_id.
284   void      release_clear_owner(JavaThread* thread);
285   // Simply set _owner field to new_value; current value must match old_value.
286   void      set_owner_from_raw(int64_t old_value, int64_t new_value);
287   // Same as above but uses owner_id of current as new value.
288   void      set_owner_from(int64_t old_value, JavaThread* current);
289   // Try to set _owner field to new_value if the current value matches
290   // old_value, using AtomicAccess::cmpxchg(). Otherwise, does not change the
291   // _owner field. Returns the prior value of the _owner field.
292   int64_t   try_set_owner_from_raw(int64_t old_value, int64_t new_value);
293   // Same as above but uses owner_id of current as new_value.
294   int64_t   try_set_owner_from(int64_t old_value, JavaThread* current);
295 
296   // Methods to check and set _succ. The successor is the thread selected
297   // from _entry_list by the current owner when releasing the monitor,
298   // to run again and re-try acquiring the monitor. It is used to avoid
299   // unnecessary wake-ups if there is already a successor set.
300   bool      has_successor() const;
301   bool      has_successor(JavaThread* thread) const;
302   void      set_successor(JavaThread* thread);
303   void      set_successor(oop vthread);
304   void      clear_successor();
305   int64_t   successor() const;
306 
307   // Returns true if _owner field == owner_id of thread, false otherwise.
308   bool has_owner(JavaThread* thread) const { return owner() == owner_id_from(thread); }
309   // Set _owner field to owner_id of thread; current value must be NO_OWNER.
310   void set_owner(JavaThread* thread) { set_owner_from(NO_OWNER, thread); }
311   // Try to set _owner field from NO_OWNER to owner_id of thread.
312   bool try_set_owner(JavaThread* thread) {
313     return try_set_owner_from(NO_OWNER, thread) == NO_OWNER;
314   }
315 
316   bool has_anonymous_owner() const { return owner_raw() == ANONYMOUS_OWNER; }
317   void set_anonymous_owner() {
318     set_owner_from_raw(NO_OWNER, ANONYMOUS_OWNER);
319   }
320   void set_owner_from_anonymous(JavaThread* owner) {
321     set_owner_from(ANONYMOUS_OWNER, owner);
322   }
323 
324   // Simply get _next_om field.
325   ObjectMonitor* next_om() const;
326   // Simply set _next_om field to new_value.
327   void set_next_om(ObjectMonitor* new_value);
328 
329   int       contentions() const;
330   void      add_to_contentions(int value);
331   intx      recursions() const                                         { return _recursions; }
332   void      set_recursions(size_t recursions);
333   void      increment_recursions(JavaThread* current);
334   void      inc_unmounted_vthreads();
335   void      dec_unmounted_vthreads();
336   bool      has_unmounted_vthreads() const;
337 
338   // JVM/TI GetObjectMonitorUsage() needs this:
339   int waiters() const;
340   ObjectWaiter* first_waiter()                                         { return _wait_set; }
341   ObjectWaiter* next_waiter(ObjectWaiter* o)                           { return o->_next; }
342   JavaThread* thread_of_waiter(ObjectWaiter* o)                        { return o->_thread; }
343 
344   ObjectMonitor(oop object);
345   ~ObjectMonitor();
346 
347   oop       object() const;
348   oop       object_peek() const;
349   bool      object_is_dead() const;
350   bool      object_refers_to(oop obj) const;
351   void      set_object_strong();
352 
353   // Returns true if the specified thread owns the ObjectMonitor. Otherwise
354   // returns false and throws IllegalMonitorStateException (IMSE).
355   bool      check_owner(TRAPS);
356 
357  private:
358   class ExitOnSuspend {
359    protected:
360     ObjectMonitor* _om;
361     bool _om_exited;
362    public:
363     ExitOnSuspend(ObjectMonitor* om) : _om(om), _om_exited(false) {}
364     void operator()(JavaThread* current);
365     bool exited() { return _om_exited; }
366   };
367   class ClearSuccOnSuspend {
368    protected:
369     ObjectMonitor* _om;
370    public:
371     ClearSuccOnSuspend(ObjectMonitor* om) : _om(om)  {}
372     void operator()(JavaThread* current);
373   };
374 
375   bool      enter_is_async_deflating();
376   void      notify_contended_enter(JavaThread *current);
377  public:
378   void      enter_for_with_contention_mark(JavaThread* locking_thread, ObjectMonitorContentionMark& contention_mark);
379   bool      enter_for(JavaThread* locking_thread);
380   bool      enter(JavaThread* current);
381   bool      try_enter(JavaThread* current, bool check_for_recursion = true);
382   bool      spin_enter(JavaThread* current);
383   void      enter_with_contention_mark(JavaThread* current, ObjectMonitorContentionMark& contention_mark);
384   void      exit(JavaThread* current, bool not_suspended = true);
385   bool      resume_operation(JavaThread* current, ObjectWaiter* node, ContinuationWrapper& cont);
386   void      wait(jlong millis, bool interruptible, TRAPS);
387   void      notify(TRAPS);
388   void      notifyAll(TRAPS);
389   void      quick_notify(JavaThread* current);
390   void      quick_notifyAll(JavaThread* current);
391 
392   void      print() const;
393 #ifdef ASSERT
394   void      print_debug_style_on(outputStream* st) const;
395 #endif
396   void      print_on(outputStream* st) const;
397 
398   // Use the following at your own risk
399   intx      complete_exit(JavaThread* current);
400 
401  private:
402   void      add_to_entry_list(JavaThread* current, ObjectWaiter* node);
403   void      add_waiter(ObjectWaiter* waiter);
404   bool      notify_internal(JavaThread* current);
405   ObjectWaiter* dequeue_waiter();
406   void      dequeue_specific_waiter(ObjectWaiter* waiter);
407   void      enter_internal(JavaThread* current);
408   void      reenter_internal(JavaThread* current, ObjectWaiter* current_node);
409   void      entry_list_build_dll(JavaThread* current);
410   void      unlink_after_acquire(JavaThread* current, ObjectWaiter* current_node);
411   ObjectWaiter* entry_list_tail(JavaThread* current);
412 
413   bool      vthread_monitor_enter(JavaThread* current, ObjectWaiter* node = nullptr);
414   void      vthread_wait(JavaThread* current, jlong millis, bool interruptible);
415   bool      vthread_wait_reenter(JavaThread* current, ObjectWaiter* node, ContinuationWrapper& cont);
416   void      vthread_epilog(JavaThread* current, ObjectWaiter* node);
417 
418   enum class TryLockResult { Interference = -1, HasOwner = 0, Success = 1 };
419 
420   bool           try_lock_with_contention_mark(JavaThread* locking_thread, ObjectMonitorContentionMark& contention_mark);
421   bool           try_lock_or_add_to_entry_list(JavaThread* current, ObjectWaiter* node);
422   TryLockResult  try_lock(JavaThread* current);
423 
424   bool      try_spin(JavaThread* current);
425   bool      short_fixed_spin(JavaThread* current, int spin_count, bool adapt);
426   void      exit_epilog(JavaThread* current, ObjectWaiter* Wakee);
427 
428  public:
429   // Deflation support
430   bool      deflate_monitor(Thread* current);
431   void      install_displaced_markword_in_object(const oop obj);
432 
433   // JFR support
434   static bool is_jfr_excluded(const Klass* monitor_klass);
435 };
436 
437 // RAII object to ensure that ObjectMonitor::is_being_async_deflated() is
438 // stable within the context of this mark.
439 class ObjectMonitorContentionMark : StackObj {
440   DEBUG_ONLY(friend class ObjectMonitor;)
441 
442   ObjectMonitor* _monitor;
443   bool _extended;
444 
445   NONCOPYABLE(ObjectMonitorContentionMark);
446 
447  public:
448   explicit ObjectMonitorContentionMark(ObjectMonitor* monitor);
449   ~ObjectMonitorContentionMark();
450 
451   // Extends the contention scope beyond this objects lifetime.
452   // Requires manual decrement of the contentions counter.
453   void extend();
454 };
455 
456 #endif // SHARE_RUNTIME_OBJECTMONITOR_HPP