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 #include "precompiled.hpp"
  26 #include "logging/log.hpp"
  27 #include "runtime/interfaceSupport.inline.hpp"
  28 #include "runtime/mutex.hpp"
  29 #include "runtime/osThread.hpp"
  30 #include "runtime/safepointMechanism.inline.hpp"
  31 #include "runtime/thread.inline.hpp"
  32 #include "utilities/events.hpp"
  33 #include "utilities/macros.hpp"
  34 
  35 #ifdef ASSERT
  36 void Mutex::check_safepoint_state(Thread* thread, bool do_safepoint_check) {
  37   // If the JavaThread checks for safepoint, verify that the lock wasn't created with safepoint_check_never.
  38   SafepointCheckRequired not_allowed = do_safepoint_check ?  Mutex::_safepoint_check_never :
  39                                                              Mutex::_safepoint_check_always;
  40   assert(!thread->is_active_Java_thread() || _safepoint_check_required != not_allowed,
  41          "This lock should %s have a safepoint check for Java threads: %s",
  42          _safepoint_check_required ? "always" : "never", name());
  43 
  44   // If defined with safepoint_check_never, a NonJavaThread should never ask to safepoint check either.
  45   assert(thread->is_Java_thread() || !do_safepoint_check || _safepoint_check_required != Mutex::_safepoint_check_never,
  46          "NonJavaThread should not check for safepoint");
  47 }
  48 #endif // ASSERT
  49 
  50 void Mutex::lock(Thread * self) {
  51   check_safepoint_state(self, true);
  52 
  53   DEBUG_ONLY(check_prelock_state(self, true));
  54   assert(_owner != self, "invariant");
  55 
  56   Mutex* in_flight_mutex = NULL;
  57   DEBUG_ONLY(int retry_cnt = 0;)
  58   bool is_active_Java_thread = self->is_active_Java_thread();
  59   while (!_lock.try_lock()) {
  60     // The lock is contended
  61 
  62   #ifdef ASSERT
  63     check_block_state(self);
  64     if (retry_cnt++ > 3) {
  65       log_trace(vmmutex)("JavaThread " INTPTR_FORMAT " on %d attempt trying to acquire vmmutex %s", p2i(self), retry_cnt, _name);
  66     }
  67   #endif // ASSERT
  68 
  69     // Is it a JavaThread participating in the safepoint protocol.
  70     if (is_active_Java_thread) {
  71       assert(rank() > Mutex::special, "Potential deadlock with special or lesser rank mutex");
  72       { ThreadBlockInVMWithDeadlockCheck tbivmdc((JavaThread *) self, &in_flight_mutex);
  73         in_flight_mutex = this;  // save for ~ThreadBlockInVMWithDeadlockCheck
  74         _lock.lock();
  75       }
  76       if (in_flight_mutex != NULL) {
  77         // Not unlocked by ~ThreadBlockInVMWithDeadlockCheck
  78         break;
  79       }
  80     } else {
  81       _lock.lock();
  82       break;
  83     }
  84   }
  85 
  86   assert_owner(NULL);
  87   set_owner(self);
  88 }
  89 
  90 void Mutex::lock() {
  91   this->lock(Thread::current());
  92 }
  93 
  94 // Lock without safepoint check - a degenerate variant of lock() for use by
  95 // JavaThreads when it is known to be safe to not check for a safepoint when
  96 // acquiring this lock. If the thread blocks acquiring the lock it is not
  97 // safepoint-safe and so will prevent a safepoint from being reached. If used
  98 // in the wrong way this can lead to a deadlock with the safepoint code.
  99 
 100 void Mutex::lock_without_safepoint_check(Thread * self) {
 101   check_safepoint_state(self, false);
 102   assert(_owner != self, "invariant");
 103   _lock.lock();
 104   assert_owner(NULL);
 105   set_owner(self);
 106 }
 107 
 108 void Mutex::lock_without_safepoint_check() {
 109   lock_without_safepoint_check(Thread::current());
 110 }
 111 
 112 
 113 // Returns true if thread succeeds in grabbing the lock, otherwise false.
 114 
 115 bool Mutex::try_lock() {
 116   Thread * const self = Thread::current();
 117   DEBUG_ONLY(check_prelock_state(self, false);)
 118 
 119   if (_lock.try_lock()) {
 120     assert_owner(NULL);
 121     set_owner(self);
 122     return true;
 123   }
 124   return false;
 125 }
 126 
 127 void Mutex::release_for_safepoint() {
 128   assert_owner(NULL);
 129   _lock.unlock();
 130 }
 131 
 132 void Mutex::unlock() {
 133   assert_owner(Thread::current());
 134   set_owner(NULL);
 135   _lock.unlock();
 136 }
 137 
 138 void Monitor::notify() {
 139   assert_owner(Thread::current());
 140   _lock.notify();
 141 }
 142 
 143 void Monitor::notify_all() {
 144   assert_owner(Thread::current());
 145   _lock.notify_all();
 146 }
 147 
 148 #ifdef ASSERT
 149 void Monitor::assert_wait_lock_state(Thread* self) {
 150   Mutex* least = get_least_ranked_lock_besides_this(self->owned_locks());
 151   assert(least != this, "Specification of get_least_... call above");
 152   if (least != NULL && least->rank() <= special) {
 153     ::tty->print("Attempting to wait on monitor %s/%d while holding"
 154                " lock %s/%d -- possible deadlock",
 155                name(), rank(), least->name(), least->rank());
 156     assert(false, "Shouldn't block(wait) while holding a lock of rank special");
 157   }
 158 }
 159 #endif // ASSERT
 160 
 161 bool Monitor::wait_without_safepoint_check(long timeout) {
 162   Thread* const self = Thread::current();
 163   check_safepoint_state(self, false);
 164 
 165   // timeout is in milliseconds - with zero meaning never timeout
 166   assert(timeout >= 0, "negative timeout");
 167 
 168   assert_owner(self);
 169   assert_wait_lock_state(self);
 170 
 171   // conceptually set the owner to NULL in anticipation of
 172   // abdicating the lock in wait
 173   set_owner(NULL);
 174   int wait_status = _lock.wait(timeout);
 175   set_owner(self);
 176   return wait_status != 0;          // return true IFF timeout
 177 }
 178 
 179 bool Monitor::wait(long timeout, bool as_suspend_equivalent) {
 180   Thread* const self = Thread::current();
 181   check_safepoint_state(self, true);
 182 
 183   // timeout is in milliseconds - with zero meaning never timeout
 184   assert(timeout >= 0, "negative timeout");
 185 
 186   assert_owner(self);
 187 
 188   // Safepoint checking logically implies an active JavaThread.
 189   guarantee(self->is_active_Java_thread(), "invariant");
 190   assert_wait_lock_state(self);
 191 
 192   int wait_status;
 193   // conceptually set the owner to NULL in anticipation of
 194   // abdicating the lock in wait
 195   set_owner(NULL);
 196   JavaThread *jt = (JavaThread *)self;
 197   Mutex* in_flight_mutex = NULL;
 198 
 199   {
 200     ThreadBlockInVMWithDeadlockCheck tbivmdc(jt, &in_flight_mutex);
 201     OSThreadWaitState osts(self->osthread(), false /* not Object.wait() */);
 202     if (as_suspend_equivalent) {
 203       jt->set_suspend_equivalent();
 204       // cleared by handle_special_suspend_equivalent_condition() or
 205       // java_suspend_self()
 206     }
 207 
 208     wait_status = _lock.wait(timeout);
 209     in_flight_mutex = this;  // save for ~ThreadBlockInVMWithDeadlockCheck
 210 
 211     // were we externally suspended while we were waiting?
 212     if (as_suspend_equivalent && jt->handle_special_suspend_equivalent_condition()) {
 213       // Our event wait has finished and we own the lock, but
 214       // while we were waiting another thread suspended us. We don't
 215       // want to hold the lock while suspended because that
 216       // would surprise the thread that suspended us.
 217       _lock.unlock();
 218       jt->java_suspend_self();
 219       _lock.lock();
 220     }
 221   }
 222 
 223   if (in_flight_mutex != NULL) {
 224     // Not unlocked by ~ThreadBlockInVMWithDeadlockCheck
 225     assert_owner(NULL);
 226     // Conceptually reestablish ownership of the lock.
 227     set_owner(self);
 228   } else {
 229     lock(self);
 230   }
 231 
 232   return wait_status != 0;          // return true IFF timeout
 233 }
 234 
 235 Mutex::~Mutex() {
 236   assert_owner(NULL);
 237 }
 238 
 239 // Only Threads_lock, Heap_lock and SR_lock may be safepoint_check_sometimes.
 240 bool is_sometimes_ok(const char* name) {
 241   return (strcmp(name, "Threads_lock") == 0 || strcmp(name, "Heap_lock") == 0 || strcmp(name, "SR_lock") == 0 ||
 242           strcmp(name, "JvmtiObjReallocRelock_lock") == 0);
 243 }
 244 
 245 Mutex::Mutex(int Rank, const char * name, bool allow_vm_block,
 246              SafepointCheckRequired safepoint_check_required) : _owner(NULL) {
 247   assert(os::mutex_init_done(), "Too early!");
 248   if (name == NULL) {
 249     strcpy(_name, "UNKNOWN");
 250   } else {
 251     strncpy(_name, name, MUTEX_NAME_LEN - 1);
 252     _name[MUTEX_NAME_LEN - 1] = '\0';
 253   }
 254 #ifdef ASSERT
 255   _allow_vm_block  = allow_vm_block;
 256   _rank            = Rank;
 257   _safepoint_check_required = safepoint_check_required;
 258 
 259   assert(_safepoint_check_required != Mutex::_safepoint_check_sometimes || is_sometimes_ok(name),
 260          "Lock has _safepoint_check_sometimes %s", name);
 261 #endif
 262 }
 263 
 264 Monitor::Monitor(int Rank, const char * name, bool allow_vm_block,
 265              SafepointCheckRequired safepoint_check_required) :
 266   Mutex(Rank, name, allow_vm_block, safepoint_check_required) {}
 267 
 268 bool Mutex::owned_by_self() const {
 269   return _owner == Thread::current();
 270 }
 271 
 272 void Mutex::print_on_error(outputStream* st) const {
 273   st->print("[" PTR_FORMAT, p2i(this));
 274   st->print("] %s", _name);
 275   st->print(" - owner thread: " PTR_FORMAT, p2i(_owner));
 276 }
 277 
 278 // ----------------------------------------------------------------------------------
 279 // Non-product code
 280 
 281 #ifndef PRODUCT
 282 void Mutex::print_on(outputStream* st) const {
 283   st->print_cr("Mutex: [" PTR_FORMAT "] %s - owner: " PTR_FORMAT,
 284                p2i(this), _name, p2i(_owner));
 285 }
 286 #endif
 287 
 288 #ifndef PRODUCT
 289 #ifdef ASSERT
 290 
 291 void Mutex::assert_owner(Thread * expected) {
 292   const char* msg = "invalid owner";
 293   if (expected == NULL) {
 294     msg = "should be un-owned";
 295   }
 296   else if (expected == Thread::current()) {
 297     msg = "should be owned by current thread";
 298   }
 299   assert(_owner == expected,
 300          "%s: owner=" INTPTR_FORMAT ", should be=" INTPTR_FORMAT,
 301          msg, p2i(_owner), p2i(expected));
 302 }
 303 
 304 Mutex* Mutex::get_least_ranked_lock(Mutex* locks) {
 305   Mutex *res, *tmp;
 306   for (res = tmp = locks; tmp != NULL; tmp = tmp->next()) {
 307     if (tmp->rank() < res->rank()) {
 308       res = tmp;
 309     }
 310   }
 311   if (!SafepointSynchronize::is_at_safepoint()) {
 312     // In this case, we expect the held locks to be
 313     // in increasing rank order (modulo any native ranks)
 314     for (tmp = locks; tmp != NULL; tmp = tmp->next()) {
 315       if (tmp->next() != NULL) {
 316         assert(tmp->rank() == Mutex::native ||
 317                tmp->rank() <= tmp->next()->rank(), "mutex rank anomaly?");
 318       }
 319     }
 320   }
 321   return res;
 322 }
 323 
 324 Mutex* Mutex::get_least_ranked_lock_besides_this(Mutex* locks) {
 325   Mutex *res, *tmp;
 326   for (res = NULL, tmp = locks; tmp != NULL; tmp = tmp->next()) {
 327     if (tmp != this && (res == NULL || tmp->rank() < res->rank())) {
 328       res = tmp;
 329     }
 330   }
 331   if (!SafepointSynchronize::is_at_safepoint()) {
 332     // In this case, we expect the held locks to be
 333     // in increasing rank order (modulo any native ranks)
 334     for (tmp = locks; tmp != NULL; tmp = tmp->next()) {
 335       if (tmp->next() != NULL) {
 336         assert(tmp->rank() == Mutex::native ||
 337                tmp->rank() <= tmp->next()->rank(), "mutex rank anomaly?");
 338       }
 339     }
 340   }
 341   return res;
 342 }
 343 
 344 
 345 bool Mutex::contains(Mutex* locks, Mutex* lock) {
 346   for (; locks != NULL; locks = locks->next()) {
 347     if (locks == lock) {
 348       return true;
 349     }
 350   }
 351   return false;
 352 }
 353 #endif
 354 
 355 // Called immediately after lock acquisition or release as a diagnostic
 356 // to track the lock-set of the thread and test for rank violations that
 357 // might indicate exposure to deadlock.
 358 // Rather like an EventListener for _owner (:>).
 359 
 360 void Mutex::set_owner_implementation(Thread *new_owner) {
 361   // This function is solely responsible for maintaining
 362   // and checking the invariant that threads and locks
 363   // are in a 1/N relation, with some some locks unowned.
 364   // It uses the Mutex::_owner, Mutex::_next, and
 365   // Thread::_owned_locks fields, and no other function
 366   // changes those fields.
 367   // It is illegal to set the mutex from one non-NULL
 368   // owner to another--it must be owned by NULL as an
 369   // intermediate state.
 370 
 371   if (new_owner != NULL) {
 372     // the thread is acquiring this lock
 373 
 374     assert(new_owner == Thread::current(), "Should I be doing this?");
 375     assert(_owner == NULL, "setting the owner thread of an already owned mutex");
 376     _owner = new_owner; // set the owner
 377 
 378     // link "this" into the owned locks list
 379 
 380 #ifdef ASSERT  // Thread::_owned_locks is under the same ifdef
 381     Mutex* locks = get_least_ranked_lock(new_owner->owned_locks());
 382     // Mutex::set_owner_implementation is a friend of Thread
 383 
 384     assert(this->rank() >= 0, "bad lock rank");
 385 
 386     // Deadlock avoidance rules require us to acquire Mutexes only in
 387     // a global total order. For example m1 is the lowest ranked mutex
 388     // that the thread holds and m2 is the mutex the thread is trying
 389     // to acquire, then deadlock avoidance rules require that the rank
 390     // of m2 be less than the rank of m1.
 391     // The rank Mutex::native  is an exception in that it is not subject
 392     // to the verification rules.
 393     if (this->rank() != Mutex::native &&
 394         this->rank() != Mutex::suspend_resume &&
 395         locks != NULL && locks->rank() <= this->rank() &&
 396         !SafepointSynchronize::is_at_safepoint()) {
 397       new_owner->print_owned_locks();
 398       fatal("acquiring lock %s/%d out of order with lock %s/%d -- "
 399             "possible deadlock", this->name(), this->rank(),
 400             locks->name(), locks->rank());
 401     }
 402 
 403     this->_next = new_owner->_owned_locks;
 404     new_owner->_owned_locks = this;
 405 #endif
 406 
 407   } else {
 408     // the thread is releasing this lock
 409 
 410     Thread* old_owner = _owner;
 411     DEBUG_ONLY(_last_owner = old_owner;)
 412 
 413     assert(old_owner != NULL, "removing the owner thread of an unowned mutex");
 414     assert(old_owner == Thread::current(), "removing the owner thread of an unowned mutex");
 415 
 416     _owner = NULL; // set the owner
 417 
 418 #ifdef ASSERT
 419     Mutex* locks = old_owner->owned_locks();
 420 
 421     // remove "this" from the owned locks list
 422 
 423     Mutex* prev = NULL;
 424     bool found = false;
 425     for (; locks != NULL; prev = locks, locks = locks->next()) {
 426       if (locks == this) {
 427         found = true;
 428         break;
 429       }
 430     }
 431     assert(found, "Removing a lock not owned");
 432     if (prev == NULL) {
 433       old_owner->_owned_locks = _next;
 434     } else {
 435       prev->_next = _next;
 436     }
 437     _next = NULL;
 438 #endif
 439   }
 440 }
 441 
 442 
 443 // Factored out common sanity checks for locking mutex'es. Used by lock() and try_lock()
 444 void Mutex::check_prelock_state(Thread *thread, bool safepoint_check) {
 445   if (safepoint_check) {
 446     assert((!thread->is_active_Java_thread() || ((JavaThread *)thread)->thread_state() == _thread_in_vm)
 447            || rank() == Mutex::special, "wrong thread state for using locks");
 448     if (thread->is_VM_thread() && !allow_vm_block()) {
 449       fatal("VM thread using lock %s (not allowed to block on)", name());
 450     }
 451     DEBUG_ONLY(if (rank() != Mutex::special) \
 452                thread->check_for_valid_safepoint_state(false);)
 453   }
 454   assert(!os::ThreadCrashProtection::is_crash_protected(thread),
 455          "locking not allowed when crash protection is set");
 456 }
 457 
 458 void Mutex::check_block_state(Thread *thread) {
 459   if (!_allow_vm_block && thread->is_VM_thread()) {
 460     warning("VM thread blocked on lock");
 461     print();
 462     BREAKPOINT;
 463   }
 464   assert(_owner != thread, "deadlock: blocking on mutex owned by current thread");
 465 }
 466 
 467 #endif // PRODUCT