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