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/basicLock.inline.hpp"
  39 #include "runtime/frame.inline.hpp"
  40 #include "runtime/globals.hpp"
  41 #include "runtime/handles.inline.hpp"
  42 #include "runtime/handshake.hpp"
  43 #include "runtime/interfaceSupport.inline.hpp"
  44 #include "runtime/javaThread.hpp"
  45 #include "runtime/lightweightSynchronizer.hpp"
  46 #include "runtime/lockStack.inline.hpp"
  47 #include "runtime/mutexLocker.hpp"
  48 #include "runtime/objectMonitor.hpp"
  49 #include "runtime/objectMonitor.inline.hpp"
  50 #include "runtime/os.inline.hpp"
  51 #include "runtime/osThread.hpp"
  52 #include "runtime/perfData.hpp"
  53 #include "runtime/safepointMechanism.inline.hpp"
  54 #include "runtime/safepointVerifiers.hpp"
  55 #include "runtime/sharedRuntime.hpp"
  56 #include "runtime/stubRoutines.hpp"
  57 #include "runtime/synchronizer.inline.hpp"
  58 #include "runtime/threads.hpp"
  59 #include "runtime/timer.hpp"
  60 #include "runtime/trimNativeHeap.hpp"
  61 #include "runtime/vframe.hpp"
  62 #include "runtime/vmThread.hpp"
  63 #include "utilities/align.hpp"
  64 #include "utilities/dtrace.hpp"
  65 #include "utilities/events.hpp"
  66 #include "utilities/globalDefinitions.hpp"
  67 #include "utilities/linkedlist.hpp"
  68 #include "utilities/preserveException.hpp"
  69 
  70 class ObjectMonitorDeflationLogging;
  71 
  72 void MonitorList::add(ObjectMonitor* m) {
  73   ObjectMonitor* head;
  74   do {
  75     head = Atomic::load(&_head);
  76     m->set_next_om(head);
  77   } while (Atomic::cmpxchg(&_head, head, m) != head);
  78 
  79   size_t count = Atomic::add(&_count, 1u);
  80   if (count > max()) {
  81     Atomic::inc(&_max);
  82   }
  83 }
  84 
  85 size_t MonitorList::count() const {
  86   return Atomic::load(&_count);
  87 }
  88 
  89 size_t MonitorList::max() const {
  90   return Atomic::load(&_max);
  91 }
  92 
  93 class ObjectMonitorDeflationSafepointer : public StackObj {
  94   JavaThread* const                    _current;
  95   ObjectMonitorDeflationLogging* const _log;
  96 
  97 public:
  98   ObjectMonitorDeflationSafepointer(JavaThread* current, ObjectMonitorDeflationLogging* log)
  99     : _current(current), _log(log) {}
 100 
 101   void block_for_safepoint(const char* op_name, const char* count_name, size_t counter);
 102 };
 103 
 104 // Walk the in-use list and unlink deflated ObjectMonitors.
 105 // Returns the number of unlinked ObjectMonitors.
 106 size_t MonitorList::unlink_deflated(size_t deflated_count,
 107                                     GrowableArray<ObjectMonitor*>* unlinked_list,
 108                                     ObjectMonitorDeflationSafepointer* safepointer) {
 109   size_t unlinked_count = 0;
 110   ObjectMonitor* prev = nullptr;
 111   ObjectMonitor* m = Atomic::load_acquire(&_head);
 112 
 113   while (m != nullptr) {
 114     if (m->is_being_async_deflated()) {
 115       // Find next live ObjectMonitor. Batch up the unlinkable monitors, so we can
 116       // modify the list once per batch. The batch starts at "m".
 117       size_t unlinked_batch = 0;
 118       ObjectMonitor* next = m;
 119       // Look for at most MonitorUnlinkBatch monitors, or the number of
 120       // deflated and not unlinked monitors, whatever comes first.
 121       assert(deflated_count >= unlinked_count, "Sanity: underflow");
 122       size_t unlinked_batch_limit = MIN2<size_t>(deflated_count - unlinked_count, MonitorUnlinkBatch);
 123       do {
 124         ObjectMonitor* next_next = next->next_om();
 125         unlinked_batch++;
 126         unlinked_list->append(next);
 127         next = next_next;
 128         if (unlinked_batch >= unlinked_batch_limit) {
 129           // Reached the max batch, so bail out of the gathering loop.
 130           break;
 131         }
 132         if (prev == nullptr && Atomic::load(&_head) != m) {
 133           // Current batch used to be at head, but it is not at head anymore.
 134           // Bail out and figure out where we currently are. This avoids long
 135           // walks searching for new prev during unlink under heavy list inserts.
 136           break;
 137         }
 138       } while (next != nullptr && next->is_being_async_deflated());
 139 
 140       // Unlink the found batch.
 141       if (prev == nullptr) {
 142         // The current batch is the first batch, so there is a chance that it starts at head.
 143         // Optimistically assume no inserts happened, and try to unlink the entire batch from the head.
 144         ObjectMonitor* prev_head = Atomic::cmpxchg(&_head, m, next);
 145         if (prev_head != m) {
 146           // Something must have updated the head. Figure out the actual prev for this batch.
 147           for (ObjectMonitor* n = prev_head; n != m; n = n->next_om()) {
 148             prev = n;
 149           }
 150           assert(prev != nullptr, "Should have found the prev for the current batch");
 151           prev->set_next_om(next);
 152         }
 153       } else {
 154         // The current batch is preceded by another batch. This guarantees the current batch
 155         // does not start at head. Unlink the entire current batch without updating the head.
 156         assert(Atomic::load(&_head) != m, "Sanity");
 157         prev->set_next_om(next);
 158       }
 159 
 160       unlinked_count += unlinked_batch;
 161       if (unlinked_count >= deflated_count) {
 162         // Reached the max so bail out of the searching loop.
 163         // There should be no more deflated monitors left.
 164         break;
 165       }
 166       m = next;
 167     } else {
 168       prev = m;
 169       m = m->next_om();
 170     }
 171 
 172     // Must check for a safepoint/handshake and honor it.
 173     safepointer->block_for_safepoint("unlinking", "unlinked_count", unlinked_count);
 174   }
 175 
 176 #ifdef ASSERT
 177   // Invariant: the code above should unlink all deflated monitors.
 178   // The code that runs after this unlinking does not expect deflated monitors.
 179   // Notably, attempting to deflate the already deflated monitor would break.
 180   {
 181     ObjectMonitor* m = Atomic::load_acquire(&_head);
 182     while (m != nullptr) {
 183       assert(!m->is_being_async_deflated(), "All deflated monitors should be unlinked");
 184       m = m->next_om();
 185     }
 186   }
 187 #endif
 188 
 189   Atomic::sub(&_count, unlinked_count);
 190   return unlinked_count;
 191 }
 192 
 193 MonitorList::Iterator MonitorList::iterator() const {
 194   return Iterator(Atomic::load_acquire(&_head));
 195 }
 196 
 197 ObjectMonitor* MonitorList::Iterator::next() {
 198   ObjectMonitor* current = _current;
 199   _current = current->next_om();
 200   return current;
 201 }
 202 
 203 // The "core" versions of monitor enter and exit reside in this file.
 204 // The interpreter and compilers contain specialized transliterated
 205 // variants of the enter-exit fast-path operations.  See c2_MacroAssembler_x86.cpp
 206 // fast_lock(...) for instance.  If you make changes here, make sure to modify the
 207 // interpreter, and both C1 and C2 fast-path inline locking code emission.
 208 //
 209 // -----------------------------------------------------------------------------
 210 
 211 #ifdef DTRACE_ENABLED
 212 
 213 // Only bother with this argument setup if dtrace is available
 214 // TODO-FIXME: probes should not fire when caller is _blocked.  assert() accordingly.
 215 
 216 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread)                           \
 217   char* bytes = nullptr;                                                      \
 218   int len = 0;                                                             \
 219   jlong jtid = SharedRuntime::get_java_tid(thread);                        \
 220   Symbol* klassname = obj->klass()->name();                                \
 221   if (klassname != nullptr) {                                                 \
 222     bytes = (char*)klassname->bytes();                                     \
 223     len = klassname->utf8_length();                                        \
 224   }
 225 
 226 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis)            \
 227   {                                                                        \
 228     if (DTraceMonitorProbes) {                                             \
 229       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
 230       HOTSPOT_MONITOR_WAIT(jtid,                                           \
 231                            (uintptr_t)(monitor), bytes, len, (millis));    \
 232     }                                                                      \
 233   }
 234 
 235 #define HOTSPOT_MONITOR_PROBE_notify HOTSPOT_MONITOR_NOTIFY
 236 #define HOTSPOT_MONITOR_PROBE_notifyAll HOTSPOT_MONITOR_NOTIFYALL
 237 #define HOTSPOT_MONITOR_PROBE_waited HOTSPOT_MONITOR_WAITED
 238 
 239 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread)                  \
 240   {                                                                        \
 241     if (DTraceMonitorProbes) {                                             \
 242       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
 243       HOTSPOT_MONITOR_PROBE_##probe(jtid, /* probe = waited */             \
 244                                     (uintptr_t)(monitor), bytes, len);     \
 245     }                                                                      \
 246   }
 247 
 248 #else //  ndef DTRACE_ENABLED
 249 
 250 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon)    {;}
 251 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon)          {;}
 252 
 253 #endif // ndef DTRACE_ENABLED
 254 
 255 // This exists only as a workaround of dtrace bug 6254741
 256 static int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, JavaThread* thr) {
 257   DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
 258   return 0;
 259 }
 260 
 261 static constexpr size_t inflation_lock_count() {
 262   return 256;
 263 }
 264 
 265 // Static storage for an array of PlatformMutex.
 266 alignas(PlatformMutex) static uint8_t _inflation_locks[inflation_lock_count()][sizeof(PlatformMutex)];
 267 
 268 static inline PlatformMutex* inflation_lock(size_t index) {
 269   return reinterpret_cast<PlatformMutex*>(_inflation_locks[index]);
 270 }
 271 
 272 void ObjectSynchronizer::initialize() {
 273   for (size_t i = 0; i < inflation_lock_count(); i++) {
 274     ::new(static_cast<void*>(inflation_lock(i))) PlatformMutex();
 275   }
 276   // Start the ceiling with the estimate for one thread.
 277   set_in_use_list_ceiling(AvgMonitorsPerThreadEstimate);
 278 
 279   // Start the timer for deflations, so it does not trigger immediately.
 280   _last_async_deflation_time_ns = os::javaTimeNanos();
 281 
 282   if (LockingMode == LM_LIGHTWEIGHT) {
 283     LightweightSynchronizer::initialize();
 284   }
 285 }
 286 
 287 MonitorList ObjectSynchronizer::_in_use_list;
 288 // monitors_used_above_threshold() policy is as follows:
 289 //
 290 // The ratio of the current _in_use_list count to the ceiling is used
 291 // to determine if we are above MonitorUsedDeflationThreshold and need
 292 // to do an async monitor deflation cycle. The ceiling is increased by
 293 // AvgMonitorsPerThreadEstimate when a thread is added to the system
 294 // and is decreased by AvgMonitorsPerThreadEstimate when a thread is
 295 // removed from the system.
 296 //
 297 // Note: If the _in_use_list max exceeds the ceiling, then
 298 // monitors_used_above_threshold() will use the in_use_list max instead
 299 // of the thread count derived ceiling because we have used more
 300 // ObjectMonitors than the estimated average.
 301 //
 302 // Note: If deflate_idle_monitors() has NoAsyncDeflationProgressMax
 303 // no-progress async monitor deflation cycles in a row, then the ceiling
 304 // is adjusted upwards by monitors_used_above_threshold().
 305 //
 306 // Start the ceiling with the estimate for one thread in initialize()
 307 // which is called after cmd line options are processed.
 308 static size_t _in_use_list_ceiling = 0;
 309 bool volatile ObjectSynchronizer::_is_async_deflation_requested = false;
 310 bool volatile ObjectSynchronizer::_is_final_audit = false;
 311 jlong ObjectSynchronizer::_last_async_deflation_time_ns = 0;
 312 static uintx _no_progress_cnt = 0;
 313 static bool _no_progress_skip_increment = false;
 314 
 315 // =====================> Quick functions
 316 
 317 // The quick_* forms are special fast-path variants used to improve
 318 // performance.  In the simplest case, a "quick_*" implementation could
 319 // simply return false, in which case the caller will perform the necessary
 320 // state transitions and call the slow-path form.
 321 // The fast-path is designed to handle frequently arising cases in an efficient
 322 // manner and is just a degenerate "optimistic" variant of the slow-path.
 323 // returns true  -- to indicate the call was satisfied.
 324 // returns false -- to indicate the call needs the services of the slow-path.
 325 // A no-loitering ordinance is in effect for code in the quick_* family
 326 // operators: safepoints or indefinite blocking (blocking that might span a
 327 // safepoint) are forbidden. Generally the thread_state() is _in_Java upon
 328 // entry.
 329 //
 330 // Consider: An interesting optimization is to have the JIT recognize the
 331 // following common idiom:
 332 //   synchronized (someobj) { .... ; notify(); }
 333 // That is, we find a notify() or notifyAll() call that immediately precedes
 334 // the monitorexit operation.  In that case the JIT could fuse the operations
 335 // into a single notifyAndExit() runtime primitive.
 336 
 337 bool ObjectSynchronizer::quick_notify(oopDesc* obj, JavaThread* current, bool all) {
 338   assert(current->thread_state() == _thread_in_Java, "invariant");
 339   NoSafepointVerifier nsv;
 340   if (obj == nullptr) return false;  // slow-path for invalid obj
 341   const markWord mark = obj->mark();
 342 
 343   if (LockingMode == LM_LIGHTWEIGHT) {
 344     if (mark.is_fast_locked() && current->lock_stack().contains(cast_to_oop(obj))) {
 345       // Degenerate notify
 346       // fast-locked by caller so by definition the implied waitset is empty.
 347       return true;
 348     }
 349   } else if (LockingMode == LM_LEGACY) {
 350     if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {
 351       // Degenerate notify
 352       // stack-locked by caller so by definition the implied waitset is empty.
 353       return true;
 354     }
 355   }
 356 
 357   if (mark.has_monitor()) {
 358     ObjectMonitor* const mon = read_monitor(current, obj, mark);
 359     if (LockingMode == LM_LIGHTWEIGHT && mon == nullptr) {
 360       // Racing with inflation/deflation go slow path
 361       return false;
 362     }
 363     assert(mon->object() == oop(obj), "invariant");
 364     if (mon->owner() != current) return false;  // slow-path for IMS exception
 365 
 366     if (mon->first_waiter() != nullptr) {
 367       // We have one or more waiters. Since this is an inflated monitor
 368       // that we own, we can transfer one or more threads from the waitset
 369       // to the entrylist here and now, avoiding the slow-path.
 370       if (all) {
 371         DTRACE_MONITOR_PROBE(notifyAll, mon, obj, current);
 372       } else {
 373         DTRACE_MONITOR_PROBE(notify, mon, obj, current);
 374       }
 375       int free_count = 0;
 376       do {
 377         mon->INotify(current);
 378         ++free_count;
 379       } while (mon->first_waiter() != nullptr && all);
 380       OM_PERFDATA_OP(Notifications, inc(free_count));
 381     }
 382     return true;
 383   }
 384 
 385   // other IMS exception states take the slow-path
 386   return false;
 387 }
 388 
 389 static bool useHeavyMonitors() {
 390 #if defined(X86) || defined(AARCH64) || defined(PPC64) || defined(RISCV64) || defined(S390)
 391   return LockingMode == LM_MONITOR;
 392 #else
 393   return false;
 394 #endif
 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 
 409   if (obj->klass()->is_value_based()) {
 410     return false;
 411   }
 412 
 413   if (useHeavyMonitors()) {
 414     return false;  // Slow path
 415   }
 416 
 417   if (LockingMode == LM_LIGHTWEIGHT) {
 418     return LightweightSynchronizer::quick_enter(obj, current, lock);









 419   }
 420 
 421   assert(LockingMode == LM_LEGACY, "legacy mode below");
 422 
 423   const markWord mark = obj->mark();
 424 
 425   if (mark.has_monitor()) {
 426 
 427     ObjectMonitor* const m = read_monitor(mark);
 428     // An async deflation or GC can race us before we manage to make
 429     // the ObjectMonitor busy by setting the owner below. If we detect
 430     // that race we just bail out to the slow-path here.
 431     if (m->object_peek() == nullptr) {
 432       return false;
 433     }
 434     JavaThread* const owner = static_cast<JavaThread*>(m->owner_raw());
 435 
 436     // Lock contention and Transactional Lock Elision (TLE) diagnostics
 437     // and observability
 438     // Case: light contention possibly amenable to TLE
 439     // Case: TLE inimical operations such as nested/recursive synchronization
 440 
 441     if (owner == current) {
 442       m->_recursions++;
 443       current->inc_held_monitor_count();
 444       return true;
 445     }
 446 
 447     // This Java Monitor is inflated so obj's header will never be
 448     // displaced to this thread's BasicLock. Make the displaced header
 449     // non-null so this BasicLock is not seen as recursive nor as
 450     // being locked. We do this unconditionally so that this thread's
 451     // BasicLock cannot be mis-interpreted by any stack walkers. For
 452     // performance reasons, stack walkers generally first check for
 453     // stack-locking in the object's header, the second check is for
 454     // recursive stack-locking in the displaced header in the BasicLock,
 455     // and last are the inflated Java Monitor (ObjectMonitor) checks.
 456     lock->set_displaced_header(markWord::unused_mark());


 457 
 458     if (owner == nullptr && m->try_set_owner_from(nullptr, current) == nullptr) {
 459       assert(m->_recursions == 0, "invariant");
 460       current->inc_held_monitor_count();
 461       return true;
 462     }
 463   }
 464 
 465   // Note that we could inflate in quick_enter.
 466   // This is likely a useful optimization
 467   // Critically, in quick_enter() we must not:
 468   // -- block indefinitely, or
 469   // -- reach a safepoint
 470 
 471   return false;        // revert to slow-path
 472 }
 473 
 474 // Handle notifications when synchronizing on value based classes
 475 void ObjectSynchronizer::handle_sync_on_value_based_class(Handle obj, JavaThread* locking_thread) {
 476   assert(locking_thread == Thread::current() || locking_thread->is_obj_deopt_suspend(), "must be");
 477   frame last_frame = locking_thread->last_frame();
 478   bool bcp_was_adjusted = false;
 479   // Don't decrement bcp if it points to the frame's first instruction.  This happens when
 480   // handle_sync_on_value_based_class() is called because of a synchronized method.  There
 481   // is no actual monitorenter instruction in the byte code in this case.
 482   if (last_frame.is_interpreted_frame() &&
 483       (last_frame.interpreter_frame_method()->code_base() < last_frame.interpreter_frame_bcp())) {
 484     // adjust bcp to point back to monitorenter so that we print the correct line numbers
 485     last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() - 1);
 486     bcp_was_adjusted = true;
 487   }
 488 
 489   if (DiagnoseSyncOnValueBasedClasses == FATAL_EXIT) {
 490     ResourceMark rm;
 491     stringStream ss;
 492     locking_thread->print_active_stack_on(&ss);
 493     char* base = (char*)strstr(ss.base(), "at");
 494     char* newline = (char*)strchr(ss.base(), '\n');
 495     if (newline != nullptr) {
 496       *newline = '\0';
 497     }
 498     fatal("Synchronizing on object " INTPTR_FORMAT " of klass %s %s", p2i(obj()), obj->klass()->external_name(), base);
 499   } else {
 500     assert(DiagnoseSyncOnValueBasedClasses == LOG_WARNING, "invalid value for DiagnoseSyncOnValueBasedClasses");
 501     ResourceMark rm;
 502     Log(valuebasedclasses) vblog;
 503 
 504     vblog.info("Synchronizing on object " INTPTR_FORMAT " of klass %s", p2i(obj()), obj->klass()->external_name());
 505     if (locking_thread->has_last_Java_frame()) {
 506       LogStream info_stream(vblog.info());
 507       locking_thread->print_active_stack_on(&info_stream);
 508     } else {
 509       vblog.info("Cannot find the last Java frame");
 510     }
 511 
 512     EventSyncOnValueBasedClass event;
 513     if (event.should_commit()) {
 514       event.set_valueBasedClass(obj->klass());
 515       event.commit();
 516     }
 517   }
 518 
 519   if (bcp_was_adjusted) {
 520     last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() + 1);
 521   }
 522 }
 523 








 524 // -----------------------------------------------------------------------------
 525 // Monitor Enter/Exit
 526 
 527 void ObjectSynchronizer::enter_for(Handle obj, BasicLock* lock, JavaThread* locking_thread) {
 528   // When called with locking_thread != Thread::current() some mechanism must synchronize
 529   // the locking_thread with respect to the current thread. Currently only used when
 530   // deoptimizing and re-locking locks. See Deoptimization::relock_objects
 531   assert(locking_thread == Thread::current() || locking_thread->is_obj_deopt_suspend(), "must be");
 532 
 533   if (LockingMode == LM_LIGHTWEIGHT) {
 534     return LightweightSynchronizer::enter_for(obj, lock, locking_thread);
 535   }
 536 
 537   if (!enter_fast_impl(obj, lock, locking_thread)) {
 538     // Inflated ObjectMonitor::enter_for is required
 539 
 540     // An async deflation can race after the inflate_for() call and before
 541     // enter_for() can make the ObjectMonitor busy. enter_for() returns false
 542     // if we have lost the race to async deflation and we simply try again.
 543     while (true) {
 544       ObjectMonitor* monitor = inflate_for(locking_thread, obj(), inflate_cause_monitor_enter);
 545       if (monitor->enter_for(locking_thread)) {
 546         return;
 547       }
 548       assert(monitor->is_being_async_deflated(), "must be");
 549     }
 550   }
 551 }
 552 
 553 void ObjectSynchronizer::enter(Handle obj, BasicLock* lock, JavaThread* current) {
 554   assert(current == Thread::current(), "must be");
 555 
 556   if (LockingMode == LM_LIGHTWEIGHT) {
 557     return LightweightSynchronizer::enter(obj, lock, current);
 558   }
 559 
 560   if (!enter_fast_impl(obj, lock, current)) {
 561     // Inflated ObjectMonitor::enter is required
 562 
 563     // An async deflation can race after the inflate() call and before
 564     // enter() can make the ObjectMonitor busy. enter() returns false if
 565     // we have lost the race to async deflation and we simply try again.
 566     while (true) {
 567       ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_monitor_enter);
 568       if (monitor->enter(current)) {
 569         return;
 570       }
 571     }
 572   }
 573 }
 574 
 575 // The interpreter and compiler assembly code tries to lock using the fast path
 576 // of this algorithm. Make sure to update that code if the following function is
 577 // changed. The implementation is extremely sensitive to race condition. Be careful.
 578 bool ObjectSynchronizer::enter_fast_impl(Handle obj, BasicLock* lock, JavaThread* locking_thread) {
 579   assert(LockingMode != LM_LIGHTWEIGHT, "Use LightweightSynchronizer");
 580 
 581   if (obj->klass()->is_value_based()) {
 582     handle_sync_on_value_based_class(obj, locking_thread);
 583   }
 584 
 585   locking_thread->inc_held_monitor_count();
 586 
 587   if (!useHeavyMonitors()) {
 588     if (LockingMode == LM_LEGACY) {






















































 589       markWord mark = obj->mark();
 590       if (mark.is_unlocked()) {
 591         // Anticipate successful CAS -- the ST of the displaced mark must
 592         // be visible <= the ST performed by the CAS.
 593         lock->set_displaced_header(mark);
 594         if (mark == obj()->cas_set_mark(markWord::from_pointer(lock), mark)) {
 595           return true;
 596         }
 597       } else if (mark.has_locker() &&
 598                  locking_thread->is_lock_owned((address) mark.locker())) {
 599         assert(lock != mark.locker(), "must not re-lock the same lock");
 600         assert(lock != (BasicLock*) obj->mark().value(), "don't relock with same BasicLock");
 601         lock->set_displaced_header(markWord::from_pointer(nullptr));
 602         return true;
 603       }
 604 
 605       // The object header will never be displaced to this lock,
 606       // so it does not matter what the value is, except that it
 607       // must be non-zero to avoid looking like a re-entrant lock,
 608       // and must not look locked either.
 609       lock->set_displaced_header(markWord::unused_mark());
 610 
 611       // Failed to fast lock.
 612       return false;
 613     }
 614   } else if (VerifyHeavyMonitors) {
 615     guarantee((obj->mark().value() & markWord::lock_mask_in_place) != markWord::locked_value, "must not be lightweight/stack-locked");
 616   }
 617 
 618   return false;
 619 }
 620 
 621 void ObjectSynchronizer::exit(oop object, BasicLock* lock, JavaThread* current) {
 622   current->dec_held_monitor_count();
 623 
 624   if (LockingMode == LM_LIGHTWEIGHT) {
 625     return LightweightSynchronizer::exit(object, current);
 626   }
 627 
 628   if (!useHeavyMonitors()) {
 629     markWord mark = object->mark();
 630     if (LockingMode == LM_LEGACY) {

























 631       markWord dhw = lock->displaced_header();
 632       if (dhw.value() == 0) {
 633         // If the displaced header is null, then this exit matches up with
 634         // a recursive enter. No real work to do here except for diagnostics.
 635 #ifndef PRODUCT
 636         if (mark != markWord::INFLATING()) {
 637           // Only do diagnostics if we are not racing an inflation. Simply
 638           // exiting a recursive enter of a Java Monitor that is being
 639           // inflated is safe; see the has_monitor() comment below.
 640           assert(!mark.is_unlocked(), "invariant");
 641           assert(!mark.has_locker() ||
 642                  current->is_lock_owned((address)mark.locker()), "invariant");
 643           if (mark.has_monitor()) {
 644             // The BasicLock's displaced_header is marked as a recursive
 645             // enter and we have an inflated Java Monitor (ObjectMonitor).
 646             // This is a special case where the Java Monitor was inflated
 647             // after this thread entered the stack-lock recursively. When a
 648             // Java Monitor is inflated, we cannot safely walk the Java
 649             // Monitor owner's stack and update the BasicLocks because a
 650             // Java Monitor can be asynchronously inflated by a thread that
 651             // does not own the Java Monitor.
 652             ObjectMonitor* m = read_monitor(mark);
 653             assert(m->object()->mark() == mark, "invariant");
 654             assert(m->is_entered(current), "invariant");
 655           }
 656         }
 657 #endif
 658         return;
 659       }
 660 
 661       if (mark == markWord::from_pointer(lock)) {
 662         // If the object is stack-locked by the current thread, try to
 663         // swing the displaced header from the BasicLock back to the mark.
 664         assert(dhw.is_neutral(), "invariant");
 665         if (object->cas_set_mark(dhw, mark) == mark) {
 666           return;
 667         }
 668       }
 669     }
 670   } else if (VerifyHeavyMonitors) {
 671     guarantee((object->mark().value() & markWord::lock_mask_in_place) != markWord::locked_value, "must not be lightweight/stack-locked");
 672   }
 673 
 674   // We have to take the slow-path of possible inflation and then exit.
 675   // The ObjectMonitor* can't be async deflated until ownership is
 676   // dropped inside exit() and the ObjectMonitor* must be !is_busy().
 677   ObjectMonitor* monitor = inflate(current, object, inflate_cause_vm_internal);
 678   assert(!monitor->is_owner_anonymous(), "must not be");
 679   monitor->exit(current);
 680 }
 681 
 682 // -----------------------------------------------------------------------------
 683 // JNI locks on java objects
 684 // NOTE: must use heavy weight monitor to handle jni monitor enter
 685 void ObjectSynchronizer::jni_enter(Handle obj, JavaThread* current) {
 686   if (obj->klass()->is_value_based()) {
 687     handle_sync_on_value_based_class(obj, current);
 688   }
 689 
 690   // the current locking is from JNI instead of Java code
 691   current->set_current_pending_monitor_is_from_java(false);
 692   // An async deflation can race after the inflate() call and before
 693   // enter() can make the ObjectMonitor busy. enter() returns false if
 694   // we have lost the race to async deflation and we simply try again.
 695   while (true) {
 696     ObjectMonitor* monitor;
 697     bool entered;
 698     if (LockingMode == LM_LIGHTWEIGHT) {
 699       entered = LightweightSynchronizer::inflate_and_enter(obj(), current, current, inflate_cause_jni_enter) != nullptr;
 700     } else {
 701       monitor = inflate(current, obj(), inflate_cause_jni_enter);
 702       entered = monitor->enter(current);
 703     }
 704 
 705     if (entered) {
 706       current->inc_held_monitor_count(1, true);
 707       break;
 708     }
 709   }
 710   current->set_current_pending_monitor_is_from_java(true);
 711 }
 712 
 713 // NOTE: must use heavy weight monitor to handle jni monitor exit
 714 void ObjectSynchronizer::jni_exit(oop obj, TRAPS) {
 715   JavaThread* current = THREAD;
 716 
 717   ObjectMonitor* monitor;
 718   if (LockingMode == LM_LIGHTWEIGHT) {
 719     monitor = LightweightSynchronizer::inflate_locked_or_imse(obj, inflate_cause_jni_exit, CHECK);
 720   } else {
 721     // The ObjectMonitor* can't be async deflated until ownership is
 722     // dropped inside exit() and the ObjectMonitor* must be !is_busy().
 723     monitor = inflate(current, obj, inflate_cause_jni_exit);
 724   }
 725   // If this thread has locked the object, exit the monitor. We
 726   // intentionally do not use CHECK on check_owner because we must exit the
 727   // monitor even if an exception was already pending.
 728   if (monitor->check_owner(THREAD)) {
 729     monitor->exit(current);
 730     current->dec_held_monitor_count(1, true);
 731   }
 732 }
 733 
 734 // -----------------------------------------------------------------------------
 735 // Internal VM locks on java objects
 736 // standard constructor, allows locking failures
 737 ObjectLocker::ObjectLocker(Handle obj, JavaThread* thread) {
 738   _thread = thread;
 739   _thread->check_for_valid_safepoint_state();
 740   _obj = obj;
 741 
 742   if (_obj() != nullptr) {
 743     ObjectSynchronizer::enter(_obj, &_lock, _thread);
 744   }
 745 }
 746 
 747 ObjectLocker::~ObjectLocker() {
 748   if (_obj() != nullptr) {
 749     ObjectSynchronizer::exit(_obj(), &_lock, _thread);
 750   }
 751 }
 752 
 753 
 754 // -----------------------------------------------------------------------------
 755 //  Wait/Notify/NotifyAll
 756 // NOTE: must use heavy weight monitor to handle wait()
 757 
 758 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
 759   JavaThread* current = THREAD;
 760   if (millis < 0) {
 761     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 762   }
 763 
 764   ObjectMonitor* monitor;
 765   if (LockingMode == LM_LIGHTWEIGHT) {
 766     monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_wait, CHECK_0);
 767   } else {
 768     // The ObjectMonitor* can't be async deflated because the _waiters
 769     // field is incremented before ownership is dropped and decremented
 770     // after ownership is regained.
 771     monitor = inflate(current, obj(), inflate_cause_wait);
 772   }
 773 
 774   DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), current, millis);
 775   monitor->wait(millis, true, THREAD); // Not CHECK as we need following code
 776 
 777   // This dummy call is in place to get around dtrace bug 6254741.  Once
 778   // that's fixed we can uncomment the following line, remove the call
 779   // and change this function back into a "void" func.
 780   // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
 781   int ret_code = dtrace_waited_probe(monitor, obj, THREAD);
 782   return ret_code;
 783 }
 784 
 785 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
 786   JavaThread* current = THREAD;
 787 
 788   markWord mark = obj->mark();
 789   if (LockingMode == LM_LIGHTWEIGHT) {
 790     if ((mark.is_fast_locked() && current->lock_stack().contains(obj()))) {
 791       // Not inflated so there can't be any waiters to notify.
 792       return;
 793     }
 794   } else if (LockingMode == LM_LEGACY) {
 795     if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {
 796       // Not inflated so there can't be any waiters to notify.
 797       return;
 798     }
 799   }
 800 
 801   ObjectMonitor* monitor;
 802   if (LockingMode == LM_LIGHTWEIGHT) {
 803     monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_notify, CHECK);
 804   } else {
 805     // The ObjectMonitor* can't be async deflated until ownership is
 806     // dropped by the calling thread.
 807     monitor = inflate(current, obj(), inflate_cause_notify);
 808   }
 809   monitor->notify(CHECK);
 810 }
 811 
 812 // NOTE: see comment of notify()
 813 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
 814   JavaThread* current = THREAD;
 815 
 816   markWord mark = obj->mark();
 817   if (LockingMode == LM_LIGHTWEIGHT) {
 818     if ((mark.is_fast_locked() && current->lock_stack().contains(obj()))) {
 819       // Not inflated so there can't be any waiters to notify.
 820       return;
 821     }
 822   } else if (LockingMode == LM_LEGACY) {
 823     if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) {
 824       // Not inflated so there can't be any waiters to notify.
 825       return;
 826     }
 827   }
 828 
 829   ObjectMonitor* monitor;
 830   if (LockingMode == LM_LIGHTWEIGHT) {
 831     monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_notify, CHECK);
 832   } else {
 833     // The ObjectMonitor* can't be async deflated until ownership is
 834     // dropped by the calling thread.
 835     monitor = inflate(current, obj(), inflate_cause_notify);
 836   }
 837   monitor->notifyAll(CHECK);
 838 }
 839 
 840 // -----------------------------------------------------------------------------
 841 // Hash Code handling
 842 
 843 struct SharedGlobals {
 844   char         _pad_prefix[OM_CACHE_LINE_SIZE];
 845   // This is a highly shared mostly-read variable.
 846   // To avoid false-sharing it needs to be the sole occupant of a cache line.
 847   volatile int stw_random;
 848   DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 849   // Hot RW variable -- Sequester to avoid false-sharing
 850   volatile int hc_sequence;
 851   DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 852 };
 853 
 854 static SharedGlobals GVars;
 855 
 856 static markWord read_stable_mark(oop obj) {
 857   markWord mark = obj->mark_acquire();
 858   if (!mark.is_being_inflated() || LockingMode == LM_LIGHTWEIGHT) {
 859     // New lightweight locking does not use the markWord::INFLATING() protocol.
 860     return mark;       // normal fast-path return
 861   }
 862 
 863   int its = 0;
 864   for (;;) {
 865     markWord mark = obj->mark_acquire();
 866     if (!mark.is_being_inflated()) {
 867       return mark;    // normal fast-path return
 868     }
 869 
 870     // The object is being inflated by some other thread.
 871     // The caller of read_stable_mark() must wait for inflation to complete.
 872     // Avoid live-lock.
 873 
 874     ++its;
 875     if (its > 10000 || !os::is_MP()) {
 876       if (its & 1) {
 877         os::naked_yield();
 878       } else {
 879         // Note that the following code attenuates the livelock problem but is not
 880         // a complete remedy.  A more complete solution would require that the inflating
 881         // thread hold the associated inflation lock.  The following code simply restricts
 882         // the number of spinners to at most one.  We'll have N-2 threads blocked
 883         // on the inflationlock, 1 thread holding the inflation lock and using
 884         // a yield/park strategy, and 1 thread in the midst of inflation.
 885         // A more refined approach would be to change the encoding of INFLATING
 886         // to allow encapsulation of a native thread pointer.  Threads waiting for
 887         // inflation to complete would use CAS to push themselves onto a singly linked
 888         // list rooted at the markword.  Once enqueued, they'd loop, checking a per-thread flag
 889         // and calling park().  When inflation was complete the thread that accomplished inflation
 890         // would detach the list and set the markword to inflated with a single CAS and
 891         // then for each thread on the list, set the flag and unpark() the thread.
 892 
 893         // Index into the lock array based on the current object address.
 894         static_assert(is_power_of_2(inflation_lock_count()), "must be");
 895         size_t ix = (cast_from_oop<intptr_t>(obj) >> 5) & (inflation_lock_count() - 1);
 896         int YieldThenBlock = 0;
 897         assert(ix < inflation_lock_count(), "invariant");
 898         inflation_lock(ix)->lock();
 899         while (obj->mark_acquire() == markWord::INFLATING()) {
 900           // Beware: naked_yield() is advisory and has almost no effect on some platforms
 901           // so we periodically call current->_ParkEvent->park(1).
 902           // We use a mixed spin/yield/block mechanism.
 903           if ((YieldThenBlock++) >= 16) {
 904             Thread::current()->_ParkEvent->park(1);
 905           } else {
 906             os::naked_yield();
 907           }
 908         }
 909         inflation_lock(ix)->unlock();
 910       }
 911     } else {
 912       SpinPause();       // SMP-polite spinning
 913     }
 914   }
 915 }
 916 
 917 // hashCode() generation :
 918 //
 919 // Possibilities:
 920 // * MD5Digest of {obj,stw_random}
 921 // * CRC32 of {obj,stw_random} or any linear-feedback shift register function.
 922 // * A DES- or AES-style SBox[] mechanism
 923 // * One of the Phi-based schemes, such as:
 924 //   2654435761 = 2^32 * Phi (golden ratio)
 925 //   HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stw_random ;
 926 // * A variation of Marsaglia's shift-xor RNG scheme.
 927 // * (obj ^ stw_random) is appealing, but can result
 928 //   in undesirable regularity in the hashCode values of adjacent objects
 929 //   (objects allocated back-to-back, in particular).  This could potentially
 930 //   result in hashtable collisions and reduced hashtable efficiency.
 931 //   There are simple ways to "diffuse" the middle address bits over the
 932 //   generated hashCode values:
 933 
 934 static intptr_t get_next_hash(Thread* current, oop obj) {
 935   intptr_t value = 0;
 936   if (hashCode == 0) {
 937     // This form uses global Park-Miller RNG.
 938     // On MP system we'll have lots of RW access to a global, so the
 939     // mechanism induces lots of coherency traffic.
 940     value = os::random();
 941   } else if (hashCode == 1) {
 942     // This variation has the property of being stable (idempotent)
 943     // between STW operations.  This can be useful in some of the 1-0
 944     // synchronization schemes.
 945     intptr_t addr_bits = cast_from_oop<intptr_t>(obj) >> 3;
 946     value = addr_bits ^ (addr_bits >> 5) ^ GVars.stw_random;
 947   } else if (hashCode == 2) {
 948     value = 1;            // for sensitivity testing
 949   } else if (hashCode == 3) {
 950     value = ++GVars.hc_sequence;
 951   } else if (hashCode == 4) {
 952     value = cast_from_oop<intptr_t>(obj);
 953   } else {
 954     // Marsaglia's xor-shift scheme with thread-specific state
 955     // This is probably the best overall implementation -- we'll
 956     // likely make this the default in future releases.
 957     unsigned t = current->_hashStateX;
 958     t ^= (t << 11);
 959     current->_hashStateX = current->_hashStateY;
 960     current->_hashStateY = current->_hashStateZ;
 961     current->_hashStateZ = current->_hashStateW;
 962     unsigned v = current->_hashStateW;
 963     v = (v ^ (v >> 19)) ^ (t ^ (t >> 8));
 964     current->_hashStateW = v;
 965     value = v;
 966   }
 967 
 968   value &= UseCompactObjectHeaders ? markWord::hash_mask_compact : markWord::hash_mask;
 969   if (value == 0) value = 0xBAD;
 970   assert(value != markWord::no_hash, "invariant");
 971   return value;
 972 }
 973 
 974 static intptr_t install_hash_code(Thread* current, oop obj) {
 975   assert(UseObjectMonitorTable && LockingMode == LM_LIGHTWEIGHT, "must be");
 976 
 977   markWord mark = obj->mark_acquire();
 978   for(;;) {
 979     intptr_t hash = mark.hash();
 980     if (hash != 0) {
 981       return hash;
 982     }
 983 
 984     hash = get_next_hash(current, obj);
 985     const markWord old_mark = mark;
 986     const markWord new_mark = old_mark.copy_set_hash(hash);
 987 
 988     mark = obj->cas_set_mark(new_mark, old_mark);
 989     if (old_mark == mark) {
 990       return hash;
 991     }
 992   }
 993 }
 994 
 995 intptr_t ObjectSynchronizer::FastHashCode(Thread* current, oop obj) {
 996   // Since the monitor isn't in the object header, it can simply be installed.
 997   if (UseObjectMonitorTable && LockingMode == LM_LIGHTWEIGHT) {
 998     return install_hash_code(current, obj);
 999   }
1000 
1001   while (true) {
1002     ObjectMonitor* monitor = nullptr;
1003     markWord temp, test;
1004     intptr_t hash;
1005     markWord mark = read_stable_mark(obj);
1006     if (VerifyHeavyMonitors) {
1007       assert(LockingMode == LM_MONITOR, "+VerifyHeavyMonitors requires LockingMode == 0 (LM_MONITOR)");
1008       guarantee((obj->mark().value() & markWord::lock_mask_in_place) != markWord::locked_value, "must not be lightweight/stack-locked");
1009     }
1010     if (mark.is_unlocked() || (LockingMode == LM_LIGHTWEIGHT && mark.is_fast_locked())) {
1011       hash = mark.hash();
1012       if (hash != 0) {                     // if it has a hash, just return it
1013         return hash;
1014       }
1015       hash = get_next_hash(current, obj);  // get a new hash
1016       temp = mark.copy_set_hash(hash);     // merge the hash into header
1017                                            // try to install the hash
1018       test = obj->cas_set_mark(temp, mark);
1019       if (test == mark) {                  // if the hash was installed, return it
1020         return hash;
1021       }
1022       if (LockingMode == LM_LIGHTWEIGHT) {
1023         // CAS failed, retry
1024         continue;
1025       }
1026       // Failed to install the hash. It could be that another thread
1027       // installed the hash just before our attempt or inflation has
1028       // occurred or... so we fall thru to inflate the monitor for
1029       // stability and then install the hash.
1030     } else if (mark.has_monitor()) {
1031       monitor = mark.monitor();
1032       temp = monitor->header();
1033       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
1034       hash = temp.hash();
1035       if (hash != 0) {
1036         // It has a hash.
1037 
1038         // Separate load of dmw/header above from the loads in
1039         // is_being_async_deflated().
1040 
1041         // dmw/header and _contentions may get written by different threads.
1042         // Make sure to observe them in the same order when having several observers.
1043         OrderAccess::loadload_for_IRIW();
1044 
1045         if (monitor->is_being_async_deflated()) {
1046           // But we can't safely use the hash if we detect that async
1047           // deflation has occurred. So we attempt to restore the
1048           // header/dmw to the object's header so that we only retry
1049           // once if the deflater thread happens to be slow.
1050           monitor->install_displaced_markword_in_object(obj);
1051           continue;
1052         }
1053         return hash;
1054       }
1055       // Fall thru so we only have one place that installs the hash in
1056       // the ObjectMonitor.
1057     } else if (LockingMode == LM_LEGACY && mark.has_locker()
1058                && current->is_Java_thread()
1059                && JavaThread::cast(current)->is_lock_owned((address)mark.locker())) {
1060       // This is a stack-lock owned by the calling thread so fetch the
1061       // displaced markWord from the BasicLock on the stack.
1062       temp = mark.displaced_mark_helper();
1063       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
1064       hash = temp.hash();
1065       if (hash != 0) {                  // if it has a hash, just return it
1066         return hash;
1067       }
1068       // WARNING:
1069       // The displaced header in the BasicLock on a thread's stack
1070       // is strictly immutable. It CANNOT be changed in ANY cases.
1071       // So we have to inflate the stack-lock into an ObjectMonitor
1072       // even if the current thread owns the lock. The BasicLock on
1073       // a thread's stack can be asynchronously read by other threads
1074       // during an inflate() call so any change to that stack memory
1075       // may not propagate to other threads correctly.
1076     }
1077 
1078     // Inflate the monitor to set the hash.
1079 
1080     // There's no need to inflate if the mark has already got a monitor.
1081     // NOTE: an async deflation can race after we get the monitor and
1082     // before we can update the ObjectMonitor's header with the hash
1083     // value below.
1084     monitor = mark.has_monitor() ? mark.monitor() : inflate(current, obj, inflate_cause_hash_code);
1085     // Load ObjectMonitor's header/dmw field and see if it has a hash.
1086     mark = monitor->header();
1087     assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value());
1088     hash = mark.hash();
1089     if (hash == 0) {                       // if it does not have a hash
1090       hash = get_next_hash(current, obj);  // get a new hash
1091       temp = mark.copy_set_hash(hash)   ;  // merge the hash into header
1092       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
1093       uintptr_t v = Atomic::cmpxchg(monitor->metadata_addr(), mark.value(), temp.value());
1094       test = markWord(v);
1095       if (test != mark) {
1096         // The attempt to update the ObjectMonitor's header/dmw field
1097         // did not work. This can happen if another thread managed to
1098         // merge in the hash just before our cmpxchg().
1099         // If we add any new usages of the header/dmw field, this code
1100         // will need to be updated.
1101         hash = test.hash();
1102         assert(test.is_neutral(), "invariant: header=" INTPTR_FORMAT, test.value());
1103         assert(hash != 0, "should only have lost the race to a thread that set a non-zero hash");
1104       }
1105       if (monitor->is_being_async_deflated() && !UseObjectMonitorTable) {
1106         // If we detect that async deflation has occurred, then we
1107         // attempt to restore the header/dmw to the object's header
1108         // so that we only retry once if the deflater thread happens
1109         // to be slow.
1110         monitor->install_displaced_markword_in_object(obj);
1111         continue;
1112       }
1113     }
1114     // We finally get the hash.
1115     return hash;
1116   }
1117 }
1118 
1119 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* current,
1120                                                    Handle h_obj) {
1121   assert(current == JavaThread::current(), "Can only be called on current thread");
1122   oop obj = h_obj();
1123 
1124   markWord mark = read_stable_mark(obj);
1125 
1126   if (LockingMode == LM_LEGACY && mark.has_locker()) {
1127     // stack-locked case, header points into owner's stack
1128     return current->is_lock_owned((address)mark.locker());
1129   }
1130 
1131   if (LockingMode == LM_LIGHTWEIGHT && mark.is_fast_locked()) {
1132     // fast-locking case, see if lock is in current's lock stack
1133     return current->lock_stack().contains(h_obj());
1134   }
1135 
1136   while (LockingMode == LM_LIGHTWEIGHT && mark.has_monitor()) {
1137     ObjectMonitor* monitor = read_monitor(current, obj, mark);
1138     if (monitor != nullptr) {
1139       return monitor->is_entered(current) != 0;
1140     }
1141     // Racing with inflation/deflation, retry
1142     mark = obj->mark_acquire();
1143 
1144     if (mark.is_fast_locked()) {
1145       // Some other thread fast_locked, current could not have held the lock
1146       return false;
1147     }
1148   }
1149 
1150   if (LockingMode != LM_LIGHTWEIGHT && mark.has_monitor()) {
1151     // Inflated monitor so header points to ObjectMonitor (tagged pointer).
1152     // The first stage of async deflation does not affect any field
1153     // used by this comparison so the ObjectMonitor* is usable here.
1154     ObjectMonitor* monitor = read_monitor(mark);
1155     return monitor->is_entered(current) != 0;
1156   }
1157   // Unlocked case, header in place
1158   assert(mark.is_unlocked(), "sanity check");
1159   return false;
1160 }
1161 
1162 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) {
1163   oop obj = h_obj();
1164   markWord mark = read_stable_mark(obj);
1165 
1166   if (LockingMode == LM_LEGACY && mark.has_locker()) {
1167     // stack-locked so header points into owner's stack.
1168     // owning_thread_from_monitor_owner() may also return null here:
1169     return Threads::owning_thread_from_monitor_owner(t_list, (address) mark.locker());
1170   }
1171 
1172   if (LockingMode == LM_LIGHTWEIGHT && mark.is_fast_locked()) {
1173     // fast-locked so get owner from the object.
1174     // owning_thread_from_object() may also return null here:
1175     return Threads::owning_thread_from_object(t_list, h_obj());
1176   }
1177 
1178   while (LockingMode == LM_LIGHTWEIGHT && mark.has_monitor()) {
1179     ObjectMonitor* monitor = read_monitor(Thread::current(), obj, mark);
1180     if (monitor != nullptr) {
1181       return Threads::owning_thread_from_monitor(t_list, monitor);
1182     }
1183     // Racing with inflation/deflation, retry
1184     mark = obj->mark_acquire();
1185 
1186     if (mark.is_fast_locked()) {
1187       // Some other thread fast_locked
1188       return Threads::owning_thread_from_object(t_list, h_obj());
1189     }
1190   }
1191 
1192   if (LockingMode != LM_LIGHTWEIGHT && mark.has_monitor()) {
1193     // Inflated monitor so header points to ObjectMonitor (tagged pointer).
1194     // The first stage of async deflation does not affect any field
1195     // used by this comparison so the ObjectMonitor* is usable here.
1196     ObjectMonitor* monitor = read_monitor(mark);
1197     assert(monitor != nullptr, "monitor should be non-null");
1198     // owning_thread_from_monitor() may also return null here:
1199     return Threads::owning_thread_from_monitor(t_list, monitor);
1200   }
1201 
1202   // Unlocked case, header in place
1203   // Cannot have assertion since this object may have been
1204   // locked by another thread when reaching here.
1205   // assert(mark.is_unlocked(), "sanity check");
1206 
1207   return nullptr;
1208 }
1209 
1210 // Visitors ...
1211 
1212 // Iterate over all ObjectMonitors.
1213 template <typename Function>
1214 void ObjectSynchronizer::monitors_iterate(Function function) {
1215   MonitorList::Iterator iter = _in_use_list.iterator();
1216   while (iter.has_next()) {
1217     ObjectMonitor* monitor = iter.next();
1218     function(monitor);
1219   }
1220 }
1221 
1222 // Iterate ObjectMonitors owned by any thread and where the owner `filter`
1223 // returns true.
1224 template <typename OwnerFilter>
1225 void ObjectSynchronizer::owned_monitors_iterate_filtered(MonitorClosure* closure, OwnerFilter filter) {
1226   monitors_iterate([&](ObjectMonitor* monitor) {
1227     // This function is only called at a safepoint or when the
1228     // target thread is suspended or when the target thread is
1229     // operating on itself. The current closures in use today are
1230     // only interested in an owned ObjectMonitor and ownership
1231     // cannot be dropped under the calling contexts so the
1232     // ObjectMonitor cannot be async deflated.
1233     if (monitor->has_owner() && filter(monitor->owner_raw())) {
1234       assert(!monitor->is_being_async_deflated(), "Owned monitors should not be deflating");
1235 
1236       closure->do_monitor(monitor);
1237     }
1238   });
1239 }
1240 
1241 // Iterate ObjectMonitors where the owner == thread; this does NOT include
1242 // ObjectMonitors where owner is set to a stack-lock address in thread.
1243 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure, JavaThread* thread) {
1244   auto thread_filter = [&](void* owner) { return owner == thread; };
1245   return owned_monitors_iterate_filtered(closure, thread_filter);
1246 }
1247 
1248 // Iterate ObjectMonitors owned by any thread.
1249 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure) {
1250   auto all_filter = [&](void* owner) { return true; };
1251   return owned_monitors_iterate_filtered(closure, all_filter);
1252 }
1253 
1254 static bool monitors_used_above_threshold(MonitorList* list) {
1255   if (MonitorUsedDeflationThreshold == 0) {  // disabled case is easy
1256     return false;
1257   }
1258   // Start with ceiling based on a per-thread estimate:
1259   size_t ceiling = ObjectSynchronizer::in_use_list_ceiling();
1260   size_t old_ceiling = ceiling;
1261   if (ceiling < list->max()) {
1262     // The max used by the system has exceeded the ceiling so use that:
1263     ceiling = list->max();
1264   }
1265   size_t monitors_used = list->count();
1266   if (monitors_used == 0) {  // empty list is easy
1267     return false;
1268   }
1269   if (NoAsyncDeflationProgressMax != 0 &&
1270       _no_progress_cnt >= NoAsyncDeflationProgressMax) {
1271     double remainder = (100.0 - MonitorUsedDeflationThreshold) / 100.0;
1272     size_t new_ceiling = ceiling / remainder + 1;
1273     ObjectSynchronizer::set_in_use_list_ceiling(new_ceiling);
1274     log_info(monitorinflation)("Too many deflations without progress; "
1275                                "bumping in_use_list_ceiling from " SIZE_FORMAT
1276                                " to " SIZE_FORMAT, old_ceiling, new_ceiling);
1277     _no_progress_cnt = 0;
1278     ceiling = new_ceiling;
1279   }
1280 
1281   // Check if our monitor usage is above the threshold:
1282   size_t monitor_usage = (monitors_used * 100LL) / ceiling;
1283   if (int(monitor_usage) > MonitorUsedDeflationThreshold) {
1284     log_info(monitorinflation)("monitors_used=" SIZE_FORMAT ", ceiling=" SIZE_FORMAT
1285                                ", monitor_usage=" SIZE_FORMAT ", threshold=%d",
1286                                monitors_used, ceiling, monitor_usage, MonitorUsedDeflationThreshold);
1287     return true;
1288   }
1289 
1290   return false;
1291 }
1292 
1293 size_t ObjectSynchronizer::in_use_list_ceiling() {
1294   return _in_use_list_ceiling;
1295 }
1296 
1297 void ObjectSynchronizer::dec_in_use_list_ceiling() {
1298   Atomic::sub(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate);
1299 }
1300 
1301 void ObjectSynchronizer::inc_in_use_list_ceiling() {
1302   Atomic::add(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate);
1303 }
1304 
1305 void ObjectSynchronizer::set_in_use_list_ceiling(size_t new_value) {
1306   _in_use_list_ceiling = new_value;
1307 }
1308 
1309 bool ObjectSynchronizer::is_async_deflation_needed() {
1310   if (is_async_deflation_requested()) {
1311     // Async deflation request.
1312     log_info(monitorinflation)("Async deflation needed: explicit request");
1313     return true;
1314   }
1315 
1316   jlong time_since_last = time_since_last_async_deflation_ms();
1317 
1318   if (AsyncDeflationInterval > 0 &&
1319       time_since_last > AsyncDeflationInterval &&
1320       monitors_used_above_threshold(&_in_use_list)) {
1321     // It's been longer than our specified deflate interval and there
1322     // are too many monitors in use. We don't deflate more frequently
1323     // than AsyncDeflationInterval (unless is_async_deflation_requested)
1324     // in order to not swamp the MonitorDeflationThread.
1325     log_info(monitorinflation)("Async deflation needed: monitors used are above the threshold");
1326     return true;
1327   }
1328 
1329   if (GuaranteedAsyncDeflationInterval > 0 &&
1330       time_since_last > GuaranteedAsyncDeflationInterval) {
1331     // It's been longer than our specified guaranteed deflate interval.
1332     // We need to clean up the used monitors even if the threshold is
1333     // not reached, to keep the memory utilization at bay when many threads
1334     // touched many monitors.
1335     log_info(monitorinflation)("Async deflation needed: guaranteed interval (" INTX_FORMAT " ms) "
1336                                "is greater than time since last deflation (" JLONG_FORMAT " ms)",
1337                                GuaranteedAsyncDeflationInterval, time_since_last);
1338 
1339     // If this deflation has no progress, then it should not affect the no-progress
1340     // tracking, otherwise threshold heuristics would think it was triggered, experienced
1341     // no progress, and needs to backoff more aggressively. In this "no progress" case,
1342     // the generic code would bump the no-progress counter, and we compensate for that
1343     // by telling it to skip the update.
1344     //
1345     // If this deflation has progress, then it should let non-progress tracking
1346     // know about this, otherwise the threshold heuristics would kick in, potentially
1347     // experience no-progress due to aggressive cleanup by this deflation, and think
1348     // it is still in no-progress stride. In this "progress" case, the generic code would
1349     // zero the counter, and we allow it to happen.
1350     _no_progress_skip_increment = true;
1351 
1352     return true;
1353   }
1354 
1355   return false;
1356 }
1357 
1358 void ObjectSynchronizer::request_deflate_idle_monitors() {
1359   MonitorLocker ml(MonitorDeflation_lock, Mutex::_no_safepoint_check_flag);
1360   set_is_async_deflation_requested(true);
1361   ml.notify_all();
1362 }
1363 
1364 bool ObjectSynchronizer::request_deflate_idle_monitors_from_wb() {
1365   JavaThread* current = JavaThread::current();
1366   bool ret_code = false;
1367 
1368   jlong last_time = last_async_deflation_time_ns();
1369 
1370   request_deflate_idle_monitors();
1371 
1372   const int N_CHECKS = 5;
1373   for (int i = 0; i < N_CHECKS; i++) {  // sleep for at most 5 seconds
1374     if (last_async_deflation_time_ns() > last_time) {
1375       log_info(monitorinflation)("Async Deflation happened after %d check(s).", i);
1376       ret_code = true;
1377       break;
1378     }
1379     {
1380       // JavaThread has to honor the blocking protocol.
1381       ThreadBlockInVM tbivm(current);
1382       os::naked_short_sleep(999);  // sleep for almost 1 second
1383     }
1384   }
1385   if (!ret_code) {
1386     log_info(monitorinflation)("Async Deflation DID NOT happen after %d checks.", N_CHECKS);
1387   }
1388 
1389   return ret_code;
1390 }
1391 
1392 jlong ObjectSynchronizer::time_since_last_async_deflation_ms() {
1393   return (os::javaTimeNanos() - last_async_deflation_time_ns()) / (NANOUNITS / MILLIUNITS);
1394 }
1395 
1396 static void post_monitor_inflate_event(EventJavaMonitorInflate* event,
1397                                        const oop obj,
1398                                        ObjectSynchronizer::InflateCause cause) {
1399   assert(event != nullptr, "invariant");
1400   event->set_monitorClass(obj->klass());
1401   event->set_address((uintptr_t)(void*)obj);
1402   event->set_cause((u1)cause);
1403   event->commit();
1404 }
1405 
1406 // Fast path code shared by multiple functions
1407 void ObjectSynchronizer::inflate_helper(oop obj) {
1408   if (LockingMode == LM_LIGHTWEIGHT) {
1409     return;
1410   }
1411   markWord mark = obj->mark_acquire();
1412   if (mark.has_monitor()) {
1413     ObjectMonitor* monitor = read_monitor(mark);
1414     markWord dmw = monitor->header();
1415     assert(dmw.is_neutral(), "sanity check: header=" INTPTR_FORMAT, dmw.value());
1416     return;
1417   }
1418   (void)inflate(Thread::current(), obj, inflate_cause_vm_internal);
1419 }
1420 
1421 ObjectMonitor* ObjectSynchronizer::inflate(Thread* current, oop obj, const InflateCause cause) {
1422   assert(current == Thread::current(), "must be");
1423   if (LockingMode == LM_LIGHTWEIGHT) {
1424     return LightweightSynchronizer::inflate_into_object_header(current, nullptr, obj, cause);
1425   } else {
1426     return inflate_impl(obj, cause);
1427   }

1428 }
1429 
1430 ObjectMonitor* ObjectSynchronizer::inflate_for(JavaThread* thread, oop obj, const InflateCause cause) {
1431   assert(thread == Thread::current() || thread->is_obj_deopt_suspend(), "must be");
1432   assert(LockingMode != LM_LIGHTWEIGHT, "LM_LIGHTWEIGHT cannot use inflate_for");
1433   return inflate_impl(obj, cause);
1434 }
1435 
1436 ObjectMonitor* ObjectSynchronizer::inflate_impl(oop object, const InflateCause cause) {
1437   assert(LockingMode != LM_LIGHTWEIGHT, "LM_LIGHTWEIGHT cannot use inflate_impl");






1438   EventJavaMonitorInflate event;
1439 
1440   for (;;) {
1441     const markWord mark = object->mark_acquire();
1442 
1443     // The mark can be in one of the following states:
1444     // *  inflated     - Just return it.






1445     // *  stack-locked - Coerce it to inflated from stack-locked.
1446     // *  INFLATING    - Busy wait for conversion from stack-locked to
1447     //                   inflated.
1448     // *  unlocked     - Aggressively inflate the object.
1449 
1450     // CASE: inflated
1451     if (mark.has_monitor()) {
1452       ObjectMonitor* inf = mark.monitor();
1453       markWord dmw = inf->header();
1454       assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value());






1455       return inf;
1456     }
1457 
1458     // CASE: inflation in progress - inflating over a stack-lock.
1459     // Some other thread is converting from stack-locked to inflated.
1460     // Only that thread can complete inflation -- other threads must wait.
1461     // The INFLATING value is transient.
1462     // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
1463     // We could always eliminate polling by parking the thread on some auxiliary list.
1464     if (mark == markWord::INFLATING()) {
1465       read_stable_mark(object);
1466       continue;
























































1467     }
1468 
1469     // CASE: stack-locked
1470     // Could be stack-locked either by current or by some other thread.
1471     //
1472     // Note that we allocate the ObjectMonitor speculatively, _before_ attempting
1473     // to install INFLATING into the mark word.  We originally installed INFLATING,
1474     // allocated the ObjectMonitor, and then finally STed the address of the
1475     // ObjectMonitor into the mark.  This was correct, but artificially lengthened
1476     // the interval in which INFLATING appeared in the mark, thus increasing
1477     // the odds of inflation contention. If we lose the race to set INFLATING,
1478     // then we just delete the ObjectMonitor and loop around again.
1479     //
1480     LogStreamHandle(Trace, monitorinflation) lsh;
1481     if (LockingMode == LM_LEGACY && mark.has_locker()) {

1482       ObjectMonitor* m = new ObjectMonitor(object);
1483       // Optimistically prepare the ObjectMonitor - anticipate successful CAS
1484       // We do this before the CAS in order to minimize the length of time
1485       // in which INFLATING appears in the mark.
1486 
1487       markWord cmp = object->cas_set_mark(markWord::INFLATING(), mark);
1488       if (cmp != mark) {
1489         delete m;
1490         continue;       // Interference -- just retry
1491       }
1492 
1493       // We've successfully installed INFLATING (0) into the mark-word.
1494       // This is the only case where 0 will appear in a mark-word.
1495       // Only the singular thread that successfully swings the mark-word
1496       // to 0 can perform (or more precisely, complete) inflation.
1497       //
1498       // Why do we CAS a 0 into the mark-word instead of just CASing the
1499       // mark-word from the stack-locked value directly to the new inflated state?
1500       // Consider what happens when a thread unlocks a stack-locked object.
1501       // It attempts to use CAS to swing the displaced header value from the
1502       // on-stack BasicLock back into the object header.  Recall also that the
1503       // header value (hash code, etc) can reside in (a) the object header, or
1504       // (b) a displaced header associated with the stack-lock, or (c) a displaced
1505       // header in an ObjectMonitor.  The inflate() routine must copy the header
1506       // value from the BasicLock on the owner's stack to the ObjectMonitor, all
1507       // the while preserving the hashCode stability invariants.  If the owner
1508       // decides to release the lock while the value is 0, the unlock will fail
1509       // and control will eventually pass from slow_exit() to inflate.  The owner
1510       // will then spin, waiting for the 0 value to disappear.   Put another way,
1511       // the 0 causes the owner to stall if the owner happens to try to
1512       // drop the lock (restoring the header from the BasicLock to the object)
1513       // while inflation is in-progress.  This protocol avoids races that might
1514       // would otherwise permit hashCode values to change or "flicker" for an object.
1515       // Critically, while object->mark is 0 mark.displaced_mark_helper() is stable.
1516       // 0 serves as a "BUSY" inflate-in-progress indicator.
1517 
1518 
1519       // fetch the displaced mark from the owner's stack.
1520       // The owner can't die or unwind past the lock while our INFLATING
1521       // object is in the mark.  Furthermore the owner can't complete
1522       // an unlock on the object, either.
1523       markWord dmw = mark.displaced_mark_helper();
1524       // Catch if the object's header is not neutral (not locked and
1525       // not marked is what we care about here).
1526       assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value());
1527 
1528       // Setup monitor fields to proper values -- prepare the monitor
1529       m->set_header(dmw);
1530 
1531       // Optimization: if the mark.locker stack address is associated
1532       // with this thread we could simply set m->_owner = current.
1533       // Note that a thread can inflate an object
1534       // that it has stack-locked -- as might happen in wait() -- directly
1535       // with CAS.  That is, we can avoid the xchg-nullptr .... ST idiom.
1536       m->set_owner_from(nullptr, mark.locker());
1537       // TODO-FIXME: assert BasicLock->dhw != 0.
1538 
1539       // Must preserve store ordering. The monitor state must
1540       // be stable at the time of publishing the monitor address.
1541       guarantee(object->mark() == markWord::INFLATING(), "invariant");
1542       // Release semantics so that above set_object() is seen first.
1543       object->release_set_mark(markWord::encode(m));
1544 
1545       // Once ObjectMonitor is configured and the object is associated
1546       // with the ObjectMonitor, it is safe to allow async deflation:
1547       _in_use_list.add(m);
1548 
1549       // Hopefully the performance counters are allocated on distinct cache lines
1550       // to avoid false sharing on MP systems ...
1551       OM_PERFDATA_OP(Inflations, inc());
1552       if (log_is_enabled(Trace, monitorinflation)) {
1553         ResourceMark rm;
1554         lsh.print_cr("inflate(has_locker): object=" INTPTR_FORMAT ", mark="
1555                      INTPTR_FORMAT ", type='%s'", p2i(object),
1556                      object->mark().value(), object->klass()->external_name());
1557       }
1558       if (event.should_commit()) {
1559         post_monitor_inflate_event(&event, object, cause);
1560       }
1561       return m;
1562     }
1563 
1564     // CASE: unlocked
1565     // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
1566     // If we know we're inflating for entry it's better to inflate by swinging a
1567     // pre-locked ObjectMonitor pointer into the object header.   A successful
1568     // CAS inflates the object *and* confers ownership to the inflating thread.
1569     // In the current implementation we use a 2-step mechanism where we CAS()
1570     // to inflate and then CAS() again to try to swing _owner from null to current.
1571     // An inflateTry() method that we could call from enter() would be useful.
1572 
1573     assert(mark.is_unlocked(), "invariant: header=" INTPTR_FORMAT, mark.value());
1574     ObjectMonitor* m = new ObjectMonitor(object);
1575     // prepare m for installation - set monitor to initial state
1576     m->set_header(mark);
1577 
1578     if (object->cas_set_mark(markWord::encode(m), mark) != mark) {
1579       delete m;
1580       m = nullptr;
1581       continue;
1582       // interference - the markword changed - just retry.
1583       // The state-transitions are one-way, so there's no chance of
1584       // live-lock -- "Inflated" is an absorbing state.
1585     }
1586 
1587     // Once the ObjectMonitor is configured and object is associated
1588     // with the ObjectMonitor, it is safe to allow async deflation:
1589     _in_use_list.add(m);
1590 
1591     // Hopefully the performance counters are allocated on distinct
1592     // cache lines to avoid false sharing on MP systems ...
1593     OM_PERFDATA_OP(Inflations, inc());
1594     if (log_is_enabled(Trace, monitorinflation)) {
1595       ResourceMark rm;
1596       lsh.print_cr("inflate(unlocked): object=" INTPTR_FORMAT ", mark="
1597                    INTPTR_FORMAT ", type='%s'", p2i(object),
1598                    object->mark().value(), object->klass()->external_name());
1599     }
1600     if (event.should_commit()) {
1601       post_monitor_inflate_event(&event, object, cause);
1602     }
1603     return m;
1604   }
1605 }
1606 
1607 // Walk the in-use list and deflate (at most MonitorDeflationMax) idle
1608 // ObjectMonitors. Returns the number of deflated ObjectMonitors.
1609 //
1610 size_t ObjectSynchronizer::deflate_monitor_list(ObjectMonitorDeflationSafepointer* safepointer) {
1611   MonitorList::Iterator iter = _in_use_list.iterator();
1612   size_t deflated_count = 0;
1613   Thread* current = Thread::current();
1614 
1615   while (iter.has_next()) {
1616     if (deflated_count >= (size_t)MonitorDeflationMax) {
1617       break;
1618     }
1619     ObjectMonitor* mid = iter.next();
1620     if (mid->deflate_monitor(current)) {
1621       deflated_count++;
1622     }
1623 
1624     // Must check for a safepoint/handshake and honor it.
1625     safepointer->block_for_safepoint("deflation", "deflated_count", deflated_count);
1626   }
1627 
1628   return deflated_count;
1629 }
1630 
1631 class HandshakeForDeflation : public HandshakeClosure {
1632  public:
1633   HandshakeForDeflation() : HandshakeClosure("HandshakeForDeflation") {}
1634 
1635   void do_thread(Thread* thread) {
1636     log_trace(monitorinflation)("HandshakeForDeflation::do_thread: thread="
1637                                 INTPTR_FORMAT, p2i(thread));
1638     if (thread->is_Java_thread()) {
1639       // Clear OM cache
1640       JavaThread* jt = JavaThread::cast(thread);
1641       jt->om_clear_monitor_cache();
1642     }
1643   }
1644 };
1645 
1646 class VM_RendezvousGCThreads : public VM_Operation {
1647 public:
1648   bool evaluate_at_safepoint() const override { return false; }
1649   VMOp_Type type() const override { return VMOp_RendezvousGCThreads; }
1650   void doit() override {
1651     Universe::heap()->safepoint_synchronize_begin();
1652     Universe::heap()->safepoint_synchronize_end();
1653   };
1654 };
1655 
1656 static size_t delete_monitors(GrowableArray<ObjectMonitor*>* delete_list,
1657                               ObjectMonitorDeflationSafepointer* safepointer) {
1658   NativeHeapTrimmer::SuspendMark sm("monitor deletion");
1659   size_t deleted_count = 0;
1660   for (ObjectMonitor* monitor: *delete_list) {
1661     delete monitor;
1662     deleted_count++;
1663     // A JavaThread must check for a safepoint/handshake and honor it.
1664     safepointer->block_for_safepoint("deletion", "deleted_count", deleted_count);
1665   }
1666   return deleted_count;
1667 }
1668 
1669 class ObjectMonitorDeflationLogging: public StackObj {
1670   LogStreamHandle(Debug, monitorinflation) _debug;
1671   LogStreamHandle(Info, monitorinflation)  _info;
1672   LogStream*                               _stream;
1673   elapsedTimer                             _timer;
1674 
1675   size_t ceiling() const { return ObjectSynchronizer::in_use_list_ceiling(); }
1676   size_t count() const   { return ObjectSynchronizer::_in_use_list.count(); }
1677   size_t max() const     { return ObjectSynchronizer::_in_use_list.max(); }
1678 
1679 public:
1680   ObjectMonitorDeflationLogging()
1681     : _debug(), _info(), _stream(nullptr) {
1682     if (_debug.is_enabled()) {
1683       _stream = &_debug;
1684     } else if (_info.is_enabled()) {
1685       _stream = &_info;
1686     }
1687   }
1688 
1689   void begin() {
1690     if (_stream != nullptr) {
1691       _stream->print_cr("begin deflating: in_use_list stats: ceiling=" SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT,
1692                         ceiling(), count(), max());
1693       _timer.start();
1694     }
1695   }
1696 
1697   void before_handshake(size_t unlinked_count) {
1698     if (_stream != nullptr) {
1699       _timer.stop();
1700       _stream->print_cr("before handshaking: unlinked_count=" SIZE_FORMAT
1701                         ", in_use_list stats: ceiling=" SIZE_FORMAT ", count="
1702                         SIZE_FORMAT ", max=" SIZE_FORMAT,
1703                         unlinked_count, ceiling(), count(), max());
1704     }
1705   }
1706 
1707   void after_handshake() {
1708     if (_stream != nullptr) {
1709       _stream->print_cr("after handshaking: in_use_list stats: ceiling="
1710                         SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT,
1711                         ceiling(), count(), max());
1712       _timer.start();
1713     }
1714   }
1715 
1716   void end(size_t deflated_count, size_t unlinked_count) {
1717     if (_stream != nullptr) {
1718       _timer.stop();
1719       if (deflated_count != 0 || unlinked_count != 0 || _debug.is_enabled()) {
1720         _stream->print_cr("deflated_count=" SIZE_FORMAT ", {unlinked,deleted}_count=" SIZE_FORMAT " monitors in %3.7f secs",
1721                           deflated_count, unlinked_count, _timer.seconds());
1722       }
1723       _stream->print_cr("end deflating: in_use_list stats: ceiling=" SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT,
1724                         ceiling(), count(), max());
1725     }
1726   }
1727 
1728   void before_block_for_safepoint(const char* op_name, const char* cnt_name, size_t cnt) {
1729     if (_stream != nullptr) {
1730       _timer.stop();
1731       _stream->print_cr("pausing %s: %s=" SIZE_FORMAT ", in_use_list stats: ceiling="
1732                         SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT,
1733                         op_name, cnt_name, cnt, ceiling(), count(), max());
1734     }
1735   }
1736 
1737   void after_block_for_safepoint(const char* op_name) {
1738     if (_stream != nullptr) {
1739       _stream->print_cr("resuming %s: in_use_list stats: ceiling=" SIZE_FORMAT
1740                         ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT, op_name,
1741                         ceiling(), count(), max());
1742       _timer.start();
1743     }
1744   }
1745 };
1746 
1747 void ObjectMonitorDeflationSafepointer::block_for_safepoint(const char* op_name, const char* count_name, size_t counter) {
1748   if (!SafepointMechanism::should_process(_current)) {
1749     return;
1750   }
1751 
1752   // A safepoint/handshake has started.
1753   _log->before_block_for_safepoint(op_name, count_name, counter);
1754 
1755   {
1756     // Honor block request.
1757     ThreadBlockInVM tbivm(_current);
1758   }
1759 
1760   _log->after_block_for_safepoint(op_name);
1761 }
1762 
1763 // This function is called by the MonitorDeflationThread to deflate
1764 // ObjectMonitors.
1765 size_t ObjectSynchronizer::deflate_idle_monitors() {
1766   JavaThread* current = JavaThread::current();
1767   assert(current->is_monitor_deflation_thread(), "The only monitor deflater");
1768 
1769   // The async deflation request has been processed.
1770   _last_async_deflation_time_ns = os::javaTimeNanos();
1771   set_is_async_deflation_requested(false);
1772 
1773   ObjectMonitorDeflationLogging log;
1774   ObjectMonitorDeflationSafepointer safepointer(current, &log);
1775 
1776   log.begin();
1777 
1778   // Deflate some idle ObjectMonitors.
1779   size_t deflated_count = deflate_monitor_list(&safepointer);
1780 
1781   // Unlink the deflated ObjectMonitors from the in-use list.
1782   size_t unlinked_count = 0;
1783   size_t deleted_count = 0;
1784   if (deflated_count > 0) {
1785     ResourceMark rm(current);
1786     GrowableArray<ObjectMonitor*> delete_list((int)deflated_count);
1787     unlinked_count = _in_use_list.unlink_deflated(deflated_count, &delete_list, &safepointer);
1788 
1789 #ifdef ASSERT
1790     if (UseObjectMonitorTable) {
1791       for (ObjectMonitor* monitor : delete_list) {
1792         assert(!LightweightSynchronizer::contains_monitor(current, monitor), "Should have been removed");
1793       }
1794     }
1795 #endif
1796 
1797     log.before_handshake(unlinked_count);
1798 
1799     // A JavaThread needs to handshake in order to safely free the
1800     // ObjectMonitors that were deflated in this cycle.
1801     HandshakeForDeflation hfd_hc;
1802     Handshake::execute(&hfd_hc);
1803     // Also, we sync and desync GC threads around the handshake, so that they can
1804     // safely read the mark-word and look-through to the object-monitor, without
1805     // being afraid that the object-monitor is going away.
1806     VM_RendezvousGCThreads sync_gc;
1807     VMThread::execute(&sync_gc);
1808 
1809     log.after_handshake();
1810 
1811     // After the handshake, safely free the ObjectMonitors that were
1812     // deflated and unlinked in this cycle.
1813 
1814     // Delete the unlinked ObjectMonitors.
1815     deleted_count = delete_monitors(&delete_list, &safepointer);
1816     assert(unlinked_count == deleted_count, "must be");
1817   }
1818 
1819   log.end(deflated_count, unlinked_count);
1820 
1821   OM_PERFDATA_OP(MonExtant, set_value(_in_use_list.count()));
1822   OM_PERFDATA_OP(Deflations, inc(deflated_count));
1823 
1824   GVars.stw_random = os::random();
1825 
1826   if (deflated_count != 0) {
1827     _no_progress_cnt = 0;
1828   } else if (_no_progress_skip_increment) {
1829     _no_progress_skip_increment = false;
1830   } else {
1831     _no_progress_cnt++;
1832   }
1833 
1834   return deflated_count;
1835 }
1836 
1837 // Monitor cleanup on JavaThread::exit
1838 
1839 // Iterate through monitor cache and attempt to release thread's monitors
1840 class ReleaseJavaMonitorsClosure: public MonitorClosure {
1841  private:
1842   JavaThread* _thread;
1843 
1844  public:
1845   ReleaseJavaMonitorsClosure(JavaThread* thread) : _thread(thread) {}
1846   void do_monitor(ObjectMonitor* mid) {
1847     intx rec = mid->complete_exit(_thread);
1848     _thread->dec_held_monitor_count(rec + 1);
1849   }
1850 };
1851 
1852 // Release all inflated monitors owned by current thread.  Lightweight monitors are
1853 // ignored.  This is meant to be called during JNI thread detach which assumes
1854 // all remaining monitors are heavyweight.  All exceptions are swallowed.
1855 // Scanning the extant monitor list can be time consuming.
1856 // A simple optimization is to add a per-thread flag that indicates a thread
1857 // called jni_monitorenter() during its lifetime.
1858 //
1859 // Instead of NoSafepointVerifier it might be cheaper to
1860 // use an idiom of the form:
1861 //   auto int tmp = SafepointSynchronize::_safepoint_counter ;
1862 //   <code that must not run at safepoint>
1863 //   guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ;
1864 // Since the tests are extremely cheap we could leave them enabled
1865 // for normal product builds.
1866 
1867 void ObjectSynchronizer::release_monitors_owned_by_thread(JavaThread* current) {
1868   assert(current == JavaThread::current(), "must be current Java thread");
1869   NoSafepointVerifier nsv;
1870   ReleaseJavaMonitorsClosure rjmc(current);
1871   ObjectSynchronizer::owned_monitors_iterate(&rjmc, current);
1872   assert(!current->has_pending_exception(), "Should not be possible");
1873   current->clear_pending_exception();
1874   assert(current->held_monitor_count() == 0, "Should not be possible");
1875   // All monitors (including entered via JNI) have been unlocked above, so we need to clear jni count.
1876   current->clear_jni_monitor_count();
1877 }
1878 
1879 const char* ObjectSynchronizer::inflate_cause_name(const InflateCause cause) {
1880   switch (cause) {
1881     case inflate_cause_vm_internal:    return "VM Internal";
1882     case inflate_cause_monitor_enter:  return "Monitor Enter";
1883     case inflate_cause_wait:           return "Monitor Wait";
1884     case inflate_cause_notify:         return "Monitor Notify";
1885     case inflate_cause_hash_code:      return "Monitor Hash Code";
1886     case inflate_cause_jni_enter:      return "JNI Monitor Enter";
1887     case inflate_cause_jni_exit:       return "JNI Monitor Exit";
1888     default:
1889       ShouldNotReachHere();
1890   }
1891   return "Unknown";
1892 }
1893 
1894 //------------------------------------------------------------------------------
1895 // Debugging code
1896 
1897 u_char* ObjectSynchronizer::get_gvars_addr() {
1898   return (u_char*)&GVars;
1899 }
1900 
1901 u_char* ObjectSynchronizer::get_gvars_hc_sequence_addr() {
1902   return (u_char*)&GVars.hc_sequence;
1903 }
1904 
1905 size_t ObjectSynchronizer::get_gvars_size() {
1906   return sizeof(SharedGlobals);
1907 }
1908 
1909 u_char* ObjectSynchronizer::get_gvars_stw_random_addr() {
1910   return (u_char*)&GVars.stw_random;
1911 }
1912 
1913 // Do the final audit and print of ObjectMonitor stats; must be done
1914 // by the VMThread at VM exit time.
1915 void ObjectSynchronizer::do_final_audit_and_print_stats() {
1916   assert(Thread::current()->is_VM_thread(), "sanity check");
1917 
1918   if (is_final_audit()) {  // Only do the audit once.
1919     return;
1920   }
1921   set_is_final_audit();
1922   log_info(monitorinflation)("Starting the final audit.");
1923 
1924   if (log_is_enabled(Info, monitorinflation)) {
1925     LogStreamHandle(Info, monitorinflation) ls;
1926     audit_and_print_stats(&ls, true /* on_exit */);
1927   }
1928 }
1929 
1930 // This function can be called by the MonitorDeflationThread or it can be called when
1931 // we are trying to exit the VM. The list walker functions can run in parallel with
1932 // the other list operations.
1933 // Calls to this function can be added in various places as a debugging
1934 // aid.
1935 //
1936 void ObjectSynchronizer::audit_and_print_stats(outputStream* ls, bool on_exit) {
1937   int error_cnt = 0;
1938 
1939   ls->print_cr("Checking in_use_list:");
1940   chk_in_use_list(ls, &error_cnt);
1941 
1942   if (error_cnt == 0) {
1943     ls->print_cr("No errors found in in_use_list checks.");
1944   } else {
1945     log_error(monitorinflation)("found in_use_list errors: error_cnt=%d", error_cnt);
1946   }
1947 
1948   // When exiting, only log the interesting entries at the Info level.
1949   // When called at intervals by the MonitorDeflationThread, log output
1950   // at the Trace level since there can be a lot of it.
1951   if (!on_exit && log_is_enabled(Trace, monitorinflation)) {
1952     LogStreamHandle(Trace, monitorinflation) ls_tr;
1953     log_in_use_monitor_details(&ls_tr, true /* log_all */);
1954   } else if (on_exit) {
1955     log_in_use_monitor_details(ls, false /* log_all */);
1956   }
1957 
1958   ls->flush();
1959 
1960   guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt);
1961 }
1962 
1963 // Check the in_use_list; log the results of the checks.
1964 void ObjectSynchronizer::chk_in_use_list(outputStream* out, int *error_cnt_p) {
1965   size_t l_in_use_count = _in_use_list.count();
1966   size_t l_in_use_max = _in_use_list.max();
1967   out->print_cr("count=" SIZE_FORMAT ", max=" SIZE_FORMAT, l_in_use_count,
1968                 l_in_use_max);
1969 
1970   size_t ck_in_use_count = 0;
1971   MonitorList::Iterator iter = _in_use_list.iterator();
1972   while (iter.has_next()) {
1973     ObjectMonitor* mid = iter.next();
1974     chk_in_use_entry(mid, out, error_cnt_p);
1975     ck_in_use_count++;
1976   }
1977 
1978   if (l_in_use_count == ck_in_use_count) {
1979     out->print_cr("in_use_count=" SIZE_FORMAT " equals ck_in_use_count="
1980                   SIZE_FORMAT, l_in_use_count, ck_in_use_count);
1981   } else {
1982     out->print_cr("WARNING: in_use_count=" SIZE_FORMAT " is not equal to "
1983                   "ck_in_use_count=" SIZE_FORMAT, l_in_use_count,
1984                   ck_in_use_count);
1985   }
1986 
1987   size_t ck_in_use_max = _in_use_list.max();
1988   if (l_in_use_max == ck_in_use_max) {
1989     out->print_cr("in_use_max=" SIZE_FORMAT " equals ck_in_use_max="
1990                   SIZE_FORMAT, l_in_use_max, ck_in_use_max);
1991   } else {
1992     out->print_cr("WARNING: in_use_max=" SIZE_FORMAT " is not equal to "
1993                   "ck_in_use_max=" SIZE_FORMAT, l_in_use_max, ck_in_use_max);
1994   }
1995 }
1996 
1997 // Check an in-use monitor entry; log any errors.
1998 void ObjectSynchronizer::chk_in_use_entry(ObjectMonitor* n, outputStream* out,
1999                                           int* error_cnt_p) {
2000   if (n->owner_is_DEFLATER_MARKER()) {
2001     // This could happen when monitor deflation blocks for a safepoint.
2002     return;
2003   }
2004 
2005 
2006   if (n->metadata() == 0) {
2007     out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor must "
2008                   "have non-null _metadata (header/hash) field.", p2i(n));
2009     *error_cnt_p = *error_cnt_p + 1;
2010   }
2011 
2012   const oop obj = n->object_peek();
2013   if (obj == nullptr) {
2014     return;
2015   }
2016 
2017   const markWord mark = obj->mark();
2018   if (!mark.has_monitor()) {
2019     out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's "
2020                   "object does not think it has a monitor: obj="
2021                   INTPTR_FORMAT ", mark=" INTPTR_FORMAT, p2i(n),
2022                   p2i(obj), mark.value());
2023     *error_cnt_p = *error_cnt_p + 1;
2024     return;
2025   }
2026 
2027   ObjectMonitor* const obj_mon = read_monitor(Thread::current(), obj, mark);
2028   if (n != obj_mon) {
2029     out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's "
2030                   "object does not refer to the same monitor: obj="
2031                   INTPTR_FORMAT ", mark=" INTPTR_FORMAT ", obj_mon="
2032                   INTPTR_FORMAT, p2i(n), p2i(obj), mark.value(), p2i(obj_mon));
2033     *error_cnt_p = *error_cnt_p + 1;
2034   }
2035 }
2036 
2037 // Log details about ObjectMonitors on the in_use_list. The 'BHL'
2038 // flags indicate why the entry is in-use, 'object' and 'object type'
2039 // indicate the associated object and its type.
2040 void ObjectSynchronizer::log_in_use_monitor_details(outputStream* out, bool log_all) {
2041   if (_in_use_list.count() > 0) {
2042     stringStream ss;
2043     out->print_cr("In-use monitor info:");
2044     out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
2045     out->print_cr("%18s  %s  %18s  %18s",
2046                   "monitor", "BHL", "object", "object type");
2047     out->print_cr("==================  ===  ==================  ==================");
2048 
2049     auto is_interesting = [&](ObjectMonitor* monitor) {
2050       return log_all || monitor->has_owner() || monitor->is_busy();
2051     };
2052 
2053     monitors_iterate([&](ObjectMonitor* monitor) {
2054       if (is_interesting(monitor)) {
2055         const oop obj = monitor->object_peek();
2056         const intptr_t hash = UseObjectMonitorTable ? monitor->hash() : monitor->header().hash();
2057         ResourceMark rm;
2058         out->print(INTPTR_FORMAT "  %d%d%d  " INTPTR_FORMAT "  %s", p2i(monitor),
2059                    monitor->is_busy(), hash != 0, monitor->owner() != nullptr,
2060                    p2i(obj), obj == nullptr ? "" : obj->klass()->external_name());
2061         if (monitor->is_busy()) {
2062           out->print(" (%s)", monitor->is_busy_to_string(&ss));
2063           ss.reset();
2064         }
2065         out->cr();
2066       }
2067     });
2068   }
2069 
2070   out->flush();
2071 }
--- EOF ---