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