1 /*
   2  * Copyright (c) 1998, 2019, 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_MUTEX_HPP
  26 #define SHARE_RUNTIME_MUTEX_HPP
  27 
  28 #include "memory/allocation.hpp"
  29 #include "runtime/os.hpp"
  30 
  31 // A Mutex/Monitor is a simple wrapper around a native lock plus condition
  32 // variable that supports lock ownership tracking, lock ranking for deadlock
  33 // detection and coordinates with the safepoint protocol.
  34 
  35 // The default length of monitor name was originally chosen to be 64 to avoid
  36 // false sharing. Now, PaddedMonitor is available for this purpose.
  37 // TODO: Check if _name[MONITOR_NAME_LEN] should better get replaced by const char*.
  38 static const int MONITOR_NAME_LEN = 64;
  39 
  40 class Monitor : public CHeapObj<mtSynchronizer> {
  41 
  42  public:
  43   // A special lock: Is a lock where you are guaranteed not to block while you are
  44   // holding it, i.e., no vm operation can happen, taking other (blocking) locks, etc.
  45   // The rank 'access' is similar to 'special' and has the same restrictions on usage.
  46   // It is reserved for locks that may be required in order to perform memory accesses
  47   // that require special barriers, e.g. SATB GC barriers, that in turn uses locks.
  48   // The rank 'tty' is also similar to 'special' and has the same restrictions.
  49   // It is reserved for the tty_lock.
  50   // Since memory accesses should be able to be performed pretty much anywhere
  51   // in the code, that requires locks required for performing accesses being
  52   // inherently a bit more special than even locks of the 'special' rank.
  53   // NOTE: It is critical that the rank 'special' be the lowest (earliest)
  54   // (except for "event" and "access") for the deadlock detection to work correctly.
  55   // The rank native is only for use in Mutex's created by JVM_RawMonitorCreate,
  56   // which being external to the VM are not subject to deadlock detection.
  57   // While at a safepoint no mutexes of rank safepoint are held by any thread.
  58   // The rank named "leaf" is probably historical (and should
  59   // be changed) -- mutexes of this rank aren't really leaf mutexes
  60   // at all.
  61   enum lock_types {
  62        event,
  63        access         = event          +   1,
  64        tty            = access         +   2,
  65        special        = tty            +   1,
  66        suspend_resume = special        +   1,
  67        vmweak         = suspend_resume +   2,
  68        leaf           = vmweak         +   2,
  69        safepoint      = leaf           +  10,
  70        barrier        = safepoint      +   1,
  71        nonleaf        = barrier        +   1,
  72        max_nonleaf    = nonleaf        + 900,
  73        native         = max_nonleaf    +   1
  74   };
  75 
  76  protected:                              // Monitor-Mutex metadata
  77   Thread * volatile _owner;              // The owner of the lock
  78   os::PlatformMonitor _lock;             // Native monitor implementation
  79   char _name[MONITOR_NAME_LEN];          // Name of mutex/monitor
  80 
  81   // Debugging fields for naming, deadlock detection, etc. (some only used in debug mode)
  82 #ifndef PRODUCT
  83   bool      _allow_vm_block;
  84   DEBUG_ONLY(int _rank;)                 // rank (to avoid/detect potential deadlocks)
  85   DEBUG_ONLY(Monitor * _next;)           // Used by a Thread to link up owned locks
  86   DEBUG_ONLY(Thread* _last_owner;)       // the last thread to own the lock
  87   DEBUG_ONLY(static bool contains(Monitor * locks, Monitor * lock);)
  88   DEBUG_ONLY(static Monitor * get_least_ranked_lock(Monitor * locks);)
  89   DEBUG_ONLY(Monitor * get_least_ranked_lock_besides_this(Monitor * locks);)
  90 #endif
  91 
  92   void set_owner_implementation(Thread* owner)                        PRODUCT_RETURN;
  93   void check_prelock_state     (Thread* thread, bool safepoint_check) PRODUCT_RETURN;
  94   void check_block_state       (Thread* thread)                       PRODUCT_RETURN;
  95   void assert_owner            (Thread* expected)                     NOT_DEBUG_RETURN;
  96 
  97  public:
  98   enum {
  99     _no_safepoint_check_flag    = true,
 100     _allow_vm_block_flag        = true,
 101     _as_suspend_equivalent_flag = true
 102   };
 103 
 104   // Locks can be acquired with or without safepoint check.
 105   // Monitor::lock and Monitor::lock_without_safepoint_check
 106   // checks these flags when acquiring a lock to ensure
 107   // consistent checking for each lock.
 108   // A few existing locks will sometimes have a safepoint check and
 109   // sometimes not, but these locks are set up in such a way to avoid deadlocks.
 110   // Note: monitors that may be shared between JavaThreads and the VMThread
 111   // should never encounter a safepoint check whilst they are held, else a
 112   // deadlock with the VMThread can occur.
 113   enum SafepointCheckRequired {
 114     _safepoint_check_never,       // Monitors with this value will cause errors
 115                                   // when acquired with a safepoint check.
 116     _safepoint_check_sometimes,   // Certain locks are called sometimes with and
 117                                   // sometimes without safepoint checks. These
 118                                   // locks will not produce errors when locked.
 119     _safepoint_check_always       // Causes error if locked without a safepoint
 120                                   // check.
 121   };
 122 
 123   NOT_PRODUCT(SafepointCheckRequired _safepoint_check_required;)
 124 
 125  protected:
 126    static void ClearMonitor (Monitor * m, const char* name = NULL) ;
 127    Monitor() ;
 128 
 129  public:
 130   Monitor(int rank, const char *name, bool allow_vm_block = false,
 131           SafepointCheckRequired safepoint_check_required = _safepoint_check_always);
 132   ~Monitor();
 133 
 134   // Wait until monitor is notified (or times out).
 135   // Defaults are to make safepoint checks, wait time is forever (i.e.,
 136   // zero), and not a suspend-equivalent condition. Returns true if wait
 137   // times out; otherwise returns false.
 138   bool wait(bool no_safepoint_check = !_no_safepoint_check_flag,
 139             long timeout = 0,
 140             bool as_suspend_equivalent = !_as_suspend_equivalent_flag);
 141   void notify();
 142   void notify_all();
 143 
 144 
 145   void lock(); // prints out warning if VM thread blocks
 146   void lock(Thread *thread); // overloaded with current thread
 147   void unlock();
 148   bool is_locked() const                     { return _owner != NULL; }
 149 
 150   bool try_lock(); // Like lock(), but unblocking. It returns false instead
 151 
 152   void release_for_safepoint();
 153 
 154   // Lock without safepoint check. Should ONLY be used by safepoint code and other code
 155   // that is guaranteed not to block while running inside the VM.
 156   void lock_without_safepoint_check();
 157   void lock_without_safepoint_check (Thread * Self) ;
 158 
 159   // Current owner - not not MT-safe. Can only be used to guarantee that
 160   // the current running thread owns the lock
 161   Thread* owner() const         { return _owner; }
 162   bool owned_by_self() const;
 163 
 164   // Support for JVM_RawMonitorEnter & JVM_RawMonitorExit. These can be called by
 165   // non-Java thread. (We should really have a RawMonitor abstraction)
 166   void jvm_raw_lock();
 167   void jvm_raw_unlock();
 168   const char *name() const                  { return _name; }
 169 
 170   void print_on_error(outputStream* st) const;
 171 
 172   #ifndef PRODUCT
 173     void print_on(outputStream* st) const;
 174     void print() const                      { print_on(::tty); }
 175     DEBUG_ONLY(int    rank() const          { return _rank; })
 176     bool   allow_vm_block()                 { return _allow_vm_block; }
 177 
 178     DEBUG_ONLY(Monitor *next()  const         { return _next; })
 179     DEBUG_ONLY(void   set_next(Monitor *next) { _next = next; })
 180   #endif
 181 
 182   void set_owner(Thread* owner) {
 183   #ifndef PRODUCT
 184     set_owner_implementation(owner);
 185     DEBUG_ONLY(void verify_Monitor(Thread* thr);)
 186   #else
 187     _owner = owner;
 188   #endif
 189   }
 190 
 191 };
 192 
 193 class PaddedMonitor : public Monitor {
 194   enum {
 195     CACHE_LINE_PADDING = (int)DEFAULT_CACHE_LINE_SIZE - (int)sizeof(Monitor),
 196     PADDING_LEN = CACHE_LINE_PADDING > 0 ? CACHE_LINE_PADDING : 1
 197   };
 198   char _padding[PADDING_LEN];
 199  public:
 200   PaddedMonitor(int rank, const char *name, bool allow_vm_block = false,
 201                SafepointCheckRequired safepoint_check_required = _safepoint_check_always) :
 202     Monitor(rank, name, allow_vm_block, safepoint_check_required) {};
 203 };
 204 
 205 // Normally we'd expect Monitor to extend Mutex in the sense that a monitor
 206 // constructed from pthreads primitives might extend a mutex by adding
 207 // a condvar and some extra metadata.  In fact this was the case until J2SE7.
 208 //
 209 // Currently, however, the base object is a monitor.  Monitor contains all the
 210 // logic for wait(), notify(), etc.   Mutex extends monitor and restricts the
 211 // visibility of wait(), notify(), and notify_all().
 212 //
 213 // Another viable alternative would have been to have Monitor extend Mutex and
 214 // implement all the normal mutex and wait()-notify() logic in Mutex base class.
 215 // The wait()-notify() facility would be exposed via special protected member functions
 216 // (e.g., _Wait() and _Notify()) in Mutex.  Monitor would extend Mutex and expose wait()
 217 // as a call to _Wait().  That is, the public wait() would be a wrapper for the protected
 218 // _Wait().
 219 //
 220 // An even better alternative is to simply eliminate Mutex:: and use Monitor:: instead.
 221 // After all, monitors are sufficient for Java-level synchronization.   At one point in time
 222 // there may have been some benefit to having distinct mutexes and monitors, but that time
 223 // has past.
 224 //
 225 
 226 class Mutex : public Monitor {      // degenerate Monitor
 227  public:
 228    Mutex(int rank, const char *name, bool allow_vm_block = false,
 229          SafepointCheckRequired safepoint_check_required = _safepoint_check_always);
 230   // default destructor
 231  private:
 232    void notify ()    { ShouldNotReachHere(); }
 233    void notify_all() { ShouldNotReachHere(); }
 234    bool wait (bool no_safepoint_check, long timeout, bool as_suspend_equivalent) {
 235      ShouldNotReachHere() ;
 236      return false ;
 237    }
 238 };
 239 
 240 class PaddedMutex : public Mutex {
 241   enum {
 242     CACHE_LINE_PADDING = (int)DEFAULT_CACHE_LINE_SIZE - (int)sizeof(Mutex),
 243     PADDING_LEN = CACHE_LINE_PADDING > 0 ? CACHE_LINE_PADDING : 1
 244   };
 245   char _padding[PADDING_LEN];
 246 public:
 247   PaddedMutex(int rank, const char *name, bool allow_vm_block = false,
 248               SafepointCheckRequired safepoint_check_required = _safepoint_check_always) :
 249     Mutex(rank, name, allow_vm_block, safepoint_check_required) {};
 250 };
 251 
 252 #endif // SHARE_RUNTIME_MUTEX_HPP