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