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