1 /*
   2  * Copyright (c) 1998, 2018, 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_VM_RUNTIME_OBJECTMONITOR_HPP
  26 #define SHARE_VM_RUNTIME_OBJECTMONITOR_HPP
  27 
  28 #include "memory/allocation.hpp"
  29 #include "memory/padded.hpp"
  30 #include "runtime/os.hpp"
  31 #include "runtime/park.hpp"
  32 #include "runtime/perfData.hpp"
  33 


  34 // ObjectWaiter serves as a "proxy" or surrogate thread.
  35 // TODO-FIXME: Eliminate ObjectWaiter and use the thread-specific
  36 // ParkEvent instead.  Beware, however, that the JVMTI code
  37 // knows about ObjectWaiters, so we'll have to reconcile that code.
  38 // See next_waiter(), first_waiter(), etc.
  39 
  40 class ObjectWaiter : public StackObj {
  41  public:
  42   enum TStates { TS_UNDEF, TS_READY, TS_RUN, TS_WAIT, TS_ENTER, TS_CXQ };
  43   enum Sorted  { PREPEND, APPEND, SORTED };
  44   ObjectWaiter * volatile _next;
  45   ObjectWaiter * volatile _prev;
  46   Thread*       _thread;
  47   jlong         _notifier_tid;
  48   ParkEvent *   _event;
  49   volatile int  _notified;
  50   volatile TStates TState;
  51   Sorted        _Sorted;           // List placement disposition
  52   bool          _active;           // Contention monitoring is enabled
  53  public:
  54   ObjectWaiter(Thread* thread);
  55 
  56   void wait_reenter_begin(ObjectMonitor *mon);
  57   void wait_reenter_end(ObjectMonitor *mon);
  58 };
  59 
  60 // forward declaration to avoid include tracing.hpp
  61 class EventJavaMonitorWait;
  62 
  63 // The ObjectMonitor class implements the heavyweight version of a
  64 // JavaMonitor. The lightweight BasicLock/stack lock version has been
  65 // inflated into an ObjectMonitor. This inflation is typically due to
  66 // contention or use of Object.wait().
  67 //
  68 // WARNING: This is a very sensitive and fragile class. DO NOT make any
  69 // changes unless you are fully aware of the underlying semantics.
  70 //
  71 // Class JvmtiRawMonitor currently inherits from ObjectMonitor so
  72 // changes in this class must be careful to not break JvmtiRawMonitor.
  73 // These two subsystems should be separated.
  74 //
  75 // ObjectMonitor Layout Overview/Highlights/Restrictions:
  76 //
  77 // - The _header field must be at offset 0 because the displaced header
  78 //   from markOop is stored there. We do not want markOop.hpp to include
  79 //   ObjectMonitor.hpp to avoid exposing ObjectMonitor everywhere. This
  80 //   means that ObjectMonitor cannot inherit from any other class nor can
  81 //   it use any virtual member functions. This restriction is critical to
  82 //   the proper functioning of the VM.
  83 // - The _header and _owner fields should be separated by enough space
  84 //   to avoid false sharing due to parallel access by different threads.
  85 //   This is an advisory recommendation.
  86 // - The general layout of the fields in ObjectMonitor is:
  87 //     _header
  88 //     <lightly_used_fields>
  89 //     <optional padding>
  90 //     _owner
  91 //     <remaining_fields>
  92 // - The VM assumes write ordering and machine word alignment with
  93 //   respect to the _owner field and the <remaining_fields> that can
  94 //   be read in parallel by other threads.
  95 // - Generally fields that are accessed closely together in time should
  96 //   be placed proximally in space to promote data cache locality. That
  97 //   is, temporal locality should condition spatial locality.
  98 // - We have to balance avoiding false sharing with excessive invalidation
  99 //   from coherence traffic. As such, we try to cluster fields that tend
 100 //   to be _written_ at approximately the same time onto the same data
 101 //   cache line.
 102 // - We also have to balance the natural tension between minimizing
 103 //   single threaded capacity misses with excessive multi-threaded
 104 //   coherency misses. There is no single optimal layout for both
 105 //   single-threaded and multi-threaded environments.
 106 //
 107 // - See ObjectMonitor::sanity_checks() for how critical restrictions are
 108 //   enforced and advisory recommendations are reported.
 109 // - Adjacent ObjectMonitors should be separated by enough space to avoid
 110 //   false sharing. This is handled by the ObjectMonitor allocation code
 111 //   in synchronizer.cpp. Also see ObjectSynchronizer::sanity_checks().
 112 //
 113 // Futures notes:
 114 //   - Separating _owner from the <remaining_fields> by enough space to
 115 //     avoid false sharing might be profitable. Given
 116 //     http://blogs.oracle.com/dave/entry/cas_and_cache_trivia_invalidate
 117 //     we know that the CAS in monitorenter will invalidate the line
 118 //     underlying _owner. We want to avoid an L1 data cache miss on that
 119 //     same line for monitorexit. Putting these <remaining_fields>:
 120 //     _recursions, _EntryList, _cxq, and _succ, all of which may be
 121 //     fetched in the inflated unlock path, on a different cache line
 122 //     would make them immune to CAS-based invalidation from the _owner
 123 //     field.
 124 //
 125 //   - The _recursions field should be of type int, or int32_t but not
 126 //     intptr_t. There's no reason to use a 64-bit type for this field
 127 //     in a 64-bit JVM.
 128 
 129 class ObjectMonitor {
 130  public:
 131   enum {
 132     OM_OK,                    // no error
 133     OM_SYSTEM_ERROR,          // operating system error
 134     OM_ILLEGAL_MONITOR_STATE, // IllegalMonitorStateException
 135     OM_INTERRUPTED,           // Thread.interrupt()
 136     OM_TIMED_OUT              // Object.wait() timed out
 137   };
 138 
 139  private:
 140   friend class ObjectSynchronizer;
 141   friend class ObjectWaiter;
 142   friend class VMStructs;
 143 
 144   volatile markOop   _header;       // displaced object header word - mark
 145   void*     volatile _object;       // backward object pointer - strong root
 146  public:
 147   ObjectMonitor*     FreeNext;      // Free list linkage
 148  private:
 149   DEFINE_PAD_MINUS_SIZE(0, DEFAULT_CACHE_LINE_SIZE,
 150                         sizeof(volatile markOop) + sizeof(void * volatile) +
 151                         sizeof(ObjectMonitor *));
 152  protected:                         // protected for JvmtiRawMonitor
 153   void *  volatile _owner;          // pointer to owning thread OR BasicLock
 154   volatile jlong _previous_owner_tid;  // thread id of the previous owner of the monitor
 155   volatile intptr_t  _recursions;   // recursion count, 0 for first entry
 156   ObjectWaiter * volatile _EntryList; // Threads blocked on entry or reentry.
 157                                       // The list is actually composed of WaitNodes,
 158                                       // acting as proxies for Threads.
 159  private:
 160   ObjectWaiter * volatile _cxq;     // LL of recently-arrived threads blocked on entry.
 161   Thread * volatile _succ;          // Heir presumptive thread - used for futile wakeup throttling
 162   Thread * volatile _Responsible;
 163 
 164   volatile int _Spinner;            // for exit->spinner handoff optimization
 165   volatile int _SpinDuration;
 166 
 167   volatile jint  _count;            // reference count to prevent reclamation/deflation
 168                                     // at stop-the-world time.  See deflate_idle_monitors().
 169                                     // _count is approximately |_WaitSet| + |_EntryList|
 170  protected:
 171   ObjectWaiter * volatile _WaitSet; // LL of threads wait()ing on the monitor
 172   volatile jint  _waiters;          // number of waiting threads
 173  private:
 174   volatile int _WaitSetLock;        // protects Wait Queue - simple spinlock
 175 
 176  public:
 177   static void Initialize();
 178 
 179   // Only perform a PerfData operation if the PerfData object has been
 180   // allocated and if the PerfDataManager has not freed the PerfData
 181   // objects which can happen at normal VM shutdown.
 182   //
 183   #define OM_PERFDATA_OP(f, op_str)              \
 184     do {                                         \
 185       if (ObjectMonitor::_sync_ ## f != NULL &&  \
 186           PerfDataManager::has_PerfData()) {     \
 187         ObjectMonitor::_sync_ ## f->op_str;      \
 188       }                                          \
 189     } while (0)
 190 
 191   static PerfCounter * _sync_ContendedLockAttempts;
 192   static PerfCounter * _sync_FutileWakeups;
 193   static PerfCounter * _sync_Parks;
 194   static PerfCounter * _sync_Notifications;
 195   static PerfCounter * _sync_Inflations;
 196   static PerfCounter * _sync_Deflations;
 197   static PerfLongVariable * _sync_MonExtant;
 198 
 199   static int Knob_ExitRelease;
 200   static int Knob_Verbose;
 201   static int Knob_VerifyInUse;
 202   static int Knob_VerifyMatch;
 203   static int Knob_SpinLimit;
 204 
 205   void* operator new (size_t size) throw();
 206   void* operator new[] (size_t size) throw();
 207   void operator delete(void* p);
 208   void operator delete[] (void *p);
 209 
 210   // TODO-FIXME: the "offset" routines should return a type of off_t instead of int ...
 211   // ByteSize would also be an appropriate type.
 212   static int header_offset_in_bytes()      { return offset_of(ObjectMonitor, _header); }
 213   static int object_offset_in_bytes()      { return offset_of(ObjectMonitor, _object); }
 214   static int owner_offset_in_bytes()       { return offset_of(ObjectMonitor, _owner); }
 215   static int count_offset_in_bytes()       { return offset_of(ObjectMonitor, _count); }
 216   static int recursions_offset_in_bytes()  { return offset_of(ObjectMonitor, _recursions); }
 217   static int cxq_offset_in_bytes()         { return offset_of(ObjectMonitor, _cxq); }
 218   static int succ_offset_in_bytes()        { return offset_of(ObjectMonitor, _succ); }
 219   static int EntryList_offset_in_bytes()   { return offset_of(ObjectMonitor, _EntryList); }
 220 
 221   // ObjectMonitor references can be ORed with markOopDesc::monitor_value
 222   // as part of the ObjectMonitor tagging mechanism. When we combine an
 223   // ObjectMonitor reference with an offset, we need to remove the tag
 224   // value in order to generate the proper address.
 225   //
 226   // We can either adjust the ObjectMonitor reference and then add the
 227   // offset or we can adjust the offset that is added to the ObjectMonitor
 228   // reference. The latter avoids an AGI (Address Generation Interlock)
 229   // stall so the helper macro adjusts the offset value that is returned
 230   // to the ObjectMonitor reference manipulation code:
 231   //
 232   #define OM_OFFSET_NO_MONITOR_VALUE_TAG(f) \
 233     ((ObjectMonitor::f ## _offset_in_bytes()) - markOopDesc::monitor_value)
 234 
 235   markOop   header() const;
 236   volatile markOop* header_addr();
 237   void      set_header(markOop hdr);
 238 
 239   intptr_t is_busy() const {
 240     // TODO-FIXME: merge _count and _waiters.
 241     // TODO-FIXME: assert _owner == null implies _recursions = 0
 242     // TODO-FIXME: assert _WaitSet != null implies _count > 0
 243     return _count|_waiters|intptr_t(_owner)|intptr_t(_cxq)|intptr_t(_EntryList);
 244   }
 245 
 246   intptr_t  is_entered(Thread* current) const;
 247 
 248   void*     owner() const;
 249   void      set_owner(void* owner);
 250 
 251   jint      waiters() const;
 252 
 253   jint      count() const;
 254   void      set_count(jint count);
 255   jint      contentions() const;
 256   intptr_t  recursions() const                                         { return _recursions; }
 257 
 258   // JVM/TI GetObjectMonitorUsage() needs this:
 259   ObjectWaiter* first_waiter()                                         { return _WaitSet; }
 260   ObjectWaiter* next_waiter(ObjectWaiter* o)                           { return o->_next; }
 261   Thread* thread_of_waiter(ObjectWaiter* o)                            { return o->_thread; }
 262 
 263  protected:
 264   // We don't typically expect or want the ctors or dtors to run.
 265   // normal ObjectMonitors are type-stable and immortal.
 266   ObjectMonitor() { ::memset((void *)this, 0, sizeof(*this)); }
 267 
 268   ~ObjectMonitor() {
 269     // TODO: Add asserts ...
 270     // _cxq == 0 _succ == NULL _owner == NULL _waiters == 0
 271     // _count == 0 _EntryList  == NULL etc
 272   }
 273 
 274  private:
 275   void Recycle() {
 276     // TODO: add stronger asserts ...
 277     // _cxq == 0 _succ == NULL _owner == NULL _waiters == 0
 278     // _count == 0 EntryList  == NULL
 279     // _recursions == 0 _WaitSet == NULL
 280     assert(((is_busy()|_recursions) == 0), "freeing inuse monitor");
 281     _succ          = NULL;
 282     _EntryList     = NULL;
 283     _cxq           = NULL;
 284     _WaitSet       = NULL;
 285     _recursions    = 0;
 286   }
 287 
 288  public:
 289 
 290   void*     object() const;
 291   void*     object_addr();
 292   void      set_object(void* obj);
 293 
 294   bool      check(TRAPS);       // true if the thread owns the monitor.
 295   void      check_slow(TRAPS);
 296   void      clear();
 297   static void sanity_checks();  // public for -XX:+ExecuteInternalVMTests
 298                                 // in PRODUCT for -XX:SyncKnobs=Verbose=1
 299 
 300   void      enter(TRAPS);
 301   void      exit(bool not_suspended, TRAPS);
 302   void      wait(jlong millis, bool interruptable, TRAPS);
 303   void      notify(TRAPS);
 304   void      notifyAll(TRAPS);
 305 
 306 // Use the following at your own risk
 307   intptr_t  complete_exit(TRAPS);
 308   void      reenter(intptr_t recursions, TRAPS);
 309 
 310  private:
 311   void      AddWaiter(ObjectWaiter * waiter);
 312   static    void DeferredInitialize();
 313   void      INotify(Thread * Self);
 314   ObjectWaiter * DequeueWaiter();
 315   void      DequeueSpecificWaiter(ObjectWaiter * waiter);
 316   void      EnterI(TRAPS);
 317   void      ReenterI(Thread * Self, ObjectWaiter * SelfNode);
 318   void      UnlinkAfterAcquire(Thread * Self, ObjectWaiter * SelfNode);
 319   int       TryLock(Thread * Self);
 320   int       NotRunnable(Thread * Self, Thread * Owner);
 321   int       TrySpin(Thread * Self);
 322   void      ExitEpilog(Thread * Self, ObjectWaiter * Wakee);
 323   bool      ExitSuspendEquivalent(JavaThread * Self);
 324   void      post_monitor_wait_event(EventJavaMonitorWait * event,
 325                                     jlong notifier_tid,
 326                                     jlong timeout,
 327                                     bool timedout);
 328 
 329 };
 330 
 331 #undef TEVENT
 332 #define TEVENT(nom) { if (SyncVerbose) FEVENT(nom); }
 333 
 334 #define FEVENT(nom)                             \
 335   {                                             \
 336     static volatile int ctr = 0;                \
 337     int v = ++ctr;                              \
 338     if ((v & (v - 1)) == 0) {                   \
 339       tty->print_cr("INFO: " #nom " : %d", v);  \
 340       tty->flush();                             \
 341     }                                           \
 342   }
 343 
 344 #undef  TEVENT
 345 #define TEVENT(nom) {;}
 346 
 347 
 348 #endif // SHARE_VM_RUNTIME_OBJECTMONITOR_HPP
--- EOF ---