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