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