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