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