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 
 36 class ObjectMonitor;
 37 class ObjectMonitorContentionMark;
 38 class ParkEvent;
 39 class BasicLock;
 40 class ContinuationWrapper;
 41 
 42 
 43 class ObjectWaiter : public CHeapObj<mtThread> {
 44  public:
 45   enum TStates : uint8_t { TS_UNDEF, TS_READY, TS_RUN, TS_WAIT, TS_ENTER };
 46   ObjectWaiter* volatile _next;
 47   ObjectWaiter* volatile _prev;
 48   JavaThread*     _thread;
 49   OopHandle      _vthread;
 50   ObjectMonitor* _monitor;
 51   uint64_t  _notifier_tid;
 52   int         _recursions;
 53   volatile TStates TState;
 54   volatile bool _notified;
 55   bool           _is_wait;
 56   bool        _at_reenter;
 57   bool       _interrupted;
 58   bool     _interruptible;
 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 notified()           const { return _notified; }
 70   bool at_reenter()         const { return _at_reenter; }
 71   bool at_monitorenter()    const { return !_is_wait || _at_reenter || _notified; }
 72   oop vthread() const;
 73   void wait_reenter_begin(ObjectMonitor *mon);
 74   void wait_reenter_end(ObjectMonitor *mon);
 75 
 76   ObjectWaiter* const badObjectWaiterPtr = (ObjectWaiter*) 0xBAD;
 77   void set_bad_pointers() {
 78 #ifdef ASSERT
 79     this->_prev  = badObjectWaiterPtr;
 80     this->_next  = badObjectWaiterPtr;
 81     this->TState = ObjectWaiter::TS_RUN;
 82 #endif
 83   }
 84   ObjectWaiter* next() {
 85     assert (_next != badObjectWaiterPtr, "corrupted list!");
 86     return _next;
 87   }
 88   ObjectWaiter* prev() {
 89     assert (_prev != badObjectWaiterPtr, "corrupted list!");
 90     return _prev;
 91   }
 92 };
 93 
 94 // The ObjectMonitor class implements the heavyweight version of a
 95 // JavaMonitor. The lightweight BasicLock/stack lock version has been
 96 // inflated into an ObjectMonitor. This inflation is typically due to
 97 // contention or use of Object.wait().
 98 //
 99 // WARNING: This is a very sensitive and fragile class. DO NOT make any
