1 /*
   2  * Copyright (c) 1998, 2017, 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_MUTEX_HPP
  26 #define SHARE_VM_RUNTIME_MUTEX_HPP
  27 
  28 #include "memory/allocation.hpp"
  29 #include "runtime/os.hpp"
  30 #include "utilities/histogram.hpp"
  31 
  32 // The SplitWord construct allows us to colocate the contention queue
  33 // (cxq) with the lock-byte.  The queue elements are ParkEvents, which are
  34 // always aligned on 256-byte addresses - the least significant byte of
  35 // a ParkEvent is always 0.  Colocating the lock-byte with the queue
  36 // allows us to easily avoid what would otherwise be a race in lock()
  37 // if we were to use two completely separate fields for the contention queue
  38 // and the lock indicator.  Specifically, colocation renders us immune
  39 // from the race where a thread might enqueue itself in the lock() slow-path
  40 // immediately after the lock holder drops the outer lock in the unlock()
  41 // fast-path.
  42 //
  43 // Colocation allows us to use a fast-path unlock() form that uses
  44 // A MEMBAR instead of a CAS.  MEMBAR has lower local latency than CAS
  45 // on many platforms.
  46 //
  47 // See:
  48 // +  http://blogs.sun.com/dave/entry/biased_locking_in_hotspot
  49 // +  http://blogs.sun.com/dave/resource/synchronization-public2.pdf
  50 //
  51 // Note that we're *not* using word-tearing the classic sense.
  52 // The lock() fast-path will CAS the lockword and the unlock()
  53 // fast-path will store into the lock-byte colocated within the lockword.
  54 // We depend on the fact that all our reference platforms have
  55 // coherent and atomic byte accesses.  More precisely, byte stores
  56 // interoperate in a safe, sane, and expected manner with respect to
  57 // CAS, ST and LDs to the full-word containing the byte.
  58 // If you're porting HotSpot to a platform where that isn't the case
  59 // then you'll want change the unlock() fast path from:
  60 //    STB;MEMBAR #storeload; LDN
  61 // to a full-word CAS of the lockword.
  62 
  63 
  64 union SplitWord {   // full-word with separately addressable LSB
  65   volatile intptr_t FullWord ;
  66   volatile void * Address ;
  67   volatile jbyte Bytes [sizeof(intptr_t)] ;
  68 } ;
  69 
  70 class ParkEvent ;
  71 
  72 // See orderAccess.hpp.  We assume throughout the VM that mutex lock and
  73 // try_lock do fence-lock-acquire, and that unlock does a release-unlock,
  74 // *in that order*.  If their implementations change such that these
  75 // assumptions are violated, a whole lot of code will break.
  76 
  77 // The default length of monitor name was originally chosen to be 64 to avoid
  78 // false sharing. Now, PaddedMonitor is available for this purpose.
  79 // TODO: Check if _name[MONITOR_NAME_LEN] should better get replaced by const char*.
  80 static const int MONITOR_NAME_LEN = 64;
  81 
  82 class Monitor : public CHeapObj<mtInternal> {
  83 
  84  public:
  85   // A special lock: Is a lock where you are guaranteed not to block while you are
  86   // holding it, i.e., no vm operation can happen, taking other (blocking) locks, etc.
  87   // The rank 'access' is similar to 'special' and has the same restrictions on usage.
  88   // It is reserved for locks that may be required in order to perform memory accesses
  89   // that require special barriers, e.g. SATB GC barriers, that in turn uses locks.
  90   // Since memory accesses should be able to be performed pretty much anywhere
  91   // in the code, that requires locks required for performing accesses being
  92   // inherently a bit more special than even locks of the 'special' rank.
  93   // NOTE: It is critical that the rank 'special' be the lowest (earliest)
  94   // (except for "event" and "access") for the deadlock detection to work correctly.
  95   // The rank native is only for use in Mutex's created by JVM_RawMonitorCreate,
  96   // which being external to the VM are not subject to deadlock detection.
  97   // The rank safepoint is used only for synchronization in reaching a
  98   // safepoint and leaving a safepoint.  It is only used for the Safepoint_lock
  99   // currently.  While at a safepoint no mutexes of rank safepoint are held
 100   // by any thread.
 101   // The rank named "leaf" is probably historical (and should
 102   // be changed) -- mutexes of this rank aren't really leaf mutexes
 103   // at all.
 104   enum lock_types {
 105        event,
 106        access         = event          +   1,
 107        special        = access         +   2,
 108        suspend_resume = special        +   1,
 109        leaf           = suspend_resume +   2,
 110        safepoint      = leaf           +  10,
 111        barrier        = safepoint      +   1,
 112        nonleaf        = barrier        +   1,
 113        max_nonleaf    = nonleaf        + 900,
 114        native         = max_nonleaf    +   1
 115   };
 116 
 117   // The WaitSet and EntryList linked lists are composed of ParkEvents.
 118   // I use ParkEvent instead of threads as ParkEvents are immortal and
 119   // type-stable, meaning we can safely unpark() a possibly stale
 120   // list element in the unlock()-path.
 121 
 122  protected:                              // Monitor-Mutex metadata
 123   SplitWord _LockWord ;                  // Contention queue (cxq) colocated with Lock-byte
 124   Thread * volatile _owner;              // The owner of the lock
 125                                          // Consider sequestering _owner on its own $line
 126                                          // to aid future synchronization mechanisms.
 127   ParkEvent * volatile _EntryList ;      // List of threads waiting for entry
 128   ParkEvent * volatile _OnDeck ;         // heir-presumptive
 129   volatile intptr_t _WaitLock [1] ;      // Protects _WaitSet
 130   ParkEvent * volatile  _WaitSet ;       // LL of ParkEvents
 131   volatile bool     _snuck;              // Used for sneaky locking (evil).
 132   int NotifyCount ;                      // diagnostic assist
 133   char _name[MONITOR_NAME_LEN];          // Name of mutex
 134 
 135   // Debugging fields for naming, deadlock detection, etc. (some only used in debug mode)
 136 #ifndef PRODUCT
 137   bool      _allow_vm_block;
 138   debug_only(int _rank;)                 // rank (to avoid/detect potential deadlocks)
 139   debug_only(Monitor * _next;)           // Used by a Thread to link up owned locks
 140   debug_only(Thread* _last_owner;)       // the last thread to own the lock
 141   debug_only(static bool contains(Monitor * locks, Monitor * lock);)
 142   debug_only(static Monitor * get_least_ranked_lock(Monitor * locks);)
 143   debug_only(Monitor * get_least_ranked_lock_besides_this(Monitor * locks);)
 144 #endif
 145 
 146   void set_owner_implementation(Thread* owner)                        PRODUCT_RETURN;
 147   void check_prelock_state     (Thread* thread)                       PRODUCT_RETURN;
 148   void check_block_state       (Thread* thread)                       PRODUCT_RETURN;
 149 
 150   // platform-dependent support code can go here (in os_<os_family>.cpp)
 151  public:
 152   enum {
 153     _no_safepoint_check_flag    = true,
 154     _allow_vm_block_flag        = true,
 155     _as_suspend_equivalent_flag = true
 156   };
 157 
 158   // Locks can be acquired with or without safepoint check.
 159   // Monitor::lock and Monitor::lock_without_safepoint_check
 160   // checks these flags when acquiring a lock to ensure
 161   // consistent checking for each lock.
 162   // A few existing locks will sometimes have a safepoint check and
 163   // sometimes not, but these locks are set up in such a way to avoid deadlocks.
 164   enum SafepointCheckRequired {
 165     _safepoint_check_never,       // Monitors with this value will cause errors
 166                                   // when acquired with a safepoint check.
 167     _safepoint_check_sometimes,   // Certain locks are called sometimes with and
 168                                   // sometimes without safepoint checks. These
 169                                   // locks will not produce errors when locked.
 170     _safepoint_check_always       // Causes error if locked without a safepoint
 171                                   // check.
 172   };
 173 
 174   NOT_PRODUCT(SafepointCheckRequired _safepoint_check_required;)
 175 
 176   enum WaitResults {
 177     CONDVAR_EVENT,         // Wait returned because of condition variable notification
 178     INTERRUPT_EVENT,       // Wait returned because waiting thread was interrupted
 179     NUMBER_WAIT_RESULTS
 180   };
 181 
 182  private:
 183    int  TrySpin (Thread * Self) ;
 184    int  TryLock () ;
 185    int  TryFast () ;
 186    int  AcquireOrPush (ParkEvent * ev) ;
 187    void IUnlock (bool RelaxAssert) ;
 188    void ILock (Thread * Self) ;
 189    int  IWait (Thread * Self, jlong timo);
 190    int  ILocked () ;
 191 
 192  protected:
 193    static void ClearMonitor (Monitor * m, const char* name = NULL) ;
 194    Monitor() ;
 195 
 196  public:
 197   Monitor(int rank, const char *name, bool allow_vm_block = false,
 198           SafepointCheckRequired safepoint_check_required = _safepoint_check_always);
 199   ~Monitor();
 200 
 201   // Wait until monitor is notified (or times out).
 202   // Defaults are to make safepoint checks, wait time is forever (i.e.,
 203   // zero), and not a suspend-equivalent condition. Returns true if wait
 204   // times out; otherwise returns false.
 205   bool wait(bool no_safepoint_check = !_no_safepoint_check_flag,
 206             long timeout = 0,
 207             bool as_suspend_equivalent = !_as_suspend_equivalent_flag);
 208   bool notify();
 209   bool notify_all();
 210 
 211 
 212   void lock(); // prints out warning if VM thread blocks
 213   void lock(Thread *thread); // overloaded with current thread
 214   void unlock();
 215   bool is_locked() const                     { return _owner != NULL; }
 216 
 217   bool try_lock(); // Like lock(), but unblocking. It returns false instead
 218 
 219   // Lock without safepoint check. Should ONLY be used by safepoint code and other code
 220   // that is guaranteed not to block while running inside the VM.
 221   void lock_without_safepoint_check();
 222   void lock_without_safepoint_check (Thread * Self) ;
 223 
 224   // Current owner - not not MT-safe. Can only be used to guarantee that
 225   // the current running thread owns the lock
 226   Thread* owner() const         { return _owner; }
 227   bool owned_by_self() const;
 228 
 229   // Support for JVM_RawMonitorEnter & JVM_RawMonitorExit. These can be called by
 230   // non-Java thread. (We should really have a RawMonitor abstraction)
 231   void jvm_raw_lock();
 232   void jvm_raw_unlock();
 233   const char *name() const                  { return _name; }
 234 
 235   void print_on_error(outputStream* st) const;
 236 
 237   #ifndef PRODUCT
 238     void print_on(outputStream* st) const;
 239     void print() const                      { print_on(tty); }
 240     debug_only(int    rank() const          { return _rank; })
 241     bool   allow_vm_block()                 { return _allow_vm_block; }
 242 
 243     debug_only(Monitor *next()  const         { return _next; })
 244     debug_only(void   set_next(Monitor *next) { _next = next; })
 245   #endif
 246 
 247   void set_owner(Thread* owner) {
 248   #ifndef PRODUCT
 249     set_owner_implementation(owner);
 250     debug_only(void verify_Monitor(Thread* thr));
 251   #else
 252     _owner = owner;
 253   #endif
 254   }
 255 
 256 };
 257 
 258 class PaddedMonitor : public Monitor {
 259   enum {
 260     CACHE_LINE_PADDING = (int)DEFAULT_CACHE_LINE_SIZE - (int)sizeof(Monitor),
 261     PADDING_LEN = CACHE_LINE_PADDING > 0 ? CACHE_LINE_PADDING : 1
 262   };
 263   char _padding[PADDING_LEN];
 264  public:
 265   PaddedMonitor(int rank, const char *name, bool allow_vm_block = false,
 266                SafepointCheckRequired safepoint_check_required = _safepoint_check_always) :
 267     Monitor(rank, name, allow_vm_block, safepoint_check_required) {};
 268 };
 269 
 270 // Normally we'd expect Monitor to extend Mutex in the sense that a monitor
 271 // constructed from pthreads primitives might extend a mutex by adding
 272 // a condvar and some extra metadata.  In fact this was the case until J2SE7.
 273 //
 274 // Currently, however, the base object is a monitor.  Monitor contains all the
 275 // logic for wait(), notify(), etc.   Mutex extends monitor and restricts the
 276 // visibility of wait(), notify(), and notify_all().
 277 //
 278 // Another viable alternative would have been to have Monitor extend Mutex and
 279 // implement all the normal mutex and wait()-notify() logic in Mutex base class.
 280 // The wait()-notify() facility would be exposed via special protected member functions
 281 // (e.g., _Wait() and _Notify()) in Mutex.  Monitor would extend Mutex and expose wait()
 282 // as a call to _Wait().  That is, the public wait() would be a wrapper for the protected
 283 // _Wait().
 284 //
 285 // An even better alternative is to simply eliminate Mutex:: and use Monitor:: instead.
 286 // After all, monitors are sufficient for Java-level synchronization.   At one point in time
 287 // there may have been some benefit to having distinct mutexes and monitors, but that time
 288 // has past.
 289 //
 290 // The Mutex/Monitor design parallels that of Java-monitors, being based on
 291 // thread-specific park-unpark platform-specific primitives.
 292 
 293 
 294 class Mutex : public Monitor {      // degenerate Monitor
 295  public:
 296    Mutex(int rank, const char *name, bool allow_vm_block = false,
 297          SafepointCheckRequired safepoint_check_required = _safepoint_check_always);
 298   // default destructor
 299  private:
 300    bool notify ()    { ShouldNotReachHere(); return false; }
 301    bool notify_all() { ShouldNotReachHere(); return false; }
 302    bool wait (bool no_safepoint_check, long timeout, bool as_suspend_equivalent) {
 303      ShouldNotReachHere() ;
 304      return false ;
 305    }
 306 };
 307 
 308 class PaddedMutex : public Mutex {
 309   enum {
 310     CACHE_LINE_PADDING = (int)DEFAULT_CACHE_LINE_SIZE - (int)sizeof(Mutex),
 311     PADDING_LEN = CACHE_LINE_PADDING > 0 ? CACHE_LINE_PADDING : 1
 312   };
 313   char _padding[PADDING_LEN];
 314 public:
 315   PaddedMutex(int rank, const char *name, bool allow_vm_block = false,
 316               SafepointCheckRequired safepoint_check_required = _safepoint_check_always) :
 317     Mutex(rank, name, allow_vm_block, safepoint_check_required) {};
 318 };
 319 
 320 #endif // SHARE_VM_RUNTIME_MUTEX_HPP