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