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