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