100 // changes unless you are fully aware of the underlying semantics.
101 //
102 // ObjectMonitor Layout Overview/Highlights/Restrictions:
103 //
104 // - For performance reasons we ensure the _metadata field is located at offset 0,
105 //   which in turn means that ObjectMonitor can't inherit from any other class nor use
106 //   any virtual member functions.
107 // - The _metadata and _owner fields should be separated by enough space
108 //   to avoid false sharing due to parallel access by different threads.
109 //   This is an advisory recommendation.
110 // - The general layout of the fields in ObjectMonitor is:
111 //     _metadata
112 //     <lightly_used_fields>
113 //     <optional padding>
114 //     _owner
115 //     <optional padding>
116 //     <remaining_fields>
117 // - The VM assumes write ordering and machine word alignment with
118 //   respect to the _owner field and the <remaining_fields> that can
119 //   be read in parallel by other threads.
120 // - Generally fields that are accessed closely together in time should
121 //   be placed proximally in space to promote data cache locality. That
122 //   is, temporal locality should condition spatial locality.
123 // - We have to balance avoiding false sharing with excessive invalidation
124 //   from coherence traffic. As such, we try to cluster fields that tend
125 //   to be _written_ at approximately the same time onto the same data
126 //   cache line.
127 // - We also have to balance the natural tension between minimizing
128 //   single threaded capacity misses with excessive multi-threaded
129 //   coherency misses. There is no single optimal layout for both
130 //   single-threaded and multi-threaded environments.
131 //
132 // - See TEST_VM(ObjectMonitor, sanity) gtest for how critical restrictions are
133 //   enforced.
134 //
135 // - Separating _owner from the <remaining_fields> by enough space to
136 //   avoid false sharing might be profitable. Given that the CAS in
137 //   monitorenter will invalidate the line underlying _owner. We want
138 //   to avoid an L1 data cache miss on that same line for monitorexit.
139 //   Putting these <remaining_fields>:
140 //   _recursions, _entry_list and _succ, all of which may be
141 //   fetched in the inflated unlock path, on a different cache line
142 //   would make them immune to CAS-based invalidation from the _owner
143 //   field.
144 //
145 // - TODO: The _recursions field should be of type int, or int32_t but not
146 //   intptr_t. There's no reason to use a 64-bit type for this field
147 //   in a 64-bit JVM.
148 
149 #define OM_CACHE_LINE_SIZE DEFAULT_CACHE_LINE_SIZE
150 
151 class ObjectMonitor : public CHeapObj<mtObjectMonitor> {
152   friend class VMStructs;
153   JVMCI_ONLY(friend class JVMCIVMStructs;)
154 
155   static OopStorage* _oop_storage;
156 
157   // List of j.l.VirtualThread waiting to be unblocked by unblocker thread.
158   static OopHandle _vthread_list_head;
159   // ParkEvent of unblocker thread.
160   static ParkEvent* _vthread_unparker_ParkEvent;
161 
162   // Because of frequent access, the metadata field is at offset zero (0).
163   // Enforced by the assert() in metadata_addr().
164   // * LM_LIGHTWEIGHT with UseObjectMonitorTable:
165   // Contains the _object's hashCode.
166   // * LM_LEGACY, LM_MONITOR, LM_LIGHTWEIGHT without UseObjectMonitorTable:
167   // Contains the displaced object header word - mark
168   volatile uintptr_t _metadata;     // metadata
169   WeakHandle _object;               // backward object pointer
170   // Separate _metadata and _owner on different cache lines since both can
171   // have busy multi-threaded access. _metadata and _object are set at initial
172   // inflation. The _object does not change, so it is a good choice to share
173   // its cache line with _metadata.
174   DEFINE_PAD_MINUS_SIZE(0, OM_CACHE_LINE_SIZE, sizeof(_metadata) +
175                         sizeof(WeakHandle));
176 
177   static const int64_t NO_OWNER = 0;
178   static const int64_t ANONYMOUS_OWNER = 1;
179   static const int64_t DEFLATER_MARKER = 2;
180 
181   int64_t volatile _owner;  // Either owner_id of owner, NO_OWNER, ANONYMOUS_OWNER or DEFLATER_MARKER.
182   volatile uint64_t _previous_owner_tid;  // thread id of the previous owner of the monitor
183   // Separate _owner and _next_om on different cache lines since
184   // both can have busy multi-threaded access. _previous_owner_tid is only
185   // changed by ObjectMonitor::exit() so it is a good choice to share the
186   // cache line with _owner.
187   DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(void* volatile) +
188                         sizeof(volatile uint64_t));
189   ObjectMonitor* _next_om;          // Next ObjectMonitor* linkage
190   volatile intx _recursions;        // recursion count, 0 for first entry
191   ObjectWaiter* volatile _entry_list;  // Threads blocked on entry or reentry.
192                                        // The list is actually composed of wait-nodes,
193                                        // acting as proxies for Threads.
194   ObjectWaiter* volatile _entry_list_tail; // _entry_list is the head, this is the tail.
195   int64_t volatile _succ;           // Heir presumptive thread - used for futile wakeup throttling
196 
197   volatile int _SpinDuration;
198 
199   int _contentions;                 // Number of active contentions in enter(). It is used by is_busy()
200                                     // along with other fields to determine if an ObjectMonitor can be
201                                     // deflated. It is also used by the async deflation protocol. See
202                                     // ObjectMonitor::deflate_monitor().
203   int64_t _unmounted_vthreads;      // Number of nodes in the _entry_list associated with unmounted vthreads.
204                                     // It might be temporarily more than the actual number but never less.
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 
210   // Used in LM_LEGACY mode to store BasicLock* in case of inflation by contending thread.
211   BasicLock* volatile _stack_locker;
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 Atomic::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   // Get and set _stack_locker.
325   BasicLock* stack_locker() const;
326   void set_stack_locker(BasicLock* locker);
327 
328   // Simply get _next_om field.
329   ObjectMonitor* next_om() const;
330   // Simply set _next_om field to new_value.
331   void set_next_om(ObjectMonitor* new_value);
332 
333   int       contentions() const;
334   void      add_to_contentions(int value);
335   intx      recursions() const                                         { return _recursions; }
336   void      set_recursions(size_t recursions);
337   void      increment_recursions(JavaThread* current);
338   void      inc_unmounted_vthreads();
339   void      dec_unmounted_vthreads();
340   bool      has_unmounted_vthreads() const;
341 
342   // JVM/TI GetObjectMonitorUsage() needs this:
343   int waiters() const;
344   ObjectWaiter* first_waiter()                                         { return _wait_set; }
345   ObjectWaiter* next_waiter(ObjectWaiter* o)                           { return o->_next; }
346   JavaThread* thread_of_waiter(ObjectWaiter* o)                        { return o->_thread; }
347 
348   ObjectMonitor(oop object);
349   ~ObjectMonitor();
350 
351   oop       object() const;
352   oop       object_peek() const;
353   bool      object_is_dead() const;
354   bool      object_refers_to(oop obj) const;
355 
356   // Returns true if the specified thread owns the ObjectMonitor. Otherwise
357   // returns false and throws IllegalMonitorStateException (IMSE).
358   bool      check_owner(TRAPS);
359 
360  private:
361   class ExitOnSuspend {
362    protected:
363     ObjectMonitor* _om;
364     bool _om_exited;
365    public:
366     ExitOnSuspend(ObjectMonitor* om) : _om(om), _om_exited(false) {}
367     void operator()(JavaThread* current);
368     bool exited() { return _om_exited; }
369   };
370   class ClearSuccOnSuspend {
371    protected:
372     ObjectMonitor* _om;
373    public:
374     ClearSuccOnSuspend(ObjectMonitor* om) : _om(om)  {}
375     void operator()(JavaThread* current);
376   };
377 
378   bool      enter_is_async_deflating();
379   void      notify_contended_enter(JavaThread *current);
380  public:
381   void      enter_for_with_contention_mark(JavaThread* locking_thread, ObjectMonitorContentionMark& contention_mark);
382   bool      enter_for(JavaThread* locking_thread);
383   bool      enter(JavaThread* current);
384   bool      try_enter(JavaThread* current, bool check_for_recursion = true);
385   bool      spin_enter(JavaThread* current);
386   void      enter_with_contention_mark(JavaThread* current, ObjectMonitorContentionMark& contention_mark);
387   void      exit(JavaThread* current, bool not_suspended = true);
388   bool      resume_operation(JavaThread* current, ObjectWaiter* node, ContinuationWrapper& cont);
389   void      wait(jlong millis, bool interruptible, TRAPS);
390   void      notify(TRAPS);
391   void      notifyAll(TRAPS);
392   void      quick_notify(JavaThread* current);
393   void      quick_notifyAll(JavaThread* current);
394 
395   void      print() const;
396 #ifdef ASSERT
397   void      print_debug_style_on(outputStream* st) const;
398 #endif
399   void      print_on(outputStream* st) const;
400 
401   // Use the following at your own risk
402   intx      complete_exit(JavaThread* current);
403 
404  private:
405   void      add_to_entry_list(JavaThread* current, ObjectWaiter* node);
406   void      add_waiter(ObjectWaiter* waiter);
407   bool      notify_internal(JavaThread* current);
408   ObjectWaiter* dequeue_waiter();
409   void      dequeue_specific_waiter(ObjectWaiter* waiter);
410   void      enter_internal(JavaThread* current);
411   void      reenter_internal(JavaThread* current, ObjectWaiter* current_node);
412   void      entry_list_build_dll(JavaThread* current);
413   void      unlink_after_acquire(JavaThread* current, ObjectWaiter* current_node);
414   ObjectWaiter* entry_list_tail(JavaThread* current);
415 
416   bool      vthread_monitor_enter(JavaThread* current, ObjectWaiter* node = nullptr);
417   void      vthread_wait(JavaThread* current, jlong millis, bool interruptible);
418   bool      vthread_wait_reenter(JavaThread* current, ObjectWaiter* node, ContinuationWrapper& cont);
419   void      vthread_epilog(JavaThread* current, ObjectWaiter* node);
420 
421   enum class TryLockResult { Interference = -1, HasOwner = 0, Success = 1 };
422 
423   bool           try_lock_with_contention_mark(JavaThread* locking_thread, ObjectMonitorContentionMark& contention_mark);
424   bool           try_lock_or_add_to_entry_list(JavaThread* current, ObjectWaiter* node);
425   TryLockResult  try_lock(JavaThread* current);
426 
427   bool      try_spin(JavaThread* current);
428   bool      short_fixed_spin(JavaThread* current, int spin_count, bool adapt);
429   void      exit_epilog(JavaThread* current, ObjectWaiter* Wakee);
430 
431  public:
432   // Deflation support
433   bool      deflate_monitor(Thread* current);
434   void      install_displaced_markword_in_object(const oop obj);
435 
436   // JFR support
437   static bool is_jfr_excluded(const Klass* monitor_klass);
438 };
439 
440 // RAII object to ensure that ObjectMonitor::is_being_async_deflated() is
441 // stable within the context of this mark.
442 class ObjectMonitorContentionMark : StackObj {
443   DEBUG_ONLY(friend class ObjectMonitor;)
444 
445   ObjectMonitor* _monitor;
446   bool _extended;
447 
448   NONCOPYABLE(ObjectMonitorContentionMark);
449 
450  public:
451   explicit ObjectMonitorContentionMark(ObjectMonitor* monitor);
452   ~ObjectMonitorContentionMark();
453 
454   // Extends the contention scope beyond this objects lifetime.
455   // Requires manual decrement of the contentions counter.
456   void extend();
457 };
458 
459 #endif // SHARE_RUNTIME_OBJECTMONITOR_HPP