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