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