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