1 /*
  2  * Copyright (c) 1998, 2024, 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.inline.hpp"
 32 #include "oops/weakHandle.hpp"
 33 #include "runtime/javaThread.hpp"
 34 #include "runtime/perfDataTypes.hpp"
 35 #include "utilities/checkedCast.hpp"
 36 
 37 class ObjectMonitor;
 38 class ParkEvent;
 39 class BasicLock;
 40 
 41 // ObjectWaiter serves as a "proxy" or surrogate thread.
 42 // TODO-FIXME: Eliminate ObjectWaiter and use the thread-specific
 43 // ParkEvent instead.  Beware, however, that the JVMTI code
 44 // knows about ObjectWaiters, so we'll have to reconcile that code.
 45 // See next_waiter(), first_waiter(), etc.
 46 
 47 class ObjectWaiter : public CHeapObj<mtThread> {
 48  public:
 49   enum TStates { TS_UNDEF, TS_READY, TS_RUN, TS_WAIT, TS_ENTER, TS_CXQ };
 50   ObjectWaiter* volatile _next;
 51   ObjectWaiter* volatile _prev;
 52   JavaThread*   _thread;
 53   OopHandle _vthread;
 54   uint64_t      _notifier_tid;
 55   ParkEvent *   _event;
 56   volatile int  _notified;
 57   volatile TStates TState;
 58   bool          _active;           // Contention monitoring is enabled
 59  public:
 60   ObjectWaiter(JavaThread* current);
 61   ObjectWaiter(oop vthread);
 62   ~ObjectWaiter() {
 63     if (is_vthread()) {
 64       assert(_vthread.resolve() != nullptr, "invariant");
 65       _vthread.release(JavaThread::thread_oop_storage());
 66     }
 67   }
 68   oop vthread() { return _vthread.resolve(); }
 69   bool is_vthread() { return _thread == nullptr; }
 70   void wait_reenter_begin(ObjectMonitor *mon);
 71   void wait_reenter_end(ObjectMonitor *mon);
 72 };
 73 
 74 // The ObjectMonitor class implements the heavyweight version of a
 75 // JavaMonitor. The lightweight BasicLock/stack lock version has been
 76 // inflated into an ObjectMonitor. This inflation is typically due to
 77 // contention or use of Object.wait().
 78 //
 79 // WARNING: This is a very sensitive and fragile class. DO NOT make any
 80 // changes unless you are fully aware of the underlying semantics.
 81 //
 82 // ObjectMonitor Layout Overview/Highlights/Restrictions:
 83 //
 84 // - The _header field must be at offset 0 because the displaced header
 85 //   from markWord is stored there. We do not want markWord.hpp to include
 86 //   ObjectMonitor.hpp to avoid exposing ObjectMonitor everywhere. This
 87 //   means that ObjectMonitor cannot inherit from any other class nor can
 88 //   it use any virtual member functions. This restriction is critical to
 89 //   the proper functioning of the VM.
 90 // - The _header and _owner fields should be separated by enough space
 91 //   to avoid false sharing due to parallel access by different threads.
 92 //   This is an advisory recommendation.
 93 // - The general layout of the fields in ObjectMonitor is:
 94 //     _header
 95 //     <lightly_used_fields>
 96 //     <optional padding>
 97 //     _owner
 98 //     <remaining_fields>
 99 // - The VM assumes write ordering and machine word alignment with
100 //   respect to the _owner field and the <remaining_fields> that can
101 //   be read in parallel by other threads.
102 // - Generally fields that are accessed closely together in time should
103 //   be placed proximally in space to promote data cache locality. That
104 //   is, temporal locality should condition spatial locality.
105 // - We have to balance avoiding false sharing with excessive invalidation
106 //   from coherence traffic. As such, we try to cluster fields that tend
107 //   to be _written_ at approximately the same time onto the same data
108 //   cache line.
109 // - We also have to balance the natural tension between minimizing
110 //   single threaded capacity misses with excessive multi-threaded
111 //   coherency misses. There is no single optimal layout for both
112 //   single-threaded and multi-threaded environments.
113 //
114 // - See TEST_VM(ObjectMonitor, sanity) gtest for how critical restrictions are
115 //   enforced.
116 // - Adjacent ObjectMonitors should be separated by enough space to avoid
117 //   false sharing. This is handled by the ObjectMonitor allocation code
118 //   in synchronizer.cpp. Also see TEST_VM(SynchronizerTest, sanity) gtest.
119 //
120 // Futures notes:
121 //   - Separating _owner from the <remaining_fields> by enough space to
122 //     avoid false sharing might be profitable. Given
123 //     http://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate
124 //     we know that the CAS in monitorenter will invalidate the line
125 //     underlying _owner. We want to avoid an L1 data cache miss on that
126 //     same line for monitorexit. Putting these <remaining_fields>:
127 //     _recursions, _EntryList, _cxq, and _succ, all of which may be
128 //     fetched in the inflated unlock path, on a different cache line
129 //     would make them immune to CAS-based invalidation from the _owner
130 //     field.
131 //
132 //   - The _recursions field should be of type int, or int32_t but not
133 //     intptr_t. There's no reason to use a 64-bit type for this field
134 //     in a 64-bit JVM.
135 
136 #define OM_CACHE_LINE_SIZE DEFAULT_CACHE_LINE_SIZE
137 
138 class ObjectMonitor : public CHeapObj<mtObjectMonitor> {
139   friend class ObjectSynchronizer;
140   friend class ObjectWaiter;
141   friend class VMStructs;
142   friend class MonitorList;
143   JVMCI_ONLY(friend class JVMCIVMStructs;)
144 
145   static OopStorage* _oop_storage;
146 
147   static OopHandle _vthread_cxq_head;
148   static ParkEvent* _vthread_unparker_ParkEvent;
149 
150   // The sync code expects the header field to be at offset zero (0).
151   // Enforced by the assert() in header_addr().
152   volatile markWord _header;        // displaced object header word - mark
153   WeakHandle _object;               // backward object pointer
154   // Separate _header and _owner on different cache lines since both can
155   // have busy multi-threaded access. _header and _object are set at initial
156   // inflation. The _object does not change, so it is a good choice to share
157   // its cache line with _header.
158   DEFINE_PAD_MINUS_SIZE(0, OM_CACHE_LINE_SIZE, sizeof(volatile markWord) +
159                         sizeof(WeakHandle));
160   // Used by async deflation as a marker in the _owner field.
161   // Note that the choice of the two markers is peculiar:
162   // - They need to represent values that cannot be pointers. In particular,
163   //   we achieve this by using the lowest two bits.
164   // - ANONYMOUS_OWNER should be a small value, it is used in generated code
165   //   and small values encode much better.
166   // - We test for anonymous owner by testing for the lowest bit, therefore
167   //   DEFLATER_MARKER must *not* have that bit set.
168   #define DEFLATER_MARKER reinterpret_cast<void*>(2)
169 public:
170   // NOTE: Typed as uintptr_t so that we can pick it up in SA, via vmStructs.
171   static const uintptr_t ANONYMOUS_OWNER = 1;
172 
173 private:
174   static void* anon_owner_ptr() { return reinterpret_cast<void*>(ANONYMOUS_OWNER); }
175 
176   void* volatile _owner;            // pointer to owning thread OR BasicLock
177   BasicLock* volatile _stack_locker;      // can this share a cache line with owner? they're used together
178   volatile uint64_t _previous_owner_tid;  // thread id of the previous owner of the monitor
179   // Separate _owner and _next_om on different cache lines since
180   // both can have busy multi-threaded access. _previous_owner_tid is only
181   // changed by ObjectMonitor::exit() so it is a good choice to share the
182   // cache line with _owner.
183   DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, 2 * sizeof(void* volatile) +
184                         sizeof(volatile uint64_t));
185   ObjectMonitor* _next_om;          // Next ObjectMonitor* linkage
186   volatile intx _recursions;        // recursion count, 0 for first entry
187   ObjectWaiter* volatile _EntryList;  // Threads blocked on entry or reentry.
188                                       // The list is actually composed of WaitNodes,
189                                       // acting as proxies for Threads.
190 
191   ObjectWaiter* volatile _cxq;      // LL of recently-arrived threads blocked on entry.
192   JavaThread* volatile _succ;       // Heir presumptive thread - used for futile wakeup throttling
193   JavaThread* volatile _Responsible;
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  protected:
202   ObjectWaiter* volatile _WaitSet;  // LL of threads wait()ing on the monitor
203   volatile int  _waiters;           // number of waiting threads
204  private:
205   volatile int _WaitSetLock;        // protects Wait Queue - simple spinlock
206 
207  public:
208 
209   static void Initialize();
210   static void Initialize2();
211 
212   static OopHandle& vthread_cxq_head() { return _vthread_cxq_head; }
213   static ParkEvent* vthread_unparker_ParkEvent() { return _vthread_unparker_ParkEvent; }
214 
215   // Only perform a PerfData operation if the PerfData object has been
216   // allocated and if the PerfDataManager has not freed the PerfData
217   // objects which can happen at normal VM shutdown.
218   //
219   #define OM_PERFDATA_OP(f, op_str)                 \
220     do {                                            \
221       if (ObjectMonitor::_sync_ ## f != nullptr &&  \
222           PerfDataManager::has_PerfData()) {        \
223         ObjectMonitor::_sync_ ## f->op_str;         \
224       }                                             \
225     } while (0)
226 
227   static PerfCounter * _sync_ContendedLockAttempts;
228   static PerfCounter * _sync_FutileWakeups;
229   static PerfCounter * _sync_Parks;
230   static PerfCounter * _sync_Notifications;
231   static PerfCounter * _sync_Inflations;
232   static PerfCounter * _sync_Deflations;
233   static PerfLongVariable * _sync_MonExtant;
234 
235   static int Knob_SpinLimit;
236 
237   static ByteSize owner_offset()       { return byte_offset_of(ObjectMonitor, _owner); }
238   static ByteSize recursions_offset()  { return byte_offset_of(ObjectMonitor, _recursions); }
239   static ByteSize cxq_offset()         { return byte_offset_of(ObjectMonitor, _cxq); }
240   static ByteSize succ_offset()        { return byte_offset_of(ObjectMonitor, _succ); }
241   static ByteSize EntryList_offset()   { return byte_offset_of(ObjectMonitor, _EntryList); }
242   static ByteSize stack_locker_offset(){ return byte_offset_of(ObjectMonitor, _stack_locker); }
243 
244   // ObjectMonitor references can be ORed with markWord::monitor_value
245   // as part of the ObjectMonitor tagging mechanism. When we combine an
246   // ObjectMonitor reference with an offset, we need to remove the tag
247   // value in order to generate the proper address.
248   //
249   // We can either adjust the ObjectMonitor reference and then add the
250   // offset or we can adjust the offset that is added to the ObjectMonitor
251   // reference. The latter avoids an AGI (Address Generation Interlock)
252   // stall so the helper macro adjusts the offset value that is returned
253   // to the ObjectMonitor reference manipulation code:
254   //
255   #define OM_OFFSET_NO_MONITOR_VALUE_TAG(f) \
256     ((in_bytes(ObjectMonitor::f ## _offset())) - checked_cast<int>(markWord::monitor_value))
257 
258   markWord           header() const;
259   volatile markWord* header_addr();
260   void               set_header(markWord hdr);
261 
262   bool is_busy() const {
263     // TODO-FIXME: assert _owner == null implies _recursions = 0
264     intptr_t ret_code = intptr_t(_waiters) | intptr_t(_cxq) | intptr_t(_EntryList);
265     int cnts = contentions(); // read once
266     if (cnts > 0) {
267       ret_code |= intptr_t(cnts);
268     }
269     if (!owner_is_DEFLATER_MARKER()) {
270       ret_code |= intptr_t(owner_raw());
271     }
272     return ret_code != 0;
273   }
274   const char* is_busy_to_string(stringStream* ss);
275 
276   bool is_entered(JavaThread* current) const;
277   int contentions() const;
278 
279   // Returns true if this OM has an owner, false otherwise.
280   bool   has_owner() const;
281   void*  owner() const;  // Returns null if DEFLATER_MARKER is observed.
282   bool   is_owner(JavaThread* thread) const { return owner() == owner_for(thread); }
283   bool   is_owner_anonymous() const { return owner_raw() == anon_owner_ptr(); }
284   bool   is_stack_locker(JavaThread* current);
285   BasicLock* stack_locker() const;
286 
287  private:
288   void*     owner_raw() const;
289   void*     owner_for(JavaThread* thread) const;
290   // Returns true if owner field == DEFLATER_MARKER and false otherwise.
291   bool      owner_is_DEFLATER_MARKER() const;
292   // Returns true if 'this' is being async deflated and false otherwise.
293   bool      is_being_async_deflated();
294   // Clear _owner field; current value must match old_value.
295   void      release_clear_owner(JavaThread* old_value);
296   // Simply set _owner field to new_value; current value must match old_value.
297   void      set_owner_from_raw(void* old_value, void* new_value);
298   void      set_owner_from(void* old_value, JavaThread* current);
299   // Simply set _owner field to current; current value must match basic_lock_p.
300   void      set_owner_from_BasicLock(JavaThread* current);
301   // Try to set _owner field to new_value if the current value matches
302   // old_value, using Atomic::cmpxchg(). Otherwise, does not change the
303   // _owner field. Returns the prior value of the _owner field.
304   void*     try_set_owner_from_raw(void* old_value, void* new_value);
305   void*     try_set_owner_from(void* old_value, JavaThread* current);
306 
307   void set_stack_locker(BasicLock* locker);
308 
309   void set_owner_anonymous() {
310     set_owner_from_raw(nullptr, anon_owner_ptr());
311   }
312 
313   void set_owner_from_anonymous(JavaThread* owner) {
314     set_owner_from(anon_owner_ptr(), owner);
315   }
316 
317   // Simply get _next_om field.
318   ObjectMonitor* next_om() const;
319   // Simply set _next_om field to new_value.
320   void set_next_om(ObjectMonitor* new_value);
321 
322   void      add_to_contentions(int value);
323   intx      recursions() const                                         { return _recursions; }
324   void      set_recursions(size_t recursions);
325 
326  public:
327   // JVM/TI GetObjectMonitorUsage() needs this:
328   int waiters() const;
329   ObjectWaiter* first_waiter()                                         { return _WaitSet; }
330   ObjectWaiter* next_waiter(ObjectWaiter* o)                           { return o->_next; }
331   JavaThread* thread_of_waiter(ObjectWaiter* o)                        { return o->_thread; }
332 
333   ObjectMonitor(oop object);
334   ~ObjectMonitor();
335 
336   oop       object() const;
337   oop       object_peek() const;
338 
339   // Returns true if the specified thread owns the ObjectMonitor. Otherwise
340   // returns false and throws IllegalMonitorStateException (IMSE).
341   bool      check_owner(TRAPS);
342 
343  private:
344   class ExitOnSuspend {
345    protected:
346     ObjectMonitor* _om;
347     bool _om_exited;
348    public:
349     ExitOnSuspend(ObjectMonitor* om) : _om(om), _om_exited(false) {}
350     void operator()(JavaThread* current);
351     bool exited() { return _om_exited; }
352   };
353   class ClearSuccOnSuspend {
354    protected:
355     ObjectMonitor* _om;
356    public:
357     ClearSuccOnSuspend(ObjectMonitor* om) : _om(om)  {}
358     void operator()(JavaThread* current);
359   };
360  public:
361   bool      enter_for(JavaThread* locking_thread);
362   bool      enter(JavaThread* current);
363   void      redo_enter(JavaThread* current);
364   void      exit(JavaThread* current, bool not_suspended = true);
365   void      wait(jlong millis, bool interruptible, TRAPS);
366   void      notify(TRAPS);
367   void      notifyAll(TRAPS);
368 
369   void      print() const;
370 #ifdef ASSERT
371   void      print_debug_style_on(outputStream* st) const;
372 #endif
373   void      print_on(outputStream* st) const;
374 
375   // Use the following at your own risk
376   intx      complete_exit(JavaThread* current);
377 
378  private:
379   void      AddWaiter(ObjectWaiter* waiter);
380   void      INotify(JavaThread* current);
381   ObjectWaiter* DequeueWaiter();
382   void      DequeueSpecificWaiter(ObjectWaiter* waiter);
383   void      EnterI(JavaThread* current);
384   void      ReenterI(JavaThread* current, ObjectWaiter* current_node);
385   bool      HandlePreemptedVThread(JavaThread* current);
386   void      VThreadEpilog(JavaThread* current);
387   void      UnlinkAfterAcquire(JavaThread* current, ObjectWaiter* current_node, oop vthread = nullptr);
388   ObjectWaiter* LookupWaiter(int64_t threadid);
389 
390 
391   enum class TryLockResult { Interference = -1, HasOwner = 0, Success = 1 };
392 
393   TryLockResult  TryLock(JavaThread* current);
394 
395   bool      TrySpin(JavaThread* current);
396   bool      short_fixed_spin(JavaThread* current, int spin_count, bool adapt);
397   void      ExitEpilog(JavaThread* current, ObjectWaiter* Wakee);
398 
399   // Deflation support
400   bool      deflate_monitor();
401   void      install_displaced_markword_in_object(const oop obj);
402 };
403 
404 #endif // SHARE_RUNTIME_OBJECTMONITOR_HPP