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