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