src/share/vm/runtime/synchronizer.cpp

Tue, 29 Jul 2014 13:56:29 +0200

author
thartmann
date
Tue, 29 Jul 2014 13:56:29 +0200
changeset 7002
a073be2ce5c2
parent 6680
78bbf4d43a14
child 6876
710a3c8b516e
child 8189
c60b9a314312
permissions
-rw-r--r--

8049043: Load variable through a pointer of an incompatible type in hotspot/src/share/vm/runtime/sharedRuntimeMath.hpp
Summary: Fixed parfait warnings caused by __HI and __LO macros in sharedRuntimeMath.hpp by using a union.
Reviewed-by: kvn

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

mercurial