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