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 mutex name was originally chosen to be 64 to avoid
  36 // false sharing. Now, PaddedMutex and PaddedMonitor are available for this purpose.
  37 // TODO: Check if _name[MUTEX_NAME_LEN] should better get replaced by const char*.
  38 static const int MUTEX_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            +   2,
  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[MUTEX_NAME_LEN];            // Name of mutex/monitor
  82 
  83   // Debugging fields for naming, deadlock detection, etc. (some only used in debug mode)
  84 #ifdef ASSERT
  85   bool    _allow_vm_block;
  86   int     _rank;                 // rank (to avoid/detect potential deadlocks)
  87   Mutex*  _next;                 // Used by a Thread to link up owned locks
  88   Thread* _last_owner;           // the last thread to own the lock
  89   static bool contains(Mutex* locks, Mutex* lock);
  90   static Mutex* get_least_ranked_lock(Mutex* locks);
  91   Mutex* get_least_ranked_lock_besides_this(Mutex* locks);
  92 #endif  // ASSERT
  93 
  94   void set_owner_implementation(Thread* owner)                        NOT_DEBUG({ _owner = owner;});
  95   void check_block_state       (Thread* thread)                       NOT_DEBUG_RETURN;
  96   void check_safepoint_state   (Thread* thread)                       NOT_DEBUG_RETURN;
  97   void check_no_safepoint_state(Thread* thread)                       NOT_DEBUG_RETURN;
  98   void assert_owner            (Thread* expected)                     NOT_DEBUG_RETURN;
  99   void no_safepoint_verifier   (Thread* thread, bool enable)          NOT_DEBUG_RETURN;
 100 
 101  public:
 102   enum {
 103     _allow_vm_block_flag        = true,
 104     _as_suspend_equivalent_flag = true
 105   };
 106 
 107   // Locks can be acquired with or without a safepoint check. NonJavaThreads do not follow
 108   // the safepoint protocol when acquiring locks.
 109 
 110   // Each lock can be acquired by only JavaThreads, only NonJavaThreads, or shared between
 111   // Java and NonJavaThreads. When the lock is initialized with _safepoint_check_always,
 112   // that means that whenever the lock is acquired by a JavaThread, it will verify that
 113   // it is done with a safepoint check. In corollary, when the lock is initialized with
 114   // _safepoint_check_never, that means that whenever the lock is acquired by a JavaThread
 115   // it will verify that it is done without a safepoint check.
 116 
 117 
 118   // There are a couple of existing locks that will sometimes have a safepoint check and
 119   // sometimes not when acquired by a JavaThread, but these locks are set up carefully
 120   // to avoid deadlocks. TODO: Fix these locks and remove _safepoint_check_sometimes.
 121 
 122   // TODO: Locks that are shared between JavaThreads and NonJavaThreads
 123   // should never encounter a safepoint check while they are held, or else a
 124   // deadlock can occur. We should check this by noting which
 125   // locks are shared, and walk held locks during safepoint checking.
 126 
 127   enum SafepointCheckFlag {
 128     _safepoint_check_flag,
 129     _no_safepoint_check_flag
 130   };
 131 
 132   enum SafepointCheckRequired {
 133     _safepoint_check_never,       // Mutexes with this value will cause errors
 134                                   // when acquired by a JavaThread with a safepoint check.
 135     _safepoint_check_sometimes,   // A couple of special locks are acquired by JavaThreads sometimes
 136                                   // with and sometimes without safepoint checks. These
 137                                   // locks will not produce errors when locked.
 138     _safepoint_check_always       // Mutexes with this value will cause errors
 139                                   // when acquired by a JavaThread without a safepoint check.
 140   };
 141 
 142   NOT_PRODUCT(SafepointCheckRequired _safepoint_check_required;)
 143 
 144  public:
 145   Mutex(int rank, const char *name, bool allow_vm_block = false,
 146         SafepointCheckRequired safepoint_check_required = _safepoint_check_always);
 147   ~Mutex();
 148 
 149   void lock(); // prints out warning if VM thread blocks
 150   void lock(Thread *thread); // overloaded with current thread
 151   void unlock();
 152   bool is_locked() const                     { return _owner != NULL; }
 153 
 154   bool try_lock(); // Like lock(), but unblocking. It returns false instead
 155 
 156   void release_for_safepoint();
 157 
 158   // Lock without safepoint check. Should ONLY be used by safepoint code and other code
 159   // that is guaranteed not to block while running inside the VM.
 160   void lock_without_safepoint_check();
 161   void lock_without_safepoint_check(Thread* self);
 162 
 163   // Current owner - not not MT-safe. Can only be used to guarantee that
 164   // the current running thread owns the lock
 165   Thread* owner() const         { return _owner; }
 166   bool owned_by_self() const;
 167 
 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   #endif
 176   #ifdef ASSERT
 177     int    rank() const          { return _rank; }
 178     bool   allow_vm_block()      { return _allow_vm_block; }
 179 
 180     Mutex *next()  const         { return _next; }
 181     void   set_next(Mutex *next) { _next = next; }
 182   #endif // ASSERT
 183 
 184   void set_owner(Thread* owner)             { set_owner_implementation(owner); }
 185 };
 186 
 187 class Monitor : public Mutex {
 188   void assert_wait_lock_state  (Thread* self)                         NOT_DEBUG_RETURN;
 189  public:
 190    Monitor(int rank, const char *name, bool allow_vm_block = false,
 191          SafepointCheckRequired safepoint_check_required = _safepoint_check_always);
 192    // default destructor
 193 
 194   // Wait until monitor is notified (or times out).
 195   // Defaults are to make safepoint checks, wait time is forever (i.e.,
 196   // zero), and not a suspend-equivalent condition. Returns true if wait
 197   // times out; otherwise returns false.
 198   bool wait(long timeout = 0,
 199             bool as_suspend_equivalent = !_as_suspend_equivalent_flag);
 200   bool wait_without_safepoint_check(long timeout = 0);
 201   void notify();
 202   void notify_all();
 203 };
 204 
 205 
 206 class PaddedMutex : public Mutex {
 207   enum {
 208     CACHE_LINE_PADDING = (int)DEFAULT_CACHE_LINE_SIZE - (int)sizeof(Mutex),
 209     PADDING_LEN = CACHE_LINE_PADDING > 0 ? CACHE_LINE_PADDING : 1
 210   };
 211   char _padding[PADDING_LEN];
 212 public:
 213   PaddedMutex(int rank, const char *name, bool allow_vm_block = false,
 214               SafepointCheckRequired safepoint_check_required = _safepoint_check_always) :
 215     Mutex(rank, name, allow_vm_block, safepoint_check_required) {};
 216 };
 217 
 218 class PaddedMonitor : public Monitor {
 219   enum {
 220     CACHE_LINE_PADDING = (int)DEFAULT_CACHE_LINE_SIZE - (int)sizeof(Monitor),
 221     PADDING_LEN = CACHE_LINE_PADDING > 0 ? CACHE_LINE_PADDING : 1
 222   };
 223   char _padding[PADDING_LEN];
 224  public:
 225   PaddedMonitor(int rank, const char *name, bool allow_vm_block = false,
 226                SafepointCheckRequired safepoint_check_required = _safepoint_check_always) :
 227     Monitor(rank, name, allow_vm_block, safepoint_check_required) {};
 228 };
 229 
 230 #endif // SHARE_RUNTIME_MUTEX_HPP