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, TRAPS) : _thread(THREAD), _obj(obj),
 717   _npm(_thread, _thread->at_preemptable_init() /* ignore_mark */), _skip_exit(false) {
 718   assert(!_thread->preempting(), "");
 719 
 720   _thread->check_for_valid_safepoint_state();
 721 
 722   if (_obj() != nullptr) {
 723     ObjectSynchronizer::enter(_obj, &_lock, _thread);
 724 
 725     if (_thread->preempting()) {
 726       // If preemption was cancelled we acquired the monitor after freezing
 727       // the frames. Redoing the vm call laterĀ in thaw will require us to
 728       // release it since the call should look like the original one. We
 729       // do it in ~ObjectLocker to reduce the window of time we hold the
 730       // monitor since we can't do anything useful with it now, and would
 731       // otherwise just force other vthreads to preempt in case they try
 732       // to acquire this monitor.
 733       _skip_exit = !_thread->preemption_cancelled();
 734       _thread->set_pending_preempted_exception();
 735     }
 736   }
 737 }
 738 
 739 ObjectLocker::~ObjectLocker() {
 740   if (_obj() != nullptr && !_skip_exit) {
 741     ObjectSynchronizer::exit(_obj(), &_lock, _thread);
 742   }
 743 }
 744 
 745 void ObjectLocker::wait_uninterruptibly(TRAPS) {
 746   ObjectSynchronizer::waitUninterruptibly(_obj, 0, _thread);
 747   if (_thread->preempting()) {
 748     _skip_exit = true;
 749     _thread->set_pending_preempted_exception();
 750     _thread->set_class_to_be_initialized(nullptr);
 751   }
 752 }
 753 
 754 // -----------------------------------------------------------------------------
 755 //  Wait/Notify/NotifyAll
 756 // NOTE: must use heavy weight monitor to handle wait()
 757 
 758 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
 759   JavaThread* current = THREAD;
 760   if (millis < 0) {
 761     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 762   }
 763 
 764   ObjectMonitor* monitor;
 765   if (LockingMode == LM_LIGHTWEIGHT) {
 766     monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_wait, CHECK_0);
 767   } else {
 768     // The ObjectMonitor* can't be async deflated because the _waiters
 769     // field is incremented before ownership is dropped and decremented
 770     // after ownership is regained.
 771     monitor = inflate(current, obj(), inflate_cause_wait);
 772   }
 773 
 774   DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), current, millis);
 775   monitor->wait(millis, true, THREAD); // Not CHECK as we need following code
 776 
 777   // This dummy call is in place to get around dtrace bug 6254741.  Once
 778   // that's fixed we can uncomment the following line, remove the call
 779   // and change this function back into a "void" func.
 780   // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
 781   int ret_code = dtrace_waited_probe(monitor, obj, THREAD);
 782   return ret_code;
 783 }
 784 
 785 void ObjectSynchronizer::waitUninterruptibly(Handle obj, jlong millis, TRAPS) {
 786   assert(millis >= 0, "timeout value is negative");
 787 
 788   ObjectMonitor* monitor;
 789   if (LockingMode == LM_LIGHTWEIGHT) {
 790     monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_wait, CHECK);
 791   } else {
 792     monitor = inflate(THREAD, obj(), inflate_cause_wait);
 793   }
 794   monitor->wait(millis, false, THREAD);
 795 }
 796 
 797 
 798 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
 799   JavaThread* current = THREAD;
 800 
 801   markWord mark = obj->mark();
 802   if (LockingMode == LM_LIGHTWEIGHT) {
 803     if ((mark.is_fast_locked() && current->lock_stack().contains(obj()))) {
 804       // Not inflated so there can't be any waiters to notify.
 805       return;
 806     }
 807   } else if (LockingMode == LM_LEGACY) {
 808     if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {
 809       // Not inflated so there can't be any waiters to notify.
 810       return;
 811     }
 812   }
 813 
 814   ObjectMonitor* monitor;
 815   if (LockingMode == LM_LIGHTWEIGHT) {
 816     monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_notify, CHECK);
 817   } else {
 818     // The ObjectMonitor* can't be async deflated until ownership is
 819     // dropped by the calling thread.
 820     monitor = inflate(current, obj(), inflate_cause_notify);
 821   }
 822   monitor->notify(CHECK);
 823 }
 824 
 825 // NOTE: see comment of notify()
 826 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
 827   JavaThread* current = THREAD;
 828 
 829   markWord mark = obj->mark();
 830   if (LockingMode == LM_LIGHTWEIGHT) {
 831     if ((mark.is_fast_locked() && current->lock_stack().contains(obj()))) {
 832       // Not inflated so there can't be any waiters to notify.
 833       return;
 834     }
 835   } else if (LockingMode == LM_LEGACY) {
 836     if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {
 837       // Not inflated so there can't be any waiters to notify.
 838       return;
 839     }
 840   }
 841 
 842   ObjectMonitor* monitor;
 843   if (LockingMode == LM_LIGHTWEIGHT) {
 844     monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_notify, CHECK);
 845   } else {
 846     // The ObjectMonitor* can't be async deflated until ownership is
 847     // dropped by the calling thread.
 848     monitor = inflate(current, obj(), inflate_cause_notify);
 849   }
 850   monitor->notifyAll(CHECK);
 851 }
 852 
 853 // -----------------------------------------------------------------------------
 854 // Hash Code handling
 855 
 856 struct SharedGlobals {
 857   char         _pad_prefix[OM_CACHE_LINE_SIZE];
 858   // This is a highly shared mostly-read variable.
 859   // To avoid false-sharing it needs to be the sole occupant of a cache line.
 860   volatile int stw_random;
 861   DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 862   // Hot RW variable -- Sequester to avoid false-sharing
 863   volatile int hc_sequence;
 864   DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 865 };
 866 
 867 static SharedGlobals GVars;
 868 
 869 static markWord read_stable_mark(oop obj) {
 870   markWord mark = obj->mark_acquire();
 871   if (!mark.is_being_inflated() || LockingMode == LM_LIGHTWEIGHT) {
 872     // New lightweight locking does not use the markWord::INFLATING() protocol.
 873     return mark;       // normal fast-path return
 874   }
 875 
 876   int its = 0;
 877   for (;;) {
 878     markWord mark = obj->mark_acquire();
 879     if (!mark.is_being_inflated()) {
 880       return mark;    // normal fast-path return
 881     }
 882 
 883     // The object is being inflated by some other thread.
 884     // The caller of read_stable_mark() must wait for inflation to complete.
 885     // Avoid live-lock.
 886 
 887     ++its;
 888     if (its > 10000 || !os::is_MP()) {
 889       if (its & 1) {
 890         os::naked_yield();
 891       } else {
 892         // Note that the following code attenuates the livelock problem but is not
 893         // a complete remedy.  A more complete solution would require that the inflating
 894         // thread hold the associated inflation lock.  The following code simply restricts
 895         // the number of spinners to at most one.  We'll have N-2 threads blocked
 896         // on the inflationlock, 1 thread holding the inflation lock and using
 897         // a yield/park strategy, and 1 thread in the midst of inflation.
 898         // A more refined approach would be to change the encoding of INFLATING
 899         // to allow encapsulation of a native thread pointer.  Threads waiting for
 900         // inflation to complete would use CAS to push themselves onto a singly linked
 901         // list rooted at the markword.  Once enqueued, they'd loop, checking a per-thread flag
 902         // and calling park().  When inflation was complete the thread that accomplished inflation
 903         // would detach the list and set the markword to inflated with a single CAS and
 904         // then for each thread on the list, set the flag and unpark() the thread.
 905 
 906         // Index into the lock array based on the current object address.
 907         static_assert(is_power_of_2(inflation_lock_count()), "must be");
 908         size_t ix = (cast_from_oop<intptr_t>(obj) >> 5) & (inflation_lock_count() - 1);
 909         int YieldThenBlock = 0;
 910         assert(ix < inflation_lock_count(), "invariant");
 911         inflation_lock(ix)->lock();
 912         while (obj->mark_acquire() == markWord::INFLATING()) {
 913           // Beware: naked_yield() is advisory and has almost no effect on some platforms
 914           // so we periodically call current->_ParkEvent->park(1).
 915           // We use a mixed spin/yield/block mechanism.
 916           if ((YieldThenBlock++) >= 16) {
 917             Thread::current()->_ParkEvent->park(1);
 918           } else {
 919             os::naked_yield();
 920           }
 921         }
 922         inflation_lock(ix)->unlock();
 923       }
 924     } else {
 925       SpinPause();       // SMP-polite spinning
 926     }
 927   }
 928 }
 929 
 930 // hashCode() generation :
 931 //
 932 // Possibilities:
 933 // * MD5Digest of {obj,stw_random}
 934 // * CRC32 of {obj,stw_random} or any linear-feedback shift register function.
 935 // * A DES- or AES-style SBox[] mechanism
 936 // * One of the Phi-based schemes, such as:
 937 //   2654435761 = 2^32 * Phi (golden ratio)
 938 //   HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stw_random ;
 939 // * A variation of Marsaglia's shift-xor RNG scheme.
 940 // * (obj ^ stw_random) is appealing, but can result
 941 //   in undesirable regularity in the hashCode values of adjacent objects
 942 //   (objects allocated back-to-back, in particular).  This could potentially
 943 //   result in hashtable collisions and reduced hashtable efficiency.
 944 //   There are simple ways to "diffuse" the middle address bits over the
 945 //   generated hashCode values:
 946 
 947 static intptr_t get_next_hash(Thread* current, oop obj) {
 948   intptr_t value = 0;
 949   if (hashCode == 0) {
 950     // This form uses global Park-Miller RNG.
 951     // On MP system we'll have lots of RW access to a global, so the
 952     // mechanism induces lots of coherency traffic.
 953     value = os::random();
 954   } else if (hashCode == 1) {
 955     // This variation has the property of being stable (idempotent)
 956     // between STW operations.  This can be useful in some of the 1-0
 957     // synchronization schemes.
 958     intptr_t addr_bits = cast_from_oop<intptr_t>(obj) >> 3;
 959     value = addr_bits ^ (addr_bits >> 5) ^ GVars.stw_random;
 960   } else if (hashCode == 2) {
 961     value = 1;            // for sensitivity testing
 962   } else if (hashCode == 3) {
 963     value = ++GVars.hc_sequence;
 964   } else if (hashCode == 4) {
 965     value = cast_from_oop<intptr_t>(obj);
 966   } else {
 967     // Marsaglia's xor-shift scheme with thread-specific state
 968     // This is probably the best overall implementation -- we'll
 969     // likely make this the default in future releases.
 970     unsigned t = current->_hashStateX;
 971     t ^= (t << 11);
 972     current->_hashStateX = current->_hashStateY;
 973     current->_hashStateY = current->_hashStateZ;
 974     current->_hashStateZ = current->_hashStateW;
 975     unsigned v = current->_hashStateW;
 976     v = (v ^ (v >> 19)) ^ (t ^ (t >> 8));
 977     current->_hashStateW = v;
 978     value = v;
 979   }
 980 
 981   value &= markWord::hash_mask;
 982   if (value == 0) value = 0xBAD;
 983   assert(value != markWord::no_hash, "invariant");
 984   return value;
 985 }
 986 
 987 static intptr_t install_hash_code(Thread* current, oop obj) {
 988   assert(UseObjectMonitorTable && LockingMode == LM_LIGHTWEIGHT, "must be");
 989 
 990   markWord mark = obj->mark_acquire();
 991   for (;;) {
 992     intptr_t hash = mark.hash();
 993     if (hash != 0) {
 994       return hash;
 995     }
 996 
 997     hash = get_next_hash(current, obj);
 998     const markWord old_mark = mark;
 999     const markWord new_mark = old_mark.copy_set_hash(hash);
1000 
1001     mark = obj->cas_set_mark(new_mark, old_mark);
1002     if (old_mark == mark) {
1003       return hash;
1004     }
1005   }
1006 }
1007 
1008 intptr_t ObjectSynchronizer::FastHashCode(Thread* current, oop obj) {
1009   if (UseObjectMonitorTable) {
1010     // Since the monitor isn't in the object header, the hash can simply be
1011     // installed in the object header.
1012     return install_hash_code(current, obj);
1013   }
1014 
1015   while (true) {
1016     ObjectMonitor* monitor = nullptr;
1017     markWord temp, test;
1018     intptr_t hash;
1019     markWord mark = read_stable_mark(obj);
1020     if (VerifyHeavyMonitors) {
1021       assert(LockingMode == LM_MONITOR, "+VerifyHeavyMonitors requires LockingMode == 0 (LM_MONITOR)");
1022       guarantee((obj->mark().value() & markWord::lock_mask_in_place) != markWord::locked_value, "must not be lightweight/stack-locked");
1023     }
1024     if (mark.is_unlocked() || (LockingMode == LM_LIGHTWEIGHT && mark.is_fast_locked())) {
1025       hash = mark.hash();
1026       if (hash != 0) {                     // if it has a hash, just return it
1027         return hash;
1028       }
1029       hash = get_next_hash(current, obj);  // get a new hash
1030       temp = mark.copy_set_hash(hash);     // merge the hash into header
1031                                            // try to install the hash
1032       test = obj->cas_set_mark(temp, mark);
1033       if (test == mark) {                  // if the hash was installed, return it
1034         return hash;
1035       }
1036       if (LockingMode == LM_LIGHTWEIGHT) {
1037         // CAS failed, retry
1038         continue;
1039       }
1040       // Failed to install the hash. It could be that another thread
1041       // installed the hash just before our attempt or inflation has
1042       // occurred or... so we fall thru to inflate the monitor for
1043       // stability and then install the hash.
1044     } else if (mark.has_monitor()) {
1045       monitor = mark.monitor();
1046       temp = monitor->header();
1047       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
1048       hash = temp.hash();
1049       if (hash != 0) {
1050         // It has a hash.
1051 
1052         // Separate load of dmw/header above from the loads in
1053         // is_being_async_deflated().
1054 
1055         // dmw/header and _contentions may get written by different threads.
1056         // Make sure to observe them in the same order when having several observers.
1057         OrderAccess::loadload_for_IRIW();
1058 
1059         if (monitor->is_being_async_deflated()) {
1060           // But we can't safely use the hash if we detect that async
1061           // deflation has occurred. So we attempt to restore the
1062           // header/dmw to the object's header so that we only retry
1063           // once if the deflater thread happens to be slow.
1064           monitor->install_displaced_markword_in_object(obj);
1065           continue;
1066         }
1067         return hash;
1068       }
1069       // Fall thru so we only have one place that installs the hash in
1070       // the ObjectMonitor.
1071     } else if (LockingMode == LM_LEGACY && mark.has_locker()
1072                && current->is_Java_thread()
1073                && JavaThread::cast(current)->is_lock_owned((address)mark.locker())) {
1074       // This is a stack-lock owned by the calling thread so fetch the
1075       // displaced markWord from the BasicLock on the stack.
1076       temp = mark.displaced_mark_helper();
1077       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
1078       hash = temp.hash();
1079       if (hash != 0) {                  // if it has a hash, just return it
1080         return hash;
1081       }
1082       // WARNING:
1083       // The displaced header in the BasicLock on a thread's stack
1084       // is strictly immutable. It CANNOT be changed in ANY cases.
1085       // So we have to inflate the stack-lock into an ObjectMonitor
1086       // even if the current thread owns the lock. The BasicLock on
1087       // a thread's stack can be asynchronously read by other threads
1088       // during an inflate() call so any change to that stack memory
1089       // may not propagate to other threads correctly.
1090     }
1091 
1092     // Inflate the monitor to set the hash.
1093 
1094     // There's no need to inflate if the mark has already got a monitor.
1095     // NOTE: an async deflation can race after we get the monitor and
1096     // before we can update the ObjectMonitor's header with the hash
1097     // value below.
1098     monitor = mark.has_monitor() ? mark.monitor() : inflate(current, obj, inflate_cause_hash_code);
1099     // Load ObjectMonitor's header/dmw field and see if it has a hash.
1100     mark = monitor->header();
1101     assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value());
1102     hash = mark.hash();
1103     if (hash == 0) {                       // if it does not have a hash
1104       hash = get_next_hash(current, obj);  // get a new hash
1105       temp = mark.copy_set_hash(hash)   ;  // merge the hash into header
1106       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
1107       uintptr_t v = Atomic::cmpxchg(monitor->metadata_addr(), mark.value(), temp.value());
1108       test = markWord(v);
1109       if (test != mark) {
1110         // The attempt to update the ObjectMonitor's header/dmw field
1111         // did not work. This can happen if another thread managed to
1112         // merge in the hash just before our cmpxchg().
1113         // If we add any new usages of the header/dmw field, this code
1114         // will need to be updated.
1115         hash = test.hash();
1116         assert(test.is_neutral(), "invariant: header=" INTPTR_FORMAT, test.value());
1117         assert(hash != 0, "should only have lost the race to a thread that set a non-zero hash");
1118       }
1119       if (monitor->is_being_async_deflated() && !UseObjectMonitorTable) {
1120         // If we detect that async deflation has occurred, then we
1121         // attempt to restore the header/dmw to the object's header
1122         // so that we only retry once if the deflater thread happens
1123         // to be slow.
1124         monitor->install_displaced_markword_in_object(obj);
1125         continue;
1126       }
1127     }
1128     // We finally get the hash.
1129     return hash;
1130   }
1131 }
1132 
1133 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* current,
1134                                                    Handle h_obj) {
1135   assert(current == JavaThread::current(), "Can only be called on current thread");
1136   oop obj = h_obj();
1137 
1138   markWord mark = read_stable_mark(obj);
1139 
1140   if (LockingMode == LM_LEGACY && mark.has_locker()) {
1141     // stack-locked case, header points into owner's stack
1142     return current->is_lock_owned((address)mark.locker());
1143   }
1144 
1145   if (LockingMode == LM_LIGHTWEIGHT && mark.is_fast_locked()) {
1146     // fast-locking case, see if lock is in current's lock stack
1147     return current->lock_stack().contains(h_obj());
1148   }
1149 
1150   while (LockingMode == LM_LIGHTWEIGHT && mark.has_monitor()) {
1151     ObjectMonitor* monitor = read_monitor(current, obj, mark);
1152     if (monitor != nullptr) {
1153       return monitor->is_entered(current) != 0;
1154     }
1155     // Racing with inflation/deflation, retry
1156     mark = obj->mark_acquire();
1157 
1158     if (mark.is_fast_locked()) {
1159       // Some other thread fast_locked, current could not have held the lock
1160       return false;
1161     }
1162   }
1163 
1164   if (LockingMode != LM_LIGHTWEIGHT && mark.has_monitor()) {
1165     // Inflated monitor so header points to ObjectMonitor (tagged pointer).
1166     // The first stage of async deflation does not affect any field
1167     // used by this comparison so the ObjectMonitor* is usable here.
1168     ObjectMonitor* monitor = read_monitor(mark);
1169     return monitor->is_entered(current) != 0;
1170   }
1171   // Unlocked case, header in place
1172   assert(mark.is_unlocked(), "sanity check");
1173   return false;
1174 }
1175 
1176 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) {
1177   oop obj = h_obj();
1178   markWord mark = read_stable_mark(obj);
1179 
1180   if (LockingMode == LM_LEGACY && mark.has_locker()) {
1181     // stack-locked so header points into owner's stack.
1182     // owning_thread_from_monitor_owner() may also return null here:
1183     return Threads::owning_thread_from_stacklock(t_list, (address) mark.locker());
1184   }
1185 
1186   if (LockingMode == LM_LIGHTWEIGHT && mark.is_fast_locked()) {
1187     // fast-locked so get owner from the object.
1188     // owning_thread_from_object() may also return null here:
1189     return Threads::owning_thread_from_object(t_list, h_obj());
1190   }
1191 
1192   while (LockingMode == LM_LIGHTWEIGHT && mark.has_monitor()) {
1193     ObjectMonitor* monitor = read_monitor(Thread::current(), obj, mark);
1194     if (monitor != nullptr) {
1195       return Threads::owning_thread_from_monitor(t_list, monitor);
1196     }
1197     // Racing with inflation/deflation, retry
1198     mark = obj->mark_acquire();
1199 
1200     if (mark.is_fast_locked()) {
1201       // Some other thread fast_locked
1202       return Threads::owning_thread_from_object(t_list, h_obj());
1203     }
1204   }
1205 
1206   if (LockingMode != LM_LIGHTWEIGHT && mark.has_monitor()) {
1207     // Inflated monitor so header points to ObjectMonitor (tagged pointer).
1208     // The first stage of async deflation does not affect any field
1209     // used by this comparison so the ObjectMonitor* is usable here.
1210     ObjectMonitor* monitor = read_monitor(mark);
1211     assert(monitor != nullptr, "monitor should be non-null");
1212     // owning_thread_from_monitor() may also return null here:
1213     return Threads::owning_thread_from_monitor(t_list, monitor);
1214   }
1215 
1216   // Unlocked case, header in place
1217   // Cannot have assertion since this object may have been
1218   // locked by another thread when reaching here.
1219   // assert(mark.is_unlocked(), "sanity check");
1220 
1221   return nullptr;
1222 }
1223 
1224 // Visitors ...
1225 
1226 // Iterate over all ObjectMonitors.
1227 template <typename Function>
1228 void ObjectSynchronizer::monitors_iterate(Function function) {
1229   MonitorList::Iterator iter = _in_use_list.iterator();
1230   while (iter.has_next()) {
1231     ObjectMonitor* monitor = iter.next();
1232     function(monitor);
1233   }
1234 }
1235 
1236 // Iterate ObjectMonitors owned by any thread and where the owner `filter`
1237 // returns true.
1238 template <typename OwnerFilter>
1239 void ObjectSynchronizer::owned_monitors_iterate_filtered(MonitorClosure* closure, OwnerFilter filter) {
1240   monitors_iterate([&](ObjectMonitor* monitor) {
1241     // This function is only called at a safepoint or when the
1242     // target thread is suspended or when the target thread is
1243     // operating on itself. The current closures in use today are
1244     // only interested in an owned ObjectMonitor and ownership
1245     // cannot be dropped under the calling contexts so the
1246     // ObjectMonitor cannot be async deflated.
1247     if (monitor->has_owner() && filter(monitor)) {
1248       assert(!monitor->is_being_async_deflated(), "Owned monitors should not be deflating");
1249 
1250       closure->do_monitor(monitor);
1251     }
1252   });
1253 }
1254 
1255 // Iterate ObjectMonitors where the owner == thread; this does NOT include
1256 // ObjectMonitors where owner is set to a stack-lock address in thread.
1257 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure, JavaThread* thread) {
1258   int64_t key = ObjectMonitor::owner_id_from(thread);
1259   auto thread_filter = [&](ObjectMonitor* monitor) { return monitor->owner() == key; };
1260   return owned_monitors_iterate_filtered(closure, thread_filter);
1261 }
1262 
1263 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure, oop vthread) {
1264   int64_t key = ObjectMonitor::owner_id_from(vthread);
1265   auto thread_filter = [&](ObjectMonitor* monitor) { return monitor->owner() == key; };
1266   return owned_monitors_iterate_filtered(closure, thread_filter);
1267 }
1268 
1269 // Iterate ObjectMonitors owned by any thread.
1270 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure) {
1271   auto all_filter = [&](ObjectMonitor* monitor) { return true; };
1272   return owned_monitors_iterate_filtered(closure, all_filter);
1273 }
1274 
1275 static bool monitors_used_above_threshold(MonitorList* list) {
1276   if (MonitorUsedDeflationThreshold == 0) {  // disabled case is easy
1277     return false;
1278   }
1279   size_t monitors_used = list->count();
1280   if (monitors_used == 0) {  // empty list is easy
1281     return false;
1282   }
1283   size_t old_ceiling = ObjectSynchronizer::in_use_list_ceiling();
1284   // Make sure that we use a ceiling value that is not lower than
1285   // previous, not lower than the recorded max used by the system, and
1286   // not lower than the current number of monitors in use (which can
1287   // race ahead of max). The result is guaranteed > 0.
1288   size_t ceiling = MAX3(old_ceiling, list->max(), monitors_used);
1289 
1290   // Check if our monitor usage is above the threshold:
1291   size_t monitor_usage = (monitors_used * 100LL) / ceiling;
1292   if (int(monitor_usage) > MonitorUsedDeflationThreshold) {
1293     // Deflate monitors if over the threshold percentage, unless no
1294     // progress on previous deflations.
1295     bool is_above_threshold = true;
1296 
1297     // Check if it's time to adjust the in_use_list_ceiling up, due
1298     // to too many async deflation attempts without any progress.
1299     if (NoAsyncDeflationProgressMax != 0 &&
1300         _no_progress_cnt >= NoAsyncDeflationProgressMax) {
1301       double remainder = (100.0 - MonitorUsedDeflationThreshold) / 100.0;
1302       size_t delta = (size_t)(ceiling * remainder) + 1;
1303       size_t new_ceiling = (ceiling > SIZE_MAX - delta)
1304         ? SIZE_MAX         // Overflow, let's clamp new_ceiling.
1305         : ceiling + delta;
1306 
1307       ObjectSynchronizer::set_in_use_list_ceiling(new_ceiling);
1308       log_info(monitorinflation)("Too many deflations without progress; "
1309                                  "bumping in_use_list_ceiling from %zu"
1310                                  " to %zu", old_ceiling, new_ceiling);
1311       _no_progress_cnt = 0;
1312       ceiling = new_ceiling;
1313 
1314       // Check if our monitor usage is still above the threshold:
1315       monitor_usage = (monitors_used * 100LL) / ceiling;
1316       is_above_threshold = int(monitor_usage) > MonitorUsedDeflationThreshold;
1317     }
1318     log_info(monitorinflation)("monitors_used=%zu, ceiling=%zu"
1319                                ", monitor_usage=%zu, threshold=%d",
1320                                monitors_used, ceiling, monitor_usage, MonitorUsedDeflationThreshold);
1321     return is_above_threshold;
1322   }
1323 
1324   return false;
1325 }
1326 
1327 size_t ObjectSynchronizer::in_use_list_count() {
1328   return _in_use_list.count();
1329 }
1330 
1331 size_t ObjectSynchronizer::in_use_list_max() {
1332   return _in_use_list.max();
1333 }
1334 
1335 size_t ObjectSynchronizer::in_use_list_ceiling() {
1336   return _in_use_list_ceiling;
1337 }
1338 
1339 void ObjectSynchronizer::dec_in_use_list_ceiling() {
1340   Atomic::sub(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate);
1341 }
1342 
1343 void ObjectSynchronizer::inc_in_use_list_ceiling() {
1344   Atomic::add(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate);
1345 }
1346 
1347 void ObjectSynchronizer::set_in_use_list_ceiling(size_t new_value) {
1348   _in_use_list_ceiling = new_value;
1349 }
1350 
1351 bool ObjectSynchronizer::is_async_deflation_needed() {
1352   if (is_async_deflation_requested()) {
1353     // Async deflation request.
1354     log_info(monitorinflation)("Async deflation needed: explicit request");
1355     return true;
1356   }
1357 
1358   jlong time_since_last = time_since_last_async_deflation_ms();
1359 
1360   if (AsyncDeflationInterval > 0 &&
1361       time_since_last > AsyncDeflationInterval &&
1362       monitors_used_above_threshold(&_in_use_list)) {
1363     // It's been longer than our specified deflate interval and there
1364     // are too many monitors in use. We don't deflate more frequently
1365     // than AsyncDeflationInterval (unless is_async_deflation_requested)
1366     // in order to not swamp the MonitorDeflationThread.
1367     log_info(monitorinflation)("Async deflation needed: monitors used are above the threshold");
1368     return true;
1369   }
1370 
1371   if (GuaranteedAsyncDeflationInterval > 0 &&
1372       time_since_last > GuaranteedAsyncDeflationInterval) {
1373     // It's been longer than our specified guaranteed deflate interval.
1374     // We need to clean up the used monitors even if the threshold is
1375     // not reached, to keep the memory utilization at bay when many threads
1376     // touched many monitors.
1377     log_info(monitorinflation)("Async deflation needed: guaranteed interval (%zd ms) "
1378                                "is greater than time since last deflation (" JLONG_FORMAT " ms)",
1379                                GuaranteedAsyncDeflationInterval, time_since_last);
1380 
1381     // If this deflation has no progress, then it should not affect the no-progress
1382     // tracking, otherwise threshold heuristics would think it was triggered, experienced
1383     // no progress, and needs to backoff more aggressively. In this "no progress" case,
1384     // the generic code would bump the no-progress counter, and we compensate for that
1385     // by telling it to skip the update.
1386     //
1387     // If this deflation has progress, then it should let non-progress tracking
1388     // know about this, otherwise the threshold heuristics would kick in, potentially
1389     // experience no-progress due to aggressive cleanup by this deflation, and think
1390     // it is still in no-progress stride. In this "progress" case, the generic code would
1391     // zero the counter, and we allow it to happen.
1392     _no_progress_skip_increment = true;
1393 
1394     return true;
1395   }
1396 
1397   return false;
1398 }
1399 
1400 void ObjectSynchronizer::request_deflate_idle_monitors() {
1401   MonitorLocker ml(MonitorDeflation_lock, Mutex::_no_safepoint_check_flag);
1402   set_is_async_deflation_requested(true);
1403   ml.notify_all();
1404 }
1405 
1406 bool ObjectSynchronizer::request_deflate_idle_monitors_from_wb() {
1407   JavaThread* current = JavaThread::current();
1408   bool ret_code = false;
1409 
1410   jlong last_time = last_async_deflation_time_ns();
1411 
1412   request_deflate_idle_monitors();
1413 
1414   const int N_CHECKS = 5;
1415   for (int i = 0; i < N_CHECKS; i++) {  // sleep for at most 5 seconds
1416     if (last_async_deflation_time_ns() > last_time) {
1417       log_info(monitorinflation)("Async Deflation happened after %d check(s).", i);
1418       ret_code = true;
1419       break;
1420     }
1421     {
1422       // JavaThread has to honor the blocking protocol.
1423       ThreadBlockInVM tbivm(current);
1424       os::naked_short_sleep(999);  // sleep for almost 1 second
1425     }
1426   }
1427   if (!ret_code) {
1428     log_info(monitorinflation)("Async Deflation DID NOT happen after %d checks.", N_CHECKS);
1429   }
1430 
1431   return ret_code;
1432 }
1433 
1434 jlong ObjectSynchronizer::time_since_last_async_deflation_ms() {
1435   return (os::javaTimeNanos() - last_async_deflation_time_ns()) / (NANOUNITS / MILLIUNITS);
1436 }
1437 
1438 static void post_monitor_inflate_event(EventJavaMonitorInflate* event,
1439                                        const oop obj,
1440                                        ObjectSynchronizer::InflateCause cause) {
1441   assert(event != nullptr, "invariant");
1442   const Klass* monitor_klass = obj->klass();
1443   if (ObjectMonitor::is_jfr_excluded(monitor_klass)) {
1444     return;
1445   }
1446   event->set_monitorClass(monitor_klass);
1447   event->set_address((uintptr_t)(void*)obj);
1448   event->set_cause((u1)cause);
1449   event->commit();
1450 }
1451 
1452 // Fast path code shared by multiple functions
1453 void ObjectSynchronizer::inflate_helper(oop obj) {
1454   assert(LockingMode != LM_LIGHTWEIGHT, "only inflate through enter");
1455   markWord mark = obj->mark_acquire();
1456   if (mark.has_monitor()) {
1457     ObjectMonitor* monitor = read_monitor(mark);
1458     markWord dmw = monitor->header();
1459     assert(dmw.is_neutral(), "sanity check: header=" INTPTR_FORMAT, dmw.value());
1460     return;
1461   }
1462   (void)inflate(Thread::current(), obj, inflate_cause_vm_internal);
1463 }
1464 
1465 ObjectMonitor* ObjectSynchronizer::inflate(Thread* current, oop obj, const InflateCause cause) {
1466   assert(current == Thread::current(), "must be");
1467   assert(LockingMode != LM_LIGHTWEIGHT, "only inflate through enter");
1468   return inflate_impl(current->is_Java_thread() ? JavaThread::cast(current) : nullptr, obj, cause);
1469 }
1470 
1471 ObjectMonitor* ObjectSynchronizer::inflate_for(JavaThread* thread, oop obj, const InflateCause cause) {
1472   assert(thread == Thread::current() || thread->is_obj_deopt_suspend(), "must be");
1473   assert(LockingMode != LM_LIGHTWEIGHT, "LM_LIGHTWEIGHT cannot use inflate_for");
1474   return inflate_impl(thread, obj, cause);
1475 }
1476 
1477 ObjectMonitor* ObjectSynchronizer::inflate_impl(JavaThread* locking_thread, oop object, const InflateCause cause) {
1478   // The JavaThread* locking_thread requires that the locking_thread == Thread::current() or
1479   // is suspended throughout the call by some other mechanism.
1480   // The thread might be nullptr when called from a non JavaThread. (As may still be
1481   // the case from FastHashCode). However it is only important for correctness that the
1482   // thread is set when called from ObjectSynchronizer::enter from the owning thread,
1483   // ObjectSynchronizer::enter_for from any thread, or ObjectSynchronizer::exit.
1484   assert(LockingMode != LM_LIGHTWEIGHT, "LM_LIGHTWEIGHT cannot use inflate_impl");
1485   EventJavaMonitorInflate event;
1486 
1487   for (;;) {
1488     const markWord mark = object->mark_acquire();
1489 
1490     // The mark can be in one of the following states:
1491     // *  inflated     - If the ObjectMonitor owner is anonymous and the
1492     //                   locking_thread owns the object lock, then we
1493     //                   make the locking_thread the ObjectMonitor owner.
1494     // *  stack-locked - Coerce it to inflated from stack-locked.
1495     // *  INFLATING    - Busy wait for conversion from stack-locked to
1496     //                   inflated.
1497     // *  unlocked     - Aggressively inflate the object.
1498 
1499     // CASE: inflated
1500     if (mark.has_monitor()) {
1501       ObjectMonitor* inf = mark.monitor();
1502       markWord dmw = inf->header();
1503       assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value());
1504       if (inf->has_anonymous_owner() && locking_thread != nullptr) {
1505         assert(LockingMode == LM_LEGACY, "invariant");
1506         if (locking_thread->is_lock_owned((address)inf->stack_locker())) {
1507           inf->set_stack_locker(nullptr);
1508           inf->set_owner_from_anonymous(locking_thread);
1509         }
1510       }
1511       return inf;
1512     }
1513 
1514     // CASE: inflation in progress - inflating over a stack-lock.
1515     // Some other thread is converting from stack-locked to inflated.
1516     // Only that thread can complete inflation -- other threads must wait.
1517     // The INFLATING value is transient.
1518     // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
1519     // We could always eliminate polling by parking the thread on some auxiliary list.
1520     if (mark == markWord::INFLATING()) {
1521       read_stable_mark(object);
1522       continue;
1523     }
1524 
1525     // CASE: stack-locked
1526     // Could be stack-locked either by current or by some other thread.
1527     //
1528     // Note that we allocate the ObjectMonitor speculatively, _before_ attempting
1529     // to install INFLATING into the mark word.  We originally installed INFLATING,
1530     // allocated the ObjectMonitor, and then finally STed the address of the
1531     // ObjectMonitor into the mark.  This was correct, but artificially lengthened
1532     // the interval in which INFLATING appeared in the mark, thus increasing
1533     // the odds of inflation contention. If we lose the race to set INFLATING,
1534     // then we just delete the ObjectMonitor and loop around again.
1535     //
1536     LogStreamHandle(Trace, monitorinflation) lsh;
1537     if (LockingMode == LM_LEGACY && mark.has_locker()) {
1538       ObjectMonitor* m = new ObjectMonitor(object);
1539       // Optimistically prepare the ObjectMonitor - anticipate successful CAS
1540       // We do this before the CAS in order to minimize the length of time
1541       // in which INFLATING appears in the mark.
1542 
1543       markWord cmp = object->cas_set_mark(markWord::INFLATING(), mark);
1544       if (cmp != mark) {
1545         delete m;
1546         continue;       // Interference -- just retry
1547       }
1548 
1549       // We've successfully installed INFLATING (0) into the mark-word.
1550       // This is the only case where 0 will appear in a mark-word.
1551       // Only the singular thread that successfully swings the mark-word
1552       // to 0 can perform (or more precisely, complete) inflation.
1553       //
1554       // Why do we CAS a 0 into the mark-word instead of just CASing the
1555       // mark-word from the stack-locked value directly to the new inflated state?
1556       // Consider what happens when a thread unlocks a stack-locked object.
1557       // It attempts to use CAS to swing the displaced header value from the
1558       // on-stack BasicLock back into the object header.  Recall also that the
1559       // header value (hash code, etc) can reside in (a) the object header, or
1560       // (b) a displaced header associated with the stack-lock, or (c) a displaced
1561       // header in an ObjectMonitor.  The inflate() routine must copy the header
1562       // value from the BasicLock on the owner's stack to the ObjectMonitor, all
1563       // the while preserving the hashCode stability invariants.  If the owner
1564       // decides to release the lock while the value is 0, the unlock will fail
1565       // and control will eventually pass from slow_exit() to inflate.  The owner
1566       // will then spin, waiting for the 0 value to disappear.   Put another way,
1567       // the 0 causes the owner to stall if the owner happens to try to
1568       // drop the lock (restoring the header from the BasicLock to the object)
1569       // while inflation is in-progress.  This protocol avoids races that might
1570       // would otherwise permit hashCode values to change or "flicker" for an object.
1571       // Critically, while object->mark is 0 mark.displaced_mark_helper() is stable.
1572       // 0 serves as a "BUSY" inflate-in-progress indicator.
1573 
1574 
1575       // fetch the displaced mark from the owner's stack.
1576       // The owner can't die or unwind past the lock while our INFLATING
1577       // object is in the mark.  Furthermore the owner can't complete
1578       // an unlock on the object, either.
1579       markWord dmw = mark.displaced_mark_helper();
1580       // Catch if the object's header is not neutral (not locked and
1581       // not marked is what we care about here).
1582       assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value());
1583 
1584       // Setup monitor fields to proper values -- prepare the monitor
1585       m->set_header(dmw);
1586 
1587       // Note that a thread can inflate an object
1588       // that it has stack-locked -- as might happen in wait() -- directly
1589       // with CAS.  That is, we can avoid the xchg-nullptr .... ST idiom.
1590       if (locking_thread != nullptr && locking_thread->is_lock_owned((address)mark.locker())) {
1591         m->set_owner(locking_thread);
1592       } else {
1593         // Use ANONYMOUS_OWNER to indicate that the owner is the BasicLock on the stack,
1594         // and set the stack locker field in the monitor.
1595         m->set_stack_locker(mark.locker());
1596         m->set_anonymous_owner();
1597       }
1598       // TODO-FIXME: assert BasicLock->dhw != 0.
1599 
1600       // Must preserve store ordering. The monitor state must
1601       // be stable at the time of publishing the monitor address.
1602       guarantee(object->mark() == markWord::INFLATING(), "invariant");
1603       // Release semantics so that above set_object() is seen first.
1604       object->release_set_mark(markWord::encode(m));
1605 
1606       // Once ObjectMonitor is configured and the object is associated
1607       // with the ObjectMonitor, it is safe to allow async deflation:
1608       _in_use_list.add(m);
1609 
1610       if (log_is_enabled(Trace, monitorinflation)) {
1611         ResourceMark rm;
1612         lsh.print_cr("inflate(has_locker): object=" INTPTR_FORMAT ", mark="
1613                      INTPTR_FORMAT ", type='%s'", p2i(object),
1614                      object->mark().value(), object->klass()->external_name());
1615       }
1616       if (event.should_commit()) {
1617         post_monitor_inflate_event(&event, object, cause);
1618       }
1619       return m;
1620     }
1621 
1622     // CASE: unlocked
1623     // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
1624     // If we know we're inflating for entry it's better to inflate by swinging a
1625     // pre-locked ObjectMonitor pointer into the object header.   A successful
1626     // CAS inflates the object *and* confers ownership to the inflating thread.
1627     // In the current implementation we use a 2-step mechanism where we CAS()
1628     // to inflate and then CAS() again to try to swing _owner from null to current.
1629     // An inflateTry() method that we could call from enter() would be useful.
1630 
1631     assert(mark.is_unlocked(), "invariant: header=" INTPTR_FORMAT, mark.value());
1632     ObjectMonitor* m = new ObjectMonitor(object);
1633     // prepare m for installation - set monitor to initial state
1634     m->set_header(mark);
1635 
1636     if (object->cas_set_mark(markWord::encode(m), mark) != mark) {
1637       delete m;
1638       m = nullptr;
1639       continue;
1640       // interference - the markword changed - just retry.
1641       // The state-transitions are one-way, so there's no chance of
1642       // live-lock -- "Inflated" is an absorbing state.
1643     }
1644 
1645     // Once the ObjectMonitor is configured and object is associated
1646     // with the ObjectMonitor, it is safe to allow async deflation:
1647     _in_use_list.add(m);
1648 
1649     if (log_is_enabled(Trace, monitorinflation)) {
1650       ResourceMark rm;
1651       lsh.print_cr("inflate(unlocked): object=" INTPTR_FORMAT ", mark="
1652                    INTPTR_FORMAT ", type='%s'", p2i(object),
1653                    object->mark().value(), object->klass()->external_name());
1654     }
1655     if (event.should_commit()) {
1656       post_monitor_inflate_event(&event, object, cause);
1657     }
1658     return m;
1659   }
1660 }
1661 
1662 // Walk the in-use list and deflate (at most MonitorDeflationMax) idle
1663 // ObjectMonitors. Returns the number of deflated ObjectMonitors.
1664 //
1665 size_t ObjectSynchronizer::deflate_monitor_list(ObjectMonitorDeflationSafepointer* safepointer) {
1666   MonitorList::Iterator iter = _in_use_list.iterator();
1667   size_t deflated_count = 0;
1668   Thread* current = Thread::current();
1669 
1670   while (iter.has_next()) {
1671     if (deflated_count >= (size_t)MonitorDeflationMax) {
1672       break;
1673     }
1674     ObjectMonitor* mid = iter.next();
1675     if (mid->deflate_monitor(current)) {
1676       deflated_count++;
1677     }
1678 
1679     // Must check for a safepoint/handshake and honor it.
1680     safepointer->block_for_safepoint("deflation", "deflated_count", deflated_count);
1681   }
1682 
1683   return deflated_count;
1684 }
1685 
1686 class HandshakeForDeflation : public HandshakeClosure {
1687  public:
1688   HandshakeForDeflation() : HandshakeClosure("HandshakeForDeflation") {}
1689 
1690   void do_thread(Thread* thread) {
1691     log_trace(monitorinflation)("HandshakeForDeflation::do_thread: thread="
1692                                 INTPTR_FORMAT, p2i(thread));
1693     if (thread->is_Java_thread()) {
1694       // Clear OM cache
1695       JavaThread* jt = JavaThread::cast(thread);
1696       jt->om_clear_monitor_cache();
1697     }
1698   }
1699 };
1700 
1701 class VM_RendezvousGCThreads : public VM_Operation {
1702 public:
1703   bool evaluate_at_safepoint() const override { return false; }
1704   VMOp_Type type() const override { return VMOp_RendezvousGCThreads; }
1705   void doit() override {
1706     Universe::heap()->safepoint_synchronize_begin();
1707     Universe::heap()->safepoint_synchronize_end();
1708   };
1709 };
1710 
1711 static size_t delete_monitors(GrowableArray<ObjectMonitor*>* delete_list,
1712                               ObjectMonitorDeflationSafepointer* safepointer) {
1713   NativeHeapTrimmer::SuspendMark sm("monitor deletion");
1714   size_t deleted_count = 0;
1715   for (ObjectMonitor* monitor: *delete_list) {
1716     delete monitor;
1717     deleted_count++;
1718     // A JavaThread must check for a safepoint/handshake and honor it.
1719     safepointer->block_for_safepoint("deletion", "deleted_count", deleted_count);
1720   }
1721   return deleted_count;
1722 }
1723 
1724 class ObjectMonitorDeflationLogging: public StackObj {
1725   LogStreamHandle(Debug, monitorinflation) _debug;
1726   LogStreamHandle(Info, monitorinflation)  _info;
1727   LogStream*                               _stream;
1728   elapsedTimer                             _timer;
1729 
1730   size_t ceiling() const { return ObjectSynchronizer::in_use_list_ceiling(); }
1731   size_t count() const   { return ObjectSynchronizer::in_use_list_count(); }
1732   size_t max() const     { return ObjectSynchronizer::in_use_list_max(); }
1733 
1734 public:
1735   ObjectMonitorDeflationLogging()
1736     : _debug(), _info(), _stream(nullptr) {
1737     if (_debug.is_enabled()) {
1738       _stream = &_debug;
1739     } else if (_info.is_enabled()) {
1740       _stream = &_info;
1741     }
1742   }
1743 
1744   void begin() {
1745     if (_stream != nullptr) {
1746       _stream->print_cr("begin deflating: in_use_list stats: ceiling=%zu, count=%zu, max=%zu",
1747                         ceiling(), count(), max());
1748       _timer.start();
1749     }
1750   }
1751 
1752   void before_handshake(size_t unlinked_count) {
1753     if (_stream != nullptr) {
1754       _timer.stop();
1755       _stream->print_cr("before handshaking: unlinked_count=%zu"
1756                         ", in_use_list stats: ceiling=%zu, count="
1757                         "%zu, max=%zu",
1758                         unlinked_count, ceiling(), count(), max());
1759     }
1760   }
1761 
1762   void after_handshake() {
1763     if (_stream != nullptr) {
1764       _stream->print_cr("after handshaking: in_use_list stats: ceiling="
1765                         "%zu, count=%zu, max=%zu",
1766                         ceiling(), count(), max());
1767       _timer.start();
1768     }
1769   }
1770 
1771   void end(size_t deflated_count, size_t unlinked_count) {
1772     if (_stream != nullptr) {
1773       _timer.stop();
1774       if (deflated_count != 0 || unlinked_count != 0 || _debug.is_enabled()) {
1775         _stream->print_cr("deflated_count=%zu, {unlinked,deleted}_count=%zu monitors in %3.7f secs",
1776                           deflated_count, unlinked_count, _timer.seconds());
1777       }
1778       _stream->print_cr("end deflating: in_use_list stats: ceiling=%zu, count=%zu, max=%zu",
1779                         ceiling(), count(), max());
1780     }
1781   }
1782 
1783   void before_block_for_safepoint(const char* op_name, const char* cnt_name, size_t cnt) {
1784     if (_stream != nullptr) {
1785       _timer.stop();
1786       _stream->print_cr("pausing %s: %s=%zu, in_use_list stats: ceiling="
1787                         "%zu, count=%zu, max=%zu",
1788                         op_name, cnt_name, cnt, ceiling(), count(), max());
1789     }
1790   }
1791 
1792   void after_block_for_safepoint(const char* op_name) {
1793     if (_stream != nullptr) {
1794       _stream->print_cr("resuming %s: in_use_list stats: ceiling=%zu"
1795                         ", count=%zu, max=%zu", op_name,
1796                         ceiling(), count(), max());
1797       _timer.start();
1798     }
1799   }
1800 };
1801 
1802 void ObjectMonitorDeflationSafepointer::block_for_safepoint(const char* op_name, const char* count_name, size_t counter) {
1803   if (!SafepointMechanism::should_process(_current)) {
1804     return;
1805   }
1806 
1807   // A safepoint/handshake has started.
1808   _log->before_block_for_safepoint(op_name, count_name, counter);
1809 
1810   {
1811     // Honor block request.
1812     ThreadBlockInVM tbivm(_current);
1813   }
1814 
1815   _log->after_block_for_safepoint(op_name);
1816 }
1817 
1818 // This function is called by the MonitorDeflationThread to deflate
1819 // ObjectMonitors.
1820 size_t ObjectSynchronizer::deflate_idle_monitors() {
1821   JavaThread* current = JavaThread::current();
1822   assert(current->is_monitor_deflation_thread(), "The only monitor deflater");
1823 
1824   // The async deflation request has been processed.
1825   _last_async_deflation_time_ns = os::javaTimeNanos();
1826   set_is_async_deflation_requested(false);
1827 
1828   ObjectMonitorDeflationLogging log;
1829   ObjectMonitorDeflationSafepointer safepointer(current, &log);
1830 
1831   log.begin();
1832 
1833   // Deflate some idle ObjectMonitors.
1834   size_t deflated_count = deflate_monitor_list(&safepointer);
1835 
1836   // Unlink the deflated ObjectMonitors from the in-use list.
1837   size_t unlinked_count = 0;
1838   size_t deleted_count = 0;
1839   if (deflated_count > 0) {
1840     ResourceMark rm(current);
1841     GrowableArray<ObjectMonitor*> delete_list((int)deflated_count);
1842     unlinked_count = _in_use_list.unlink_deflated(deflated_count, &delete_list, &safepointer);
1843 
1844 #ifdef ASSERT
1845     if (UseObjectMonitorTable) {
1846       for (ObjectMonitor* monitor : delete_list) {
1847         assert(!LightweightSynchronizer::contains_monitor(current, monitor), "Should have been removed");
1848       }
1849     }
1850 #endif
1851 
1852     log.before_handshake(unlinked_count);
1853 
1854     // A JavaThread needs to handshake in order to safely free the
1855     // ObjectMonitors that were deflated in this cycle.
1856     HandshakeForDeflation hfd_hc;
1857     Handshake::execute(&hfd_hc);
1858     // Also, we sync and desync GC threads around the handshake, so that they can
1859     // safely read the mark-word and look-through to the object-monitor, without
1860     // being afraid that the object-monitor is going away.
1861     VM_RendezvousGCThreads sync_gc;
1862     VMThread::execute(&sync_gc);
1863 
1864     log.after_handshake();
1865 
1866     // After the handshake, safely free the ObjectMonitors that were
1867     // deflated and unlinked in this cycle.
1868 
1869     // Delete the unlinked ObjectMonitors.
1870     deleted_count = delete_monitors(&delete_list, &safepointer);
1871     assert(unlinked_count == deleted_count, "must be");
1872   }
1873 
1874   log.end(deflated_count, unlinked_count);
1875 
1876   GVars.stw_random = os::random();
1877 
1878   if (deflated_count != 0) {
1879     _no_progress_cnt = 0;
1880   } else if (_no_progress_skip_increment) {
1881     _no_progress_skip_increment = false;
1882   } else {
1883     _no_progress_cnt++;
1884   }
1885 
1886   return deflated_count;
1887 }
1888 
1889 // Monitor cleanup on JavaThread::exit
1890 
1891 // Iterate through monitor cache and attempt to release thread's monitors
1892 class ReleaseJavaMonitorsClosure: public MonitorClosure {
1893  private:
1894   JavaThread* _thread;
1895 
1896  public:
1897   ReleaseJavaMonitorsClosure(JavaThread* thread) : _thread(thread) {}
1898   void do_monitor(ObjectMonitor* mid) {
1899     intx rec = mid->complete_exit(_thread);
1900     _thread->dec_held_monitor_count(rec + 1);
1901   }
1902 };
1903 
1904 // Release all inflated monitors owned by current thread.  Lightweight monitors are
1905 // ignored.  This is meant to be called during JNI thread detach which assumes
1906 // all remaining monitors are heavyweight.  All exceptions are swallowed.
1907 // Scanning the extant monitor list can be time consuming.
1908 // A simple optimization is to add a per-thread flag that indicates a thread
1909 // called jni_monitorenter() during its lifetime.
1910 //
1911 // Instead of NoSafepointVerifier it might be cheaper to
1912 // use an idiom of the form:
1913 //   auto int tmp = SafepointSynchronize::_safepoint_counter ;
1914 //   <code that must not run at safepoint>
1915 //   guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ;
1916 // Since the tests are extremely cheap we could leave them enabled
1917 // for normal product builds.
1918 
1919 void ObjectSynchronizer::release_monitors_owned_by_thread(JavaThread* current) {
1920   assert(current == JavaThread::current(), "must be current Java thread");
1921   NoSafepointVerifier nsv;
1922   ReleaseJavaMonitorsClosure rjmc(current);
1923   ObjectSynchronizer::owned_monitors_iterate(&rjmc, current);
1924   assert(!current->has_pending_exception(), "Should not be possible");
1925   current->clear_pending_exception();
1926   assert(current->held_monitor_count() == 0, "Should not be possible");
1927   // All monitors (including entered via JNI) have been unlocked above, so we need to clear jni count.
1928   current->clear_jni_monitor_count();
1929 }
1930 
1931 const char* ObjectSynchronizer::inflate_cause_name(const InflateCause cause) {
1932   switch (cause) {
1933     case inflate_cause_vm_internal:    return "VM Internal";
1934     case inflate_cause_monitor_enter:  return "Monitor Enter";
1935     case inflate_cause_wait:           return "Monitor Wait";
1936     case inflate_cause_notify:         return "Monitor Notify";
1937     case inflate_cause_hash_code:      return "Monitor Hash Code";
1938     case inflate_cause_jni_enter:      return "JNI Monitor Enter";
1939     case inflate_cause_jni_exit:       return "JNI Monitor Exit";
1940     default:
1941       ShouldNotReachHere();
1942   }
1943   return "Unknown";
1944 }
1945 
1946 //------------------------------------------------------------------------------
1947 // Debugging code
1948 
1949 u_char* ObjectSynchronizer::get_gvars_addr() {
1950   return (u_char*)&GVars;
1951 }
1952 
1953 u_char* ObjectSynchronizer::get_gvars_hc_sequence_addr() {
1954   return (u_char*)&GVars.hc_sequence;
1955 }
1956 
1957 size_t ObjectSynchronizer::get_gvars_size() {
1958   return sizeof(SharedGlobals);
1959 }
1960 
1961 u_char* ObjectSynchronizer::get_gvars_stw_random_addr() {
1962   return (u_char*)&GVars.stw_random;
1963 }
1964 
1965 // Do the final audit and print of ObjectMonitor stats; must be done
1966 // by the VMThread at VM exit time.
1967 void ObjectSynchronizer::do_final_audit_and_print_stats() {
1968   assert(Thread::current()->is_VM_thread(), "sanity check");
1969 
1970   if (is_final_audit()) {  // Only do the audit once.
1971     return;
1972   }
1973   set_is_final_audit();
1974   log_info(monitorinflation)("Starting the final audit.");
1975 
1976   if (log_is_enabled(Info, monitorinflation)) {
1977     LogStreamHandle(Info, monitorinflation) ls;
1978     audit_and_print_stats(&ls, true /* on_exit */);
1979   }
1980 }
1981 
1982 // This function can be called by the MonitorDeflationThread or it can be called when
1983 // we are trying to exit the VM. The list walker functions can run in parallel with
1984 // the other list operations.
1985 // Calls to this function can be added in various places as a debugging
1986 // aid.
1987 //
1988 void ObjectSynchronizer::audit_and_print_stats(outputStream* ls, bool on_exit) {
1989   int error_cnt = 0;
1990 
1991   ls->print_cr("Checking in_use_list:");
1992   chk_in_use_list(ls, &error_cnt);
1993 
1994   if (error_cnt == 0) {
1995     ls->print_cr("No errors found in in_use_list checks.");
1996   } else {
1997     log_error(monitorinflation)("found in_use_list errors: error_cnt=%d", error_cnt);
1998   }
1999 
2000   // When exiting, only log the interesting entries at the Info level.
2001   // When called at intervals by the MonitorDeflationThread, log output
2002   // at the Trace level since there can be a lot of it.
2003   if (!on_exit && log_is_enabled(Trace, monitorinflation)) {
2004     LogStreamHandle(Trace, monitorinflation) ls_tr;
2005     log_in_use_monitor_details(&ls_tr, true /* log_all */);
2006   } else if (on_exit) {
2007     log_in_use_monitor_details(ls, false /* log_all */);
2008   }
2009 
2010   ls->flush();
2011 
2012   guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt);
2013 }
2014 
2015 // Check the in_use_list; log the results of the checks.
2016 void ObjectSynchronizer::chk_in_use_list(outputStream* out, int *error_cnt_p) {
2017   size_t l_in_use_count = _in_use_list.count();
2018   size_t l_in_use_max = _in_use_list.max();
2019   out->print_cr("count=%zu, max=%zu", l_in_use_count,
2020                 l_in_use_max);
2021 
2022   size_t ck_in_use_count = 0;
2023   MonitorList::Iterator iter = _in_use_list.iterator();
2024   while (iter.has_next()) {
2025     ObjectMonitor* mid = iter.next();
2026     chk_in_use_entry(mid, out, error_cnt_p);
2027     ck_in_use_count++;
2028   }
2029 
2030   if (l_in_use_count == ck_in_use_count) {
2031     out->print_cr("in_use_count=%zu equals ck_in_use_count=%zu",
2032                   l_in_use_count, ck_in_use_count);
2033   } else {
2034     out->print_cr("WARNING: in_use_count=%zu is not equal to "
2035                   "ck_in_use_count=%zu", l_in_use_count,
2036                   ck_in_use_count);
2037   }
2038 
2039   size_t ck_in_use_max = _in_use_list.max();
2040   if (l_in_use_max == ck_in_use_max) {
2041     out->print_cr("in_use_max=%zu equals ck_in_use_max=%zu",
2042                   l_in_use_max, ck_in_use_max);
2043   } else {
2044     out->print_cr("WARNING: in_use_max=%zu is not equal to "
2045                   "ck_in_use_max=%zu", l_in_use_max, ck_in_use_max);
2046   }
2047 }
2048 
2049 // Check an in-use monitor entry; log any errors.
2050 void ObjectSynchronizer::chk_in_use_entry(ObjectMonitor* n, outputStream* out,
2051                                           int* error_cnt_p) {
2052   if (n->owner_is_DEFLATER_MARKER()) {
2053     // This could happen when monitor deflation blocks for a safepoint.
2054     return;
2055   }
2056 
2057 
2058   if (n->metadata() == 0) {
2059     out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor must "
2060                   "have non-null _metadata (header/hash) field.", p2i(n));
2061     *error_cnt_p = *error_cnt_p + 1;
2062   }
2063 
2064   const oop obj = n->object_peek();
2065   if (obj == nullptr) {
2066     return;
2067   }
2068 
2069   const markWord mark = obj->mark();
2070   if (!mark.has_monitor()) {
2071     out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's "
2072                   "object does not think it has a monitor: obj="
2073                   INTPTR_FORMAT ", mark=" INTPTR_FORMAT, p2i(n),
2074                   p2i(obj), mark.value());
2075     *error_cnt_p = *error_cnt_p + 1;
2076     return;
2077   }
2078 
2079   ObjectMonitor* const obj_mon = read_monitor(Thread::current(), obj, mark);
2080   if (n != obj_mon) {
2081     out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's "
2082                   "object does not refer to the same monitor: obj="
2083                   INTPTR_FORMAT ", mark=" INTPTR_FORMAT ", obj_mon="
2084                   INTPTR_FORMAT, p2i(n), p2i(obj), mark.value(), p2i(obj_mon));
2085     *error_cnt_p = *error_cnt_p + 1;
2086   }
2087 }
2088 
2089 // Log details about ObjectMonitors on the in_use_list. The 'BHL'
2090 // flags indicate why the entry is in-use, 'object' and 'object type'
2091 // indicate the associated object and its type.
2092 void ObjectSynchronizer::log_in_use_monitor_details(outputStream* out, bool log_all) {
2093   if (_in_use_list.count() > 0) {
2094     stringStream ss;
2095     out->print_cr("In-use monitor info%s:", log_all ? "" : " (eliding idle monitors)");
2096     out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
2097     out->print_cr("%18s  %s  %18s  %18s",
2098                   "monitor", "BHL", "object", "object type");
2099     out->print_cr("==================  ===  ==================  ==================");
2100 
2101     auto is_interesting = [&](ObjectMonitor* monitor) {
2102       return log_all || monitor->has_owner() || monitor->is_busy();
2103     };
2104 
2105     monitors_iterate([&](ObjectMonitor* monitor) {
2106       if (is_interesting(monitor)) {
2107         const oop obj = monitor->object_peek();
2108         const intptr_t hash = UseObjectMonitorTable ? monitor->hash() : monitor->header().hash();
2109         ResourceMark rm;
2110         out->print(INTPTR_FORMAT "  %d%d%d  " INTPTR_FORMAT "  %s", p2i(monitor),
2111                    monitor->is_busy(), hash != 0, monitor->has_owner(),
2112                    p2i(obj), obj == nullptr ? "" : obj->klass()->external_name());
2113         if (monitor->is_busy()) {
2114           out->print(" (%s)", monitor->is_busy_to_string(&ss));
2115           ss.reset();
2116         }
2117         out->cr();
2118       }
2119     });
2120   }
2121 
2122   out->flush();
2123 }