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