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