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