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