1 /*
  2  * Copyright (c) 1998, 2023, 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/atomic.hpp"
 30 
 31 #if defined(LINUX) || defined(AIX) || defined(BSD)
 32 # include "mutex_posix.hpp"
 33 #else
 34 # include OS_HEADER(mutex)
 35 #endif
 36 
 37 
 38 // A Mutex/Monitor is a simple wrapper around a native lock plus condition
 39 // variable that supports lock ownership tracking, lock ranking for deadlock
 40 // detection and coordinates with the safepoint protocol.
 41 
 42 // Locking is non-recursive: if you try to lock a mutex you already own then you
 43 // will get an assertion failure in a debug build (which should suffice to expose
 44 // usage bugs). If you call try_lock on a mutex you already own it will return false.
 45 // The underlying PlatformMutex may support recursive locking but this is not exposed
 46 // and we account for that possibility in try_lock.
 47 
 48 // A thread is not allowed to safepoint while holding a mutex whose rank
 49 // is nosafepoint or lower.
 50 
 51 class Mutex : public CHeapObj<mtSynchronizer> {
 52 
 53  public:
 54   // Special low level locks are given names and ranges avoid overlap.
 55   enum class Rank {
 56        event,
 57        service        = event          +   6,
 58        stackwatermark = service        +   3,
 59        tty            = stackwatermark +   3,
 60        oopstorage     = tty            +   3,
 61        nosafepoint    = oopstorage     +   6,
 62        safepoint      = nosafepoint    +  20
 63   };
 64 
 65   // want C++later "using enum" directives.
 66   static const Rank event          = Rank::event;
 67   static const Rank service        = Rank::service;
 68   static const Rank stackwatermark = Rank::stackwatermark;
 69   static const Rank tty            = Rank::tty;
 70   static const Rank oopstorage     = Rank::oopstorage;
 71   static const Rank nosafepoint    = Rank::nosafepoint;
 72   static const Rank safepoint      = Rank::safepoint;
 73 
 74   static void assert_no_overlap(Rank orig, Rank adjusted, int adjust);
 75 
 76   friend Rank operator-(Rank base, int adjust) {
 77     Rank result = static_cast<Rank>(static_cast<int>(base) - adjust);
 78     DEBUG_ONLY(assert_no_overlap(base, result, adjust));
 79     return result;
 80   }
 81 
 82   friend constexpr bool operator<(Rank lhs, Rank rhs) {
 83     return static_cast<int>(lhs) < static_cast<int>(rhs);
 84   }
 85 
 86   friend constexpr bool operator>(Rank lhs, Rank rhs)  { return rhs < lhs; }
 87   friend constexpr bool operator<=(Rank lhs, Rank rhs) { return !(lhs > rhs); }
 88   friend constexpr bool operator>=(Rank lhs, Rank rhs) { return !(lhs < rhs); }
 89 
 90  private:
 91   // The _owner field is only set by the current thread, either to itself after it has acquired
 92   // the low-level _lock, or to null before it has released the _lock. Accesses by any thread other
 93   // than the lock owner are inherently racy.
 94   Thread* volatile _owner;
 95   void raw_set_owner(Thread* new_owner) { Atomic::store(&_owner, new_owner); }
 96 
 97  protected:                              // Monitor-Mutex metadata
 98   PlatformMonitor _lock;                 // Native monitor implementation
 99   const char* _name;                     // Name of mutex/monitor
100 
101   // Debugging fields for naming, deadlock detection, etc. (some only used in debug mode)
102 #ifndef PRODUCT
103   bool    _allow_vm_block;
104 #endif
105 #ifdef ASSERT
106   Rank    _rank;                 // rank (to avoid/detect potential deadlocks)
107   Mutex*  _next;                 // Used by a Thread to link up owned locks
108   Thread* _last_owner;           // the last thread to own the lock
109   bool _skip_rank_check;         // read only by owner when doing rank checks
110 
111   static Mutex* get_least_ranked_lock(Mutex* locks);
112   Mutex* get_least_ranked_lock_besides_this(Mutex* locks);
113   bool skip_rank_check() {
114     assert(owned_by_self(), "only the owner should call this");
115     return _skip_rank_check;
116   }
117 
118  public:
119   Rank   rank() const          { return _rank; }
120   const char*  rank_name() const;
121   Mutex* next()  const         { return _next; }
122 #endif // ASSERT
123 
124  protected:
125   void set_owner_implementation(Thread* owner)                        NOT_DEBUG({ raw_set_owner(owner);});
126   void check_block_state       (Thread* thread)                       NOT_DEBUG_RETURN;
127   void check_safepoint_state   (Thread* thread)                       NOT_DEBUG_RETURN;
128   void check_no_safepoint_state(Thread* thread)                       NOT_DEBUG_RETURN;
129   void check_rank              (Thread* thread)                       NOT_DEBUG_RETURN;
130   void assert_owner            (Thread* expected)                     NOT_DEBUG_RETURN;
131 
132  public:
133   static const bool _allow_vm_block_flag        = true;
134 
135   // Locks can be acquired with or without a safepoint check. NonJavaThreads do not follow
136   // the safepoint protocol when acquiring locks.
137 
138   // Each lock can be acquired by only JavaThreads, only NonJavaThreads, or shared between
139   // Java and NonJavaThreads. When the lock is initialized with rank > nosafepoint,
140   // that means that whenever the lock is acquired by a JavaThread, it will verify that
141   // it is done with a safepoint check. In corollary, when the lock is initialized with
142   // rank <= nosafepoint, that means that whenever the lock is acquired by a JavaThread
143   // it will verify that it is done without a safepoint check.
144 
145   // TODO: Locks that are shared between JavaThreads and NonJavaThreads
146   // should never encounter a safepoint check while they are held, or else a
147   // deadlock can occur. We should check this by noting which
148   // locks are shared, and walk held locks during safepoint checking.
149 
150   enum class SafepointCheckFlag {
151     _safepoint_check_flag,
152     _no_safepoint_check_flag
153   };
154   // Bring the enumerator names into class scope.
155   static const SafepointCheckFlag _safepoint_check_flag =
156     SafepointCheckFlag::_safepoint_check_flag;
157   static const SafepointCheckFlag _no_safepoint_check_flag =
158     SafepointCheckFlag::_no_safepoint_check_flag;
159 
160  public:
161   Mutex(Rank rank, const char *name, bool allow_vm_block);
162 
163   Mutex(Rank rank, const char *name) :
164     Mutex(rank, name, rank > nosafepoint ? false : true) {}
165 
166   ~Mutex();
167 
168   void lock(); // prints out warning if VM thread blocks
169   void lock(Thread *thread); // overloaded with current thread
170   void unlock();
171   bool is_locked() const                     { return owner() != nullptr; }
172 
173   bool try_lock(); // Like lock(), but unblocking. It returns false instead
174  private:
175   void lock_contended(Thread *thread); // contended slow-path
176   bool try_lock_inner(bool do_rank_checks);
177  public:
178 
179   void release_for_safepoint();
180 
181   // Lock without safepoint check. Should ONLY be used by safepoint code and other code
182   // that is guaranteed not to block while running inside the VM.
183   void lock_without_safepoint_check();
184   void lock_without_safepoint_check(Thread* self);
185   // A thread should not call this if failure to acquire ownership will blocks its progress
186   bool try_lock_without_rank_check();
187 
188   // Current owner - note not MT-safe. Can only be used to guarantee that
189   // the current running thread owns the lock
190   Thread* owner() const         { return Atomic::load(&_owner); }
191   void set_owner(Thread* owner) { set_owner_implementation(owner); }
192   bool owned_by_self() const;
193 
194   const char *name() const                  { return _name; }
195 
196   void print_on_error(outputStream* st) const;
197   #ifndef PRODUCT
198     void print_on(outputStream* st) const;
199     void print() const;
200   #endif
201 };
202 
203 class Monitor : public Mutex {
204  public:
205   Monitor(Rank rank, const char *name, bool allow_vm_block)  :
206     Mutex(rank, name, allow_vm_block) {}
207 
208   Monitor(Rank rank, const char *name) :
209     Mutex(rank, name) {}
210   // default destructor
211 
212   // Wait until monitor is notified (or times out).
213   // Defaults are to make safepoint checks, wait time is forever (i.e.,
214   // zero). Returns true if wait times out; otherwise returns false.
215   bool wait(uint64_t timeout = 0);
216   bool wait_without_safepoint_check(uint64_t timeout = 0);
217   void notify();
218   void notify_all();
219 };
220 
221 
222 class PaddedMutex : public Mutex {
223   enum {
224     CACHE_LINE_PADDING = (int)DEFAULT_PADDING_SIZE - (int)sizeof(Mutex),
225     PADDING_LEN = CACHE_LINE_PADDING > 0 ? CACHE_LINE_PADDING : 1
226   };
227   char _padding[PADDING_LEN];
228 public:
229   PaddedMutex(Rank rank, const char *name, bool allow_vm_block) : Mutex(rank, name, allow_vm_block) {};
230   PaddedMutex(Rank rank, const char *name) : Mutex(rank, name) {};
231 };
232 
233 class PaddedMonitor : public Monitor {
234   enum {
235     CACHE_LINE_PADDING = (int)DEFAULT_PADDING_SIZE - (int)sizeof(Monitor),
236     PADDING_LEN = CACHE_LINE_PADDING > 0 ? CACHE_LINE_PADDING : 1
237   };
238   char _padding[PADDING_LEN];
239  public:
240   PaddedMonitor(Rank rank, const char *name, bool allow_vm_block) : Monitor(rank, name, allow_vm_block) {};
241   PaddedMonitor(Rank rank, const char *name) : Monitor(rank, name) {};
242 };
243 
244 #endif // SHARE_RUNTIME_MUTEX_HPP