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