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