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