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 check_safepoint_state   (Thread* thread, bool safepoint_check) NOT_DEBUG_RETURN;
  96   void assert_owner            (Thread* expected)                     NOT_DEBUG_RETURN;
  97   void assert_wait_lock_state  (Thread* self)                         NOT_DEBUG_RETURN;
  98 
  99  public:
 100   enum {
 101     _allow_vm_block_flag        = true,
 102     _as_suspend_equivalent_flag = true
 103   };
 104 
 105   // Locks can be acquired with or without a safepoint check. NonJavaThreads do not follow
 106   // the safepoint protocol when acquiring locks.
 107 
 108   // Each lock can be acquired by only JavaThreads, only NonJavaThreads, or shared between
 109   // Java and NonJavaThreads. When the lock is initialized with _safepoint_check_always,
 110   // that means that whenever the lock is acquired by a JavaThread, it will verify that
 111   // it is done with a safepoint check. In corollary, when the lock is initialized with
 112   // _safepoint_check_never, that means that whenever the lock is acquired by a JavaThread
 113   // it will verify that it is done without a safepoint check.
 114 
 115 
 116   // There are a couple of existing locks that will sometimes have a safepoint check and
 117   // sometimes not when acquired by a JavaThread, but these locks are set up carefully
 118   // to avoid deadlocks. TODO: Fix these locks and remove _safepoint_check_sometimes.
 119 
 120   // TODO: Locks that are shared between JavaThreads and NonJavaThreads
 121   // should never encounter a safepoint check while they are held, or else a
 122   // deadlock can occur. We should check this by noting which
 123   // locks are shared, and walk held locks during safepoint checking.
 124 
 125   enum SafepointCheckFlag {
 126     _safepoint_check_flag,
 127     _no_safepoint_check_flag
 128   };
 129 
 130   enum SafepointCheckRequired {
 131     _safepoint_check_never,       // Monitors with this value will cause errors
 132                                   // when acquired by a JavaThread with a safepoint check.
 133     _safepoint_check_sometimes,   // A couple of special locks are acquired by JavaThreads sometimes
 134                                   // with and sometimes without safepoint checks. These
 135                                   // locks will not produce errors when locked.
 136     _safepoint_check_always       // Monitors with this value will cause errors
 137                                   // when acquired by a JavaThread without a safepoint check.
 138   };
 139 
 140   NOT_PRODUCT(SafepointCheckRequired _safepoint_check_required;)
 141 
 142  protected:
 143    static void ClearMonitor (Monitor * m, const char* name = NULL) ;
 144    Monitor() ;
 145 
 146  public:
 147   Monitor(int rank, const char *name, bool allow_vm_block = false,
 148           SafepointCheckRequired safepoint_check_required = _safepoint_check_always);
 149   ~Monitor();
 150 
 151   // Wait until monitor is notified (or times out).
 152   // Defaults are to make safepoint checks, wait time is forever (i.e.,
 153   // zero), and not a suspend-equivalent condition. Returns true if wait
 154   // times out; otherwise returns false.
 155   bool wait(long timeout = 0,
 156             bool as_suspend_equivalent = !_as_suspend_equivalent_flag);
 157   bool wait_without_safepoint_check(long timeout = 0);
 158   void notify();
 159   void notify_all();
 160 
 161 
 162   void lock(); // prints out warning if VM thread blocks
 163   void lock(Thread *thread); // overloaded with current thread
 164   void unlock();
 165   bool is_locked() const                     { return _owner != NULL; }
 166 
 167   bool try_lock(); // Like lock(), but unblocking. It returns false instead
 168 
 169   void release_for_safepoint();
 170 
 171   // Lock without safepoint check. Should ONLY be used by safepoint code and other code
 172   // that is guaranteed not to block while running inside the VM.
 173   void lock_without_safepoint_check();
 174   void lock_without_safepoint_check(Thread* self);
 175 
 176   // Current owner - not not MT-safe. Can only be used to guarantee that
 177   // the current running thread owns the lock
 178   Thread* owner() const         { return _owner; }
 179   bool owned_by_self() const;
 180 
 181   // Support for JVM_RawMonitorEnter & JVM_RawMonitorExit. These can be called by
 182   // non-Java thread. (We should really have a RawMonitor abstraction)
 183   void jvm_raw_lock();
 184   void jvm_raw_unlock();
 185   const char *name() const                  { return _name; }
 186 
 187   void print_on_error(outputStream* st) const;
 188 
 189   #ifndef PRODUCT
 190     void print_on(outputStream* st) const;
 191     void print() const                      { print_on(::tty); }
 192     DEBUG_ONLY(int    rank() const          { return _rank; })
 193     bool   allow_vm_block()                 { return _allow_vm_block; }
 194 
 195     DEBUG_ONLY(Monitor *next()  const         { return _next; })
 196     DEBUG_ONLY(void   set_next(Monitor *next) { _next = next; })
 197   #endif
 198 
 199   void set_owner(Thread* owner) {
 200   #ifndef PRODUCT
 201     set_owner_implementation(owner);
 202     DEBUG_ONLY(void verify_Monitor(Thread* thr);)
 203   #else
 204     _owner = owner;
 205   #endif
 206   }
 207 
 208 };
 209 
 210 class PaddedMonitor : public Monitor {
 211   enum {
 212     CACHE_LINE_PADDING = (int)DEFAULT_CACHE_LINE_SIZE - (int)sizeof(Monitor),
 213     PADDING_LEN = CACHE_LINE_PADDING > 0 ? CACHE_LINE_PADDING : 1
 214   };
 215   char _padding[PADDING_LEN];
 216  public:
 217   PaddedMonitor(int rank, const char *name, bool allow_vm_block = false,
 218                SafepointCheckRequired safepoint_check_required = _safepoint_check_always) :
 219     Monitor(rank, name, allow_vm_block, safepoint_check_required) {};
 220 };
 221 
 222 // Normally we'd expect Monitor to extend Mutex in the sense that a monitor
 223 // constructed from pthreads primitives might extend a mutex by adding
 224 // a condvar and some extra metadata.  In fact this was the case until J2SE7.
 225 //
 226 // Currently, however, the base object is a monitor.  Monitor contains all the
 227 // logic for wait(), notify(), etc.   Mutex extends monitor and restricts the
 228 // visibility of wait(), notify(), and notify_all().
 229 //
 230 // Another viable alternative would have been to have Monitor extend Mutex and
 231 // implement all the normal mutex and wait()-notify() logic in Mutex base class.
 232 // The wait()-notify() facility would be exposed via special protected member functions
 233 // (e.g., _Wait() and _Notify()) in Mutex.  Monitor would extend Mutex and expose wait()
 234 // as a call to _Wait().  That is, the public wait() would be a wrapper for the protected
 235 // _Wait().
 236 //
 237 // An even better alternative is to simply eliminate Mutex:: and use Monitor:: instead.
 238 // After all, monitors are sufficient for Java-level synchronization.   At one point in time
 239 // there may have been some benefit to having distinct mutexes and monitors, but that time
 240 // has passed.
 241 //
 242 
 243 class Mutex : public Monitor {      // degenerate Monitor
 244  public:
 245    Mutex(int rank, const char *name, bool allow_vm_block = false,
 246          SafepointCheckRequired safepoint_check_required = _safepoint_check_always);
 247    // default destructor
 248  private:
 249    void notify();
 250    void notify_all();
 251    bool wait(long timeout, bool as_suspend_equivalent);
 252    bool wait_without_safepoint_check(long timeout);
 253 };
 254 
 255 class PaddedMutex : public Mutex {
 256   enum {
 257     CACHE_LINE_PADDING = (int)DEFAULT_CACHE_LINE_SIZE - (int)sizeof(Mutex),
 258     PADDING_LEN = CACHE_LINE_PADDING > 0 ? CACHE_LINE_PADDING : 1
 259   };
 260   char _padding[PADDING_LEN];
 261 public:
 262   PaddedMutex(int rank, const char *name, bool allow_vm_block = false,
 263               SafepointCheckRequired safepoint_check_required = _safepoint_check_always) :
 264     Mutex(rank, name, allow_vm_block, safepoint_check_required) {};
 265 };
 266 
 267 #endif // SHARE_RUNTIME_MUTEX_HPP