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