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