1 /*
   2  * Copyright (c) 1998, 2021, 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 "classfile/vmSymbols.hpp"
  27 #include "jfr/jfrEvents.hpp"
  28 #include "logging/log.hpp"
  29 #include "logging/logStream.hpp"
  30 #include "memory/allocation.inline.hpp"
  31 #include "memory/padded.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "memory/universe.hpp"
  34 #include "oops/markWord.hpp"
  35 #include "oops/oop.inline.hpp"
  36 #include "runtime/atomic.hpp"
  37 #include "runtime/handles.inline.hpp"
  38 #include "runtime/handshake.hpp"
  39 #include "runtime/interfaceSupport.inline.hpp"
  40 #include "runtime/mutexLocker.hpp"
  41 #include "runtime/objectMonitor.hpp"
  42 #include "runtime/objectMonitor.inline.hpp"
  43 #include "runtime/os.inline.hpp"
  44 #include "runtime/osThread.hpp"
  45 #include "runtime/perfData.hpp"
  46 #include "runtime/safepointMechanism.inline.hpp"
  47 #include "runtime/safepointVerifiers.hpp"
  48 #include "runtime/sharedRuntime.hpp"
  49 #include "runtime/stubRoutines.hpp"
  50 #include "runtime/synchronizer.hpp"
  51 #include "runtime/thread.inline.hpp"
  52 #include "runtime/timer.hpp"
  53 #include "runtime/vframe.hpp"
  54 #include "runtime/vmThread.hpp"
  55 #include "utilities/align.hpp"
  56 #include "utilities/dtrace.hpp"
  57 #include "utilities/events.hpp"
  58 #include "utilities/preserveException.hpp"
  59 
  60 void MonitorList::add(ObjectMonitor* m) {
  61   ObjectMonitor* head;
  62   do {
  63     head = Atomic::load(&_head);
  64     m->set_next_om(head);
  65   } while (Atomic::cmpxchg(&_head, head, m) != head);
  66 
  67   size_t count = Atomic::add(&_count, 1u);
  68   if (count > max()) {
  69     Atomic::inc(&_max);
  70   }
  71 }
  72 
  73 size_t MonitorList::count() const {
  74   return Atomic::load(&_count);
  75 }
  76 
  77 size_t MonitorList::max() const {
  78   return Atomic::load(&_max);
  79 }
  80 
  81 // Walk the in-use list and unlink (at most MonitorDeflationMax) deflated
  82 // ObjectMonitors. Returns the number of unlinked ObjectMonitors.
  83 size_t MonitorList::unlink_deflated(Thread* current, LogStream* ls,
  84                                     elapsedTimer* timer_p,
  85                                     GrowableArray<ObjectMonitor*>* unlinked_list) {
  86   size_t unlinked_count = 0;
  87   ObjectMonitor* prev = NULL;
  88   ObjectMonitor* head = Atomic::load_acquire(&_head);
  89   ObjectMonitor* m = head;
  90   // The in-use list head can be NULL during the final audit.
  91   while (m != NULL) {
  92     if (m->is_being_async_deflated()) {
  93       // Find next live ObjectMonitor.
  94       ObjectMonitor* next = m;
  95       do {
  96         ObjectMonitor* next_next = next->next_om();
  97         unlinked_count++;
  98         unlinked_list->append(next);
  99         next = next_next;
 100         if (unlinked_count >= (size_t)MonitorDeflationMax) {
 101           // Reached the max so bail out on the gathering loop.
 102           break;
 103         }
 104       } while (next != NULL && next->is_being_async_deflated());
 105       if (prev == NULL) {
 106         ObjectMonitor* prev_head = Atomic::cmpxchg(&_head, head, next);
 107         if (prev_head != head) {
 108           // Find new prev ObjectMonitor that just got inserted.
 109           for (ObjectMonitor* n = prev_head; n != m; n = n->next_om()) {
 110             prev = n;
 111           }
 112           prev->set_next_om(next);
 113         }
 114       } else {
 115         prev->set_next_om(next);
 116       }
 117       if (unlinked_count >= (size_t)MonitorDeflationMax) {
 118         // Reached the max so bail out on the searching loop.
 119         break;
 120       }
 121       m = next;
 122     } else {
 123       prev = m;
 124       m = m->next_om();
 125     }
 126 
 127     if (current->is_Java_thread()) {
 128       // A JavaThread must check for a safepoint/handshake and honor it.
 129       ObjectSynchronizer::chk_for_block_req(JavaThread::cast(current), "unlinking",
 130                                             "unlinked_count", unlinked_count,
 131                                             ls, timer_p);
 132     }
 133   }
 134   Atomic::sub(&_count, unlinked_count);
 135   return unlinked_count;
 136 }
 137 
 138 MonitorList::Iterator MonitorList::iterator() const {
 139   return Iterator(Atomic::load_acquire(&_head));
 140 }
 141 
 142 ObjectMonitor* MonitorList::Iterator::next() {
 143   ObjectMonitor* current = _current;
 144   _current = current->next_om();
 145   return current;
 146 }
 147 
 148 // The "core" versions of monitor enter and exit reside in this file.
 149 // The interpreter and compilers contain specialized transliterated
 150 // variants of the enter-exit fast-path operations.  See c2_MacroAssembler_x86.cpp
 151 // fast_lock(...) for instance.  If you make changes here, make sure to modify the
 152 // interpreter, and both C1 and C2 fast-path inline locking code emission.
 153 //
 154 // -----------------------------------------------------------------------------
 155 
 156 #ifdef DTRACE_ENABLED
 157 
 158 // Only bother with this argument setup if dtrace is available
 159 // TODO-FIXME: probes should not fire when caller is _blocked.  assert() accordingly.
 160 
 161 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread)                           \
 162   char* bytes = NULL;                                                      \
 163   int len = 0;                                                             \
 164   jlong jtid = SharedRuntime::get_java_tid(thread);                        \
 165   Symbol* klassname = obj->klass()->name();                                \
 166   if (klassname != NULL) {                                                 \
 167     bytes = (char*)klassname->bytes();                                     \
 168     len = klassname->utf8_length();                                        \
 169   }
 170 
 171 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis)            \
 172   {                                                                        \
 173     if (DTraceMonitorProbes) {                                             \
 174       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
 175       HOTSPOT_MONITOR_WAIT(jtid,                                           \
 176                            (uintptr_t)(monitor), bytes, len, (millis));    \
 177     }                                                                      \
 178   }
 179 
 180 #define HOTSPOT_MONITOR_PROBE_notify HOTSPOT_MONITOR_NOTIFY
 181 #define HOTSPOT_MONITOR_PROBE_notifyAll HOTSPOT_MONITOR_NOTIFYALL
 182 #define HOTSPOT_MONITOR_PROBE_waited HOTSPOT_MONITOR_WAITED
 183 
 184 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread)                  \
 185   {                                                                        \
 186     if (DTraceMonitorProbes) {                                             \
 187       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
 188       HOTSPOT_MONITOR_PROBE_##probe(jtid, /* probe = waited */             \
 189                                     (uintptr_t)(monitor), bytes, len);     \
 190     }                                                                      \
 191   }
 192 
 193 #else //  ndef DTRACE_ENABLED
 194 
 195 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon)    {;}
 196 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon)          {;}
 197 
 198 #endif // ndef DTRACE_ENABLED
 199 
 200 // This exists only as a workaround of dtrace bug 6254741
 201 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) {
 202   DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
 203   return 0;
 204 }
 205 
 206 static const int NINFLATIONLOCKS = 256;
 207 static os::PlatformMutex* gInflationLocks[NINFLATIONLOCKS];
 208 
 209 void ObjectSynchronizer::initialize() {
 210   for (int i = 0; i < NINFLATIONLOCKS; i++) {
 211     gInflationLocks[i] = new os::PlatformMutex();
 212   }
 213   // Start the ceiling with the estimate for one thread.
 214   set_in_use_list_ceiling(AvgMonitorsPerThreadEstimate);
 215 }
 216 
 217 MonitorList ObjectSynchronizer::_in_use_list;
 218 // monitors_used_above_threshold() policy is as follows:
 219 //
 220 // The ratio of the current _in_use_list count to the ceiling is used
 221 // to determine if we are above MonitorUsedDeflationThreshold and need
 222 // to do an async monitor deflation cycle. The ceiling is increased by
 223 // AvgMonitorsPerThreadEstimate when a thread is added to the system
 224 // and is decreased by AvgMonitorsPerThreadEstimate when a thread is
 225 // removed from the system.
 226 //
 227 // Note: If the _in_use_list max exceeds the ceiling, then
 228 // monitors_used_above_threshold() will use the in_use_list max instead
 229 // of the thread count derived ceiling because we have used more
 230 // ObjectMonitors than the estimated average.
 231 //
 232 // Note: If deflate_idle_monitors() has NoAsyncDeflationProgressMax
 233 // no-progress async monitor deflation cycles in a row, then the ceiling
 234 // is adjusted upwards by monitors_used_above_threshold().
 235 //
 236 // Start the ceiling with the estimate for one thread in initialize()
 237 // which is called after cmd line options are processed.
 238 static size_t _in_use_list_ceiling = 0;
 239 bool volatile ObjectSynchronizer::_is_async_deflation_requested = false;
 240 bool volatile ObjectSynchronizer::_is_final_audit = false;
 241 jlong ObjectSynchronizer::_last_async_deflation_time_ns = 0;
 242 static uintx _no_progress_cnt = 0;
 243 
 244 // =====================> Quick functions
 245 
 246 // The quick_* forms are special fast-path variants used to improve
 247 // performance.  In the simplest case, a "quick_*" implementation could
 248 // simply return false, in which case the caller will perform the necessary
 249 // state transitions and call the slow-path form.
 250 // The fast-path is designed to handle frequently arising cases in an efficient
 251 // manner and is just a degenerate "optimistic" variant of the slow-path.
 252 // returns true  -- to indicate the call was satisfied.
 253 // returns false -- to indicate the call needs the services of the slow-path.
 254 // A no-loitering ordinance is in effect for code in the quick_* family
 255 // operators: safepoints or indefinite blocking (blocking that might span a
 256 // safepoint) are forbidden. Generally the thread_state() is _in_Java upon
 257 // entry.
 258 //
 259 // Consider: An interesting optimization is to have the JIT recognize the
 260 // following common idiom:
 261 //   synchronized (someobj) { .... ; notify(); }
 262 // That is, we find a notify() or notifyAll() call that immediately precedes
 263 // the monitorexit operation.  In that case the JIT could fuse the operations
 264 // into a single notifyAndExit() runtime primitive.
 265 
 266 bool ObjectSynchronizer::quick_notify(oopDesc* obj, JavaThread* current, bool all) {
 267   assert(current->thread_state() == _thread_in_Java, "invariant");
 268   NoSafepointVerifier nsv;
 269   if (obj == NULL) return false;  // slow-path for invalid obj
 270   const markWord mark = obj->mark();
 271 
 272   if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {
 273     // Degenerate notify
 274     // stack-locked by caller so by definition the implied waitset is empty.
 275     return true;
 276   }
 277 
 278   if (mark.has_monitor()) {
 279     ObjectMonitor* const mon = mark.monitor();
 280     assert(mon->object() == oop(obj), "invariant");
 281     if (mon->owner() != current) return false;  // slow-path for IMS exception
 282 
 283     if (mon->first_waiter() != NULL) {
 284       // We have one or more waiters. Since this is an inflated monitor
 285       // that we own, we can transfer one or more threads from the waitset
 286       // to the entrylist here and now, avoiding the slow-path.
 287       if (all) {
 288         DTRACE_MONITOR_PROBE(notifyAll, mon, obj, current);
 289       } else {
 290         DTRACE_MONITOR_PROBE(notify, mon, obj, current);
 291       }
 292       int free_count = 0;
 293       do {
 294         mon->INotify(current);
 295         ++free_count;
 296       } while (mon->first_waiter() != NULL && all);
 297       OM_PERFDATA_OP(Notifications, inc(free_count));
 298     }
 299     return true;
 300   }
 301 
 302   // other IMS exception states take the slow-path
 303   return false;
 304 }
 305 
 306 
 307 // The LockNode emitted directly at the synchronization site would have
 308 // been too big if it were to have included support for the cases of inflated
 309 // recursive enter and exit, so they go here instead.
 310 // Note that we can't safely call AsyncPrintJavaStack() from within
 311 // quick_enter() as our thread state remains _in_Java.
 312 
 313 bool ObjectSynchronizer::quick_enter(oop obj, JavaThread* current,
 314                                      BasicLock * lock) {
 315   assert(current->thread_state() == _thread_in_Java, "invariant");
 316   NoSafepointVerifier nsv;
 317   if (obj == NULL) return false;       // Need to throw NPE
 318 
 319   if (obj->klass()->is_value_based()) {
 320     return false;
 321   }
 322 
 323   const markWord mark = obj->mark();
 324 
 325   if (mark.has_monitor()) {
 326     ObjectMonitor* const m = mark.monitor();
 327     // An async deflation or GC can race us before we manage to make
 328     // the ObjectMonitor busy by setting the owner below. If we detect
 329     // that race we just bail out to the slow-path here.
 330     if (m->object_peek() == NULL) {
 331       return false;
 332     }
 333     JavaThread* const owner = (JavaThread*) m->owner_raw();
 334 
 335     // Lock contention and Transactional Lock Elision (TLE) diagnostics
 336     // and observability
 337     // Case: light contention possibly amenable to TLE
 338     // Case: TLE inimical operations such as nested/recursive synchronization
 339 
 340     if (owner == current) {
 341       m->_recursions++;
 342       return true;
 343     }
 344 
 345     // This Java Monitor is inflated so obj's header will never be
 346     // displaced to this thread's BasicLock. Make the displaced header
 347     // non-NULL so this BasicLock is not seen as recursive nor as
 348     // being locked. We do this unconditionally so that this thread's
 349     // BasicLock cannot be mis-interpreted by any stack walkers. For
 350     // performance reasons, stack walkers generally first check for
 351     // stack-locking in the object's header, the second check is for
 352     // recursive stack-locking in the displaced header in the BasicLock,
 353     // and last are the inflated Java Monitor (ObjectMonitor) checks.
 354     lock->set_displaced_header(markWord::unused_mark());
 355 
 356     if (owner == NULL && m->try_set_owner_from(NULL, current) == NULL) {
 357       assert(m->_recursions == 0, "invariant");
 358       return true;
 359     }
 360   }
 361 
 362   // Note that we could inflate in quick_enter.
 363   // This is likely a useful optimization
 364   // Critically, in quick_enter() we must not:
 365   // -- block indefinitely, or
 366   // -- reach a safepoint
 367 
 368   return false;        // revert to slow-path
 369 }
 370 
 371 // Handle notifications when synchronizing on value based classes
 372 void ObjectSynchronizer::handle_sync_on_value_based_class(Handle obj, JavaThread* current) {
 373   frame last_frame = current->last_frame();
 374   bool bcp_was_adjusted = false;
 375   // Don't decrement bcp if it points to the frame's first instruction.  This happens when
 376   // handle_sync_on_value_based_class() is called because of a synchronized method.  There
 377   // is no actual monitorenter instruction in the byte code in this case.
 378   if (last_frame.is_interpreted_frame() &&
 379       (last_frame.interpreter_frame_method()->code_base() < last_frame.interpreter_frame_bcp())) {
 380     // adjust bcp to point back to monitorenter so that we print the correct line numbers
 381     last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() - 1);
 382     bcp_was_adjusted = true;
 383   }
 384 
 385   if (DiagnoseSyncOnValueBasedClasses == FATAL_EXIT) {
 386     ResourceMark rm(current);
 387     stringStream ss;
 388     current->print_stack_on(&ss);
 389     char* base = (char*)strstr(ss.base(), "at");
 390     char* newline = (char*)strchr(ss.base(), '\n');
 391     if (newline != NULL) {
 392       *newline = '\0';
 393     }
 394     fatal("Synchronizing on object " INTPTR_FORMAT " of klass %s %s", p2i(obj()), obj->klass()->external_name(), base);
 395   } else {
 396     assert(DiagnoseSyncOnValueBasedClasses == LOG_WARNING, "invalid value for DiagnoseSyncOnValueBasedClasses");
 397     ResourceMark rm(current);
 398     Log(valuebasedclasses) vblog;
 399 
 400     vblog.info("Synchronizing on object " INTPTR_FORMAT " of klass %s", p2i(obj()), obj->klass()->external_name());
 401     if (current->has_last_Java_frame()) {
 402       LogStream info_stream(vblog.info());
 403       current->print_stack_on(&info_stream);
 404     } else {
 405       vblog.info("Cannot find the last Java frame");
 406     }
 407 
 408     EventSyncOnValueBasedClass event;
 409     if (event.should_commit()) {
 410       event.set_valueBasedClass(obj->klass());
 411       event.commit();
 412     }
 413   }
 414 
 415   if (bcp_was_adjusted) {
 416     last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() + 1);
 417   }
 418 }
 419 
 420 // -----------------------------------------------------------------------------
 421 // Monitor Enter/Exit
 422 // The interpreter and compiler assembly code tries to lock using the fast path
 423 // of this algorithm. Make sure to update that code if the following function is
 424 // changed. The implementation is extremely sensitive to race condition. Be careful.
 425 
 426 void ObjectSynchronizer::enter(Handle obj, BasicLock* lock, JavaThread* current) {
 427   if (obj->klass()->is_value_based()) {
 428     handle_sync_on_value_based_class(obj, current);
 429   }
 430 
 431   markWord mark = obj->mark();
 432   if (mark.is_neutral()) {
 433     // Anticipate successful CAS -- the ST of the displaced mark must
 434     // be visible <= the ST performed by the CAS.
 435     lock->set_displaced_header(mark);
 436     if (mark == obj()->cas_set_mark(markWord::from_pointer(lock), mark)) {
 437       return;
 438     }
 439     // Fall through to inflate() ...
 440   } else if (mark.has_locker() &&
 441              current->is_lock_owned((address)mark.locker())) {
 442     assert(lock != mark.locker(), "must not re-lock the same lock");
 443     assert(lock != (BasicLock*)obj->mark().value(), "don't relock with same BasicLock");
 444     lock->set_displaced_header(markWord::from_pointer(NULL));
 445     return;
 446   }
 447 
 448   // The object header will never be displaced to this lock,
 449   // so it does not matter what the value is, except that it
 450   // must be non-zero to avoid looking like a re-entrant lock,
 451   // and must not look locked either.
 452   lock->set_displaced_header(markWord::unused_mark());
 453   // An async deflation can race after the inflate() call and before
 454   // enter() can make the ObjectMonitor busy. enter() returns false if
 455   // we have lost the race to async deflation and we simply try again.
 456   while (true) {
 457     ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_monitor_enter);
 458     if (monitor->enter(current)) {
 459       return;
 460     }
 461   }
 462 }
 463 
 464 void ObjectSynchronizer::exit(oop object, BasicLock* lock, JavaThread* current) {
 465   markWord mark = object->mark();
 466 
 467   markWord dhw = lock->displaced_header();
 468   if (dhw.value() == 0) {
 469     // If the displaced header is NULL, then this exit matches up with
 470     // a recursive enter. No real work to do here except for diagnostics.
 471 #ifndef PRODUCT
 472     if (mark != markWord::INFLATING()) {
 473       // Only do diagnostics if we are not racing an inflation. Simply
 474       // exiting a recursive enter of a Java Monitor that is being
 475       // inflated is safe; see the has_monitor() comment below.
 476       assert(!mark.is_neutral(), "invariant");
 477       assert(!mark.has_locker() ||
 478              current->is_lock_owned((address)mark.locker()), "invariant");
 479       if (mark.has_monitor()) {
 480         // The BasicLock's displaced_header is marked as a recursive
 481         // enter and we have an inflated Java Monitor (ObjectMonitor).
 482         // This is a special case where the Java Monitor was inflated
 483         // after this thread entered the stack-lock recursively. When a
 484         // Java Monitor is inflated, we cannot safely walk the Java
 485         // Monitor owner's stack and update the BasicLocks because a
 486         // Java Monitor can be asynchronously inflated by a thread that
 487         // does not own the Java Monitor.
 488         ObjectMonitor* m = mark.monitor();
 489         assert(m->object()->mark() == mark, "invariant");
 490         assert(m->is_entered(current), "invariant");
 491       }
 492     }
 493 #endif
 494     return;
 495   }
 496 
 497   if (mark == markWord::from_pointer(lock)) {
 498     // If the object is stack-locked by the current thread, try to
 499     // swing the displaced header from the BasicLock back to the mark.
 500     assert(dhw.is_neutral(), "invariant");
 501     if (object->cas_set_mark(dhw, mark) == mark) {
 502       return;
 503     }
 504   }
 505 
 506   // We have to take the slow-path of possible inflation and then exit.
 507   // The ObjectMonitor* can't be async deflated until ownership is
 508   // dropped inside exit() and the ObjectMonitor* must be !is_busy().
 509   ObjectMonitor* monitor = inflate(current, object, inflate_cause_vm_internal);
 510   monitor->exit(current);
 511 }
 512 
 513 // -----------------------------------------------------------------------------
 514 // Class Loader  support to workaround deadlocks on the class loader lock objects
 515 // Also used by GC
 516 // complete_exit()/reenter() are used to wait on a nested lock
 517 // i.e. to give up an outer lock completely and then re-enter
 518 // Used when holding nested locks - lock acquisition order: lock1 then lock2
 519 //  1) complete_exit lock1 - saving recursion count
 520 //  2) wait on lock2
 521 //  3) when notified on lock2, unlock lock2
 522 //  4) reenter lock1 with original recursion count
 523 //  5) lock lock2
 524 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 525 intx ObjectSynchronizer::complete_exit(Handle obj, JavaThread* current) {
 526   // The ObjectMonitor* can't be async deflated until ownership is
 527   // dropped inside exit() and the ObjectMonitor* must be !is_busy().
 528   ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_vm_internal);
 529   intptr_t ret_code = monitor->complete_exit(current);
 530   return ret_code;
 531 }
 532 
 533 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 534 void ObjectSynchronizer::reenter(Handle obj, intx recursions, JavaThread* current) {
 535   // An async deflation can race after the inflate() call and before
 536   // reenter() -> enter() can make the ObjectMonitor busy. reenter() ->
 537   // enter() returns false if we have lost the race to async deflation
 538   // and we simply try again.
 539   while (true) {
 540     ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_vm_internal);
 541     if (monitor->reenter(recursions, current)) {
 542       return;
 543     }
 544   }
 545 }
 546 
 547 // -----------------------------------------------------------------------------
 548 // JNI locks on java objects
 549 // NOTE: must use heavy weight monitor to handle jni monitor enter
 550 void ObjectSynchronizer::jni_enter(Handle obj, JavaThread* current) {
 551   if (obj->klass()->is_value_based()) {
 552     handle_sync_on_value_based_class(obj, current);
 553   }
 554 
 555   // the current locking is from JNI instead of Java code
 556   current->set_current_pending_monitor_is_from_java(false);
 557   // An async deflation can race after the inflate() call and before
 558   // enter() can make the ObjectMonitor busy. enter() returns false if
 559   // we have lost the race to async deflation and we simply try again.
 560   while (true) {
 561     ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_jni_enter);
 562     if (monitor->enter(current)) {
 563       break;
 564     }
 565   }
 566   current->set_current_pending_monitor_is_from_java(true);
 567 }
 568 
 569 // NOTE: must use heavy weight monitor to handle jni monitor exit
 570 void ObjectSynchronizer::jni_exit(oop obj, TRAPS) {
 571   JavaThread* current = THREAD;
 572 
 573   // The ObjectMonitor* can't be async deflated until ownership is
 574   // dropped inside exit() and the ObjectMonitor* must be !is_busy().
 575   ObjectMonitor* monitor = inflate(current, obj, inflate_cause_jni_exit);
 576   // If this thread has locked the object, exit the monitor. We
 577   // intentionally do not use CHECK on check_owner because we must exit the
 578   // monitor even if an exception was already pending.
 579   if (monitor->check_owner(THREAD)) {
 580     monitor->exit(current);
 581   }
 582 }
 583 
 584 // -----------------------------------------------------------------------------
 585 // Internal VM locks on java objects
 586 // standard constructor, allows locking failures
 587 ObjectLocker::ObjectLocker(Handle obj, JavaThread* thread) {
 588   _thread = thread;
 589   _thread->check_for_valid_safepoint_state();
 590   _obj = obj;
 591 
 592   if (_obj() != NULL) {
 593     ObjectSynchronizer::enter(_obj, &_lock, _thread);
 594   }
 595 }
 596 
 597 ObjectLocker::~ObjectLocker() {
 598   if (_obj() != NULL) {
 599     ObjectSynchronizer::exit(_obj(), &_lock, _thread);
 600   }
 601 }
 602 
 603 
 604 // -----------------------------------------------------------------------------
 605 //  Wait/Notify/NotifyAll
 606 // NOTE: must use heavy weight monitor to handle wait()
 607 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
 608   JavaThread* current = THREAD;
 609   if (millis < 0) {
 610     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 611   }
 612   // The ObjectMonitor* can't be async deflated because the _waiters
 613   // field is incremented before ownership is dropped and decremented
 614   // after ownership is regained.
 615   ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_wait);
 616 
 617   DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), current, millis);
 618   monitor->wait(millis, true, THREAD); // Not CHECK as we need following code
 619 
 620   // This dummy call is in place to get around dtrace bug 6254741.  Once
 621   // that's fixed we can uncomment the following line, remove the call
 622   // and change this function back into a "void" func.
 623   // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
 624   int ret_code = dtrace_waited_probe(monitor, obj, THREAD);
 625   return ret_code;
 626 }
 627 
 628 // No exception are possible in this case as we only use this internally when locking is
 629 // correct and we have to wait until notified - so no interrupts or timeouts.
 630 void ObjectSynchronizer::wait_uninterruptibly(Handle obj, JavaThread* current) {
 631   // The ObjectMonitor* can't be async deflated because the _waiters
 632   // field is incremented before ownership is dropped and decremented
 633   // after ownership is regained.
 634   ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_wait);
 635   monitor->wait(0 /* wait-forever */, false /* not interruptible */, current);
 636 }
 637 
 638 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
 639   JavaThread* current = THREAD;
 640 
 641   markWord mark = obj->mark();
 642   if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {
 643     // Not inflated so there can't be any waiters to notify.
 644     return;
 645   }
 646   // The ObjectMonitor* can't be async deflated until ownership is
 647   // dropped by the calling thread.
 648   ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_notify);
 649   monitor->notify(CHECK);
 650 }
 651 
 652 // NOTE: see comment of notify()
 653 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
 654   JavaThread* current = THREAD;
 655 
 656   markWord mark = obj->mark();
 657   if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {
 658     // Not inflated so there can't be any waiters to notify.
 659     return;
 660   }
 661   // The ObjectMonitor* can't be async deflated until ownership is
 662   // dropped by the calling thread.
 663   ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_notify);
 664   monitor->notifyAll(CHECK);
 665 }
 666 
 667 // -----------------------------------------------------------------------------
 668 // Hash Code handling
 669 
 670 struct SharedGlobals {
 671   char         _pad_prefix[OM_CACHE_LINE_SIZE];
 672   // This is a highly shared mostly-read variable.
 673   // To avoid false-sharing it needs to be the sole occupant of a cache line.
 674   volatile int stw_random;
 675   DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 676   // Hot RW variable -- Sequester to avoid false-sharing
 677   volatile int hc_sequence;
 678   DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 679 };
 680 
 681 static SharedGlobals GVars;
 682 
 683 static markWord read_stable_mark(oop obj) {
 684   markWord mark = obj->mark_acquire();
 685   if (!mark.is_being_inflated()) {
 686     return mark;       // normal fast-path return
 687   }
 688 
 689   int its = 0;
 690   for (;;) {
 691     markWord mark = obj->mark_acquire();
 692     if (!mark.is_being_inflated()) {
 693       return mark;    // normal fast-path return
 694     }
 695 
 696     // The object is being inflated by some other thread.
 697     // The caller of read_stable_mark() must wait for inflation to complete.
 698     // Avoid live-lock.
 699 
 700     ++its;
 701     if (its > 10000 || !os::is_MP()) {
 702       if (its & 1) {
 703         os::naked_yield();
 704       } else {
 705         // Note that the following code attenuates the livelock problem but is not
 706         // a complete remedy.  A more complete solution would require that the inflating
 707         // thread hold the associated inflation lock.  The following code simply restricts
 708         // the number of spinners to at most one.  We'll have N-2 threads blocked
 709         // on the inflationlock, 1 thread holding the inflation lock and using
 710         // a yield/park strategy, and 1 thread in the midst of inflation.
 711         // A more refined approach would be to change the encoding of INFLATING
 712         // to allow encapsulation of a native thread pointer.  Threads waiting for
 713         // inflation to complete would use CAS to push themselves onto a singly linked
 714         // list rooted at the markword.  Once enqueued, they'd loop, checking a per-thread flag
 715         // and calling park().  When inflation was complete the thread that accomplished inflation
 716         // would detach the list and set the markword to inflated with a single CAS and
 717         // then for each thread on the list, set the flag and unpark() the thread.
 718 
 719         // Index into the lock array based on the current object address.
 720         static_assert(is_power_of_2(NINFLATIONLOCKS), "must be");
 721         int ix = (cast_from_oop<intptr_t>(obj) >> 5) & (NINFLATIONLOCKS-1);
 722         int YieldThenBlock = 0;
 723         assert(ix >= 0 && ix < NINFLATIONLOCKS, "invariant");
 724         gInflationLocks[ix]->lock();
 725         while (obj->mark_acquire() == markWord::INFLATING()) {
 726           // Beware: naked_yield() is advisory and has almost no effect on some platforms
 727           // so we periodically call current->_ParkEvent->park(1).
 728           // We use a mixed spin/yield/block mechanism.
 729           if ((YieldThenBlock++) >= 16) {
 730             Thread::current()->_ParkEvent->park(1);
 731           } else {
 732             os::naked_yield();
 733           }
 734         }
 735         gInflationLocks[ix]->unlock();
 736       }
 737     } else {
 738       SpinPause();       // SMP-polite spinning
 739     }
 740   }
 741 }
 742 
 743 // hashCode() generation :
 744 //
 745 // Possibilities:
 746 // * MD5Digest of {obj,stw_random}
 747 // * CRC32 of {obj,stw_random} or any linear-feedback shift register function.
 748 // * A DES- or AES-style SBox[] mechanism
 749 // * One of the Phi-based schemes, such as:
 750 //   2654435761 = 2^32 * Phi (golden ratio)
 751 //   HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stw_random ;
 752 // * A variation of Marsaglia's shift-xor RNG scheme.
 753 // * (obj ^ stw_random) is appealing, but can result
 754 //   in undesirable regularity in the hashCode values of adjacent objects
 755 //   (objects allocated back-to-back, in particular).  This could potentially
 756 //   result in hashtable collisions and reduced hashtable efficiency.
 757 //   There are simple ways to "diffuse" the middle address bits over the
 758 //   generated hashCode values:
 759 
 760 static inline intptr_t get_next_hash(Thread* current, oop obj) {
 761   intptr_t value = 0;
 762   if (hashCode == 0) {
 763     // This form uses global Park-Miller RNG.
 764     // On MP system we'll have lots of RW access to a global, so the
 765     // mechanism induces lots of coherency traffic.
 766     value = os::random();
 767   } else if (hashCode == 1) {
 768     // This variation has the property of being stable (idempotent)
 769     // between STW operations.  This can be useful in some of the 1-0
 770     // synchronization schemes.
 771     intptr_t addr_bits = cast_from_oop<intptr_t>(obj) >> 3;
 772     value = addr_bits ^ (addr_bits >> 5) ^ GVars.stw_random;
 773   } else if (hashCode == 2) {
 774     value = 1;            // for sensitivity testing
 775   } else if (hashCode == 3) {
 776     value = ++GVars.hc_sequence;
 777   } else if (hashCode == 4) {
 778     value = cast_from_oop<intptr_t>(obj);
 779   } else {
 780     // Marsaglia's xor-shift scheme with thread-specific state
 781     // This is probably the best overall implementation -- we'll
 782     // likely make this the default in future releases.
 783     unsigned t = current->_hashStateX;
 784     t ^= (t << 11);
 785     current->_hashStateX = current->_hashStateY;
 786     current->_hashStateY = current->_hashStateZ;
 787     current->_hashStateZ = current->_hashStateW;
 788     unsigned v = current->_hashStateW;
 789     v = (v ^ (v >> 19)) ^ (t ^ (t >> 8));
 790     current->_hashStateW = v;
 791     value = v;
 792   }
 793 
 794   value &= markWord::hash_mask;
 795   if (value == 0) value = 0xBAD;
 796   assert(value != markWord::no_hash, "invariant");
 797   return value;
 798 }
 799 
 800 intptr_t ObjectSynchronizer::FastHashCode(Thread* current, oop obj) {
 801 
 802   while (true) {
 803     ObjectMonitor* monitor = NULL;
 804     markWord temp, test;
 805     intptr_t hash;
 806     markWord mark = read_stable_mark(obj);
 807 
 808     if (mark.is_neutral()) {               // if this is a normal header
 809       hash = mark.hash();
 810       if (hash != 0) {                     // if it has a hash, just return it
 811         return hash;
 812       }
 813       hash = get_next_hash(current, obj);  // get a new hash
 814       temp = mark.copy_set_hash(hash);     // merge the hash into header
 815                                            // try to install the hash
 816       test = obj->cas_set_mark(temp, mark);
 817       if (test == mark) {                  // if the hash was installed, return it
 818         return hash;
 819       }
 820       // Failed to install the hash. It could be that another thread
 821       // installed the hash just before our attempt or inflation has
 822       // occurred or... so we fall thru to inflate the monitor for
 823       // stability and then install the hash.
 824     } else if (mark.has_monitor()) {
 825       monitor = mark.monitor();
 826       temp = monitor->header();
 827       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
 828       hash = temp.hash();
 829       if (hash != 0) {
 830         // It has a hash.
 831 
 832         // Separate load of dmw/header above from the loads in
 833         // is_being_async_deflated().
 834 
 835         // dmw/header and _contentions may get written by different threads.
 836         // Make sure to observe them in the same order when having several observers.
 837         OrderAccess::loadload_for_IRIW();
 838 
 839         if (monitor->is_being_async_deflated()) {
 840           // But we can't safely use the hash if we detect that async
 841           // deflation has occurred. So we attempt to restore the
 842           // header/dmw to the object's header so that we only retry
 843           // once if the deflater thread happens to be slow.
 844           monitor->install_displaced_markword_in_object(obj);
 845           continue;
 846         }
 847         return hash;
 848       }
 849       // Fall thru so we only have one place that installs the hash in
 850       // the ObjectMonitor.
 851     } else if (current->is_lock_owned((address)mark.locker())) {
 852       // This is a stack lock owned by the calling thread so fetch the
 853       // displaced markWord from the BasicLock on the stack.
 854       temp = mark.displaced_mark_helper();
 855       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
 856       hash = temp.hash();
 857       if (hash != 0) {                  // if it has a hash, just return it
 858         return hash;
 859       }
 860       // WARNING:
 861       // The displaced header in the BasicLock on a thread's stack
 862       // is strictly immutable. It CANNOT be changed in ANY cases.
 863       // So we have to inflate the stack lock into an ObjectMonitor
 864       // even if the current thread owns the lock. The BasicLock on
 865       // a thread's stack can be asynchronously read by other threads
 866       // during an inflate() call so any change to that stack memory
 867       // may not propagate to other threads correctly.
 868     }
 869 
 870     // Inflate the monitor to set the hash.
 871 
 872     // An async deflation can race after the inflate() call and before we
 873     // can update the ObjectMonitor's header with the hash value below.
 874     monitor = inflate(current, obj, inflate_cause_hash_code);
 875     // Load ObjectMonitor's header/dmw field and see if it has a hash.
 876     mark = monitor->header();
 877     assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value());
 878     hash = mark.hash();
 879     if (hash == 0) {                       // if it does not have a hash
 880       hash = get_next_hash(current, obj);  // get a new hash
 881       temp = mark.copy_set_hash(hash)   ;  // merge the hash into header
 882       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
 883       uintptr_t v = Atomic::cmpxchg((volatile uintptr_t*)monitor->header_addr(), mark.value(), temp.value());
 884       test = markWord(v);
 885       if (test != mark) {
 886         // The attempt to update the ObjectMonitor's header/dmw field
 887         // did not work. This can happen if another thread managed to
 888         // merge in the hash just before our cmpxchg().
 889         // If we add any new usages of the header/dmw field, this code
 890         // will need to be updated.
 891         hash = test.hash();
 892         assert(test.is_neutral(), "invariant: header=" INTPTR_FORMAT, test.value());
 893         assert(hash != 0, "should only have lost the race to a thread that set a non-zero hash");
 894       }
 895       if (monitor->is_being_async_deflated()) {
 896         // If we detect that async deflation has occurred, then we
 897         // attempt to restore the header/dmw to the object's header
 898         // so that we only retry once if the deflater thread happens
 899         // to be slow.
 900         monitor->install_displaced_markword_in_object(obj);
 901         continue;
 902       }
 903     }
 904     // We finally get the hash.
 905     return hash;
 906   }
 907 }
 908 
 909 // Deprecated -- use FastHashCode() instead.
 910 
 911 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) {
 912   return FastHashCode(Thread::current(), obj());
 913 }
 914 
 915 
 916 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* current,
 917                                                    Handle h_obj) {
 918   assert(current == JavaThread::current(), "Can only be called on current thread");
 919   oop obj = h_obj();
 920 
 921   markWord mark = read_stable_mark(obj);
 922 
 923   // Uncontended case, header points to stack
 924   if (mark.has_locker()) {
 925     return current->is_lock_owned((address)mark.locker());
 926   }
 927   // Contended case, header points to ObjectMonitor (tagged pointer)
 928   if (mark.has_monitor()) {
 929     // The first stage of async deflation does not affect any field
 930     // used by this comparison so the ObjectMonitor* is usable here.
 931     ObjectMonitor* monitor = mark.monitor();
 932     return monitor->is_entered(current) != 0;
 933   }
 934   // Unlocked case, header in place
 935   assert(mark.is_neutral(), "sanity check");
 936   return false;
 937 }
 938 
 939 // FIXME: jvmti should call this
 940 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) {
 941   oop obj = h_obj();
 942   address owner = NULL;
 943 
 944   markWord mark = read_stable_mark(obj);
 945 
 946   // Uncontended case, header points to stack
 947   if (mark.has_locker()) {
 948     owner = (address) mark.locker();
 949   }
 950 
 951   // Contended case, header points to ObjectMonitor (tagged pointer)
 952   else if (mark.has_monitor()) {
 953     // The first stage of async deflation does not affect any field
 954     // used by this comparison so the ObjectMonitor* is usable here.
 955     ObjectMonitor* monitor = mark.monitor();
 956     assert(monitor != NULL, "monitor should be non-null");
 957     owner = (address) monitor->owner();
 958   }
 959 
 960   if (owner != NULL) {
 961     // owning_thread_from_monitor_owner() may also return NULL here
 962     return Threads::owning_thread_from_monitor_owner(t_list, owner);
 963   }
 964 
 965   // Unlocked case, header in place
 966   // Cannot have assertion since this object may have been
 967   // locked by another thread when reaching here.
 968   // assert(mark.is_neutral(), "sanity check");
 969 
 970   return NULL;
 971 }
 972 
 973 // Visitors ...
 974 
 975 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure, JavaThread* thread) {
 976   MonitorList::Iterator iter = _in_use_list.iterator();
 977   while (iter.has_next()) {
 978     ObjectMonitor* mid = iter.next();
 979     if (mid->owner() != thread) {
 980       continue;
 981     }
 982     if (!mid->is_being_async_deflated() && mid->object_peek() != NULL) {
 983       // Only process with closure if the object is set.
 984 
 985       // monitors_iterate() is only called at a safepoint or when the
 986       // target thread is suspended or when the target thread is
 987       // operating on itself. The current closures in use today are
 988       // only interested in an owned ObjectMonitor and ownership
 989       // cannot be dropped under the calling contexts so the
 990       // ObjectMonitor cannot be async deflated.
 991       closure->do_monitor(mid);
 992     }
 993   }
 994 }
 995 
 996 static bool monitors_used_above_threshold(MonitorList* list) {
 997   if (MonitorUsedDeflationThreshold == 0) {  // disabled case is easy
 998     return false;
 999   }
1000   // Start with ceiling based on a per-thread estimate:
1001   size_t ceiling = ObjectSynchronizer::in_use_list_ceiling();
1002   size_t old_ceiling = ceiling;
1003   if (ceiling < list->max()) {
1004     // The max used by the system has exceeded the ceiling so use that:
1005     ceiling = list->max();
1006   }
1007   size_t monitors_used = list->count();
1008   if (monitors_used == 0) {  // empty list is easy
1009     return false;
1010   }
1011   if (NoAsyncDeflationProgressMax != 0 &&
1012       _no_progress_cnt >= NoAsyncDeflationProgressMax) {
1013     float remainder = (100.0 - MonitorUsedDeflationThreshold) / 100.0;
1014     size_t new_ceiling = ceiling + (ceiling * remainder) + 1;
1015     ObjectSynchronizer::set_in_use_list_ceiling(new_ceiling);
1016     log_info(monitorinflation)("Too many deflations without progress; "
1017                                "bumping in_use_list_ceiling from " SIZE_FORMAT
1018                                " to " SIZE_FORMAT, old_ceiling, new_ceiling);
1019     _no_progress_cnt = 0;
1020     ceiling = new_ceiling;
1021   }
1022 
1023   // Check if our monitor usage is above the threshold:
1024   size_t monitor_usage = (monitors_used * 100LL) / ceiling;
1025   return int(monitor_usage) > MonitorUsedDeflationThreshold;
1026 }
1027 
1028 size_t ObjectSynchronizer::in_use_list_ceiling() {
1029   return _in_use_list_ceiling;
1030 }
1031 
1032 void ObjectSynchronizer::dec_in_use_list_ceiling() {
1033   Atomic::sub(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate);
1034 }
1035 
1036 void ObjectSynchronizer::inc_in_use_list_ceiling() {
1037   Atomic::add(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate);
1038 }
1039 
1040 void ObjectSynchronizer::set_in_use_list_ceiling(size_t new_value) {
1041   _in_use_list_ceiling = new_value;
1042 }
1043 
1044 bool ObjectSynchronizer::is_async_deflation_needed() {
1045   if (is_async_deflation_requested()) {
1046     // Async deflation request.
1047     return true;
1048   }
1049   if (AsyncDeflationInterval > 0 &&
1050       time_since_last_async_deflation_ms() > AsyncDeflationInterval &&
1051       monitors_used_above_threshold(&_in_use_list)) {
1052     // It's been longer than our specified deflate interval and there
1053     // are too many monitors in use. We don't deflate more frequently
1054     // than AsyncDeflationInterval (unless is_async_deflation_requested)
1055     // in order to not swamp the MonitorDeflationThread.
1056     return true;
1057   }
1058   return false;
1059 }
1060 
1061 bool ObjectSynchronizer::request_deflate_idle_monitors() {
1062   JavaThread* current = JavaThread::current();
1063   bool ret_code = false;
1064 
1065   jlong last_time = last_async_deflation_time_ns();
1066   set_is_async_deflation_requested(true);
1067   {
1068     MonitorLocker ml(MonitorDeflation_lock, Mutex::_no_safepoint_check_flag);
1069     ml.notify_all();
1070   }
1071   const int N_CHECKS = 5;
1072   for (int i = 0; i < N_CHECKS; i++) {  // sleep for at most 5 seconds
1073     if (last_async_deflation_time_ns() > last_time) {
1074       log_info(monitorinflation)("Async Deflation happened after %d check(s).", i);
1075       ret_code = true;
1076       break;
1077     }
1078     {
1079       // JavaThread has to honor the blocking protocol.
1080       ThreadBlockInVM tbivm(current);
1081       os::naked_short_sleep(999);  // sleep for almost 1 second
1082     }
1083   }
1084   if (!ret_code) {
1085     log_info(monitorinflation)("Async Deflation DID NOT happen after %d checks.", N_CHECKS);
1086   }
1087 
1088   return ret_code;
1089 }
1090 
1091 jlong ObjectSynchronizer::time_since_last_async_deflation_ms() {
1092   return (os::javaTimeNanos() - last_async_deflation_time_ns()) / (NANOUNITS / MILLIUNITS);
1093 }
1094 
1095 static void post_monitor_inflate_event(EventJavaMonitorInflate* event,
1096                                        const oop obj,
1097                                        ObjectSynchronizer::InflateCause cause) {
1098   assert(event != NULL, "invariant");
1099   assert(event->should_commit(), "invariant");
1100   event->set_monitorClass(obj->klass());
1101   event->set_address((uintptr_t)(void*)obj);
1102   event->set_cause((u1)cause);
1103   event->commit();
1104 }
1105 
1106 // Fast path code shared by multiple functions
1107 void ObjectSynchronizer::inflate_helper(oop obj) {
1108   markWord mark = obj->mark_acquire();
1109   if (mark.has_monitor()) {
1110     ObjectMonitor* monitor = mark.monitor();
1111     markWord dmw = monitor->header();
1112     assert(dmw.is_neutral(), "sanity check: header=" INTPTR_FORMAT, dmw.value());
1113     return;
1114   }
1115   (void)inflate(Thread::current(), obj, inflate_cause_vm_internal);
1116 }
1117 
1118 ObjectMonitor* ObjectSynchronizer::inflate(Thread* current, oop object,
1119                                            const InflateCause cause) {
1120   EventJavaMonitorInflate event;
1121 
1122   for (;;) {
1123     const markWord mark = object->mark_acquire();
1124 
1125     // The mark can be in one of the following states:
1126     // *  Inflated     - just return
1127     // *  Stack-locked - coerce it to inflated
1128     // *  INFLATING    - busy wait for conversion to complete
1129     // *  Neutral      - aggressively inflate the object.
1130 
1131     // CASE: inflated
1132     if (mark.has_monitor()) {
1133       ObjectMonitor* inf = mark.monitor();
1134       markWord dmw = inf->header();
1135       assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value());
1136       return inf;
1137     }
1138 
1139     // CASE: inflation in progress - inflating over a stack-lock.
1140     // Some other thread is converting from stack-locked to inflated.
1141     // Only that thread can complete inflation -- other threads must wait.
1142     // The INFLATING value is transient.
1143     // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
1144     // We could always eliminate polling by parking the thread on some auxiliary list.
1145     if (mark == markWord::INFLATING()) {
1146       read_stable_mark(object);
1147       continue;
1148     }
1149 
1150     // CASE: stack-locked
1151     // Could be stack-locked either by this thread or by some other thread.
1152     //
1153     // Note that we allocate the ObjectMonitor speculatively, _before_ attempting
1154     // to install INFLATING into the mark word.  We originally installed INFLATING,
1155     // allocated the ObjectMonitor, and then finally STed the address of the
1156     // ObjectMonitor into the mark.  This was correct, but artificially lengthened
1157     // the interval in which INFLATING appeared in the mark, thus increasing
1158     // the odds of inflation contention.
1159 
1160     LogStreamHandle(Trace, monitorinflation) lsh;
1161 
1162     if (mark.has_locker()) {
1163       ObjectMonitor* m = new ObjectMonitor(object);
1164       // Optimistically prepare the ObjectMonitor - anticipate successful CAS
1165       // We do this before the CAS in order to minimize the length of time
1166       // in which INFLATING appears in the mark.
1167 
1168       markWord cmp = object->cas_set_mark(markWord::INFLATING(), mark);
1169       if (cmp != mark) {
1170         delete m;
1171         continue;       // Interference -- just retry
1172       }
1173 
1174       // We've successfully installed INFLATING (0) into the mark-word.
1175       // This is the only case where 0 will appear in a mark-word.
1176       // Only the singular thread that successfully swings the mark-word
1177       // to 0 can perform (or more precisely, complete) inflation.
1178       //
1179       // Why do we CAS a 0 into the mark-word instead of just CASing the
1180       // mark-word from the stack-locked value directly to the new inflated state?
1181       // Consider what happens when a thread unlocks a stack-locked object.
1182       // It attempts to use CAS to swing the displaced header value from the
1183       // on-stack BasicLock back into the object header.  Recall also that the
1184       // header value (hash code, etc) can reside in (a) the object header, or
1185       // (b) a displaced header associated with the stack-lock, or (c) a displaced
1186       // header in an ObjectMonitor.  The inflate() routine must copy the header
1187       // value from the BasicLock on the owner's stack to the ObjectMonitor, all
1188       // the while preserving the hashCode stability invariants.  If the owner
1189       // decides to release the lock while the value is 0, the unlock will fail
1190       // and control will eventually pass from slow_exit() to inflate.  The owner
1191       // will then spin, waiting for the 0 value to disappear.   Put another way,
1192       // the 0 causes the owner to stall if the owner happens to try to
1193       // drop the lock (restoring the header from the BasicLock to the object)
1194       // while inflation is in-progress.  This protocol avoids races that might
1195       // would otherwise permit hashCode values to change or "flicker" for an object.
1196       // Critically, while object->mark is 0 mark.displaced_mark_helper() is stable.
1197       // 0 serves as a "BUSY" inflate-in-progress indicator.
1198 
1199 
1200       // fetch the displaced mark from the owner's stack.
1201       // The owner can't die or unwind past the lock while our INFLATING
1202       // object is in the mark.  Furthermore the owner can't complete
1203       // an unlock on the object, either.
1204       markWord dmw = mark.displaced_mark_helper();
1205       // Catch if the object's header is not neutral (not locked and
1206       // not marked is what we care about here).
1207       assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value());
1208 
1209       // Setup monitor fields to proper values -- prepare the monitor
1210       m->set_header(dmw);
1211 
1212       // Optimization: if the mark.locker stack address is associated
1213       // with this thread we could simply set m->_owner = current.
1214       // Note that a thread can inflate an object
1215       // that it has stack-locked -- as might happen in wait() -- directly
1216       // with CAS.  That is, we can avoid the xchg-NULL .... ST idiom.
1217       m->set_owner_from(NULL, mark.locker());
1218       // TODO-FIXME: assert BasicLock->dhw != 0.
1219 
1220       // Must preserve store ordering. The monitor state must
1221       // be stable at the time of publishing the monitor address.
1222       guarantee(object->mark() == markWord::INFLATING(), "invariant");
1223       // Release semantics so that above set_object() is seen first.
1224       object->release_set_mark(markWord::encode(m));
1225 
1226       // Once ObjectMonitor is configured and the object is associated
1227       // with the ObjectMonitor, it is safe to allow async deflation:
1228       _in_use_list.add(m);
1229 
1230       // Hopefully the performance counters are allocated on distinct cache lines
1231       // to avoid false sharing on MP systems ...
1232       OM_PERFDATA_OP(Inflations, inc());
1233       if (log_is_enabled(Trace, monitorinflation)) {
1234         ResourceMark rm(current);
1235         lsh.print_cr("inflate(has_locker): object=" INTPTR_FORMAT ", mark="
1236                      INTPTR_FORMAT ", type='%s'", p2i(object),
1237                      object->mark().value(), object->klass()->external_name());
1238       }
1239       if (event.should_commit()) {
1240         post_monitor_inflate_event(&event, object, cause);
1241       }
1242       return m;
1243     }
1244 
1245     // CASE: neutral
1246     // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
1247     // If we know we're inflating for entry it's better to inflate by swinging a
1248     // pre-locked ObjectMonitor pointer into the object header.   A successful
1249     // CAS inflates the object *and* confers ownership to the inflating thread.
1250     // In the current implementation we use a 2-step mechanism where we CAS()
1251     // to inflate and then CAS() again to try to swing _owner from NULL to current.
1252     // An inflateTry() method that we could call from enter() would be useful.
1253 
1254     // Catch if the object's header is not neutral (not locked and
1255     // not marked is what we care about here).
1256     assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value());
1257     ObjectMonitor* m = new ObjectMonitor(object);
1258     // prepare m for installation - set monitor to initial state
1259     m->set_header(mark);
1260 
1261     if (object->cas_set_mark(markWord::encode(m), mark) != mark) {
1262       delete m;
1263       m = NULL;
1264       continue;
1265       // interference - the markword changed - just retry.
1266       // The state-transitions are one-way, so there's no chance of
1267       // live-lock -- "Inflated" is an absorbing state.
1268     }
1269 
1270     // Once the ObjectMonitor is configured and object is associated
1271     // with the ObjectMonitor, it is safe to allow async deflation:
1272     _in_use_list.add(m);
1273 
1274     // Hopefully the performance counters are allocated on distinct
1275     // cache lines to avoid false sharing on MP systems ...
1276     OM_PERFDATA_OP(Inflations, inc());
1277     if (log_is_enabled(Trace, monitorinflation)) {
1278       ResourceMark rm(current);
1279       lsh.print_cr("inflate(neutral): object=" INTPTR_FORMAT ", mark="
1280                    INTPTR_FORMAT ", type='%s'", p2i(object),
1281                    object->mark().value(), object->klass()->external_name());
1282     }
1283     if (event.should_commit()) {
1284       post_monitor_inflate_event(&event, object, cause);
1285     }
1286     return m;
1287   }
1288 }
1289 
1290 void ObjectSynchronizer::chk_for_block_req(JavaThread* current, const char* op_name,
1291                                            const char* cnt_name, size_t cnt,
1292                                            LogStream* ls, elapsedTimer* timer_p) {
1293   if (!SafepointMechanism::should_process(current)) {
1294     return;
1295   }
1296 
1297   // A safepoint/handshake has started.
1298   if (ls != NULL) {
1299     timer_p->stop();
1300     ls->print_cr("pausing %s: %s=" SIZE_FORMAT ", in_use_list stats: ceiling="
1301                  SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT,
1302                  op_name, cnt_name, cnt, in_use_list_ceiling(),
1303                  _in_use_list.count(), _in_use_list.max());
1304   }
1305 
1306   {
1307     // Honor block request.
1308     ThreadBlockInVM tbivm(current);
1309   }
1310 
1311   if (ls != NULL) {
1312     ls->print_cr("resuming %s: in_use_list stats: ceiling=" SIZE_FORMAT
1313                  ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT, op_name,
1314                  in_use_list_ceiling(), _in_use_list.count(), _in_use_list.max());
1315     timer_p->start();
1316   }
1317 }
1318 
1319 // Walk the in-use list and deflate (at most MonitorDeflationMax) idle
1320 // ObjectMonitors. Returns the number of deflated ObjectMonitors.
1321 size_t ObjectSynchronizer::deflate_monitor_list(Thread* current, LogStream* ls,
1322                                                 elapsedTimer* timer_p) {
1323   MonitorList::Iterator iter = _in_use_list.iterator();
1324   size_t deflated_count = 0;
1325 
1326   while (iter.has_next()) {
1327     if (deflated_count >= (size_t)MonitorDeflationMax) {
1328       break;
1329     }
1330     ObjectMonitor* mid = iter.next();
1331     if (mid->deflate_monitor()) {
1332       deflated_count++;
1333     }
1334 
1335     if (current->is_Java_thread()) {
1336       // A JavaThread must check for a safepoint/handshake and honor it.
1337       chk_for_block_req(JavaThread::cast(current), "deflation", "deflated_count",
1338                         deflated_count, ls, timer_p);
1339     }
1340   }
1341 
1342   return deflated_count;
1343 }
1344 
1345 class HandshakeForDeflation : public HandshakeClosure {
1346  public:
1347   HandshakeForDeflation() : HandshakeClosure("HandshakeForDeflation") {}
1348 
1349   void do_thread(Thread* thread) {
1350     log_trace(monitorinflation)("HandshakeForDeflation::do_thread: thread="
1351                                 INTPTR_FORMAT, p2i(thread));
1352   }
1353 };
1354 
1355 // This function is called by the MonitorDeflationThread to deflate
1356 // ObjectMonitors. It is also called via do_final_audit_and_print_stats()
1357 // by the VMThread.
1358 size_t ObjectSynchronizer::deflate_idle_monitors() {
1359   Thread* current = Thread::current();
1360   if (current->is_Java_thread()) {
1361     // The async deflation request has been processed.
1362     _last_async_deflation_time_ns = os::javaTimeNanos();
1363     set_is_async_deflation_requested(false);
1364   }
1365 
1366   LogStreamHandle(Debug, monitorinflation) lsh_debug;
1367   LogStreamHandle(Info, monitorinflation) lsh_info;
1368   LogStream* ls = NULL;
1369   if (log_is_enabled(Debug, monitorinflation)) {
1370     ls = &lsh_debug;
1371   } else if (log_is_enabled(Info, monitorinflation)) {
1372     ls = &lsh_info;
1373   }
1374 
1375   elapsedTimer timer;
1376   if (ls != NULL) {
1377     ls->print_cr("begin deflating: in_use_list stats: ceiling=" SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT,
1378                  in_use_list_ceiling(), _in_use_list.count(), _in_use_list.max());
1379     timer.start();
1380   }
1381 
1382   // Deflate some idle ObjectMonitors.
1383   size_t deflated_count = deflate_monitor_list(current, ls, &timer);
1384   if (deflated_count > 0 || is_final_audit()) {
1385     // There are ObjectMonitors that have been deflated or this is the
1386     // final audit and all the remaining ObjectMonitors have been
1387     // deflated, BUT the MonitorDeflationThread blocked for the final
1388     // safepoint during unlinking.
1389 
1390     // Unlink deflated ObjectMonitors from the in-use list.
1391     ResourceMark rm;
1392     GrowableArray<ObjectMonitor*> delete_list((int)deflated_count);
1393     size_t unlinked_count = _in_use_list.unlink_deflated(current, ls, &timer,
1394                                                          &delete_list);
1395     if (current->is_Java_thread()) {
1396       if (ls != NULL) {
1397         timer.stop();
1398         ls->print_cr("before handshaking: unlinked_count=" SIZE_FORMAT
1399                      ", in_use_list stats: ceiling=" SIZE_FORMAT ", count="
1400                      SIZE_FORMAT ", max=" SIZE_FORMAT,
1401                      unlinked_count, in_use_list_ceiling(),
1402                      _in_use_list.count(), _in_use_list.max());
1403       }
1404 
1405       // A JavaThread needs to handshake in order to safely free the
1406       // ObjectMonitors that were deflated in this cycle.
1407       HandshakeForDeflation hfd_hc;
1408       Handshake::execute(&hfd_hc);
1409 
1410       if (ls != NULL) {
1411         ls->print_cr("after handshaking: in_use_list stats: ceiling="
1412                      SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT,
1413                      in_use_list_ceiling(), _in_use_list.count(), _in_use_list.max());
1414         timer.start();
1415       }
1416     }
1417 
1418     // After the handshake, safely free the ObjectMonitors that were
1419     // deflated in this cycle.
1420     size_t deleted_count = 0;
1421     for (ObjectMonitor* monitor: delete_list) {
1422       delete monitor;
1423       deleted_count++;
1424 
1425       if (current->is_Java_thread()) {
1426         // A JavaThread must check for a safepoint/handshake and honor it.
1427         chk_for_block_req(JavaThread::cast(current), "deletion", "deleted_count",
1428                           deleted_count, ls, &timer);
1429       }
1430     }
1431   }
1432 
1433   if (ls != NULL) {
1434     timer.stop();
1435     if (deflated_count != 0 || log_is_enabled(Debug, monitorinflation)) {
1436       ls->print_cr("deflated " SIZE_FORMAT " monitors in %3.7f secs",
1437                    deflated_count, timer.seconds());
1438     }
1439     ls->print_cr("end deflating: in_use_list stats: ceiling=" SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT,
1440                  in_use_list_ceiling(), _in_use_list.count(), _in_use_list.max());
1441   }
1442 
1443   OM_PERFDATA_OP(MonExtant, set_value(_in_use_list.count()));
1444   OM_PERFDATA_OP(Deflations, inc(deflated_count));
1445 
1446   GVars.stw_random = os::random();
1447 
1448   if (deflated_count != 0) {
1449     _no_progress_cnt = 0;
1450   } else {
1451     _no_progress_cnt++;
1452   }
1453 
1454   return deflated_count;
1455 }
1456 
1457 // Monitor cleanup on JavaThread::exit
1458 
1459 // Iterate through monitor cache and attempt to release thread's monitors
1460 class ReleaseJavaMonitorsClosure: public MonitorClosure {
1461  private:
1462   JavaThread* _thread;
1463 
1464  public:
1465   ReleaseJavaMonitorsClosure(JavaThread* thread) : _thread(thread) {}
1466   void do_monitor(ObjectMonitor* mid) {
1467     (void)mid->complete_exit(_thread);
1468   }
1469 };
1470 
1471 // Release all inflated monitors owned by current thread.  Lightweight monitors are
1472 // ignored.  This is meant to be called during JNI thread detach which assumes
1473 // all remaining monitors are heavyweight.  All exceptions are swallowed.
1474 // Scanning the extant monitor list can be time consuming.
1475 // A simple optimization is to add a per-thread flag that indicates a thread
1476 // called jni_monitorenter() during its lifetime.
1477 //
1478 // Instead of NoSafepointVerifier it might be cheaper to
1479 // use an idiom of the form:
1480 //   auto int tmp = SafepointSynchronize::_safepoint_counter ;
1481 //   <code that must not run at safepoint>
1482 //   guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ;
1483 // Since the tests are extremely cheap we could leave them enabled
1484 // for normal product builds.
1485 
1486 void ObjectSynchronizer::release_monitors_owned_by_thread(JavaThread* current) {
1487   assert(current == JavaThread::current(), "must be current Java thread");
1488   NoSafepointVerifier nsv;
1489   ReleaseJavaMonitorsClosure rjmc(current);
1490   ObjectSynchronizer::monitors_iterate(&rjmc, current);
1491   assert(!current->has_pending_exception(), "Should not be possible");
1492   current->clear_pending_exception();
1493 }
1494 
1495 const char* ObjectSynchronizer::inflate_cause_name(const InflateCause cause) {
1496   switch (cause) {
1497     case inflate_cause_vm_internal:    return "VM Internal";
1498     case inflate_cause_monitor_enter:  return "Monitor Enter";
1499     case inflate_cause_wait:           return "Monitor Wait";
1500     case inflate_cause_notify:         return "Monitor Notify";
1501     case inflate_cause_hash_code:      return "Monitor Hash Code";
1502     case inflate_cause_jni_enter:      return "JNI Monitor Enter";
1503     case inflate_cause_jni_exit:       return "JNI Monitor Exit";
1504     default:
1505       ShouldNotReachHere();
1506   }
1507   return "Unknown";
1508 }
1509 
1510 //------------------------------------------------------------------------------
1511 // Debugging code
1512 
1513 u_char* ObjectSynchronizer::get_gvars_addr() {
1514   return (u_char*)&GVars;
1515 }
1516 
1517 u_char* ObjectSynchronizer::get_gvars_hc_sequence_addr() {
1518   return (u_char*)&GVars.hc_sequence;
1519 }
1520 
1521 size_t ObjectSynchronizer::get_gvars_size() {
1522   return sizeof(SharedGlobals);
1523 }
1524 
1525 u_char* ObjectSynchronizer::get_gvars_stw_random_addr() {
1526   return (u_char*)&GVars.stw_random;
1527 }
1528 
1529 // Do the final audit and print of ObjectMonitor stats; must be done
1530 // by the VMThread at VM exit time.
1531 void ObjectSynchronizer::do_final_audit_and_print_stats() {
1532   assert(Thread::current()->is_VM_thread(), "sanity check");
1533 
1534   if (is_final_audit()) {  // Only do the audit once.
1535     return;
1536   }
1537   set_is_final_audit();
1538 
1539   if (log_is_enabled(Info, monitorinflation)) {
1540     // Do a deflation in order to reduce the in-use monitor population
1541     // that is reported by ObjectSynchronizer::log_in_use_monitor_details()
1542     // which is called by ObjectSynchronizer::audit_and_print_stats().
1543     while (ObjectSynchronizer::deflate_idle_monitors() != 0) {
1544       ; // empty
1545     }
1546     // The other audit_and_print_stats() call is done at the Debug
1547     // level at a safepoint in ObjectSynchronizer::do_safepoint_work().
1548     ObjectSynchronizer::audit_and_print_stats(true /* on_exit */);
1549   }
1550 }
1551 
1552 // This function can be called at a safepoint or it can be called when
1553 // we are trying to exit the VM. When we are trying to exit the VM, the
1554 // list walker functions can run in parallel with the other list
1555 // operations so spin-locking is used for safety.
1556 //
1557 // Calls to this function can be added in various places as a debugging
1558 // aid; pass 'true' for the 'on_exit' parameter to have in-use monitor
1559 // details logged at the Info level and 'false' for the 'on_exit'
1560 // parameter to have in-use monitor details logged at the Trace level.
1561 //
1562 void ObjectSynchronizer::audit_and_print_stats(bool on_exit) {
1563   assert(on_exit || SafepointSynchronize::is_at_safepoint(), "invariant");
1564 
1565   LogStreamHandle(Debug, monitorinflation) lsh_debug;
1566   LogStreamHandle(Info, monitorinflation) lsh_info;
1567   LogStreamHandle(Trace, monitorinflation) lsh_trace;
1568   LogStream* ls = NULL;
1569   if (log_is_enabled(Trace, monitorinflation)) {
1570     ls = &lsh_trace;
1571   } else if (log_is_enabled(Debug, monitorinflation)) {
1572     ls = &lsh_debug;
1573   } else if (log_is_enabled(Info, monitorinflation)) {
1574     ls = &lsh_info;
1575   }
1576   assert(ls != NULL, "sanity check");
1577 
1578   int error_cnt = 0;
1579 
1580   ls->print_cr("Checking in_use_list:");
1581   chk_in_use_list(ls, &error_cnt);
1582 
1583   if (error_cnt == 0) {
1584     ls->print_cr("No errors found in in_use_list checks.");
1585   } else {
1586     log_error(monitorinflation)("found in_use_list errors: error_cnt=%d", error_cnt);
1587   }
1588 
1589   if ((on_exit && log_is_enabled(Info, monitorinflation)) ||
1590       (!on_exit && log_is_enabled(Trace, monitorinflation))) {
1591     // When exiting this log output is at the Info level. When called
1592     // at a safepoint, this log output is at the Trace level since
1593     // there can be a lot of it.
1594     log_in_use_monitor_details(ls);
1595   }
1596 
1597   ls->flush();
1598 
1599   guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt);
1600 }
1601 
1602 // Check the in_use_list; log the results of the checks.
1603 void ObjectSynchronizer::chk_in_use_list(outputStream* out, int *error_cnt_p) {
1604   size_t l_in_use_count = _in_use_list.count();
1605   size_t l_in_use_max = _in_use_list.max();
1606   out->print_cr("count=" SIZE_FORMAT ", max=" SIZE_FORMAT, l_in_use_count,
1607                 l_in_use_max);
1608 
1609   size_t ck_in_use_count = 0;
1610   MonitorList::Iterator iter = _in_use_list.iterator();
1611   while (iter.has_next()) {
1612     ObjectMonitor* mid = iter.next();
1613     chk_in_use_entry(mid, out, error_cnt_p);
1614     ck_in_use_count++;
1615   }
1616 
1617   if (l_in_use_count == ck_in_use_count) {
1618     out->print_cr("in_use_count=" SIZE_FORMAT " equals ck_in_use_count="
1619                   SIZE_FORMAT, l_in_use_count, ck_in_use_count);
1620   } else {
1621     out->print_cr("WARNING: in_use_count=" SIZE_FORMAT " is not equal to "
1622                   "ck_in_use_count=" SIZE_FORMAT, l_in_use_count,
1623                   ck_in_use_count);
1624   }
1625 
1626   size_t ck_in_use_max = _in_use_list.max();
1627   if (l_in_use_max == ck_in_use_max) {
1628     out->print_cr("in_use_max=" SIZE_FORMAT " equals ck_in_use_max="
1629                   SIZE_FORMAT, l_in_use_max, ck_in_use_max);
1630   } else {
1631     out->print_cr("WARNING: in_use_max=" SIZE_FORMAT " is not equal to "
1632                   "ck_in_use_max=" SIZE_FORMAT, l_in_use_max, ck_in_use_max);
1633   }
1634 }
1635 
1636 // Check an in-use monitor entry; log any errors.
1637 void ObjectSynchronizer::chk_in_use_entry(ObjectMonitor* n, outputStream* out,
1638                                           int* error_cnt_p) {
1639   if (n->owner_is_DEFLATER_MARKER()) {
1640     // This should not happen, but if it does, it is not fatal.
1641     out->print_cr("WARNING: monitor=" INTPTR_FORMAT ": in-use monitor is "
1642                   "deflated.", p2i(n));
1643     return;
1644   }
1645   if (n->header().value() == 0) {
1646     out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor must "
1647                   "have non-NULL _header field.", p2i(n));
1648     *error_cnt_p = *error_cnt_p + 1;
1649   }
1650   const oop obj = n->object_peek();
1651   if (obj != NULL) {
1652     const markWord mark = obj->mark();
1653     if (!mark.has_monitor()) {
1654       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's "
1655                     "object does not think it has a monitor: obj="
1656                     INTPTR_FORMAT ", mark=" INTPTR_FORMAT, p2i(n),
1657                     p2i(obj), mark.value());
1658       *error_cnt_p = *error_cnt_p + 1;
1659     }
1660     ObjectMonitor* const obj_mon = mark.monitor();
1661     if (n != obj_mon) {
1662       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's "
1663                     "object does not refer to the same monitor: obj="
1664                     INTPTR_FORMAT ", mark=" INTPTR_FORMAT ", obj_mon="
1665                     INTPTR_FORMAT, p2i(n), p2i(obj), mark.value(), p2i(obj_mon));
1666       *error_cnt_p = *error_cnt_p + 1;
1667     }
1668   }
1669 }
1670 
1671 // Log details about ObjectMonitors on the in_use_list. The 'BHL'
1672 // flags indicate why the entry is in-use, 'object' and 'object type'
1673 // indicate the associated object and its type.
1674 void ObjectSynchronizer::log_in_use_monitor_details(outputStream* out) {
1675   stringStream ss;
1676   if (_in_use_list.count() > 0) {
1677     out->print_cr("In-use monitor info:");
1678     out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
1679     out->print_cr("%18s  %s  %18s  %18s",
1680                   "monitor", "BHL", "object", "object type");
1681     out->print_cr("==================  ===  ==================  ==================");
1682     MonitorList::Iterator iter = _in_use_list.iterator();
1683     while (iter.has_next()) {
1684       ObjectMonitor* mid = iter.next();
1685       const oop obj = mid->object_peek();
1686       const markWord mark = mid->header();
1687       ResourceMark rm;
1688       out->print(INTPTR_FORMAT "  %d%d%d  " INTPTR_FORMAT "  %s", p2i(mid),
1689                  mid->is_busy(), mark.hash() != 0, mid->owner() != NULL,
1690                  p2i(obj), obj == NULL ? "" : obj->klass()->external_name());
1691       if (mid->is_busy()) {
1692         out->print(" (%s)", mid->is_busy_to_string(&ss));
1693         ss.reset();
1694       }
1695       out->cr();
1696     }
1697   }
1698 
1699   out->flush();
1700 }