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 Mutex : 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 was only for use in Mutexes created by JVM_RawMonitorCreate,
  56   // which being external to the VM are not subject to deadlock detection,
  57   // however it has now been used by other locks that don't fit into the
  58   // deadlock detection scheme.
  59   // While at a safepoint no mutexes of rank safepoint are held by any thread.
  60   // The rank named "leaf" is probably historical (and should
  61   // be changed) -- mutexes of this rank aren't really leaf mutexes
  62   // at all.
  63   enum lock_types {
  64        event,
  65        access         = event          +   1,
  66        tty            = access         +   2,
  67        special        = tty            +   1,
  68        suspend_resume = special        +   1,
  69        oopstorage     = suspend_resume +   2,
  70        leaf           = oopstorage     +   2,
  71        safepoint      = leaf           +  10,
  72        barrier        = safepoint      +   1,
  73        nonleaf        = barrier        +   1,
  74        max_nonleaf    = nonleaf        + 900,
  75        native         = max_nonleaf    +   1
  76   };
  77 
  78  protected:                              // Monitor-Mutex metadata
  79   Thread * volatile _owner;              // The owner of the lock
  80   os::PlatformMonitor _lock;             // Native monitor implementation
  81   char _name[MONITOR_NAME_LEN];          // Name of mutex/monitor
  82 
  83   // Debugging fields for naming, deadlock detection, etc. (some only used in debug mode)
  84 #ifndef PRODUCT
  85   bool      _allow_vm_block;
  86   DEBUG_ONLY(int _rank;)                 // rank (to avoid/detect potential deadlocks)
  87   DEBUG_ONLY(Mutex* _next;)              // Used by a Thread to link up owned locks
  88   DEBUG_ONLY(Thread* _last_owner;)       // the last thread to own the lock
  89   DEBUG_ONLY(static bool contains(Mutex* locks, Mutex* lock);)
  90   DEBUG_ONLY(static Mutex* get_least_ranked_lock(Mutex* locks);)
  91   DEBUG_ONLY(Mutex* get_least_ranked_lock_besides_this(Mutex* locks);)
  92 #endif
  93 
  94   void set_owner_implementation(Thread* owner)                        PRODUCT_RETURN;
  95   void check_prelock_state     (Thread* thread, bool safepoint_check) PRODUCT_RETURN;
  96   void check_block_state       (Thread* thread)                       PRODUCT_RETURN;
  97   void check_safepoint_state   (Thread* thread, bool safepoint_check) NOT_DEBUG_RETURN;
  98   void assert_owner            (Thread* expected)                     NOT_DEBUG_RETURN;
  99 
 100  public:
 101   enum {
 102     _allow_vm_block_flag        = true,
 103     _as_suspend_equivalent_flag = true
 104   };
 105 
 106   // Locks can be acquired with or without a safepoint check. NonJavaThreads do not follow
 107   // the safepoint protocol when acquiring locks.
 108 
 109   // Each lock can be acquired by only JavaThreads, only NonJavaThreads, or shared between
 110   // Java and NonJavaThreads. When the lock is initialized with _safepoint_check_always,
 111   // that means that whenever the lock is acquired by a JavaThread, it will verify that
 112   // it is done with a safepoint check. In corollary, when the lock is initialized with
 113   // _safepoint_check_never, that means that whenever the lock is acquired by a JavaThread
 114   // it will verify that it is done without a safepoint check.
 115 
 116 
 117   // There are a couple of existing locks that will sometimes have a safepoint check and
 118   // sometimes not when acquired by a JavaThread, but these locks are set up carefully
 119   // to avoid deadlocks. TODO: Fix these locks and remove _safepoint_check_sometimes.
 120 
 121   // TODO: Locks that are shared between JavaThreads and NonJavaThreads
 122   // should never encounter a safepoint check while they are held, or else a
 123   // deadlock can occur. We should check this by noting which
 124   // locks are shared, and walk held locks during safepoint checking.
 125 
 126   enum SafepointCheckFlag {
 127     _safepoint_check_flag,
 128     _no_safepoint_check_flag
 129   };
 130 
 131   enum SafepointCheckRequired {
 132     _safepoint_check_never,       // Mutexes with this value will cause errors
 133                                   // when acquired by a JavaThread with a safepoint check.
 134     _safepoint_check_sometimes,   // A couple of special locks are acquired by JavaThreads sometimes
 135                                   // with and sometimes without safepoint checks. These
 136                                   // locks will not produce errors when locked.
 137     _safepoint_check_always       // Mutexes with this value will cause errors
 138                                   // when acquired by a JavaThread without a safepoint check.
 139   };
 140 
 141   NOT_PRODUCT(SafepointCheckRequired _safepoint_check_required;)
 142 
 143  public:
 144   Mutex(int rank, const char *name, bool allow_vm_block = false,
 145         SafepointCheckRequired safepoint_check_required = _safepoint_check_always);
 146   ~Mutex();
 147 
 148   void lock(); // prints out warning if VM thread blocks
 149   void lock(Thread *thread); // overloaded with current thread
 150   void unlock();
 151   bool is_locked() const                     { return _owner != NULL; }
 152 
 153   bool try_lock(); // Like lock(), but unblocking. It returns false instead
 154 
 155   void release_for_safepoint();
 156 
 157   // Lock without safepoint check. Should ONLY be used by safepoint code and other code
 158   // that is guaranteed not to block while running inside the VM.
 159   void lock_without_safepoint_check();
 160   void lock_without_safepoint_check(Thread* self);
 161 
 162   // Current owner - not not MT-safe. Can only be used to guarantee that
 163   // the current running thread owns the lock
 164   Thread* owner() const         { return _owner; }
 165   bool owned_by_self() const;
 166 
 167   const char *name() const                  { return _name; }
 168 
 169   void print_on_error(outputStream* st) const;
 170 
 171   #ifndef PRODUCT
 172     void print_on(outputStream* st) const;
 173     void print() const                      { print_on(::tty); }
 174     DEBUG_ONLY(int    rank() const          { return _rank; })
 175     bool   allow_vm_block()                 { return _allow_vm_block; }
 176 
 177     DEBUG_ONLY(Mutex *next()  const         { return _next; })
 178     DEBUG_ONLY(void   set_next(Mutex *next) { _next = next; })
 179   #endif
 180 
 181   void set_owner(Thread* owner) {
 182   #ifndef PRODUCT
 183     set_owner_implementation(owner);
 184     DEBUG_ONLY(void verify_mutex(Thread* thr);)
 185   #else
 186     _owner = owner;
 187   #endif
 188   }
 189 
 190 };
 191 
 192 
 193 // PlatformMonitor extends PlatformMutex so this makes sense.
 194 
 195 class Monitor : public Mutex {
 196   void assert_wait_lock_state  (Thread* self)                         NOT_DEBUG_RETURN;
 197  public:
 198    Monitor(int rank, const char *name, bool allow_vm_block = false,
 199          SafepointCheckRequired safepoint_check_required = _safepoint_check_always);
 200    // default destructor
 201 
 202   // Wait until monitor is notified (or times out).
 203   // Defaults are to make safepoint checks, wait time is forever (i.e.,
 204   // zero), and not a suspend-equivalent condition. Returns true if wait
 205   // times out; otherwise returns false.
 206   bool wait(long timeout = 0,
 207             bool as_suspend_equivalent = !_as_suspend_equivalent_flag);
 208   bool wait_without_safepoint_check(long timeout = 0);
 209   void notify();
 210   void notify_all();
 211 };
 212 
 213 
 214 class PaddedMutex : public Mutex {
 215   enum {
 216     CACHE_LINE_PADDING = (int)DEFAULT_CACHE_LINE_SIZE - (int)sizeof(Mutex),
 217     PADDING_LEN = CACHE_LINE_PADDING > 0 ? CACHE_LINE_PADDING : 1
 218   };
 219   char _padding[PADDING_LEN];
 220 public:
 221   PaddedMutex(int rank, const char *name, bool allow_vm_block = false,
 222               SafepointCheckRequired safepoint_check_required = _safepoint_check_always) :
 223     Mutex(rank, name, allow_vm_block, safepoint_check_required) {};
 224 };
 225 
 226 class PaddedMonitor : public Monitor {
 227   enum {
 228     CACHE_LINE_PADDING = (int)DEFAULT_CACHE_LINE_SIZE - (int)sizeof(Monitor),
 229     PADDING_LEN = CACHE_LINE_PADDING > 0 ? CACHE_LINE_PADDING : 1
 230   };
 231   char _padding[PADDING_LEN];
 232  public:
 233   PaddedMonitor(int rank, const char *name, bool allow_vm_block = false,
 234                SafepointCheckRequired safepoint_check_required = _safepoint_check_always) :
 235     Monitor(rank, name, allow_vm_block, safepoint_check_required) {};
 236 };
 237 
 238 #endif // SHARE_RUNTIME_MUTEX_HPP