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