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