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