1 /*
   2  * Copyright (c) 1998, 2019, 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 "logging/log.hpp"
  28 #include "logging/logStream.hpp"
  29 #include "jfr/jfrEvents.hpp"
  30 #include "memory/allocation.inline.hpp"
  31 #include "memory/metaspaceShared.hpp"
  32 #include "memory/padded.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "memory/universe.hpp"
  35 #include "oops/markOop.hpp"
  36 #include "oops/oop.inline.hpp"
  37 #include "runtime/atomic.hpp"
  38 #include "runtime/biasedLocking.hpp"
  39 #include "runtime/handles.inline.hpp"
  40 #include "runtime/interfaceSupport.inline.hpp"
  41 #include "runtime/mutexLocker.hpp"
  42 #include "runtime/objectMonitor.hpp"
  43 #include "runtime/objectMonitor.inline.hpp"
  44 #include "runtime/osThread.hpp"
  45 #include "runtime/safepointVerifiers.hpp"
  46 #include "runtime/sharedRuntime.hpp"
  47 #include "runtime/stubRoutines.hpp"
  48 #include "runtime/synchronizer.hpp"
  49 #include "runtime/thread.inline.hpp"
  50 #include "runtime/timer.hpp"
  51 #include "runtime/vframe.hpp"
  52 #include "runtime/vmThread.hpp"
  53 #include "utilities/align.hpp"
  54 #include "utilities/dtrace.hpp"
  55 #include "utilities/events.hpp"
  56 #include "utilities/preserveException.hpp"
  57 
  58 // The "core" versions of monitor enter and exit reside in this file.
  59 // The interpreter and compilers contain specialized transliterated
  60 // variants of the enter-exit fast-path operations.  See i486.ad fast_lock(),
  61 // for instance.  If you make changes here, make sure to modify the
  62 // interpreter, and both C1 and C2 fast-path inline locking code emission.
  63 //
  64 // -----------------------------------------------------------------------------
  65 
  66 #ifdef DTRACE_ENABLED
  67 
  68 // Only bother with this argument setup if dtrace is available
  69 // TODO-FIXME: probes should not fire when caller is _blocked.  assert() accordingly.
  70 
  71 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread)                           \
  72   char* bytes = NULL;                                                      \
  73   int len = 0;                                                             \
  74   jlong jtid = SharedRuntime::get_java_tid(thread);                        \
  75   Symbol* klassname = ((oop)(obj))->klass()->name();                       \
  76   if (klassname != NULL) {                                                 \
  77     bytes = (char*)klassname->bytes();                                     \
  78     len = klassname->utf8_length();                                        \
  79   }
  80 
  81 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis)            \
  82   {                                                                        \
  83     if (DTraceMonitorProbes) {                                             \
  84       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
  85       HOTSPOT_MONITOR_WAIT(jtid,                                           \
  86                            (uintptr_t)(monitor), bytes, len, (millis));    \
  87     }                                                                      \
  88   }
  89 
  90 #define HOTSPOT_MONITOR_PROBE_notify HOTSPOT_MONITOR_NOTIFY
  91 #define HOTSPOT_MONITOR_PROBE_notifyAll HOTSPOT_MONITOR_NOTIFYALL
  92 #define HOTSPOT_MONITOR_PROBE_waited HOTSPOT_MONITOR_WAITED
  93 
  94 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread)                  \
  95   {                                                                        \
  96     if (DTraceMonitorProbes) {                                             \
  97       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
  98       HOTSPOT_MONITOR_PROBE_##probe(jtid, /* probe = waited */             \
  99                                     (uintptr_t)(monitor), bytes, len);     \
 100     }                                                                      \
 101   }
 102 
 103 #else //  ndef DTRACE_ENABLED
 104 
 105 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon)    {;}
 106 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon)          {;}
 107 
 108 #endif // ndef DTRACE_ENABLED
 109 
 110 // This exists only as a workaround of dtrace bug 6254741
 111 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) {
 112   DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
 113   return 0;
 114 }
 115 
 116 #define NINFLATIONLOCKS 256
 117 static volatile intptr_t gInflationLocks[NINFLATIONLOCKS];
 118 
 119 // global list of blocks of monitors
 120 PaddedEnd<ObjectMonitor> * volatile ObjectSynchronizer::gBlockList = NULL;
 121 // global monitor free list
 122 ObjectMonitor * volatile ObjectSynchronizer::gFreeList  = NULL;
 123 // global monitor in-use list, for moribund threads,
 124 // monitors they inflated need to be scanned for deflation
 125 ObjectMonitor * volatile ObjectSynchronizer::gOmInUseList  = NULL;
 126 // count of entries in gOmInUseList
 127 int ObjectSynchronizer::gOmInUseCount = 0;
 128 
 129 static volatile intptr_t gListLock = 0;      // protects global monitor lists
 130 static volatile int gMonitorFreeCount  = 0;  // # on gFreeList
 131 static volatile int gMonitorPopulation = 0;  // # Extant -- in circulation
 132 
 133 #define CHECK_THROW_NOSYNC_IMSE(obj)  \
 134   if ((obj)->mark()->is_always_locked()) {  \
 135     ResourceMark rm(THREAD);                \
 136     THROW_MSG(vmSymbols::java_lang_IllegalMonitorStateException(), obj->klass()->external_name()); \
 137   }
 138 
 139 #define CHECK_THROW_NOSYNC_IMSE_0(obj)  \
 140     if ((obj)->mark()->is_always_locked()) {  \
 141     ResourceMark rm(THREAD);                  \
 142     THROW_MSG_0(vmSymbols::java_lang_IllegalMonitorStateException(), obj->klass()->external_name()); \
 143   }
 144 
 145 
 146 #define CHAINMARKER (cast_to_oop<intptr_t>(-1))
 147 
 148 
 149 // =====================> Quick functions
 150 
 151 // The quick_* forms are special fast-path variants used to improve
 152 // performance.  In the simplest case, a "quick_*" implementation could
 153 // simply return false, in which case the caller will perform the necessary
 154 // state transitions and call the slow-path form.
 155 // The fast-path is designed to handle frequently arising cases in an efficient
 156 // manner and is just a degenerate "optimistic" variant of the slow-path.
 157 // returns true  -- to indicate the call was satisfied.
 158 // returns false -- to indicate the call needs the services of the slow-path.
 159 // A no-loitering ordinance is in effect for code in the quick_* family
 160 // operators: safepoints or indefinite blocking (blocking that might span a
 161 // safepoint) are forbidden. Generally the thread_state() is _in_Java upon
 162 // entry.
 163 //
 164 // Consider: An interesting optimization is to have the JIT recognize the
 165 // following common idiom:
 166 //   synchronized (someobj) { .... ; notify(); }
 167 // That is, we find a notify() or notifyAll() call that immediately precedes
 168 // the monitorexit operation.  In that case the JIT could fuse the operations
 169 // into a single notifyAndExit() runtime primitive.
 170 
 171 bool ObjectSynchronizer::quick_notify(oopDesc * obj, Thread * self, bool all) {
 172   assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
 173   assert(self->is_Java_thread(), "invariant");
 174   assert(((JavaThread *) self)->thread_state() == _thread_in_Java, "invariant");
 175   NoSafepointVerifier nsv;
 176   if (obj == NULL) return false;  // slow-path for invalid obj
 177   assert(!EnableValhalla || !obj->klass()->is_value(), "monitor op on value type");
 178   const markOop mark = obj->mark();
 179 
 180   if (mark->has_locker() && self->is_lock_owned((address)mark->locker())) {
 181     // Degenerate notify
 182     // stack-locked by caller so by definition the implied waitset is empty.
 183     return true;
 184   }
 185 
 186   if (mark->has_monitor()) {
 187     ObjectMonitor * const mon = mark->monitor();
 188     assert(oopDesc::equals((oop) mon->object(), obj), "invariant");
 189     if (mon->owner() != self) return false;  // slow-path for IMS exception
 190 
 191     if (mon->first_waiter() != NULL) {
 192       // We have one or more waiters. Since this is an inflated monitor
 193       // that we own, we can transfer one or more threads from the waitset
 194       // to the entrylist here and now, avoiding the slow-path.
 195       if (all) {
 196         DTRACE_MONITOR_PROBE(notifyAll, mon, obj, self);
 197       } else {
 198         DTRACE_MONITOR_PROBE(notify, mon, obj, self);
 199       }
 200       int tally = 0;
 201       do {
 202         mon->INotify(self);
 203         ++tally;
 204       } while (mon->first_waiter() != NULL && all);
 205       OM_PERFDATA_OP(Notifications, inc(tally));
 206     }
 207     return true;
 208   }
 209 
 210   // biased locking and any other IMS exception states take the slow-path
 211   return false;
 212 }
 213 
 214 
 215 // The LockNode emitted directly at the synchronization site would have
 216 // been too big if it were to have included support for the cases of inflated
 217 // recursive enter and exit, so they go here instead.
 218 // Note that we can't safely call AsyncPrintJavaStack() from within
 219 // quick_enter() as our thread state remains _in_Java.
 220 
 221 bool ObjectSynchronizer::quick_enter(oop obj, Thread * Self,
 222                                      BasicLock * lock) {
 223   assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
 224   assert(Self->is_Java_thread(), "invariant");
 225   assert(((JavaThread *) Self)->thread_state() == _thread_in_Java, "invariant");
 226   NoSafepointVerifier nsv;
 227   if (obj == NULL) return false;       // Need to throw NPE
 228   assert(!EnableValhalla || !obj->klass()->is_value(), "monitor op on value type");
 229   const markOop mark = obj->mark();
 230 
 231   if (mark->has_monitor()) {
 232     ObjectMonitor * const m = mark->monitor();
 233     assert(oopDesc::equals((oop) m->object(), obj), "invariant");
 234     Thread * const owner = (Thread *) m->_owner;
 235 
 236     // Lock contention and Transactional Lock Elision (TLE) diagnostics
 237     // and observability
 238     // Case: light contention possibly amenable to TLE
 239     // Case: TLE inimical operations such as nested/recursive synchronization
 240 
 241     if (owner == Self) {
 242       m->_recursions++;
 243       return true;
 244     }
 245 
 246     // This Java Monitor is inflated so obj's header will never be
 247     // displaced to this thread's BasicLock. Make the displaced header
 248     // non-NULL so this BasicLock is not seen as recursive nor as
 249     // being locked. We do this unconditionally so that this thread's
 250     // BasicLock cannot be mis-interpreted by any stack walkers. For
 251     // performance reasons, stack walkers generally first check for
 252     // Biased Locking in the object's header, the second check is for
 253     // stack-locking in the object's header, the third check is for
 254     // recursive stack-locking in the displaced header in the BasicLock,
 255     // and last are the inflated Java Monitor (ObjectMonitor) checks.
 256     lock->set_displaced_header(markOopDesc::unused_mark());
 257 
 258     if (owner == NULL && Atomic::replace_if_null(Self, &(m->_owner))) {
 259       assert(m->_recursions == 0, "invariant");
 260       return true;
 261     }
 262   }
 263 
 264   // Note that we could inflate in quick_enter.
 265   // This is likely a useful optimization
 266   // Critically, in quick_enter() we must not:
 267   // -- perform bias revocation, or
 268   // -- block indefinitely, or
 269   // -- reach a safepoint
 270 
 271   return false;        // revert to slow-path
 272 }
 273 
 274 // -----------------------------------------------------------------------------
 275 //  Fast Monitor Enter/Exit
 276 // This the fast monitor enter. The interpreter and compiler use
 277 // some assembly copies of this code. Make sure update those code
 278 // if the following function is changed. The implementation is
 279 // extremely sensitive to race condition. Be careful.
 280 
 281 void ObjectSynchronizer::fast_enter(Handle obj, BasicLock* lock,
 282                                     bool attempt_rebias, TRAPS) {
 283   CHECK_THROW_NOSYNC_IMSE(obj);
 284   if (UseBiasedLocking) {
 285     if (!SafepointSynchronize::is_at_safepoint()) {
 286       BiasedLocking::Condition cond = BiasedLocking::revoke_and_rebias(obj, attempt_rebias, THREAD);
 287       if (cond == BiasedLocking::BIAS_REVOKED_AND_REBIASED) {
 288         return;
 289       }
 290     } else {
 291       assert(!attempt_rebias, "can not rebias toward VM thread");
 292       BiasedLocking::revoke_at_safepoint(obj);
 293     }
 294     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 295   }
 296 
 297   slow_enter(obj, lock, THREAD);
 298 }
 299 
 300 void ObjectSynchronizer::fast_exit(oop object, BasicLock* lock, TRAPS) {
 301   markOop mark = object->mark();
 302   if (EnableValhalla && mark->is_always_locked()) {
 303     return;
 304   }
 305   assert(!EnableValhalla || !object->klass()->is_value(), "monitor op on value type");
 306   // We cannot check for Biased Locking if we are racing an inflation.
 307   assert(mark == markOopDesc::INFLATING() ||
 308          !mark->has_bias_pattern(), "should not see bias pattern here");
 309 
 310   markOop dhw = lock->displaced_header();
 311   if (dhw == NULL) {
 312     // If the displaced header is NULL, then this exit matches up with
 313     // a recursive enter. No real work to do here except for diagnostics.
 314 #ifndef PRODUCT
 315     if (mark != markOopDesc::INFLATING()) {
 316       // Only do diagnostics if we are not racing an inflation. Simply
 317       // exiting a recursive enter of a Java Monitor that is being
 318       // inflated is safe; see the has_monitor() comment below.
 319       assert(!mark->is_neutral(), "invariant");
 320       assert(!mark->has_locker() ||
 321              THREAD->is_lock_owned((address)mark->locker()), "invariant");
 322       if (mark->has_monitor()) {
 323         // The BasicLock's displaced_header is marked as a recursive
 324         // enter and we have an inflated Java Monitor (ObjectMonitor).
 325         // This is a special case where the Java Monitor was inflated
 326         // after this thread entered the stack-lock recursively. When a
 327         // Java Monitor is inflated, we cannot safely walk the Java
 328         // Monitor owner's stack and update the BasicLocks because a
 329         // Java Monitor can be asynchronously inflated by a thread that
 330         // does not own the Java Monitor.
 331         ObjectMonitor * m = mark->monitor();
 332         assert(((oop)(m->object()))->mark() == mark, "invariant");
 333         assert(m->is_entered(THREAD), "invariant");
 334       }
 335     }
 336 #endif
 337     return;
 338   }
 339 
 340   if (mark == (markOop) lock) {
 341     // If the object is stack-locked by the current thread, try to
 342     // swing the displaced header from the BasicLock back to the mark.
 343     assert(dhw->is_neutral(), "invariant");
 344     if (object->cas_set_mark(dhw, mark) == mark) {
 345       return;
 346     }
 347   }
 348 
 349   // We have to take the slow-path of possible inflation and then exit.
 350   inflate(THREAD, object, inflate_cause_vm_internal)->exit(true, THREAD);
 351 }
 352 
 353 // -----------------------------------------------------------------------------
 354 // Interpreter/Compiler Slow Case
 355 // This routine is used to handle interpreter/compiler slow case
 356 // We don't need to use fast path here, because it must have been
 357 // failed in the interpreter/compiler code.
 358 void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) {
 359   CHECK_THROW_NOSYNC_IMSE(obj);
 360   markOop mark = obj->mark();
 361   assert(!mark->has_bias_pattern(), "should not see bias pattern here");
 362 
 363   if (mark->is_neutral()) {
 364     // Anticipate successful CAS -- the ST of the displaced mark must
 365     // be visible <= the ST performed by the CAS.
 366     lock->set_displaced_header(mark);
 367     if (mark == obj()->cas_set_mark((markOop) lock, mark)) {
 368       return;
 369     }
 370     // Fall through to inflate() ...
 371   } else if (mark->has_locker() &&
 372              THREAD->is_lock_owned((address)mark->locker())) {
 373     assert(lock != mark->locker(), "must not re-lock the same lock");
 374     assert(lock != (BasicLock*)obj->mark(), "don't relock with same BasicLock");
 375     lock->set_displaced_header(NULL);
 376     return;
 377   }
 378 
 379   // The object header will never be displaced to this lock,
 380   // so it does not matter what the value is, except that it
 381   // must be non-zero to avoid looking like a re-entrant lock,
 382   // and must not look locked either.
 383   lock->set_displaced_header(markOopDesc::unused_mark());
 384   inflate(THREAD, obj(), inflate_cause_monitor_enter)->enter(THREAD);
 385 }
 386 
 387 // This routine is used to handle interpreter/compiler slow case
 388 // We don't need to use fast path here, because it must have
 389 // failed in the interpreter/compiler code. Simply use the heavy
 390 // weight monitor should be ok, unless someone find otherwise.
 391 void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) {
 392   fast_exit(object, lock, THREAD);
 393 }
 394 
 395 // -----------------------------------------------------------------------------
 396 // Class Loader  support to workaround deadlocks on the class loader lock objects
 397 // Also used by GC
 398 // complete_exit()/reenter() are used to wait on a nested lock
 399 // i.e. to give up an outer lock completely and then re-enter
 400 // Used when holding nested locks - lock acquisition order: lock1 then lock2
 401 //  1) complete_exit lock1 - saving recursion count
 402 //  2) wait on lock2
 403 //  3) when notified on lock2, unlock lock2
 404 //  4) reenter lock1 with original recursion count
 405 //  5) lock lock2
 406 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 407 intptr_t ObjectSynchronizer::complete_exit(Handle obj, TRAPS) {
 408   assert(!EnableValhalla || !obj->klass()->is_value(), "monitor op on value type");
 409   if (UseBiasedLocking) {
 410     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 411     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 412   }
 413 
 414   ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_vm_internal);
 415 
 416   return monitor->complete_exit(THREAD);
 417 }
 418 
 419 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
 420 void ObjectSynchronizer::reenter(Handle obj, intptr_t recursion, TRAPS) {
 421   assert(!EnableValhalla || !obj->klass()->is_value(), "monitor op on value type");
 422   if (UseBiasedLocking) {
 423     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 424     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 425   }
 426 
 427   ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_vm_internal);
 428 
 429   monitor->reenter(recursion, THREAD);
 430 }
 431 // -----------------------------------------------------------------------------
 432 // JNI locks on java objects
 433 // NOTE: must use heavy weight monitor to handle jni monitor enter
 434 void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) {
 435   // the current locking is from JNI instead of Java code
 436   CHECK_THROW_NOSYNC_IMSE(obj);
 437   if (UseBiasedLocking) {
 438     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 439     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 440   }
 441   THREAD->set_current_pending_monitor_is_from_java(false);
 442   inflate(THREAD, obj(), inflate_cause_jni_enter)->enter(THREAD);
 443   THREAD->set_current_pending_monitor_is_from_java(true);
 444 }
 445 
 446 // NOTE: must use heavy weight monitor to handle jni monitor exit
 447 void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) {
 448   CHECK_THROW_NOSYNC_IMSE(obj);
 449   if (UseBiasedLocking) {
 450     Handle h_obj(THREAD, obj);
 451     BiasedLocking::revoke_and_rebias(h_obj, false, THREAD);
 452     obj = h_obj();
 453   }
 454   assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 455 
 456   ObjectMonitor* monitor = inflate(THREAD, obj, inflate_cause_jni_exit);
 457   // If this thread has locked the object, exit the monitor.  Note:  can't use
 458   // monitor->check(CHECK); must exit even if an exception is pending.
 459   if (monitor->check(THREAD)) {
 460     monitor->exit(true, THREAD);
 461   }
 462 }
 463 
 464 // -----------------------------------------------------------------------------
 465 // Internal VM locks on java objects
 466 // standard constructor, allows locking failures
 467 ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool doLock) {
 468   _dolock = doLock;
 469   _thread = thread;
 470   debug_only(if (StrictSafepointChecks) _thread->check_for_valid_safepoint_state(false);)
 471   _obj = obj;
 472 
 473   if (_dolock) {
 474     ObjectSynchronizer::fast_enter(_obj, &_lock, false, _thread);
 475   }
 476 }
 477 
 478 ObjectLocker::~ObjectLocker() {
 479   if (_dolock) {
 480     ObjectSynchronizer::fast_exit(_obj(), &_lock, _thread);
 481   }
 482 }
 483 
 484 
 485 // -----------------------------------------------------------------------------
 486 //  Wait/Notify/NotifyAll
 487 // NOTE: must use heavy weight monitor to handle wait()
 488 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
 489   CHECK_THROW_NOSYNC_IMSE_0(obj);
 490   if (UseBiasedLocking) {
 491     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 492     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 493   }
 494   if (millis < 0) {
 495     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 496   }
 497   ObjectMonitor* monitor = inflate(THREAD, obj(), inflate_cause_wait);
 498 
 499   DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis);
 500   monitor->wait(millis, true, THREAD);
 501 
 502   // This dummy call is in place to get around dtrace bug 6254741.  Once
 503   // that's fixed we can uncomment the following line, remove the call
 504   // and change this function back into a "void" func.
 505   // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
 506   return dtrace_waited_probe(monitor, obj, THREAD);
 507 }
 508 
 509 void ObjectSynchronizer::waitUninterruptibly(Handle obj, jlong millis, TRAPS) {
 510   CHECK_THROW_NOSYNC_IMSE(obj);
 511   if (UseBiasedLocking) {
 512     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 513     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 514   }
 515   if (millis < 0) {
 516     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 517   }
 518   inflate(THREAD, obj(), inflate_cause_wait)->wait(millis, false, THREAD);
 519 }
 520 
 521 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
 522   CHECK_THROW_NOSYNC_IMSE(obj);
 523   if (UseBiasedLocking) {
 524     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 525     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 526   }
 527 
 528   markOop mark = obj->mark();
 529   if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
 530     return;
 531   }
 532   inflate(THREAD, obj(), inflate_cause_notify)->notify(THREAD);
 533 }
 534 
 535 // NOTE: see comment of notify()
 536 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
 537   CHECK_THROW_NOSYNC_IMSE(obj);
 538   if (UseBiasedLocking) {
 539     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
 540     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 541   }
 542 
 543   markOop mark = obj->mark();
 544   if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
 545     return;
 546   }
 547   inflate(THREAD, obj(), inflate_cause_notify)->notifyAll(THREAD);
 548 }
 549 
 550 // -----------------------------------------------------------------------------
 551 // Hash Code handling
 552 //
 553 // Performance concern:
 554 // OrderAccess::storestore() calls release() which at one time stored 0
 555 // into the global volatile OrderAccess::dummy variable. This store was
 556 // unnecessary for correctness. Many threads storing into a common location
 557 // causes considerable cache migration or "sloshing" on large SMP systems.
 558 // As such, I avoided using OrderAccess::storestore(). In some cases
 559 // OrderAccess::fence() -- which incurs local latency on the executing
 560 // processor -- is a better choice as it scales on SMP systems.
 561 //
 562 // See http://blogs.oracle.com/dave/entry/biased_locking_in_hotspot for
 563 // a discussion of coherency costs. Note that all our current reference
 564 // platforms provide strong ST-ST order, so the issue is moot on IA32,
 565 // x64, and SPARC.
 566 //
 567 // As a general policy we use "volatile" to control compiler-based reordering
 568 // and explicit fences (barriers) to control for architectural reordering
 569 // performed by the CPU(s) or platform.
 570 
 571 struct SharedGlobals {
 572   char         _pad_prefix[DEFAULT_CACHE_LINE_SIZE];
 573   // These are highly shared mostly-read variables.
 574   // To avoid false-sharing they need to be the sole occupants of a cache line.
 575   volatile int stwRandom;
 576   volatile int stwCycle;
 577   DEFINE_PAD_MINUS_SIZE(1, DEFAULT_CACHE_LINE_SIZE, sizeof(volatile int) * 2);
 578   // Hot RW variable -- Sequester to avoid false-sharing
 579   volatile int hcSequence;
 580   DEFINE_PAD_MINUS_SIZE(2, DEFAULT_CACHE_LINE_SIZE, sizeof(volatile int));
 581 };
 582 
 583 static SharedGlobals GVars;
 584 static int MonitorScavengeThreshold = 1000000;
 585 static volatile int ForceMonitorScavenge = 0; // Scavenge required and pending
 586 
 587 static markOop ReadStableMark(oop obj) {
 588   markOop mark = obj->mark();
 589   if (!mark->is_being_inflated()) {
 590     return mark;       // normal fast-path return
 591   }
 592 
 593   int its = 0;
 594   for (;;) {
 595     markOop mark = obj->mark();
 596     if (!mark->is_being_inflated()) {
 597       return mark;    // normal fast-path return
 598     }
 599 
 600     // The object is being inflated by some other thread.
 601     // The caller of ReadStableMark() must wait for inflation to complete.
 602     // Avoid live-lock
 603     // TODO: consider calling SafepointSynchronize::do_call_back() while
 604     // spinning to see if there's a safepoint pending.  If so, immediately
 605     // yielding or blocking would be appropriate.  Avoid spinning while
 606     // there is a safepoint pending.
 607     // TODO: add inflation contention performance counters.
 608     // TODO: restrict the aggregate number of spinners.
 609 
 610     ++its;
 611     if (its > 10000 || !os::is_MP()) {
 612       if (its & 1) {
 613         os::naked_yield();
 614       } else {
 615         // Note that the following code attenuates the livelock problem but is not
 616         // a complete remedy.  A more complete solution would require that the inflating
 617         // thread hold the associated inflation lock.  The following code simply restricts
 618         // the number of spinners to at most one.  We'll have N-2 threads blocked
 619         // on the inflationlock, 1 thread holding the inflation lock and using
 620         // a yield/park strategy, and 1 thread in the midst of inflation.
 621         // A more refined approach would be to change the encoding of INFLATING
 622         // to allow encapsulation of a native thread pointer.  Threads waiting for
 623         // inflation to complete would use CAS to push themselves onto a singly linked
 624         // list rooted at the markword.  Once enqueued, they'd loop, checking a per-thread flag
 625         // and calling park().  When inflation was complete the thread that accomplished inflation
 626         // would detach the list and set the markword to inflated with a single CAS and
 627         // then for each thread on the list, set the flag and unpark() the thread.
 628         // This is conceptually similar to muxAcquire-muxRelease, except that muxRelease
 629         // wakes at most one thread whereas we need to wake the entire list.
 630         int ix = (cast_from_oop<intptr_t>(obj) >> 5) & (NINFLATIONLOCKS-1);
 631         int YieldThenBlock = 0;
 632         assert(ix >= 0 && ix < NINFLATIONLOCKS, "invariant");
 633         assert((NINFLATIONLOCKS & (NINFLATIONLOCKS-1)) == 0, "invariant");
 634         Thread::muxAcquire(gInflationLocks + ix, "gInflationLock");
 635         while (obj->mark() == markOopDesc::INFLATING()) {
 636           // Beware: NakedYield() is advisory and has almost no effect on some platforms
 637           // so we periodically call Self->_ParkEvent->park(1).
 638           // We use a mixed spin/yield/block mechanism.
 639           if ((YieldThenBlock++) >= 16) {
 640             Thread::current()->_ParkEvent->park(1);
 641           } else {
 642             os::naked_yield();
 643           }
 644         }
 645         Thread::muxRelease(gInflationLocks + ix);
 646       }
 647     } else {
 648       SpinPause();       // SMP-polite spinning
 649     }
 650   }
 651 }
 652 
 653 // hashCode() generation :
 654 //
 655 // Possibilities:
 656 // * MD5Digest of {obj,stwRandom}
 657 // * CRC32 of {obj,stwRandom} or any linear-feedback shift register function.
 658 // * A DES- or AES-style SBox[] mechanism
 659 // * One of the Phi-based schemes, such as:
 660 //   2654435761 = 2^32 * Phi (golden ratio)
 661 //   HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stwRandom ;
 662 // * A variation of Marsaglia's shift-xor RNG scheme.
 663 // * (obj ^ stwRandom) is appealing, but can result
 664 //   in undesirable regularity in the hashCode values of adjacent objects
 665 //   (objects allocated back-to-back, in particular).  This could potentially
 666 //   result in hashtable collisions and reduced hashtable efficiency.
 667 //   There are simple ways to "diffuse" the middle address bits over the
 668 //   generated hashCode values:
 669 
 670 static inline intptr_t get_next_hash(Thread * Self, oop obj) {
 671   intptr_t value = 0;
 672   if (hashCode == 0) {
 673     // This form uses global Park-Miller RNG.
 674     // On MP system we'll have lots of RW access to a global, so the
 675     // mechanism induces lots of coherency traffic.
 676     value = os::random();
 677   } else if (hashCode == 1) {
 678     // This variation has the property of being stable (idempotent)
 679     // between STW operations.  This can be useful in some of the 1-0
 680     // synchronization schemes.
 681     intptr_t addrBits = cast_from_oop<intptr_t>(obj) >> 3;
 682     value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom;
 683   } else if (hashCode == 2) {
 684     value = 1;            // for sensitivity testing
 685   } else if (hashCode == 3) {
 686     value = ++GVars.hcSequence;
 687   } else if (hashCode == 4) {
 688     value = cast_from_oop<intptr_t>(obj);
 689   } else {
 690     // Marsaglia's xor-shift scheme with thread-specific state
 691     // This is probably the best overall implementation -- we'll
 692     // likely make this the default in future releases.
 693     unsigned t = Self->_hashStateX;
 694     t ^= (t << 11);
 695     Self->_hashStateX = Self->_hashStateY;
 696     Self->_hashStateY = Self->_hashStateZ;
 697     Self->_hashStateZ = Self->_hashStateW;
 698     unsigned v = Self->_hashStateW;
 699     v = (v ^ (v >> 19)) ^ (t ^ (t >> 8));
 700     Self->_hashStateW = v;
 701     value = v;
 702   }
 703 
 704   value &= markOopDesc::hash_mask;
 705   if (value == 0) value = 0xBAD;
 706   assert(value != markOopDesc::no_hash, "invariant");
 707   return value;
 708 }
 709 
 710 intptr_t ObjectSynchronizer::FastHashCode(Thread * Self, oop obj) {
 711   if (EnableValhalla && obj->klass()->is_value()) {
 712     // Expected tooling to override hashCode for value type, just don't crash
 713     if (log_is_enabled(Debug, monitorinflation)) {
 714       ResourceMark rm;
 715       log_debug(monitorinflation)("FastHashCode for value type: %s", obj->klass()->external_name());
 716     }
 717     return obj->klass()->java_mirror()->identity_hash();
 718   }
 719   if (UseBiasedLocking) {
 720     // NOTE: many places throughout the JVM do not expect a safepoint
 721     // to be taken here, in particular most operations on perm gen
 722     // objects. However, we only ever bias Java instances and all of
 723     // the call sites of identity_hash that might revoke biases have
 724     // been checked to make sure they can handle a safepoint. The
 725     // added check of the bias pattern is to avoid useless calls to
 726     // thread-local storage.
 727     if (obj->mark()->has_bias_pattern()) {
 728       // Handle for oop obj in case of STW safepoint
 729       Handle hobj(Self, obj);
 730       // Relaxing assertion for bug 6320749.
 731       assert(Universe::verify_in_progress() ||
 732              !SafepointSynchronize::is_at_safepoint(),
 733              "biases should not be seen by VM thread here");
 734       BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current());
 735       obj = hobj();
 736       assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 737     }
 738   }
 739 
 740   // hashCode() is a heap mutator ...
 741   // Relaxing assertion for bug 6320749.
 742   assert(Universe::verify_in_progress() || DumpSharedSpaces ||
 743          !SafepointSynchronize::is_at_safepoint(), "invariant");
 744   assert(Universe::verify_in_progress() || DumpSharedSpaces ||
 745          Self->is_Java_thread() , "invariant");
 746   assert(Universe::verify_in_progress() || DumpSharedSpaces ||
 747          ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant");
 748 
 749   ObjectMonitor* monitor = NULL;
 750   markOop temp, test;
 751   intptr_t hash;
 752   markOop mark = ReadStableMark(obj);
 753 
 754   // object should remain ineligible for biased locking
 755   assert(!mark->has_bias_pattern(), "invariant");
 756 
 757   if (mark->is_neutral()) {
 758     hash = mark->hash();              // this is a normal header
 759     if (hash != 0) {                  // if it has hash, just return it
 760       return hash;
 761     }
 762     hash = get_next_hash(Self, obj);  // allocate a new hash code
 763     temp = mark->copy_set_hash(hash); // merge the hash code into header
 764     // use (machine word version) atomic operation to install the hash
 765     test = obj->cas_set_mark(temp, mark);
 766     if (test == mark) {
 767       return hash;
 768     }
 769     // If atomic operation failed, we must inflate the header
 770     // into heavy weight monitor. We could add more code here
 771     // for fast path, but it does not worth the complexity.
 772   } else if (mark->has_monitor()) {
 773     monitor = mark->monitor();
 774     temp = monitor->header();
 775     assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp));
 776     hash = temp->hash();
 777     if (hash != 0) {
 778       return hash;
 779     }
 780     // Skip to the following code to reduce code size
 781   } else if (Self->is_lock_owned((address)mark->locker())) {
 782     temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned
 783     assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp));
 784     hash = temp->hash();              // by current thread, check if the displaced
 785     if (hash != 0) {                  // header contains hash code
 786       return hash;
 787     }
 788     // WARNING:
 789     // The displaced header in the BasicLock on a thread's stack
 790     // is strictly immutable. It CANNOT be changed in ANY cases.
 791     // So we have to inflate the stack lock into an ObjectMonitor
 792     // even if the current thread owns the lock. The BasicLock on
 793     // a thread's stack can be asynchronously read by other threads
 794     // during an inflate() call so any change to that stack memory
 795     // may not propagate to other threads correctly.
 796   }
 797 
 798   // Inflate the monitor to set hash code
 799   monitor = inflate(Self, obj, inflate_cause_hash_code);
 800   // Load displaced header and check it has hash code
 801   mark = monitor->header();
 802   assert(mark->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(mark));
 803   hash = mark->hash();
 804   if (hash == 0) {
 805     hash = get_next_hash(Self, obj);
 806     temp = mark->copy_set_hash(hash); // merge hash code into header
 807     assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp));
 808     test = Atomic::cmpxchg(temp, monitor->header_addr(), mark);
 809     if (test != mark) {
 810       // The only update to the ObjectMonitor's header/dmw field
 811       // is to merge in the hash code. If someone adds a new usage
 812       // of the header/dmw field, please update this code.
 813       hash = test->hash();
 814       assert(test->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(test));
 815       assert(hash != 0, "Trivial unexpected object/monitor header usage.");
 816     }
 817   }
 818   // We finally get the hash
 819   return hash;
 820 }
 821 
 822 
 823 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread,
 824                                                    Handle h_obj) {
 825   if (EnableValhalla && h_obj->mark()->is_always_locked()) {
 826     return false;
 827   }
 828   if (UseBiasedLocking) {
 829     BiasedLocking::revoke_and_rebias(h_obj, false, thread);
 830     assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 831   }
 832 
 833   assert(thread == JavaThread::current(), "Can only be called on current thread");
 834   oop obj = h_obj();
 835 
 836   markOop mark = ReadStableMark(obj);
 837 
 838   // Uncontended case, header points to stack
 839   if (mark->has_locker()) {
 840     return thread->is_lock_owned((address)mark->locker());
 841   }
 842   // Contended case, header points to ObjectMonitor (tagged pointer)
 843   if (mark->has_monitor()) {
 844     ObjectMonitor* monitor = mark->monitor();
 845     return monitor->is_entered(thread) != 0;
 846   }
 847   // Unlocked case, header in place
 848   assert(mark->is_neutral(), "sanity check");
 849   return false;
 850 }
 851 
 852 // Be aware of this method could revoke bias of the lock object.
 853 // This method queries the ownership of the lock handle specified by 'h_obj'.
 854 // If the current thread owns the lock, it returns owner_self. If no
 855 // thread owns the lock, it returns owner_none. Otherwise, it will return
 856 // owner_other.
 857 ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership
 858 (JavaThread *self, Handle h_obj) {
 859   // The caller must beware this method can revoke bias, and
 860   // revocation can result in a safepoint.
 861   assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
 862   assert(self->thread_state() != _thread_blocked, "invariant");
 863 
 864   // Possible mark states: neutral, biased, stack-locked, inflated
 865 
 866   if (UseBiasedLocking && h_obj()->mark()->has_bias_pattern()) {
 867     // CASE: biased
 868     BiasedLocking::revoke_and_rebias(h_obj, false, self);
 869     assert(!h_obj->mark()->has_bias_pattern(),
 870            "biases should be revoked by now");
 871   }
 872 
 873   assert(self == JavaThread::current(), "Can only be called on current thread");
 874   oop obj = h_obj();
 875   markOop mark = ReadStableMark(obj);
 876 
 877   // CASE: stack-locked.  Mark points to a BasicLock on the owner's stack.
 878   if (mark->has_locker()) {
 879     return self->is_lock_owned((address)mark->locker()) ?
 880       owner_self : owner_other;
 881   }
 882 
 883   // CASE: inflated. Mark (tagged pointer) points to an ObjectMonitor.
 884   // The Object:ObjectMonitor relationship is stable as long as we're
 885   // not at a safepoint.
 886   if (mark->has_monitor()) {
 887     void * owner = mark->monitor()->_owner;
 888     if (owner == NULL) return owner_none;
 889     return (owner == self ||
 890             self->is_lock_owned((address)owner)) ? owner_self : owner_other;
 891   }
 892 
 893   // CASE: neutral
 894   assert(mark->is_neutral(), "sanity check");
 895   return owner_none;           // it's unlocked
 896 }
 897 
 898 // FIXME: jvmti should call this
 899 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) {
 900   if (UseBiasedLocking) {
 901     if (SafepointSynchronize::is_at_safepoint()) {
 902       BiasedLocking::revoke_at_safepoint(h_obj);
 903     } else {
 904       BiasedLocking::revoke_and_rebias(h_obj, false, JavaThread::current());
 905     }
 906     assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
 907   }
 908 
 909   oop obj = h_obj();
 910   address owner = NULL;
 911 
 912   markOop mark = ReadStableMark(obj);
 913 
 914   // Uncontended case, header points to stack
 915   if (mark->has_locker()) {
 916     owner = (address) mark->locker();
 917   }
 918 
 919   // Contended case, header points to ObjectMonitor (tagged pointer)
 920   else if (mark->has_monitor()) {
 921     ObjectMonitor* monitor = mark->monitor();
 922     assert(monitor != NULL, "monitor should be non-null");
 923     owner = (address) monitor->owner();
 924   }
 925 
 926   if (owner != NULL) {
 927     // owning_thread_from_monitor_owner() may also return NULL here
 928     return Threads::owning_thread_from_monitor_owner(t_list, owner);
 929   }
 930 
 931   // Unlocked case, header in place
 932   // Cannot have assertion since this object may have been
 933   // locked by another thread when reaching here.
 934   // assert(mark->is_neutral(), "sanity check");
 935 
 936   return NULL;
 937 }
 938 
 939 // Visitors ...
 940 
 941 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure) {
 942   PaddedEnd<ObjectMonitor> * block = OrderAccess::load_acquire(&gBlockList);
 943   while (block != NULL) {
 944     assert(block->object() == CHAINMARKER, "must be a block header");
 945     for (int i = _BLOCKSIZE - 1; i > 0; i--) {
 946       ObjectMonitor* mid = (ObjectMonitor *)(block + i);
 947       oop object = (oop)mid->object();
 948       if (object != NULL) {
 949         closure->do_monitor(mid);
 950       }
 951     }
 952     block = (PaddedEnd<ObjectMonitor> *)block->FreeNext;
 953   }
 954 }
 955 
 956 // Get the next block in the block list.
 957 static inline PaddedEnd<ObjectMonitor>* next(PaddedEnd<ObjectMonitor>* block) {
 958   assert(block->object() == CHAINMARKER, "must be a block header");
 959   block = (PaddedEnd<ObjectMonitor>*) block->FreeNext;
 960   assert(block == NULL || block->object() == CHAINMARKER, "must be a block header");
 961   return block;
 962 }
 963 
 964 static bool monitors_used_above_threshold() {
 965   if (gMonitorPopulation == 0) {
 966     return false;
 967   }
 968   int monitors_used = gMonitorPopulation - gMonitorFreeCount;
 969   int monitor_usage = (monitors_used * 100LL) / gMonitorPopulation;
 970   return monitor_usage > MonitorUsedDeflationThreshold;
 971 }
 972 
 973 bool ObjectSynchronizer::is_cleanup_needed() {
 974   if (MonitorUsedDeflationThreshold > 0) {
 975     return monitors_used_above_threshold();
 976   }
 977   return false;
 978 }
 979 
 980 void ObjectSynchronizer::oops_do(OopClosure* f) {
 981   // We only scan the global used list here (for moribund threads), and
 982   // the thread-local monitors in Thread::oops_do().
 983   global_used_oops_do(f);
 984 }
 985 
 986 void ObjectSynchronizer::global_used_oops_do(OopClosure* f) {
 987   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 988   list_oops_do(gOmInUseList, f);
 989 }
 990 
 991 void ObjectSynchronizer::thread_local_used_oops_do(Thread* thread, OopClosure* f) {
 992   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 993   list_oops_do(thread->omInUseList, f);
 994 }
 995 
 996 void ObjectSynchronizer::list_oops_do(ObjectMonitor* list, OopClosure* f) {
 997   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 998   ObjectMonitor* mid;
 999   for (mid = list; mid != NULL; mid = mid->FreeNext) {
1000     if (mid->object() != NULL) {
1001       f->do_oop((oop*)mid->object_addr());
1002     }
1003   }
1004 }
1005 
1006 
1007 // -----------------------------------------------------------------------------
1008 // ObjectMonitor Lifecycle
1009 // -----------------------
1010 // Inflation unlinks monitors from the global gFreeList and
1011 // associates them with objects.  Deflation -- which occurs at
1012 // STW-time -- disassociates idle monitors from objects.  Such
1013 // scavenged monitors are returned to the gFreeList.
1014 //
1015 // The global list is protected by gListLock.  All the critical sections
1016 // are short and operate in constant-time.
1017 //
1018 // ObjectMonitors reside in type-stable memory (TSM) and are immortal.
1019 //
1020 // Lifecycle:
1021 // --   unassigned and on the global free list
1022 // --   unassigned and on a thread's private omFreeList
1023 // --   assigned to an object.  The object is inflated and the mark refers
1024 //      to the objectmonitor.
1025 
1026 
1027 // Constraining monitor pool growth via MonitorBound ...
1028 //
1029 // The monitor pool is grow-only.  We scavenge at STW safepoint-time, but the
1030 // the rate of scavenging is driven primarily by GC.  As such,  we can find
1031 // an inordinate number of monitors in circulation.
1032 // To avoid that scenario we can artificially induce a STW safepoint
1033 // if the pool appears to be growing past some reasonable bound.
1034 // Generally we favor time in space-time tradeoffs, but as there's no
1035 // natural back-pressure on the # of extant monitors we need to impose some
1036 // type of limit.  Beware that if MonitorBound is set to too low a value
1037 // we could just loop. In addition, if MonitorBound is set to a low value
1038 // we'll incur more safepoints, which are harmful to performance.
1039 // See also: GuaranteedSafepointInterval
1040 //
1041 // The current implementation uses asynchronous VM operations.
1042 
1043 static void InduceScavenge(Thread * Self, const char * Whence) {
1044   // Induce STW safepoint to trim monitors
1045   // Ultimately, this results in a call to deflate_idle_monitors() in the near future.
1046   // More precisely, trigger an asynchronous STW safepoint as the number
1047   // of active monitors passes the specified threshold.
1048   // TODO: assert thread state is reasonable
1049 
1050   if (ForceMonitorScavenge == 0 && Atomic::xchg (1, &ForceMonitorScavenge) == 0) {
1051     // Induce a 'null' safepoint to scavenge monitors
1052     // Must VM_Operation instance be heap allocated as the op will be enqueue and posted
1053     // to the VMthread and have a lifespan longer than that of this activation record.
1054     // The VMThread will delete the op when completed.
1055     VMThread::execute(new VM_ScavengeMonitors());
1056   }
1057 }
1058 
1059 ObjectMonitor* ObjectSynchronizer::omAlloc(Thread * Self) {
1060   // A large MAXPRIVATE value reduces both list lock contention
1061   // and list coherency traffic, but also tends to increase the
1062   // number of objectMonitors in circulation as well as the STW
1063   // scavenge costs.  As usual, we lean toward time in space-time
1064   // tradeoffs.
1065   const int MAXPRIVATE = 1024;
1066   stringStream ss;
1067   for (;;) {
1068     ObjectMonitor * m;
1069 
1070     // 1: try to allocate from the thread's local omFreeList.
1071     // Threads will attempt to allocate first from their local list, then
1072     // from the global list, and only after those attempts fail will the thread
1073     // attempt to instantiate new monitors.   Thread-local free lists take
1074     // heat off the gListLock and improve allocation latency, as well as reducing
1075     // coherency traffic on the shared global list.
1076     m = Self->omFreeList;
1077     if (m != NULL) {
1078       Self->omFreeList = m->FreeNext;
1079       Self->omFreeCount--;
1080       guarantee(m->object() == NULL, "invariant");
1081       m->FreeNext = Self->omInUseList;
1082       Self->omInUseList = m;
1083       Self->omInUseCount++;
1084       return m;
1085     }
1086 
1087     // 2: try to allocate from the global gFreeList
1088     // CONSIDER: use muxTry() instead of muxAcquire().
1089     // If the muxTry() fails then drop immediately into case 3.
1090     // If we're using thread-local free lists then try
1091     // to reprovision the caller's free list.
1092     if (gFreeList != NULL) {
1093       // Reprovision the thread's omFreeList.
1094       // Use bulk transfers to reduce the allocation rate and heat
1095       // on various locks.
1096       Thread::muxAcquire(&gListLock, "omAlloc(1)");
1097       for (int i = Self->omFreeProvision; --i >= 0 && gFreeList != NULL;) {
1098         gMonitorFreeCount--;
1099         ObjectMonitor * take = gFreeList;
1100         gFreeList = take->FreeNext;
1101         guarantee(take->object() == NULL, "invariant");
1102         take->Recycle();
1103         omRelease(Self, take, false);
1104       }
1105       Thread::muxRelease(&gListLock);
1106       Self->omFreeProvision += 1 + (Self->omFreeProvision/2);
1107       if (Self->omFreeProvision > MAXPRIVATE) Self->omFreeProvision = MAXPRIVATE;
1108 
1109       const int mx = MonitorBound;
1110       if (mx > 0 && (gMonitorPopulation-gMonitorFreeCount) > mx) {
1111         // We can't safely induce a STW safepoint from omAlloc() as our thread
1112         // state may not be appropriate for such activities and callers may hold
1113         // naked oops, so instead we defer the action.
1114         InduceScavenge(Self, "omAlloc");
1115       }
1116       continue;
1117     }
1118 
1119     // 3: allocate a block of new ObjectMonitors
1120     // Both the local and global free lists are empty -- resort to malloc().
1121     // In the current implementation objectMonitors are TSM - immortal.
1122     // Ideally, we'd write "new ObjectMonitor[_BLOCKSIZE], but we want
1123     // each ObjectMonitor to start at the beginning of a cache line,
1124     // so we use align_up().
1125     // A better solution would be to use C++ placement-new.
1126     // BEWARE: As it stands currently, we don't run the ctors!
1127     assert(_BLOCKSIZE > 1, "invariant");
1128     size_t neededsize = sizeof(PaddedEnd<ObjectMonitor>) * _BLOCKSIZE;
1129     PaddedEnd<ObjectMonitor> * temp;
1130     size_t aligned_size = neededsize + (DEFAULT_CACHE_LINE_SIZE - 1);
1131     void* real_malloc_addr = (void *)NEW_C_HEAP_ARRAY(char, aligned_size,
1132                                                       mtInternal);
1133     temp = (PaddedEnd<ObjectMonitor> *)
1134              align_up(real_malloc_addr, DEFAULT_CACHE_LINE_SIZE);
1135 
1136     // NOTE: (almost) no way to recover if allocation failed.
1137     // We might be able to induce a STW safepoint and scavenge enough
1138     // objectMonitors to permit progress.
1139     if (temp == NULL) {
1140       vm_exit_out_of_memory(neededsize, OOM_MALLOC_ERROR,
1141                             "Allocate ObjectMonitors");
1142     }
1143     (void)memset((void *) temp, 0, neededsize);
1144 
1145     // Format the block.
1146     // initialize the linked list, each monitor points to its next
1147     // forming the single linked free list, the very first monitor
1148     // will points to next block, which forms the block list.
1149     // The trick of using the 1st element in the block as gBlockList
1150     // linkage should be reconsidered.  A better implementation would
1151     // look like: class Block { Block * next; int N; ObjectMonitor Body [N] ; }
1152 
1153     for (int i = 1; i < _BLOCKSIZE; i++) {
1154       temp[i].FreeNext = (ObjectMonitor *)&temp[i+1];
1155     }
1156 
1157     // terminate the last monitor as the end of list
1158     temp[_BLOCKSIZE - 1].FreeNext = NULL;
1159 
1160     // Element [0] is reserved for global list linkage
1161     temp[0].set_object(CHAINMARKER);
1162 
1163     // Consider carving out this thread's current request from the
1164     // block in hand.  This avoids some lock traffic and redundant
1165     // list activity.
1166 
1167     // Acquire the gListLock to manipulate gBlockList and gFreeList.
1168     // An Oyama-Taura-Yonezawa scheme might be more efficient.
1169     Thread::muxAcquire(&gListLock, "omAlloc(2)");
1170     gMonitorPopulation += _BLOCKSIZE-1;
1171     gMonitorFreeCount += _BLOCKSIZE-1;
1172 
1173     // Add the new block to the list of extant blocks (gBlockList).
1174     // The very first objectMonitor in a block is reserved and dedicated.
1175     // It serves as blocklist "next" linkage.
1176     temp[0].FreeNext = gBlockList;
1177     // There are lock-free uses of gBlockList so make sure that
1178     // the previous stores happen before we update gBlockList.
1179     OrderAccess::release_store(&gBlockList, temp);
1180 
1181     // Add the new string of objectMonitors to the global free list
1182     temp[_BLOCKSIZE - 1].FreeNext = gFreeList;
1183     gFreeList = temp + 1;
1184     Thread::muxRelease(&gListLock);
1185   }
1186 }
1187 
1188 // Place "m" on the caller's private per-thread omFreeList.
1189 // In practice there's no need to clamp or limit the number of
1190 // monitors on a thread's omFreeList as the only time we'll call
1191 // omRelease is to return a monitor to the free list after a CAS
1192 // attempt failed.  This doesn't allow unbounded #s of monitors to
1193 // accumulate on a thread's free list.
1194 //
1195 // Key constraint: all ObjectMonitors on a thread's free list and the global
1196 // free list must have their object field set to null. This prevents the
1197 // scavenger -- deflate_monitor_list() -- from reclaiming them.
1198 
1199 void ObjectSynchronizer::omRelease(Thread * Self, ObjectMonitor * m,
1200                                    bool fromPerThreadAlloc) {
1201   guarantee(m->header() == NULL, "invariant");
1202   guarantee(m->object() == NULL, "invariant");
1203   stringStream ss;
1204   guarantee((m->is_busy() | m->_recursions) == 0, "freeing in-use monitor: "
1205             "%s, recursions=" INTPTR_FORMAT, m->is_busy_to_string(&ss),
1206             m->_recursions);
1207   // Remove from omInUseList
1208   if (fromPerThreadAlloc) {
1209     ObjectMonitor* cur_mid_in_use = NULL;
1210     bool extracted = false;
1211     for (ObjectMonitor* mid = Self->omInUseList; mid != NULL; cur_mid_in_use = mid, mid = mid->FreeNext) {
1212       if (m == mid) {
1213         // extract from per-thread in-use list
1214         if (mid == Self->omInUseList) {
1215           Self->omInUseList = mid->FreeNext;
1216         } else if (cur_mid_in_use != NULL) {
1217           cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list
1218         }
1219         extracted = true;
1220         Self->omInUseCount--;
1221         break;
1222       }
1223     }
1224     assert(extracted, "Should have extracted from in-use list");
1225   }
1226 
1227   // FreeNext is used for both omInUseList and omFreeList, so clear old before setting new
1228   m->FreeNext = Self->omFreeList;
1229   Self->omFreeList = m;
1230   Self->omFreeCount++;
1231 }
1232 
1233 // Return the monitors of a moribund thread's local free list to
1234 // the global free list.  Typically a thread calls omFlush() when
1235 // it's dying.  We could also consider having the VM thread steal
1236 // monitors from threads that have not run java code over a few
1237 // consecutive STW safepoints.  Relatedly, we might decay
1238 // omFreeProvision at STW safepoints.
1239 //
1240 // Also return the monitors of a moribund thread's omInUseList to
1241 // a global gOmInUseList under the global list lock so these
1242 // will continue to be scanned.
1243 //
1244 // We currently call omFlush() from Threads::remove() _before the thread
1245 // has been excised from the thread list and is no longer a mutator.
1246 // This means that omFlush() cannot run concurrently with a safepoint and
1247 // interleave with the deflate_idle_monitors scavenge operator. In particular,
1248 // this ensures that the thread's monitors are scanned by a GC safepoint,
1249 // either via Thread::oops_do() (if safepoint happens before omFlush()) or via
1250 // ObjectSynchronizer::oops_do() (if it happens after omFlush() and the thread's
1251 // monitors have been transferred to the global in-use list).
1252 
1253 void ObjectSynchronizer::omFlush(Thread * Self) {
1254   ObjectMonitor * list = Self->omFreeList;  // Null-terminated SLL
1255   ObjectMonitor * tail = NULL;
1256   int tally = 0;
1257   if (list != NULL) {
1258     ObjectMonitor * s;
1259     // The thread is going away. Set 'tail' to the last per-thread free
1260     // monitor which will be linked to gFreeList below under the gListLock.
1261     stringStream ss;
1262     for (s = list; s != NULL; s = s->FreeNext) {
1263       tally++;
1264       tail = s;
1265       guarantee(s->object() == NULL, "invariant");
1266       guarantee(!s->is_busy(), "must be !is_busy: %s", s->is_busy_to_string(&ss));
1267     }
1268     guarantee(tail != NULL, "invariant");
1269     assert(Self->omFreeCount == tally, "free-count off");
1270     Self->omFreeList = NULL;
1271     Self->omFreeCount = 0;
1272   }
1273 
1274   ObjectMonitor * inUseList = Self->omInUseList;
1275   ObjectMonitor * inUseTail = NULL;
1276   int inUseTally = 0;
1277   if (inUseList != NULL) {
1278     ObjectMonitor *cur_om;
1279     // The thread is going away, however the omInUseList inflated
1280     // monitors may still be in-use by other threads.
1281     // Link them to inUseTail, which will be linked into the global in-use list
1282     // gOmInUseList below, under the gListLock
1283     for (cur_om = inUseList; cur_om != NULL; cur_om = cur_om->FreeNext) {
1284       inUseTail = cur_om;
1285       inUseTally++;
1286     }
1287     guarantee(inUseTail != NULL, "invariant");
1288     assert(Self->omInUseCount == inUseTally, "in-use count off");
1289     Self->omInUseList = NULL;
1290     Self->omInUseCount = 0;
1291   }
1292 
1293   Thread::muxAcquire(&gListLock, "omFlush");
1294   if (tail != NULL) {
1295     tail->FreeNext = gFreeList;
1296     gFreeList = list;
1297     gMonitorFreeCount += tally;
1298   }
1299 
1300   if (inUseTail != NULL) {
1301     inUseTail->FreeNext = gOmInUseList;
1302     gOmInUseList = inUseList;
1303     gOmInUseCount += inUseTally;
1304   }
1305 
1306   Thread::muxRelease(&gListLock);
1307 
1308   LogStreamHandle(Debug, monitorinflation) lsh_debug;
1309   LogStreamHandle(Info, monitorinflation) lsh_info;
1310   LogStream * ls = NULL;
1311   if (log_is_enabled(Debug, monitorinflation)) {
1312     ls = &lsh_debug;
1313   } else if ((tally != 0 || inUseTally != 0) &&
1314              log_is_enabled(Info, monitorinflation)) {
1315     ls = &lsh_info;
1316   }
1317   if (ls != NULL) {
1318     ls->print_cr("omFlush: jt=" INTPTR_FORMAT ", free_monitor_tally=%d"
1319                  ", in_use_monitor_tally=%d" ", omFreeProvision=%d",
1320                  p2i(Self), tally, inUseTally, Self->omFreeProvision);
1321   }
1322 }
1323 
1324 static void post_monitor_inflate_event(EventJavaMonitorInflate* event,
1325                                        const oop obj,
1326                                        ObjectSynchronizer::InflateCause cause) {
1327   assert(event != NULL, "invariant");
1328   assert(event->should_commit(), "invariant");
1329   event->set_monitorClass(obj->klass());
1330   event->set_address((uintptr_t)(void*)obj);
1331   event->set_cause((u1)cause);
1332   event->commit();
1333 }
1334 
1335 // Fast path code shared by multiple functions
1336 void ObjectSynchronizer::inflate_helper(oop obj) {
1337   markOop mark = obj->mark();
1338   if (mark->has_monitor()) {
1339     assert(ObjectSynchronizer::verify_objmon_isinpool(mark->monitor()), "monitor is invalid");
1340     assert(mark->monitor()->header()->is_neutral(), "monitor must record a good object header");
1341     return;
1342   }
1343   inflate(Thread::current(), obj, inflate_cause_vm_internal);
1344 }
1345 
1346 ObjectMonitor* ObjectSynchronizer::inflate(Thread * Self,
1347                                            oop object,
1348                                            const InflateCause cause) {
1349   // Inflate mutates the heap ...
1350   // Relaxing assertion for bug 6320749.
1351   assert(Universe::verify_in_progress() ||
1352          !SafepointSynchronize::is_at_safepoint(), "invariant");
1353 
1354   if (EnableValhalla) {
1355     guarantee(!object->klass()->is_value(), "Attempt to inflate value type");
1356   }
1357 
1358   EventJavaMonitorInflate event;
1359 
1360   for (;;) {
1361     const markOop mark = object->mark();
1362     assert(!mark->has_bias_pattern(), "invariant");
1363 
1364     // The mark can be in one of the following states:
1365     // *  Inflated     - just return
1366     // *  Stack-locked - coerce it to inflated
1367     // *  INFLATING    - busy wait for conversion to complete
1368     // *  Neutral      - aggressively inflate the object.
1369     // *  BIASED       - Illegal.  We should never see this
1370 
1371     // CASE: inflated
1372     if (mark->has_monitor()) {
1373       ObjectMonitor * inf = mark->monitor();
1374       markOop dmw = inf->header();
1375       assert(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw));
1376       assert(oopDesc::equals((oop) inf->object(), object), "invariant");
1377       assert(ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid");
1378       return inf;
1379     }
1380 
1381     // CASE: inflation in progress - inflating over a stack-lock.
1382     // Some other thread is converting from stack-locked to inflated.
1383     // Only that thread can complete inflation -- other threads must wait.
1384     // The INFLATING value is transient.
1385     // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
1386     // We could always eliminate polling by parking the thread on some auxiliary list.
1387     if (mark == markOopDesc::INFLATING()) {
1388       ReadStableMark(object);
1389       continue;
1390     }
1391 
1392     // CASE: stack-locked
1393     // Could be stack-locked either by this thread or by some other thread.
1394     //
1395     // Note that we allocate the objectmonitor speculatively, _before_ attempting
1396     // to install INFLATING into the mark word.  We originally installed INFLATING,
1397     // allocated the objectmonitor, and then finally STed the address of the
1398     // objectmonitor into the mark.  This was correct, but artificially lengthened
1399     // the interval in which INFLATED appeared in the mark, thus increasing
1400     // the odds of inflation contention.
1401     //
1402     // We now use per-thread private objectmonitor free lists.
1403     // These list are reprovisioned from the global free list outside the
1404     // critical INFLATING...ST interval.  A thread can transfer
1405     // multiple objectmonitors en-mass from the global free list to its local free list.
1406     // This reduces coherency traffic and lock contention on the global free list.
1407     // Using such local free lists, it doesn't matter if the omAlloc() call appears
1408     // before or after the CAS(INFLATING) operation.
1409     // See the comments in omAlloc().
1410 
1411     LogStreamHandle(Trace, monitorinflation) lsh;
1412 
1413     if (mark->has_locker()) {
1414       ObjectMonitor * m = omAlloc(Self);
1415       // Optimistically prepare the objectmonitor - anticipate successful CAS
1416       // We do this before the CAS in order to minimize the length of time
1417       // in which INFLATING appears in the mark.
1418       m->Recycle();
1419       m->_Responsible  = NULL;
1420       m->_SpinDuration = ObjectMonitor::Knob_SpinLimit;   // Consider: maintain by type/class
1421 
1422       markOop cmp = object->cas_set_mark(markOopDesc::INFLATING(), mark);
1423       if (cmp != mark) {
1424         omRelease(Self, m, true);
1425         continue;       // Interference -- just retry
1426       }
1427 
1428       // We've successfully installed INFLATING (0) into the mark-word.
1429       // This is the only case where 0 will appear in a mark-word.
1430       // Only the singular thread that successfully swings the mark-word
1431       // to 0 can perform (or more precisely, complete) inflation.
1432       //
1433       // Why do we CAS a 0 into the mark-word instead of just CASing the
1434       // mark-word from the stack-locked value directly to the new inflated state?
1435       // Consider what happens when a thread unlocks a stack-locked object.
1436       // It attempts to use CAS to swing the displaced header value from the
1437       // on-stack basiclock back into the object header.  Recall also that the
1438       // header value (hash code, etc) can reside in (a) the object header, or
1439       // (b) a displaced header associated with the stack-lock, or (c) a displaced
1440       // header in an objectMonitor.  The inflate() routine must copy the header
1441       // value from the basiclock on the owner's stack to the objectMonitor, all
1442       // the while preserving the hashCode stability invariants.  If the owner
1443       // decides to release the lock while the value is 0, the unlock will fail
1444       // and control will eventually pass from slow_exit() to inflate.  The owner
1445       // will then spin, waiting for the 0 value to disappear.   Put another way,
1446       // the 0 causes the owner to stall if the owner happens to try to
1447       // drop the lock (restoring the header from the basiclock to the object)
1448       // while inflation is in-progress.  This protocol avoids races that might
1449       // would otherwise permit hashCode values to change or "flicker" for an object.
1450       // Critically, while object->mark is 0 mark->displaced_mark_helper() is stable.
1451       // 0 serves as a "BUSY" inflate-in-progress indicator.
1452 
1453 
1454       // fetch the displaced mark from the owner's stack.
1455       // The owner can't die or unwind past the lock while our INFLATING
1456       // object is in the mark.  Furthermore the owner can't complete
1457       // an unlock on the object, either.
1458       markOop dmw = mark->displaced_mark_helper();
1459       // Catch if the object's header is not neutral (not locked and
1460       // not marked is what we care about here).
1461       assert(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw));
1462 
1463       // Setup monitor fields to proper values -- prepare the monitor
1464       m->set_header(dmw);
1465 
1466       // Optimization: if the mark->locker stack address is associated
1467       // with this thread we could simply set m->_owner = Self.
1468       // Note that a thread can inflate an object
1469       // that it has stack-locked -- as might happen in wait() -- directly
1470       // with CAS.  That is, we can avoid the xchg-NULL .... ST idiom.
1471       m->set_owner(mark->locker());
1472       m->set_object(object);
1473       // TODO-FIXME: assert BasicLock->dhw != 0.
1474 
1475       // Must preserve store ordering. The monitor state must
1476       // be stable at the time of publishing the monitor address.
1477       guarantee(object->mark() == markOopDesc::INFLATING(), "invariant");
1478       object->release_set_mark(markOopDesc::encode(m));
1479 
1480       // Hopefully the performance counters are allocated on distinct cache lines
1481       // to avoid false sharing on MP systems ...
1482       OM_PERFDATA_OP(Inflations, inc());
1483       if (log_is_enabled(Trace, monitorinflation)) {
1484         ResourceMark rm(Self);
1485         lsh.print_cr("inflate(has_locker): object=" INTPTR_FORMAT ", mark="
1486                      INTPTR_FORMAT ", type='%s'", p2i(object),
1487                      p2i(object->mark()), object->klass()->external_name());
1488       }
1489       if (event.should_commit()) {
1490         post_monitor_inflate_event(&event, object, cause);
1491       }
1492       return m;
1493     }
1494 
1495     // CASE: neutral
1496     // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
1497     // If we know we're inflating for entry it's better to inflate by swinging a
1498     // pre-locked objectMonitor pointer into the object header.   A successful
1499     // CAS inflates the object *and* confers ownership to the inflating thread.
1500     // In the current implementation we use a 2-step mechanism where we CAS()
1501     // to inflate and then CAS() again to try to swing _owner from NULL to Self.
1502     // An inflateTry() method that we could call from fast_enter() and slow_enter()
1503     // would be useful.
1504 
1505     // Catch if the object's header is not neutral (not locked and
1506     // not marked is what we care about here).
1507     assert(mark->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(mark));
1508     ObjectMonitor * m = omAlloc(Self);
1509     // prepare m for installation - set monitor to initial state
1510     m->Recycle();
1511     m->set_header(mark);
1512     m->set_object(object);
1513     m->_Responsible  = NULL;
1514     m->_SpinDuration = ObjectMonitor::Knob_SpinLimit;       // consider: keep metastats by type/class
1515 
1516     if (object->cas_set_mark(markOopDesc::encode(m), mark) != mark) {
1517       m->set_header(NULL);
1518       m->set_object(NULL);
1519       m->Recycle();
1520       omRelease(Self, m, true);
1521       m = NULL;
1522       continue;
1523       // interference - the markword changed - just retry.
1524       // The state-transitions are one-way, so there's no chance of
1525       // live-lock -- "Inflated" is an absorbing state.
1526     }
1527 
1528     // Hopefully the performance counters are allocated on distinct
1529     // cache lines to avoid false sharing on MP systems ...
1530     OM_PERFDATA_OP(Inflations, inc());
1531     if (log_is_enabled(Trace, monitorinflation)) {
1532       ResourceMark rm(Self);
1533       lsh.print_cr("inflate(neutral): object=" INTPTR_FORMAT ", mark="
1534                    INTPTR_FORMAT ", type='%s'", p2i(object),
1535                    p2i(object->mark()), object->klass()->external_name());
1536     }
1537     if (event.should_commit()) {
1538       post_monitor_inflate_event(&event, object, cause);
1539     }
1540     return m;
1541   }
1542 }
1543 
1544 
1545 // We maintain a list of in-use monitors for each thread.
1546 //
1547 // deflate_thread_local_monitors() scans a single thread's in-use list, while
1548 // deflate_idle_monitors() scans only a global list of in-use monitors which
1549 // is populated only as a thread dies (see omFlush()).
1550 //
1551 // These operations are called at all safepoints, immediately after mutators
1552 // are stopped, but before any objects have moved. Collectively they traverse
1553 // the population of in-use monitors, deflating where possible. The scavenged
1554 // monitors are returned to the global monitor free list.
1555 //
1556 // Beware that we scavenge at *every* stop-the-world point. Having a large
1557 // number of monitors in-use could negatively impact performance. We also want
1558 // to minimize the total # of monitors in circulation, as they incur a small
1559 // footprint penalty.
1560 //
1561 // Perversely, the heap size -- and thus the STW safepoint rate --
1562 // typically drives the scavenge rate.  Large heaps can mean infrequent GC,
1563 // which in turn can mean large(r) numbers of ObjectMonitors in circulation.
1564 // This is an unfortunate aspect of this design.
1565 
1566 // Deflate a single monitor if not in-use
1567 // Return true if deflated, false if in-use
1568 bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj,
1569                                          ObjectMonitor** freeHeadp,
1570                                          ObjectMonitor** freeTailp) {
1571   bool deflated;
1572   // Normal case ... The monitor is associated with obj.
1573   const markOop mark = obj->mark();
1574   guarantee(mark == markOopDesc::encode(mid), "should match: mark="
1575             INTPTR_FORMAT ", encoded mid=" INTPTR_FORMAT, p2i(mark),
1576             p2i(markOopDesc::encode(mid)));
1577   // Make sure that mark->monitor() and markOopDesc::encode() agree:
1578   guarantee(mark->monitor() == mid, "should match: monitor()=" INTPTR_FORMAT
1579             ", mid=" INTPTR_FORMAT, p2i(mark->monitor()), p2i(mid));
1580   const markOop dmw = mid->header();
1581   guarantee(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw));
1582 
1583   if (mid->is_busy()) {
1584     deflated = false;
1585   } else {
1586     // Deflate the monitor if it is no longer being used
1587     // It's idle - scavenge and return to the global free list
1588     // plain old deflation ...
1589     if (log_is_enabled(Trace, monitorinflation)) {
1590       ResourceMark rm;
1591       log_trace(monitorinflation)("deflate_monitor: "
1592                                   "object=" INTPTR_FORMAT ", mark="
1593                                   INTPTR_FORMAT ", type='%s'", p2i(obj),
1594                                   p2i(mark), obj->klass()->external_name());
1595     }
1596 
1597     // Restore the header back to obj
1598     obj->release_set_mark(dmw);
1599     mid->clear();
1600 
1601     assert(mid->object() == NULL, "invariant: object=" INTPTR_FORMAT,
1602            p2i(mid->object()));
1603 
1604     // Move the object to the working free list defined by freeHeadp, freeTailp
1605     if (*freeHeadp == NULL) *freeHeadp = mid;
1606     if (*freeTailp != NULL) {
1607       ObjectMonitor * prevtail = *freeTailp;
1608       assert(prevtail->FreeNext == NULL, "cleaned up deflated?");
1609       prevtail->FreeNext = mid;
1610     }
1611     *freeTailp = mid;
1612     deflated = true;
1613   }
1614   return deflated;
1615 }
1616 
1617 // Walk a given monitor list, and deflate idle monitors
1618 // The given list could be a per-thread list or a global list
1619 // Caller acquires gListLock as needed.
1620 //
1621 // In the case of parallel processing of thread local monitor lists,
1622 // work is done by Threads::parallel_threads_do() which ensures that
1623 // each Java thread is processed by exactly one worker thread, and
1624 // thus avoid conflicts that would arise when worker threads would
1625 // process the same monitor lists concurrently.
1626 //
1627 // See also ParallelSPCleanupTask and
1628 // SafepointSynchronize::do_cleanup_tasks() in safepoint.cpp and
1629 // Threads::parallel_java_threads_do() in thread.cpp.
1630 int ObjectSynchronizer::deflate_monitor_list(ObjectMonitor** listHeadp,
1631                                              ObjectMonitor** freeHeadp,
1632                                              ObjectMonitor** freeTailp) {
1633   ObjectMonitor* mid;
1634   ObjectMonitor* next;
1635   ObjectMonitor* cur_mid_in_use = NULL;
1636   int deflated_count = 0;
1637 
1638   for (mid = *listHeadp; mid != NULL;) {
1639     oop obj = (oop) mid->object();
1640     if (obj != NULL && deflate_monitor(mid, obj, freeHeadp, freeTailp)) {
1641       // if deflate_monitor succeeded,
1642       // extract from per-thread in-use list
1643       if (mid == *listHeadp) {
1644         *listHeadp = mid->FreeNext;
1645       } else if (cur_mid_in_use != NULL) {
1646         cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list
1647       }
1648       next = mid->FreeNext;
1649       mid->FreeNext = NULL;  // This mid is current tail in the freeHeadp list
1650       mid = next;
1651       deflated_count++;
1652     } else {
1653       cur_mid_in_use = mid;
1654       mid = mid->FreeNext;
1655     }
1656   }
1657   return deflated_count;
1658 }
1659 
1660 void ObjectSynchronizer::prepare_deflate_idle_monitors(DeflateMonitorCounters* counters) {
1661   counters->nInuse = 0;              // currently associated with objects
1662   counters->nInCirculation = 0;      // extant
1663   counters->nScavenged = 0;          // reclaimed (global and per-thread)
1664   counters->perThreadScavenged = 0;  // per-thread scavenge total
1665   counters->perThreadTimes = 0.0;    // per-thread scavenge times
1666 }
1667 
1668 void ObjectSynchronizer::deflate_idle_monitors(DeflateMonitorCounters* counters) {
1669   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1670   bool deflated = false;
1671 
1672   ObjectMonitor * freeHeadp = NULL;  // Local SLL of scavenged monitors
1673   ObjectMonitor * freeTailp = NULL;
1674   elapsedTimer timer;
1675 
1676   if (log_is_enabled(Info, monitorinflation)) {
1677     timer.start();
1678   }
1679 
1680   // Prevent omFlush from changing mids in Thread dtor's during deflation
1681   // And in case the vm thread is acquiring a lock during a safepoint
1682   // See e.g. 6320749
1683   Thread::muxAcquire(&gListLock, "deflate_idle_monitors");
1684 
1685   // Note: the thread-local monitors lists get deflated in
1686   // a separate pass. See deflate_thread_local_monitors().
1687 
1688   // For moribund threads, scan gOmInUseList
1689   int deflated_count = 0;
1690   if (gOmInUseList) {
1691     counters->nInCirculation += gOmInUseCount;
1692     deflated_count = deflate_monitor_list((ObjectMonitor **)&gOmInUseList, &freeHeadp, &freeTailp);
1693     gOmInUseCount -= deflated_count;
1694     counters->nScavenged += deflated_count;
1695     counters->nInuse += gOmInUseCount;
1696   }
1697 
1698   // Move the scavenged monitors back to the global free list.
1699   if (freeHeadp != NULL) {
1700     guarantee(freeTailp != NULL && counters->nScavenged > 0, "invariant");
1701     assert(freeTailp->FreeNext == NULL, "invariant");
1702     // constant-time list splice - prepend scavenged segment to gFreeList
1703     freeTailp->FreeNext = gFreeList;
1704     gFreeList = freeHeadp;
1705   }
1706   Thread::muxRelease(&gListLock);
1707   timer.stop();
1708 
1709   LogStreamHandle(Debug, monitorinflation) lsh_debug;
1710   LogStreamHandle(Info, monitorinflation) lsh_info;
1711   LogStream * ls = NULL;
1712   if (log_is_enabled(Debug, monitorinflation)) {
1713     ls = &lsh_debug;
1714   } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) {
1715     ls = &lsh_info;
1716   }
1717   if (ls != NULL) {
1718     ls->print_cr("deflating global idle monitors, %3.7f secs, %d monitors", timer.seconds(), deflated_count);
1719   }
1720 }
1721 
1722 void ObjectSynchronizer::finish_deflate_idle_monitors(DeflateMonitorCounters* counters) {
1723   // Report the cumulative time for deflating each thread's idle
1724   // monitors. Note: if the work is split among more than one
1725   // worker thread, then the reported time will likely be more
1726   // than a beginning to end measurement of the phase.
1727   log_info(safepoint, cleanup)("deflating per-thread idle monitors, %3.7f secs, monitors=%d", counters->perThreadTimes, counters->perThreadScavenged);
1728 
1729   gMonitorFreeCount += counters->nScavenged;
1730 
1731   if (log_is_enabled(Debug, monitorinflation)) {
1732     // exit_globals()'s call to audit_and_print_stats() is done
1733     // at the Info level.
1734     ObjectSynchronizer::audit_and_print_stats(false /* on_exit */);
1735   } else if (log_is_enabled(Info, monitorinflation)) {
1736     Thread::muxAcquire(&gListLock, "finish_deflate_idle_monitors");
1737     log_info(monitorinflation)("gMonitorPopulation=%d, gOmInUseCount=%d, "
1738                                "gMonitorFreeCount=%d", gMonitorPopulation,
1739                                gOmInUseCount, gMonitorFreeCount);
1740     Thread::muxRelease(&gListLock);
1741   }
1742 
1743   ForceMonitorScavenge = 0;    // Reset
1744 
1745   OM_PERFDATA_OP(Deflations, inc(counters->nScavenged));
1746   OM_PERFDATA_OP(MonExtant, set_value(counters->nInCirculation));
1747 
1748   GVars.stwRandom = os::random();
1749   GVars.stwCycle++;
1750 }
1751 
1752 void ObjectSynchronizer::deflate_thread_local_monitors(Thread* thread, DeflateMonitorCounters* counters) {
1753   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1754 
1755   ObjectMonitor * freeHeadp = NULL;  // Local SLL of scavenged monitors
1756   ObjectMonitor * freeTailp = NULL;
1757   elapsedTimer timer;
1758 
1759   if (log_is_enabled(Info, safepoint, cleanup) ||
1760       log_is_enabled(Info, monitorinflation)) {
1761     timer.start();
1762   }
1763 
1764   int deflated_count = deflate_monitor_list(thread->omInUseList_addr(), &freeHeadp, &freeTailp);
1765 
1766   Thread::muxAcquire(&gListLock, "deflate_thread_local_monitors");
1767 
1768   // Adjust counters
1769   counters->nInCirculation += thread->omInUseCount;
1770   thread->omInUseCount -= deflated_count;
1771   counters->nScavenged += deflated_count;
1772   counters->nInuse += thread->omInUseCount;
1773   counters->perThreadScavenged += deflated_count;
1774 
1775   // Move the scavenged monitors back to the global free list.
1776   if (freeHeadp != NULL) {
1777     guarantee(freeTailp != NULL && deflated_count > 0, "invariant");
1778     assert(freeTailp->FreeNext == NULL, "invariant");
1779 
1780     // constant-time list splice - prepend scavenged segment to gFreeList
1781     freeTailp->FreeNext = gFreeList;
1782     gFreeList = freeHeadp;
1783   }
1784 
1785   timer.stop();
1786   // Safepoint logging cares about cumulative perThreadTimes and
1787   // we'll capture most of the cost, but not the muxRelease() which
1788   // should be cheap.
1789   counters->perThreadTimes += timer.seconds();
1790 
1791   Thread::muxRelease(&gListLock);
1792 
1793   LogStreamHandle(Debug, monitorinflation) lsh_debug;
1794   LogStreamHandle(Info, monitorinflation) lsh_info;
1795   LogStream * ls = NULL;
1796   if (log_is_enabled(Debug, monitorinflation)) {
1797     ls = &lsh_debug;
1798   } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) {
1799     ls = &lsh_info;
1800   }
1801   if (ls != NULL) {
1802     ls->print_cr("jt=" INTPTR_FORMAT ": deflating per-thread idle monitors, %3.7f secs, %d monitors", p2i(thread), timer.seconds(), deflated_count);
1803   }
1804 }
1805 
1806 // Monitor cleanup on JavaThread::exit
1807 
1808 // Iterate through monitor cache and attempt to release thread's monitors
1809 // Gives up on a particular monitor if an exception occurs, but continues
1810 // the overall iteration, swallowing the exception.
1811 class ReleaseJavaMonitorsClosure: public MonitorClosure {
1812  private:
1813   TRAPS;
1814 
1815  public:
1816   ReleaseJavaMonitorsClosure(Thread* thread) : THREAD(thread) {}
1817   void do_monitor(ObjectMonitor* mid) {
1818     if (mid->owner() == THREAD) {
1819       (void)mid->complete_exit(CHECK);
1820     }
1821   }
1822 };
1823 
1824 // Release all inflated monitors owned by THREAD.  Lightweight monitors are
1825 // ignored.  This is meant to be called during JNI thread detach which assumes
1826 // all remaining monitors are heavyweight.  All exceptions are swallowed.
1827 // Scanning the extant monitor list can be time consuming.
1828 // A simple optimization is to add a per-thread flag that indicates a thread
1829 // called jni_monitorenter() during its lifetime.
1830 //
1831 // Instead of No_Savepoint_Verifier it might be cheaper to
1832 // use an idiom of the form:
1833 //   auto int tmp = SafepointSynchronize::_safepoint_counter ;
1834 //   <code that must not run at safepoint>
1835 //   guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ;
1836 // Since the tests are extremely cheap we could leave them enabled
1837 // for normal product builds.
1838 
1839 void ObjectSynchronizer::release_monitors_owned_by_thread(TRAPS) {
1840   assert(THREAD == JavaThread::current(), "must be current Java thread");
1841   NoSafepointVerifier nsv;
1842   ReleaseJavaMonitorsClosure rjmc(THREAD);
1843   Thread::muxAcquire(&gListLock, "release_monitors_owned_by_thread");
1844   ObjectSynchronizer::monitors_iterate(&rjmc);
1845   Thread::muxRelease(&gListLock);
1846   THREAD->clear_pending_exception();
1847 }
1848 
1849 const char* ObjectSynchronizer::inflate_cause_name(const InflateCause cause) {
1850   switch (cause) {
1851     case inflate_cause_vm_internal:    return "VM Internal";
1852     case inflate_cause_monitor_enter:  return "Monitor Enter";
1853     case inflate_cause_wait:           return "Monitor Wait";
1854     case inflate_cause_notify:         return "Monitor Notify";
1855     case inflate_cause_hash_code:      return "Monitor Hash Code";
1856     case inflate_cause_jni_enter:      return "JNI Monitor Enter";
1857     case inflate_cause_jni_exit:       return "JNI Monitor Exit";
1858     default:
1859       ShouldNotReachHere();
1860   }
1861   return "Unknown";
1862 }
1863 
1864 //------------------------------------------------------------------------------
1865 // Debugging code
1866 
1867 u_char* ObjectSynchronizer::get_gvars_addr() {
1868   return (u_char*)&GVars;
1869 }
1870 
1871 u_char* ObjectSynchronizer::get_gvars_hcSequence_addr() {
1872   return (u_char*)&GVars.hcSequence;
1873 }
1874 
1875 size_t ObjectSynchronizer::get_gvars_size() {
1876   return sizeof(SharedGlobals);
1877 }
1878 
1879 u_char* ObjectSynchronizer::get_gvars_stwRandom_addr() {
1880   return (u_char*)&GVars.stwRandom;
1881 }
1882 
1883 void ObjectSynchronizer::audit_and_print_stats(bool on_exit) {
1884   assert(on_exit || SafepointSynchronize::is_at_safepoint(), "invariant");
1885 
1886   LogStreamHandle(Debug, monitorinflation) lsh_debug;
1887   LogStreamHandle(Info, monitorinflation) lsh_info;
1888   LogStreamHandle(Trace, monitorinflation) lsh_trace;
1889   LogStream * ls = NULL;
1890   if (log_is_enabled(Trace, monitorinflation)) {
1891     ls = &lsh_trace;
1892   } else if (log_is_enabled(Debug, monitorinflation)) {
1893     ls = &lsh_debug;
1894   } else if (log_is_enabled(Info, monitorinflation)) {
1895     ls = &lsh_info;
1896   }
1897   assert(ls != NULL, "sanity check");
1898 
1899   if (!on_exit) {
1900     // Not at VM exit so grab the global list lock.
1901     Thread::muxAcquire(&gListLock, "audit_and_print_stats");
1902   }
1903 
1904   // Log counts for the global and per-thread monitor lists:
1905   int chkMonitorPopulation = log_monitor_list_counts(ls);
1906   int error_cnt = 0;
1907 
1908   ls->print_cr("Checking global lists:");
1909 
1910   // Check gMonitorPopulation:
1911   if (gMonitorPopulation == chkMonitorPopulation) {
1912     ls->print_cr("gMonitorPopulation=%d equals chkMonitorPopulation=%d",
1913                  gMonitorPopulation, chkMonitorPopulation);
1914   } else {
1915     ls->print_cr("ERROR: gMonitorPopulation=%d is not equal to "
1916                  "chkMonitorPopulation=%d", gMonitorPopulation,
1917                  chkMonitorPopulation);
1918     error_cnt++;
1919   }
1920 
1921   // Check gOmInUseList and gOmInUseCount:
1922   chk_global_in_use_list_and_count(ls, &error_cnt);
1923 
1924   // Check gFreeList and gMonitorFreeCount:
1925   chk_global_free_list_and_count(ls, &error_cnt);
1926 
1927   if (!on_exit) {
1928     Thread::muxRelease(&gListLock);
1929   }
1930 
1931   ls->print_cr("Checking per-thread lists:");
1932 
1933   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
1934     // Check omInUseList and omInUseCount:
1935     chk_per_thread_in_use_list_and_count(jt, ls, &error_cnt);
1936 
1937     // Check omFreeList and omFreeCount:
1938     chk_per_thread_free_list_and_count(jt, ls, &error_cnt);
1939   }
1940 
1941   if (error_cnt == 0) {
1942     ls->print_cr("No errors found in monitor list checks.");
1943   } else {
1944     log_error(monitorinflation)("found monitor list errors: error_cnt=%d", error_cnt);
1945   }
1946 
1947   if ((on_exit && log_is_enabled(Info, monitorinflation)) ||
1948       (!on_exit && log_is_enabled(Trace, monitorinflation))) {
1949     // When exiting this log output is at the Info level. When called
1950     // at a safepoint, this log output is at the Trace level since
1951     // there can be a lot of it.
1952     log_in_use_monitor_details(ls, on_exit);
1953   }
1954 
1955   ls->flush();
1956 
1957   guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt);
1958 }
1959 
1960 // Check a free monitor entry; log any errors.
1961 void ObjectSynchronizer::chk_free_entry(JavaThread * jt, ObjectMonitor * n,
1962                                         outputStream * out, int *error_cnt_p) {
1963   stringStream ss;
1964   if (n->is_busy()) {
1965     if (jt != NULL) {
1966       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
1967                     ": free per-thread monitor must not be busy: %s", p2i(jt),
1968                     p2i(n), n->is_busy_to_string(&ss));
1969     } else {
1970       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
1971                     "must not be busy: %s", p2i(n), n->is_busy_to_string(&ss));
1972     }
1973     *error_cnt_p = *error_cnt_p + 1;
1974   }
1975   if (n->header() != NULL) {
1976     if (jt != NULL) {
1977       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
1978                     ": free per-thread monitor must have NULL _header "
1979                     "field: _header=" INTPTR_FORMAT, p2i(jt), p2i(n),
1980                     p2i(n->header()));
1981     } else {
1982       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
1983                     "must have NULL _header field: _header=" INTPTR_FORMAT,
1984                     p2i(n), p2i(n->header()));
1985     }
1986     *error_cnt_p = *error_cnt_p + 1;
1987   }
1988   if (n->object() != NULL) {
1989     if (jt != NULL) {
1990       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
1991                     ": free per-thread monitor must have NULL _object "
1992                     "field: _object=" INTPTR_FORMAT, p2i(jt), p2i(n),
1993                     p2i(n->object()));
1994     } else {
1995       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor "
1996                     "must have NULL _object field: _object=" INTPTR_FORMAT,
1997                     p2i(n), p2i(n->object()));
1998     }
1999     *error_cnt_p = *error_cnt_p + 1;
2000   }
2001 }
2002 
2003 // Check the global free list and count; log the results of the checks.
2004 void ObjectSynchronizer::chk_global_free_list_and_count(outputStream * out,
2005                                                         int *error_cnt_p) {
2006   int chkMonitorFreeCount = 0;
2007   for (ObjectMonitor * n = gFreeList; n != NULL; n = n->FreeNext) {
2008     chk_free_entry(NULL /* jt */, n, out, error_cnt_p);
2009     chkMonitorFreeCount++;
2010   }
2011   if (gMonitorFreeCount == chkMonitorFreeCount) {
2012     out->print_cr("gMonitorFreeCount=%d equals chkMonitorFreeCount=%d",
2013                   gMonitorFreeCount, chkMonitorFreeCount);
2014   } else {
2015     out->print_cr("ERROR: gMonitorFreeCount=%d is not equal to "
2016                   "chkMonitorFreeCount=%d", gMonitorFreeCount,
2017                   chkMonitorFreeCount);
2018     *error_cnt_p = *error_cnt_p + 1;
2019   }
2020 }
2021 
2022 // Check the global in-use list and count; log the results of the checks.
2023 void ObjectSynchronizer::chk_global_in_use_list_and_count(outputStream * out,
2024                                                           int *error_cnt_p) {
2025   int chkOmInUseCount = 0;
2026   for (ObjectMonitor * n = gOmInUseList; n != NULL; n = n->FreeNext) {
2027     chk_in_use_entry(NULL /* jt */, n, out, error_cnt_p);
2028     chkOmInUseCount++;
2029   }
2030   if (gOmInUseCount == chkOmInUseCount) {
2031     out->print_cr("gOmInUseCount=%d equals chkOmInUseCount=%d", gOmInUseCount,
2032                   chkOmInUseCount);
2033   } else {
2034     out->print_cr("ERROR: gOmInUseCount=%d is not equal to chkOmInUseCount=%d",
2035                   gOmInUseCount, chkOmInUseCount);
2036     *error_cnt_p = *error_cnt_p + 1;
2037   }
2038 }
2039 
2040 // Check an in-use monitor entry; log any errors.
2041 void ObjectSynchronizer::chk_in_use_entry(JavaThread * jt, ObjectMonitor * n,
2042                                           outputStream * out, int *error_cnt_p) {
2043   if (n->header() == NULL) {
2044     if (jt != NULL) {
2045       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2046                     ": in-use per-thread monitor must have non-NULL _header "
2047                     "field.", p2i(jt), p2i(n));
2048     } else {
2049       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global monitor "
2050                     "must have non-NULL _header field.", p2i(n));
2051     }
2052     *error_cnt_p = *error_cnt_p + 1;
2053   }
2054   if (n->object() == NULL) {
2055     if (jt != NULL) {
2056       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2057                     ": in-use per-thread monitor must have non-NULL _object "
2058                     "field.", p2i(jt), p2i(n));
2059     } else {
2060       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global monitor "
2061                     "must have non-NULL _object field.", p2i(n));
2062     }
2063     *error_cnt_p = *error_cnt_p + 1;
2064   }
2065   const oop obj = (oop)n->object();
2066   const markOop mark = obj->mark();
2067   if (!mark->has_monitor()) {
2068     if (jt != NULL) {
2069       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2070                     ": in-use per-thread monitor's object does not think "
2071                     "it has a monitor: obj=" INTPTR_FORMAT ", mark="
2072                     INTPTR_FORMAT,  p2i(jt), p2i(n), p2i(obj), p2i(mark));
2073     } else {
2074       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global "
2075                     "monitor's object does not think it has a monitor: obj="
2076                     INTPTR_FORMAT ", mark=" INTPTR_FORMAT, p2i(n),
2077                     p2i(obj), p2i(mark));
2078     }
2079     *error_cnt_p = *error_cnt_p + 1;
2080   }
2081   ObjectMonitor * const obj_mon = mark->monitor();
2082   if (n != obj_mon) {
2083     if (jt != NULL) {
2084       out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT
2085                     ": in-use per-thread monitor's object does not refer "
2086                     "to the same monitor: obj=" INTPTR_FORMAT ", mark="
2087                     INTPTR_FORMAT ", obj_mon=" INTPTR_FORMAT, p2i(jt),
2088                     p2i(n), p2i(obj), p2i(mark), p2i(obj_mon));
2089     } else {
2090       out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global "
2091                     "monitor's object does not refer to the same monitor: obj="
2092                     INTPTR_FORMAT ", mark=" INTPTR_FORMAT ", obj_mon="
2093                     INTPTR_FORMAT, p2i(n), p2i(obj), p2i(mark), p2i(obj_mon));
2094     }
2095     *error_cnt_p = *error_cnt_p + 1;
2096   }
2097 }
2098 
2099 // Check the thread's free list and count; log the results of the checks.
2100 void ObjectSynchronizer::chk_per_thread_free_list_and_count(JavaThread *jt,
2101                                                             outputStream * out,
2102                                                             int *error_cnt_p) {
2103   int chkOmFreeCount = 0;
2104   for (ObjectMonitor * n = jt->omFreeList; n != NULL; n = n->FreeNext) {
2105     chk_free_entry(jt, n, out, error_cnt_p);
2106     chkOmFreeCount++;
2107   }
2108   if (jt->omFreeCount == chkOmFreeCount) {
2109     out->print_cr("jt=" INTPTR_FORMAT ": omFreeCount=%d equals "
2110                   "chkOmFreeCount=%d", p2i(jt), jt->omFreeCount, chkOmFreeCount);
2111   } else {
2112     out->print_cr("ERROR: jt=" INTPTR_FORMAT ": omFreeCount=%d is not "
2113                   "equal to chkOmFreeCount=%d", p2i(jt), jt->omFreeCount,
2114                   chkOmFreeCount);
2115     *error_cnt_p = *error_cnt_p + 1;
2116   }
2117 }
2118 
2119 // Check the thread's in-use list and count; log the results of the checks.
2120 void ObjectSynchronizer::chk_per_thread_in_use_list_and_count(JavaThread *jt,
2121                                                               outputStream * out,
2122                                                               int *error_cnt_p) {
2123   int chkOmInUseCount = 0;
2124   for (ObjectMonitor * n = jt->omInUseList; n != NULL; n = n->FreeNext) {
2125     chk_in_use_entry(jt, n, out, error_cnt_p);
2126     chkOmInUseCount++;
2127   }
2128   if (jt->omInUseCount == chkOmInUseCount) {
2129     out->print_cr("jt=" INTPTR_FORMAT ": omInUseCount=%d equals "
2130                   "chkOmInUseCount=%d", p2i(jt), jt->omInUseCount,
2131                   chkOmInUseCount);
2132   } else {
2133     out->print_cr("ERROR: jt=" INTPTR_FORMAT ": omInUseCount=%d is not "
2134                   "equal to chkOmInUseCount=%d", p2i(jt), jt->omInUseCount,
2135                   chkOmInUseCount);
2136     *error_cnt_p = *error_cnt_p + 1;
2137   }
2138 }
2139 
2140 // Log details about ObjectMonitors on the in-use lists. The 'BHL'
2141 // flags indicate why the entry is in-use, 'object' and 'object type'
2142 // indicate the associated object and its type.
2143 void ObjectSynchronizer::log_in_use_monitor_details(outputStream * out,
2144                                                     bool on_exit) {
2145   if (!on_exit) {
2146     // Not at VM exit so grab the global list lock.
2147     Thread::muxAcquire(&gListLock, "log_in_use_monitor_details");
2148   }
2149 
2150   stringStream ss;
2151   if (gOmInUseCount > 0) {
2152     out->print_cr("In-use global monitor info:");
2153     out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
2154     out->print_cr("%18s  %s  %18s  %18s",
2155                   "monitor", "BHL", "object", "object type");
2156     out->print_cr("==================  ===  ==================  ==================");
2157     for (ObjectMonitor * n = gOmInUseList; n != NULL; n = n->FreeNext) {
2158       const oop obj = (oop) n->object();
2159       const markOop mark = n->header();
2160       ResourceMark rm;
2161       out->print(INTPTR_FORMAT "  %d%d%d  " INTPTR_FORMAT "  %s", p2i(n),
2162                  n->is_busy() != 0, mark->hash() != 0, n->owner() != NULL,
2163                  p2i(obj), obj->klass()->external_name());
2164       if (n->is_busy() != 0) {
2165         out->print(" (%s)", n->is_busy_to_string(&ss));
2166         ss.reset();
2167       }
2168       out->cr();
2169     }
2170   }
2171 
2172   if (!on_exit) {
2173     Thread::muxRelease(&gListLock);
2174   }
2175 
2176   out->print_cr("In-use per-thread monitor info:");
2177   out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
2178   out->print_cr("%18s  %18s  %s  %18s  %18s",
2179                 "jt", "monitor", "BHL", "object", "object type");
2180   out->print_cr("==================  ==================  ===  ==================  ==================");
2181   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
2182     for (ObjectMonitor * n = jt->omInUseList; n != NULL; n = n->FreeNext) {
2183       const oop obj = (oop) n->object();
2184       const markOop mark = n->header();
2185       ResourceMark rm;
2186       out->print(INTPTR_FORMAT "  " INTPTR_FORMAT "  %d%d%d  " INTPTR_FORMAT
2187                  "  %s", p2i(jt), p2i(n), n->is_busy() != 0,
2188                  mark->hash() != 0, n->owner() != NULL, p2i(obj),
2189                  obj->klass()->external_name());
2190       if (n->is_busy() != 0) {
2191         out->print(" (%s)", n->is_busy_to_string(&ss));
2192         ss.reset();
2193       }
2194       out->cr();
2195     }
2196   }
2197 
2198   out->flush();
2199 }
2200 
2201 // Log counts for the global and per-thread monitor lists and return
2202 // the population count.
2203 int ObjectSynchronizer::log_monitor_list_counts(outputStream * out) {
2204   int popCount = 0;
2205   out->print_cr("%18s  %10s  %10s  %10s",
2206                 "Global Lists:", "InUse", "Free", "Total");
2207   out->print_cr("==================  ==========  ==========  ==========");
2208   out->print_cr("%18s  %10d  %10d  %10d", "",
2209                 gOmInUseCount, gMonitorFreeCount, gMonitorPopulation);
2210   popCount += gOmInUseCount + gMonitorFreeCount;
2211 
2212   out->print_cr("%18s  %10s  %10s  %10s",
2213                 "Per-Thread Lists:", "InUse", "Free", "Provision");
2214   out->print_cr("==================  ==========  ==========  ==========");
2215 
2216   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
2217     out->print_cr(INTPTR_FORMAT "  %10d  %10d  %10d", p2i(jt),
2218                   jt->omInUseCount, jt->omFreeCount, jt->omFreeProvision);
2219     popCount += jt->omInUseCount + jt->omFreeCount;
2220   }
2221   return popCount;
2222 }
2223 
2224 #ifndef PRODUCT
2225 
2226 // Check if monitor belongs to the monitor cache
2227 // The list is grow-only so it's *relatively* safe to traverse
2228 // the list of extant blocks without taking a lock.
2229 
2230 int ObjectSynchronizer::verify_objmon_isinpool(ObjectMonitor *monitor) {
2231   PaddedEnd<ObjectMonitor> * block = OrderAccess::load_acquire(&gBlockList);
2232   while (block != NULL) {
2233     assert(block->object() == CHAINMARKER, "must be a block header");
2234     if (monitor > &block[0] && monitor < &block[_BLOCKSIZE]) {
2235       address mon = (address)monitor;
2236       address blk = (address)block;
2237       size_t diff = mon - blk;
2238       assert((diff % sizeof(PaddedEnd<ObjectMonitor>)) == 0, "must be aligned");
2239       return 1;
2240     }
2241     block = (PaddedEnd<ObjectMonitor> *)block->FreeNext;
2242   }
2243   return 0;
2244 }
2245 
2246 #endif