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