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