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