1 /*
   2  * Copyright (c) 1998, 2013, 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 "runtime/os.hpp"
  29 #include "runtime/park.hpp"
  30 #include "runtime/perfData.hpp"
  31 
  32 class ObjectMonitor;
  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 // WARNING:
  64 //   This is a very sensitive and fragile class. DO NOT make any
  65 // change unless you are fully aware of the underlying semantics.
  66 
  67 //   This class can not inherit from any other class, because I have
  68 // to let the displaced header be the very first word. Otherwise I
  69 // have to let markOop include this file, which would export the
  70 // monitor data structure to everywhere.
  71 //
  72 // The ObjectMonitor class is used to implement JavaMonitors which have
  73 // transformed from the lightweight structure of the thread stack to a
  74 // heavy weight lock due to contention
  75 
  76 // It is also used as RawMonitor by the JVMTI
  77 
  78 
  79 class ObjectMonitor {
  80  public:
  81   enum {
  82     OM_OK,                    // no error
  83     OM_SYSTEM_ERROR,          // operating system error
  84     OM_ILLEGAL_MONITOR_STATE, // IllegalMonitorStateException
  85     OM_INTERRUPTED,           // Thread.interrupt()
  86     OM_TIMED_OUT              // Object.wait() timed out
  87   };
  88 
  89  public:
  90   // TODO-FIXME: the "offset" routines should return a type of off_t instead of int ...
  91   // ByteSize would also be an appropriate type.
  92   static int header_offset_in_bytes()      { return offset_of(ObjectMonitor, _header);     }
  93   static int object_offset_in_bytes()      { return offset_of(ObjectMonitor, _object);     }
  94   static int owner_offset_in_bytes()       { return offset_of(ObjectMonitor, _owner);      }
  95   static int count_offset_in_bytes()       { return offset_of(ObjectMonitor, _count);      }
  96   static int recursions_offset_in_bytes()  { return offset_of(ObjectMonitor, _recursions); }
  97   static int cxq_offset_in_bytes()         { return offset_of(ObjectMonitor, _cxq) ;       }
  98   static int succ_offset_in_bytes()        { return offset_of(ObjectMonitor, _succ) ;      }
  99   static int EntryList_offset_in_bytes()   { return offset_of(ObjectMonitor, _EntryList);  }
 100   static int FreeNext_offset_in_bytes()    { return offset_of(ObjectMonitor, FreeNext);    }
 101   static int WaitSet_offset_in_bytes()     { return offset_of(ObjectMonitor, _WaitSet) ;   }
 102   static int Responsible_offset_in_bytes() { return offset_of(ObjectMonitor, _Responsible);}
 103   static int Spinner_offset_in_bytes()     { return offset_of(ObjectMonitor, _Spinner);    }
 104 
 105  public:
 106   // Eventaully we'll make provisions for multiple callbacks, but
 107   // now one will suffice.
 108   static int (*SpinCallbackFunction)(intptr_t, int) ;
 109   static intptr_t SpinCallbackArgument ;
 110 
 111 
 112  public:
 113   markOop   header() const;
 114   void      set_header(markOop hdr);
 115 
 116   intptr_t is_busy() const {
 117     // TODO-FIXME: merge _count and _waiters.
 118     // TODO-FIXME: assert _owner == null implies _recursions = 0
 119     // TODO-FIXME: assert _WaitSet != null implies _count > 0
 120     return _count|_waiters|intptr_t(_owner)|intptr_t(_cxq)|intptr_t(_EntryList ) ;
 121   }
 122 
 123   intptr_t  is_entered(Thread* current) const;
 124 
 125   void*     owner() const;
 126   void      set_owner(void* owner);
 127 
 128   intptr_t  waiters() const;
 129 
 130   intptr_t  count() const;
 131   void      set_count(intptr_t count);
 132   intptr_t  contentions() const ;
 133   intptr_t  recursions() const                                         { return _recursions; }
 134 
 135   // JVM/DI GetMonitorInfo() needs this
 136   ObjectWaiter* first_waiter()                                         { return _WaitSet; }
 137   ObjectWaiter* next_waiter(ObjectWaiter* o)                           { return o->_next; }
 138   Thread* thread_of_waiter(ObjectWaiter* o)                            { return o->_thread; }
 139 
 140   // initialize the monitor, exception the semaphore, all other fields
 141   // are simple integers or pointers
 142   ObjectMonitor() {
 143     _header       = NULL;
 144     _count        = 0;
 145     _waiters      = 0,
 146     _recursions   = 0;
 147     _object       = NULL;
 148     _owner        = NULL;
 149     _WaitSet      = NULL;
 150     _WaitSetLock  = 0 ;
 151     _Responsible  = NULL ;
 152     _succ         = NULL ;
 153     _cxq          = NULL ;
 154     FreeNext      = NULL ;
 155     _EntryList    = NULL ;
 156     _SpinFreq     = 0 ;
 157     _SpinClock    = 0 ;
 158     OwnerIsThread = 0 ;
 159     _previous_owner_tid = 0;
 160   }
 161 
 162   ~ObjectMonitor() {
 163    // TODO: Add asserts ...
 164    // _cxq == 0 _succ == NULL _owner == NULL _waiters == 0
 165    // _count == 0 _EntryList  == NULL etc
 166   }
 167 
 168 private:
 169   void Recycle () {
 170     // TODO: add stronger asserts ...
 171     // _cxq == 0 _succ == NULL _owner == NULL _waiters == 0
 172     // _count == 0 EntryList  == NULL
 173     // _recursions == 0 _WaitSet == NULL
 174     // TODO: assert (is_busy()|_recursions) == 0
 175     _succ          = NULL ;
 176     _EntryList     = NULL ;
 177     _cxq           = NULL ;
 178     _WaitSet       = NULL ;
 179     _recursions    = 0 ;
 180     _SpinFreq      = 0 ;
 181     _SpinClock     = 0 ;
 182     OwnerIsThread  = 0 ;
 183   }
 184 
 185 public:
 186 
 187   void*     object() const;
 188   void*     object_addr();
 189   void      set_object(void* obj);
 190 
 191   bool      check(TRAPS);       // true if the thread owns the monitor.
 192   void      check_slow(TRAPS);
 193   void      clear();
 194   static void sanity_checks();  // public for -XX:+ExecuteInternalVMTests
 195                                 // in PRODUCT for -XX:SyncKnobs=Verbose=1
 196 #ifndef PRODUCT
 197   void      verify();
 198   void      print();
 199 #endif
 200 
 201   bool      try_enter (TRAPS) ;
 202   void      enter(TRAPS);
 203   void      exit(bool not_suspended, TRAPS);
 204   void      wait(jlong millis, bool interruptable, TRAPS);
 205   void      notify(TRAPS);
 206   void      notifyAll(TRAPS);
 207 
 208 // Use the following at your own risk
 209   intptr_t  complete_exit(TRAPS);
 210   void      reenter(intptr_t recursions, TRAPS);
 211 
 212  private:
 213   void      AddWaiter (ObjectWaiter * waiter) ;
 214   static    void DeferredInitialize();
 215 
 216   ObjectWaiter * DequeueWaiter () ;
 217   void      DequeueSpecificWaiter (ObjectWaiter * waiter) ;
 218   void      EnterI (TRAPS) ;
 219   void      ReenterI (Thread * Self, ObjectWaiter * SelfNode) ;
 220   void      UnlinkAfterAcquire (Thread * Self, ObjectWaiter * SelfNode) ;
 221   int       TryLock (Thread * Self) ;
 222   int       NotRunnable (Thread * Self, Thread * Owner) ;
 223   int       TrySpin_Fixed (Thread * Self) ;
 224   int       TrySpin_VaryFrequency (Thread * Self) ;
 225   int       TrySpin_VaryDuration  (Thread * Self) ;
 226   void      ctAsserts () ;
 227   void      ExitEpilog (Thread * Self, ObjectWaiter * Wakee) ;
 228   bool      ExitSuspendEquivalent (JavaThread * Self) ;
 229   void      post_monitor_wait_event(EventJavaMonitorWait * event,
 230                                                    jlong notifier_tid,
 231                                                    jlong timeout,
 232                                                    bool timedout);
 233 
 234  private:
 235   friend class ObjectSynchronizer;
 236   friend class ObjectWaiter;
 237   friend class VMStructs;
 238 
 239   // WARNING: this must be the very first word of ObjectMonitor
 240   // This means this class can't use any virtual member functions.
 241 
 242   volatile markOop   _header;       // displaced object header word - mark
 243   void*     volatile _object;       // backward object pointer - strong root
 244 
 245   double SharingPad [1] ;           // temp to reduce false sharing
 246 
 247   // All the following fields must be machine word aligned
 248   // The VM assumes write ordering wrt these fields, which can be
 249   // read from other threads.
 250 
 251  protected:                         // protected for jvmtiRawMonitor
 252   void *  volatile _owner;          // pointer to owning thread OR BasicLock
 253   volatile jlong _previous_owner_tid; // thread id of the previous owner of the monitor
 254   volatile intptr_t  _recursions;   // recursion count, 0 for first entry
 255  private:
 256   int OwnerIsThread ;               // _owner is (Thread *) vs SP/BasicLock
 257   ObjectWaiter * volatile _cxq ;    // LL of recently-arrived threads blocked on entry.
 258                                     // The list is actually composed of WaitNodes, acting
 259                                     // as proxies for Threads.
 260  protected:
 261   ObjectWaiter * volatile _EntryList ;     // Threads blocked on entry or reentry.
 262  private:
 263   Thread * volatile _succ ;          // Heir presumptive thread - used for futile wakeup throttling
 264   Thread * volatile _Responsible ;
 265   int _PromptDrain ;                // rqst to drain cxq into EntryList ASAP
 266 
 267   volatile int _Spinner ;           // for exit->spinner handoff optimization
 268   volatile int _SpinFreq ;          // Spin 1-out-of-N attempts: success rate
 269   volatile int _SpinClock ;
 270   volatile int _SpinDuration ;
 271   volatile intptr_t _SpinState ;    // MCS/CLH list of spinners
 272 
 273   // TODO-FIXME: _count, _waiters and _recursions should be of
 274   // type int, or int32_t but not intptr_t.  There's no reason
 275   // to use 64-bit fields for these variables on a 64-bit JVM.
 276 
 277   volatile intptr_t  _count;        // reference count to prevent reclaimation/deflation
 278                                     // at stop-the-world time.  See deflate_idle_monitors().
 279                                     // _count is approximately |_WaitSet| + |_EntryList|
 280  protected:
 281   volatile intptr_t  _waiters;      // number of waiting threads
 282  private:
 283  protected:
 284   ObjectWaiter * volatile _WaitSet; // LL of threads wait()ing on the monitor
 285  private:
 286   volatile int _WaitSetLock;        // protects Wait Queue - simple spinlock
 287 
 288  public:
 289   int _QMix ;                       // Mixed prepend queue discipline
 290   ObjectMonitor * FreeNext ;        // Free list linkage
 291   intptr_t StatA, StatsB ;
 292 
 293  public:
 294   static void Initialize () ;
 295   static PerfCounter * _sync_ContendedLockAttempts ;
 296   static PerfCounter * _sync_FutileWakeups ;
 297   static PerfCounter * _sync_Parks ;
 298   static PerfCounter * _sync_EmptyNotifications ;
 299   static PerfCounter * _sync_Notifications ;
 300   static PerfCounter * _sync_SlowEnter ;
 301   static PerfCounter * _sync_SlowExit ;
 302   static PerfCounter * _sync_SlowNotify ;
 303   static PerfCounter * _sync_SlowNotifyAll ;
 304   static PerfCounter * _sync_FailedSpins ;
 305   static PerfCounter * _sync_SuccessfulSpins ;
 306   static PerfCounter * _sync_PrivateA ;
 307   static PerfCounter * _sync_PrivateB ;
 308   static PerfCounter * _sync_MonInCirculation ;
 309   static PerfCounter * _sync_MonScavenged ;
 310   static PerfCounter * _sync_Inflations ;
 311   static PerfCounter * _sync_Deflations ;
 312   static PerfLongVariable * _sync_MonExtant ;
 313 
 314  public:
 315   static int Knob_Verbose;
 316   static int Knob_SpinLimit;
 317   void* operator new (size_t size) throw() {
 318     return AllocateHeap(size, mtInternal);
 319   }
 320   void* operator new[] (size_t size) throw() {
 321     return operator new (size);
 322   }
 323   void operator delete(void* p) {
 324     FreeHeap(p, mtInternal);
 325   }
 326   void operator delete[] (void *p) {
 327     operator delete(p);
 328   }
 329 };
 330 
 331 #undef TEVENT
 332 #define TEVENT(nom) {if (SyncVerbose) FEVENT(nom); }
 333 
 334 #define FEVENT(nom) { static volatile int ctr = 0 ; int v = ++ctr ; if ((v & (v-1)) == 0) { ::printf (#nom " : %d \n", v); ::fflush(stdout); }}
 335 
 336 #undef  TEVENT
 337 #define TEVENT(nom) {;}
 338 
 339 
 340 #endif // SHARE_VM_RUNTIME_OBJECTMONITOR_HPP