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