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