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