src/share/vm/runtime/synchronizer.cpp

Thu, 24 May 2018 20:03:11 +0800

author
aoqi
date
Thu, 24 May 2018 20:03:11 +0800
changeset 8868
91ddc23482a4
parent 8856
ac27a9c85bea
child 9852
70aa912cebe5
permissions
-rw-r--r--

Increase MaxHeapSize for better performance on MIPS

     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_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 at one time stored 0
   441 // into the global volatile OrderAccess::dummy variable. This store was
   442 // unnecessary for correctness. Many threads storing into a common location
   443 // causes considerable cache migration or "sloshing" on large SMP systems.
   444 // As such, I avoided using OrderAccess::storestore(). In some cases
   445 // OrderAccess::fence() -- which incurs local latency on the executing
   446 // processor -- is a better choice as it scales on SMP systems.
   447 //
   448 // See http://blogs.oracle.com/dave/entry/biased_locking_in_hotspot for
   449 // a discussion of coherency costs. Note that all our current reference
   450 // platforms provide strong ST-ST order, so the issue is moot on IA32,
   451 // x64, and SPARC.
   452 //
   453 // As a general policy we use "volatile" to control compiler-based reordering
   454 // and explicit fences (barriers) to control for architectural reordering
   455 // performed by the CPU(s) or platform.
   457 struct SharedGlobals {
   458     // These are highly shared mostly-read variables.
   459     // To avoid false-sharing they need to be the sole occupants of a $ line.
   460     double padPrefix [8];
   461     volatile int stwRandom ;
   462     volatile int stwCycle ;
   464     // Hot RW variables -- Sequester to avoid false-sharing
   465     double padSuffix [16];
   466     volatile int hcSequence ;
   467     double padFinal [8] ;
   468 } ;
   470 static SharedGlobals GVars ;
   471 static int MonitorScavengeThreshold = 1000000 ;
   472 static volatile int ForceMonitorScavenge = 0 ; // Scavenge required and pending
   474 static markOop ReadStableMark (oop obj) {
   475   markOop mark = obj->mark() ;
   476   if (!mark->is_being_inflated()) {
   477     return mark ;       // normal fast-path return
   478   }
   480   int its = 0 ;
   481   for (;;) {
   482     markOop mark = obj->mark() ;
   483     if (!mark->is_being_inflated()) {
   484       return mark ;    // normal fast-path return
   485     }
   487     // The object is being inflated by some other thread.
   488     // The caller of ReadStableMark() must wait for inflation to complete.
   489     // Avoid live-lock
   490     // TODO: consider calling SafepointSynchronize::do_call_back() while
   491     // spinning to see if there's a safepoint pending.  If so, immediately
   492     // yielding or blocking would be appropriate.  Avoid spinning while
   493     // there is a safepoint pending.
   494     // TODO: add inflation contention performance counters.
   495     // TODO: restrict the aggregate number of spinners.
   497     ++its ;
   498     if (its > 10000 || !os::is_MP()) {
   499        if (its & 1) {
   500          os::NakedYield() ;
   501          TEVENT (Inflate: INFLATING - yield) ;
   502        } else {
   503          // Note that the following code attenuates the livelock problem but is not
   504          // a complete remedy.  A more complete solution would require that the inflating
   505          // thread hold the associated inflation lock.  The following code simply restricts
   506          // the number of spinners to at most one.  We'll have N-2 threads blocked
   507          // on the inflationlock, 1 thread holding the inflation lock and using
   508          // a yield/park strategy, and 1 thread in the midst of inflation.
   509          // A more refined approach would be to change the encoding of INFLATING
   510          // to allow encapsulation of a native thread pointer.  Threads waiting for
   511          // inflation to complete would use CAS to push themselves onto a singly linked
   512          // list rooted at the markword.  Once enqueued, they'd loop, checking a per-thread flag
   513          // and calling park().  When inflation was complete the thread that accomplished inflation
   514          // would detach the list and set the markword to inflated with a single CAS and
   515          // then for each thread on the list, set the flag and unpark() the thread.
   516          // This is conceptually similar to muxAcquire-muxRelease, except that muxRelease
   517          // wakes at most one thread whereas we need to wake the entire list.
   518          int ix = (cast_from_oop<intptr_t>(obj) >> 5) & (NINFLATIONLOCKS-1) ;
   519          int YieldThenBlock = 0 ;
   520          assert (ix >= 0 && ix < NINFLATIONLOCKS, "invariant") ;
   521          assert ((NINFLATIONLOCKS & (NINFLATIONLOCKS-1)) == 0, "invariant") ;
   522          Thread::muxAcquire (InflationLocks + ix, "InflationLock") ;
   523          while (obj->mark() == markOopDesc::INFLATING()) {
   524            // Beware: NakedYield() is advisory and has almost no effect on some platforms
   525            // so we periodically call Self->_ParkEvent->park(1).
   526            // We use a mixed spin/yield/block mechanism.
   527            if ((YieldThenBlock++) >= 16) {
   528               Thread::current()->_ParkEvent->park(1) ;
   529            } else {
   530               os::NakedYield() ;
   531            }
   532          }
   533          Thread::muxRelease (InflationLocks + ix ) ;
   534          TEVENT (Inflate: INFLATING - yield/park) ;
   535        }
   536     } else {
   537        SpinPause() ;       // SMP-polite spinning
   538     }
   539   }
   540 }
   542 // hashCode() generation :
   543 //
   544 // Possibilities:
   545 // * MD5Digest of {obj,stwRandom}
   546 // * CRC32 of {obj,stwRandom} or any linear-feedback shift register function.
   547 // * A DES- or AES-style SBox[] mechanism
   548 // * One of the Phi-based schemes, such as:
   549 //   2654435761 = 2^32 * Phi (golden ratio)
   550 //   HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stwRandom ;
   551 // * A variation of Marsaglia's shift-xor RNG scheme.
   552 // * (obj ^ stwRandom) is appealing, but can result
   553 //   in undesirable regularity in the hashCode values of adjacent objects
   554 //   (objects allocated back-to-back, in particular).  This could potentially
   555 //   result in hashtable collisions and reduced hashtable efficiency.
   556 //   There are simple ways to "diffuse" the middle address bits over the
   557 //   generated hashCode values:
   558 //
   560 static inline intptr_t get_next_hash(Thread * Self, oop obj) {
   561   intptr_t value = 0 ;
   562   if (hashCode == 0) {
   563      // This form uses an unguarded global Park-Miller RNG,
   564      // so it's possible for two threads to race and generate the same RNG.
   565      // On MP system we'll have lots of RW access to a global, so the
   566      // mechanism induces lots of coherency traffic.
   567      value = os::random() ;
   568   } else
   569   if (hashCode == 1) {
   570      // This variation has the property of being stable (idempotent)
   571      // between STW operations.  This can be useful in some of the 1-0
   572      // synchronization schemes.
   573      intptr_t addrBits = cast_from_oop<intptr_t>(obj) >> 3 ;
   574      value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom ;
   575   } else
   576   if (hashCode == 2) {
   577      value = 1 ;            // for sensitivity testing
   578   } else
   579   if (hashCode == 3) {
   580      value = ++GVars.hcSequence ;
   581   } else
   582   if (hashCode == 4) {
   583      value = cast_from_oop<intptr_t>(obj) ;
   584   } else {
   585      // Marsaglia's xor-shift scheme with thread-specific state
   586      // This is probably the best overall implementation -- we'll
   587      // likely make this the default in future releases.
   588      unsigned t = Self->_hashStateX ;
   589      t ^= (t << 11) ;
   590      Self->_hashStateX = Self->_hashStateY ;
   591      Self->_hashStateY = Self->_hashStateZ ;
   592      Self->_hashStateZ = Self->_hashStateW ;
   593      unsigned v = Self->_hashStateW ;
   594      v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)) ;
   595      Self->_hashStateW = v ;
   596      value = v ;
   597   }
   599   value &= markOopDesc::hash_mask;
   600   if (value == 0) value = 0xBAD ;
   601   assert (value != markOopDesc::no_hash, "invariant") ;
   602   TEVENT (hashCode: GENERATE) ;
   603   return value;
   604 }
   605 //
   606 intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) {
   607   if (UseBiasedLocking) {
   608     // NOTE: many places throughout the JVM do not expect a safepoint
   609     // to be taken here, in particular most operations on perm gen
   610     // objects. However, we only ever bias Java instances and all of
   611     // the call sites of identity_hash that might revoke biases have
   612     // been checked to make sure they can handle a safepoint. The
   613     // added check of the bias pattern is to avoid useless calls to
   614     // thread-local storage.
   615     if (obj->mark()->has_bias_pattern()) {
   616       // Box and unbox the raw reference just in case we cause a STW safepoint.
   617       Handle hobj (Self, obj) ;
   618       // Relaxing assertion for bug 6320749.
   619       assert (Universe::verify_in_progress() ||
   620               !SafepointSynchronize::is_at_safepoint(),
   621              "biases should not be seen by VM thread here");
   622       BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current());
   623       obj = hobj() ;
   624       assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
   625     }
   626   }
   628   // hashCode() is a heap mutator ...
   629   // Relaxing assertion for bug 6320749.
   630   assert (Universe::verify_in_progress() ||
   631           !SafepointSynchronize::is_at_safepoint(), "invariant") ;
   632   assert (Universe::verify_in_progress() ||
   633           Self->is_Java_thread() , "invariant") ;
   634   assert (Universe::verify_in_progress() ||
   635          ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant") ;
   637   ObjectMonitor* monitor = NULL;
   638   markOop temp, test;
   639   intptr_t hash;
   640   markOop mark = ReadStableMark (obj);
   642   // object should remain ineligible for biased locking
   643   assert (!mark->has_bias_pattern(), "invariant") ;
   645   if (mark->is_neutral()) {
   646     hash = mark->hash();              // this is a normal header
   647     if (hash) {                       // if it has hash, just return it
   648       return hash;
   649     }
   650     hash = get_next_hash(Self, obj);  // allocate a new hash code
   651     temp = mark->copy_set_hash(hash); // merge the hash code into header
   652     // use (machine word version) atomic operation to install the hash
   653     test = (markOop) Atomic::cmpxchg_ptr(temp, obj->mark_addr(), mark);
   654     if (test == mark) {
   655       return hash;
   656     }
   657     // If atomic operation failed, we must inflate the header
   658     // into heavy weight monitor. We could add more code here
   659     // for fast path, but it does not worth the complexity.
   660   } else if (mark->has_monitor()) {
   661     monitor = mark->monitor();
   662     temp = monitor->header();
   663     assert (temp->is_neutral(), "invariant") ;
   664     hash = temp->hash();
   665     if (hash) {
   666       return hash;
   667     }
   668     // Skip to the following code to reduce code size
   669   } else if (Self->is_lock_owned((address)mark->locker())) {
   670     temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned
   671     assert (temp->is_neutral(), "invariant") ;
   672     hash = temp->hash();              // by current thread, check if the displaced
   673     if (hash) {                       // header contains hash code
   674       return hash;
   675     }
   676     // WARNING:
   677     //   The displaced header is strictly immutable.
   678     // It can NOT be changed in ANY cases. So we have
   679     // to inflate the header into heavyweight monitor
   680     // even the current thread owns the lock. The reason
   681     // is the BasicLock (stack slot) will be asynchronously
   682     // read by other threads during the inflate() function.
   683     // Any change to stack may not propagate to other threads
   684     // correctly.
   685   }
   687   // Inflate the monitor to set hash code
   688   monitor = ObjectSynchronizer::inflate(Self, obj);
   689   // Load displaced header and check it has hash code
   690   mark = monitor->header();
   691   assert (mark->is_neutral(), "invariant") ;
   692   hash = mark->hash();
   693   if (hash == 0) {
   694     hash = get_next_hash(Self, obj);
   695     temp = mark->copy_set_hash(hash); // merge hash code into header
   696     assert (temp->is_neutral(), "invariant") ;
   697     test = (markOop) Atomic::cmpxchg_ptr(temp, monitor, mark);
   698     if (test != mark) {
   699       // The only update to the header in the monitor (outside GC)
   700       // is install the hash code. If someone add new usage of
   701       // displaced header, please update this code
   702       hash = test->hash();
   703       assert (test->is_neutral(), "invariant") ;
   704       assert (hash != 0, "Trivial unexpected object/monitor header usage.");
   705     }
   706   }
   707   // We finally get the hash
   708   return hash;
   709 }
   711 // Deprecated -- use FastHashCode() instead.
   713 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) {
   714   return FastHashCode (Thread::current(), obj()) ;
   715 }
   718 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread,
   719                                                    Handle h_obj) {
   720   if (UseBiasedLocking) {
   721     BiasedLocking::revoke_and_rebias(h_obj, false, thread);
   722     assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
   723   }
   725   assert(thread == JavaThread::current(), "Can only be called on current thread");
   726   oop obj = h_obj();
   728   markOop mark = ReadStableMark (obj) ;
   730   // Uncontended case, header points to stack
   731   if (mark->has_locker()) {
   732     return thread->is_lock_owned((address)mark->locker());
   733   }
   734   // Contended case, header points to ObjectMonitor (tagged pointer)
   735   if (mark->has_monitor()) {
   736     ObjectMonitor* monitor = mark->monitor();
   737     return monitor->is_entered(thread) != 0 ;
   738   }
   739   // Unlocked case, header in place
   740   assert(mark->is_neutral(), "sanity check");
   741   return false;
   742 }
   744 // Be aware of this method could revoke bias of the lock object.
   745 // This method querys the ownership of the lock handle specified by 'h_obj'.
   746 // If the current thread owns the lock, it returns owner_self. If no
   747 // thread owns the lock, it returns owner_none. Otherwise, it will return
   748 // ower_other.
   749 ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership
   750 (JavaThread *self, Handle h_obj) {
   751   // The caller must beware this method can revoke bias, and
   752   // revocation can result in a safepoint.
   753   assert (!SafepointSynchronize::is_at_safepoint(), "invariant") ;
   754   assert (self->thread_state() != _thread_blocked , "invariant") ;
   756   // Possible mark states: neutral, biased, stack-locked, inflated
   758   if (UseBiasedLocking && h_obj()->mark()->has_bias_pattern()) {
   759     // CASE: biased
   760     BiasedLocking::revoke_and_rebias(h_obj, false, self);
   761     assert(!h_obj->mark()->has_bias_pattern(),
   762            "biases should be revoked by now");
   763   }
   765   assert(self == JavaThread::current(), "Can only be called on current thread");
   766   oop obj = h_obj();
   767   markOop mark = ReadStableMark (obj) ;
   769   // CASE: stack-locked.  Mark points to a BasicLock on the owner's stack.
   770   if (mark->has_locker()) {
   771     return self->is_lock_owned((address)mark->locker()) ?
   772       owner_self : owner_other;
   773   }
   775   // CASE: inflated. Mark (tagged pointer) points to an objectMonitor.
   776   // The Object:ObjectMonitor relationship is stable as long as we're
   777   // not at a safepoint.
   778   if (mark->has_monitor()) {
   779     void * owner = mark->monitor()->_owner ;
   780     if (owner == NULL) return owner_none ;
   781     return (owner == self ||
   782             self->is_lock_owned((address)owner)) ? owner_self : owner_other;
   783   }
   785   // CASE: neutral
   786   assert(mark->is_neutral(), "sanity check");
   787   return owner_none ;           // it's unlocked
   788 }
   790 // FIXME: jvmti should call this
   791 JavaThread* ObjectSynchronizer::get_lock_owner(Handle h_obj, bool doLock) {
   792   if (UseBiasedLocking) {
   793     if (SafepointSynchronize::is_at_safepoint()) {
   794       BiasedLocking::revoke_at_safepoint(h_obj);
   795     } else {
   796       BiasedLocking::revoke_and_rebias(h_obj, false, JavaThread::current());
   797     }
   798     assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
   799   }
   801   oop obj = h_obj();
   802   address owner = NULL;
   804   markOop mark = ReadStableMark (obj) ;
   806   // Uncontended case, header points to stack
   807   if (mark->has_locker()) {
   808     owner = (address) mark->locker();
   809   }
   811   // Contended case, header points to ObjectMonitor (tagged pointer)
   812   if (mark->has_monitor()) {
   813     ObjectMonitor* monitor = mark->monitor();
   814     assert(monitor != NULL, "monitor should be non-null");
   815     owner = (address) monitor->owner();
   816   }
   818   if (owner != NULL) {
   819     // owning_thread_from_monitor_owner() may also return NULL here
   820     return Threads::owning_thread_from_monitor_owner(owner, doLock);
   821   }
   823   // Unlocked case, header in place
   824   // Cannot have assertion since this object may have been
   825   // locked by another thread when reaching here.
   826   // assert(mark->is_neutral(), "sanity check");
   828   return NULL;
   829 }
   830 // Visitors ...
   832 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure) {
   833   ObjectMonitor* block = gBlockList;
   834   ObjectMonitor* mid;
   835   while (block) {
   836     assert(block->object() == CHAINMARKER, "must be a block header");
   837     for (int i = _BLOCKSIZE - 1; i > 0; i--) {
   838       mid = block + i;
   839       oop object = (oop) mid->object();
   840       if (object != NULL) {
   841         closure->do_monitor(mid);
   842       }
   843     }
   844     block = (ObjectMonitor*) block->FreeNext;
   845   }
   846 }
   848 // Get the next block in the block list.
   849 static inline ObjectMonitor* next(ObjectMonitor* block) {
   850   assert(block->object() == CHAINMARKER, "must be a block header");
   851   block = block->FreeNext ;
   852   assert(block == NULL || block->object() == CHAINMARKER, "must be a block header");
   853   return block;
   854 }
   857 void ObjectSynchronizer::oops_do(OopClosure* f) {
   858   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
   859   for (ObjectMonitor* block = gBlockList; block != NULL; block = next(block)) {
   860     assert(block->object() == CHAINMARKER, "must be a block header");
   861     for (int i = 1; i < _BLOCKSIZE; i++) {
   862       ObjectMonitor* mid = &block[i];
   863       if (mid->object() != NULL) {
   864         f->do_oop((oop*)mid->object_addr());
   865       }
   866     }
   867   }
   868 }
   871 // -----------------------------------------------------------------------------
   872 // ObjectMonitor Lifecycle
   873 // -----------------------
   874 // Inflation unlinks monitors from the global gFreeList and
   875 // associates them with objects.  Deflation -- which occurs at
   876 // STW-time -- disassociates idle monitors from objects.  Such
   877 // scavenged monitors are returned to the gFreeList.
   878 //
   879 // The global list is protected by ListLock.  All the critical sections
   880 // are short and operate in constant-time.
   881 //
   882 // ObjectMonitors reside in type-stable memory (TSM) and are immortal.
   883 //
   884 // Lifecycle:
   885 // --   unassigned and on the global free list
   886 // --   unassigned and on a thread's private omFreeList
   887 // --   assigned to an object.  The object is inflated and the mark refers
   888 //      to the objectmonitor.
   889 //
   892 // Constraining monitor pool growth via MonitorBound ...
   893 //
   894 // The monitor pool is grow-only.  We scavenge at STW safepoint-time, but the
   895 // the rate of scavenging is driven primarily by GC.  As such,  we can find
   896 // an inordinate number of monitors in circulation.
   897 // To avoid that scenario we can artificially induce a STW safepoint
   898 // if the pool appears to be growing past some reasonable bound.
   899 // Generally we favor time in space-time tradeoffs, but as there's no
   900 // natural back-pressure on the # of extant monitors we need to impose some
   901 // type of limit.  Beware that if MonitorBound is set to too low a value
   902 // we could just loop. In addition, if MonitorBound is set to a low value
   903 // we'll incur more safepoints, which are harmful to performance.
   904 // See also: GuaranteedSafepointInterval
   905 //
   906 // The current implementation uses asynchronous VM operations.
   907 //
   909 static void InduceScavenge (Thread * Self, const char * Whence) {
   910   // Induce STW safepoint to trim monitors
   911   // Ultimately, this results in a call to deflate_idle_monitors() in the near future.
   912   // More precisely, trigger an asynchronous STW safepoint as the number
   913   // of active monitors passes the specified threshold.
   914   // TODO: assert thread state is reasonable
   916   if (ForceMonitorScavenge == 0 && Atomic::xchg (1, &ForceMonitorScavenge) == 0) {
   917     if (ObjectMonitor::Knob_Verbose) {
   918       ::printf ("Monitor scavenge - Induced STW @%s (%d)\n", Whence, ForceMonitorScavenge) ;
   919       ::fflush(stdout) ;
   920     }
   921     // Induce a 'null' safepoint to scavenge monitors
   922     // Must VM_Operation instance be heap allocated as the op will be enqueue and posted
   923     // to the VMthread and have a lifespan longer than that of this activation record.
   924     // The VMThread will delete the op when completed.
   925     VMThread::execute (new VM_ForceAsyncSafepoint()) ;
   927     if (ObjectMonitor::Knob_Verbose) {
   928       ::printf ("Monitor scavenge - STW posted @%s (%d)\n", Whence, ForceMonitorScavenge) ;
   929       ::fflush(stdout) ;
   930     }
   931   }
   932 }
   933 /* Too slow for general assert or debug
   934 void ObjectSynchronizer::verifyInUse (Thread *Self) {
   935    ObjectMonitor* mid;
   936    int inusetally = 0;
   937    for (mid = Self->omInUseList; mid != NULL; mid = mid->FreeNext) {
   938      inusetally ++;
   939    }
   940    assert(inusetally == Self->omInUseCount, "inuse count off");
   942    int freetally = 0;
   943    for (mid = Self->omFreeList; mid != NULL; mid = mid->FreeNext) {
   944      freetally ++;
   945    }
   946    assert(freetally == Self->omFreeCount, "free count off");
   947 }
   948 */
   949 ObjectMonitor * ATTR ObjectSynchronizer::omAlloc (Thread * Self) {
   950     // A large MAXPRIVATE value reduces both list lock contention
   951     // and list coherency traffic, but also tends to increase the
   952     // number of objectMonitors in circulation as well as the STW
   953     // scavenge costs.  As usual, we lean toward time in space-time
   954     // tradeoffs.
   955     const int MAXPRIVATE = 1024 ;
   956     for (;;) {
   957         ObjectMonitor * m ;
   959         // 1: try to allocate from the thread's local omFreeList.
   960         // Threads will attempt to allocate first from their local list, then
   961         // from the global list, and only after those attempts fail will the thread
   962         // attempt to instantiate new monitors.   Thread-local free lists take
   963         // heat off the ListLock and improve allocation latency, as well as reducing
   964         // coherency traffic on the shared global list.
   965         m = Self->omFreeList ;
   966         if (m != NULL) {
   967            Self->omFreeList = m->FreeNext ;
   968            Self->omFreeCount -- ;
   969            // CONSIDER: set m->FreeNext = BAD -- diagnostic hygiene
   970            guarantee (m->object() == NULL, "invariant") ;
   971            if (MonitorInUseLists) {
   972              m->FreeNext = Self->omInUseList;
   973              Self->omInUseList = m;
   974              Self->omInUseCount ++;
   975              // verifyInUse(Self);
   976            } else {
   977              m->FreeNext = NULL;
   978            }
   979            return m ;
   980         }
   982         // 2: try to allocate from the global gFreeList
   983         // CONSIDER: use muxTry() instead of muxAcquire().
   984         // If the muxTry() fails then drop immediately into case 3.
   985         // If we're using thread-local free lists then try
   986         // to reprovision the caller's free list.
   987         if (gFreeList != NULL) {
   988             // Reprovision the thread's omFreeList.
   989             // Use bulk transfers to reduce the allocation rate and heat
   990             // on various locks.
   991             Thread::muxAcquire (&ListLock, "omAlloc") ;
   992             for (int i = Self->omFreeProvision; --i >= 0 && gFreeList != NULL; ) {
   993                 MonitorFreeCount --;
   994                 ObjectMonitor * take = gFreeList ;
   995                 gFreeList = take->FreeNext ;
   996                 guarantee (take->object() == NULL, "invariant") ;
   997                 guarantee (!take->is_busy(), "invariant") ;
   998                 take->Recycle() ;
   999                 omRelease (Self, take, false) ;
  1001             Thread::muxRelease (&ListLock) ;
  1002             Self->omFreeProvision += 1 + (Self->omFreeProvision/2) ;
  1003             if (Self->omFreeProvision > MAXPRIVATE ) Self->omFreeProvision = MAXPRIVATE ;
  1004             TEVENT (omFirst - reprovision) ;
  1006             const int mx = MonitorBound ;
  1007             if (mx > 0 && (MonitorPopulation-MonitorFreeCount) > mx) {
  1008               // We can't safely induce a STW safepoint from omAlloc() as our thread
  1009               // state may not be appropriate for such activities and callers may hold
  1010               // naked oops, so instead we defer the action.
  1011               InduceScavenge (Self, "omAlloc") ;
  1013             continue;
  1016         // 3: allocate a block of new ObjectMonitors
  1017         // Both the local and global free lists are empty -- resort to malloc().
  1018         // In the current implementation objectMonitors are TSM - immortal.
  1019         assert (_BLOCKSIZE > 1, "invariant") ;
  1020         ObjectMonitor * temp = new ObjectMonitor[_BLOCKSIZE];
  1022         // NOTE: (almost) no way to recover if allocation failed.
  1023         // We might be able to induce a STW safepoint and scavenge enough
  1024         // objectMonitors to permit progress.
  1025         if (temp == NULL) {
  1026             vm_exit_out_of_memory (sizeof (ObjectMonitor[_BLOCKSIZE]), OOM_MALLOC_ERROR,
  1027                                    "Allocate ObjectMonitors");
  1030         // Format the block.
  1031         // initialize the linked list, each monitor points to its next
  1032         // forming the single linked free list, the very first monitor
  1033         // will points to next block, which forms the block list.
  1034         // The trick of using the 1st element in the block as gBlockList
  1035         // linkage should be reconsidered.  A better implementation would
  1036         // look like: class Block { Block * next; int N; ObjectMonitor Body [N] ; }
  1038         for (int i = 1; i < _BLOCKSIZE ; i++) {
  1039            temp[i].FreeNext = &temp[i+1];
  1042         // terminate the last monitor as the end of list
  1043         temp[_BLOCKSIZE - 1].FreeNext = NULL ;
  1045         // Element [0] is reserved for global list linkage
  1046         temp[0].set_object(CHAINMARKER);
  1048         // Consider carving out this thread's current request from the
  1049         // block in hand.  This avoids some lock traffic and redundant
  1050         // list activity.
  1052         // Acquire the ListLock to manipulate BlockList and FreeList.
  1053         // An Oyama-Taura-Yonezawa scheme might be more efficient.
  1054         Thread::muxAcquire (&ListLock, "omAlloc [2]") ;
  1055         MonitorPopulation += _BLOCKSIZE-1;
  1056         MonitorFreeCount += _BLOCKSIZE-1;
  1058         // Add the new block to the list of extant blocks (gBlockList).
  1059         // The very first objectMonitor in a block is reserved and dedicated.
  1060         // It serves as blocklist "next" linkage.
  1061         temp[0].FreeNext = gBlockList;
  1062         gBlockList = temp;
  1064         // Add the new string of objectMonitors to the global free list
  1065         temp[_BLOCKSIZE - 1].FreeNext = gFreeList ;
  1066         gFreeList = temp + 1;
  1067         Thread::muxRelease (&ListLock) ;
  1068         TEVENT (Allocate block of monitors) ;
  1072 // Place "m" on the caller's private per-thread omFreeList.
  1073 // In practice there's no need to clamp or limit the number of
  1074 // monitors on a thread's omFreeList as the only time we'll call
  1075 // omRelease is to return a monitor to the free list after a CAS
  1076 // attempt failed.  This doesn't allow unbounded #s of monitors to
  1077 // accumulate on a thread's free list.
  1078 //
  1080 void ObjectSynchronizer::omRelease (Thread * Self, ObjectMonitor * m, bool fromPerThreadAlloc) {
  1081     guarantee (m->object() == NULL, "invariant") ;
  1083     // Remove from omInUseList
  1084     if (MonitorInUseLists && fromPerThreadAlloc) {
  1085       ObjectMonitor* curmidinuse = NULL;
  1086       for (ObjectMonitor* mid = Self->omInUseList; mid != NULL; ) {
  1087        if (m == mid) {
  1088          // extract from per-thread in-use-list
  1089          if (mid == Self->omInUseList) {
  1090            Self->omInUseList = mid->FreeNext;
  1091          } else if (curmidinuse != NULL) {
  1092            curmidinuse->FreeNext = mid->FreeNext; // maintain the current thread inuselist
  1094          Self->omInUseCount --;
  1095          // verifyInUse(Self);
  1096          break;
  1097        } else {
  1098          curmidinuse = mid;
  1099          mid = mid->FreeNext;
  1104   // FreeNext is used for both onInUseList and omFreeList, so clear old before setting new
  1105   m->FreeNext = Self->omFreeList ;
  1106   Self->omFreeList = m ;
  1107   Self->omFreeCount ++ ;
  1110 // Return the monitors of a moribund thread's local free list to
  1111 // the global free list.  Typically a thread calls omFlush() when
  1112 // it's dying.  We could also consider having the VM thread steal
  1113 // monitors from threads that have not run java code over a few
  1114 // consecutive STW safepoints.  Relatedly, we might decay
  1115 // omFreeProvision at STW safepoints.
  1116 //
  1117 // Also return the monitors of a moribund thread"s omInUseList to
  1118 // a global gOmInUseList under the global list lock so these
  1119 // will continue to be scanned.
  1120 //
  1121 // We currently call omFlush() from the Thread:: dtor _after the thread
  1122 // has been excised from the thread list and is no longer a mutator.
  1123 // That means that omFlush() can run concurrently with a safepoint and
  1124 // the scavenge operator.  Calling omFlush() from JavaThread::exit() might
  1125 // be a better choice as we could safely reason that that the JVM is
  1126 // not at a safepoint at the time of the call, and thus there could
  1127 // be not inopportune interleavings between omFlush() and the scavenge
  1128 // operator.
  1130 void ObjectSynchronizer::omFlush (Thread * Self) {
  1131     ObjectMonitor * List = Self->omFreeList ;  // Null-terminated SLL
  1132     Self->omFreeList = NULL ;
  1133     ObjectMonitor * Tail = NULL ;
  1134     int Tally = 0;
  1135     if (List != NULL) {
  1136       ObjectMonitor * s ;
  1137       for (s = List ; s != NULL ; s = s->FreeNext) {
  1138           Tally ++ ;
  1139           Tail = s ;
  1140           guarantee (s->object() == NULL, "invariant") ;
  1141           guarantee (!s->is_busy(), "invariant") ;
  1142           s->set_owner (NULL) ;   // redundant but good hygiene
  1143           TEVENT (omFlush - Move one) ;
  1145       guarantee (Tail != NULL && List != NULL, "invariant") ;
  1148     ObjectMonitor * InUseList = Self->omInUseList;
  1149     ObjectMonitor * InUseTail = NULL ;
  1150     int InUseTally = 0;
  1151     if (InUseList != NULL) {
  1152       Self->omInUseList = NULL;
  1153       ObjectMonitor *curom;
  1154       for (curom = InUseList; curom != NULL; curom = curom->FreeNext) {
  1155         InUseTail = curom;
  1156         InUseTally++;
  1158 // TODO debug
  1159       assert(Self->omInUseCount == InUseTally, "inuse count off");
  1160       Self->omInUseCount = 0;
  1161       guarantee (InUseTail != NULL && InUseList != NULL, "invariant");
  1164     Thread::muxAcquire (&ListLock, "omFlush") ;
  1165     if (Tail != NULL) {
  1166       Tail->FreeNext = gFreeList ;
  1167       gFreeList = List ;
  1168       MonitorFreeCount += Tally;
  1171     if (InUseTail != NULL) {
  1172       InUseTail->FreeNext = gOmInUseList;
  1173       gOmInUseList = InUseList;
  1174       gOmInUseCount += InUseTally;
  1177     Thread::muxRelease (&ListLock) ;
  1178     TEVENT (omFlush) ;
  1181 // Fast path code shared by multiple functions
  1182 ObjectMonitor* ObjectSynchronizer::inflate_helper(oop obj) {
  1183   markOop mark = obj->mark();
  1184   if (mark->has_monitor()) {
  1185     assert(ObjectSynchronizer::verify_objmon_isinpool(mark->monitor()), "monitor is invalid");
  1186     assert(mark->monitor()->header()->is_neutral(), "monitor must record a good object header");
  1187     return mark->monitor();
  1189   return ObjectSynchronizer::inflate(Thread::current(), obj);
  1193 // Note that we could encounter some performance loss through false-sharing as
  1194 // multiple locks occupy the same $ line.  Padding might be appropriate.
  1197 ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) {
  1198   // Inflate mutates the heap ...
  1199   // Relaxing assertion for bug 6320749.
  1200   assert (Universe::verify_in_progress() ||
  1201           !SafepointSynchronize::is_at_safepoint(), "invariant") ;
  1203   for (;;) {
  1204       const markOop mark = object->mark() ;
  1205       assert (!mark->has_bias_pattern(), "invariant") ;
  1207       // The mark can be in one of the following states:
  1208       // *  Inflated     - just return
  1209       // *  Stack-locked - coerce it to inflated
  1210       // *  INFLATING    - busy wait for conversion to complete
  1211       // *  Neutral      - aggressively inflate the object.
  1212       // *  BIASED       - Illegal.  We should never see this
  1214       // CASE: inflated
  1215       if (mark->has_monitor()) {
  1216           ObjectMonitor * inf = mark->monitor() ;
  1217           assert (inf->header()->is_neutral(), "invariant");
  1218           assert (inf->object() == object, "invariant") ;
  1219           assert (ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid");
  1220           return inf ;
  1223       // CASE: inflation in progress - inflating over a stack-lock.
  1224       // Some other thread is converting from stack-locked to inflated.
  1225       // Only that thread can complete inflation -- other threads must wait.
  1226       // The INFLATING value is transient.
  1227       // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
  1228       // We could always eliminate polling by parking the thread on some auxiliary list.
  1229       if (mark == markOopDesc::INFLATING()) {
  1230          TEVENT (Inflate: spin while INFLATING) ;
  1231          ReadStableMark(object) ;
  1232          continue ;
  1235       // CASE: stack-locked
  1236       // Could be stack-locked either by this thread or by some other thread.
  1237       //
  1238       // Note that we allocate the objectmonitor speculatively, _before_ attempting
  1239       // to install INFLATING into the mark word.  We originally installed INFLATING,
  1240       // allocated the objectmonitor, and then finally STed the address of the
  1241       // objectmonitor into the mark.  This was correct, but artificially lengthened
  1242       // the interval in which INFLATED appeared in the mark, thus increasing
  1243       // the odds of inflation contention.
  1244       //
  1245       // We now use per-thread private objectmonitor free lists.
  1246       // These list are reprovisioned from the global free list outside the
  1247       // critical INFLATING...ST interval.  A thread can transfer
  1248       // multiple objectmonitors en-mass from the global free list to its local free list.
  1249       // This reduces coherency traffic and lock contention on the global free list.
  1250       // Using such local free lists, it doesn't matter if the omAlloc() call appears
  1251       // before or after the CAS(INFLATING) operation.
  1252       // See the comments in omAlloc().
  1254       if (mark->has_locker()) {
  1255           ObjectMonitor * m = omAlloc (Self) ;
  1256           // Optimistically prepare the objectmonitor - anticipate successful CAS
  1257           // We do this before the CAS in order to minimize the length of time
  1258           // in which INFLATING appears in the mark.
  1259           m->Recycle();
  1260           m->_Responsible  = NULL ;
  1261           m->OwnerIsThread = 0 ;
  1262           m->_recursions   = 0 ;
  1263           m->_SpinDuration = ObjectMonitor::Knob_SpinLimit ;   // Consider: maintain by type/class
  1265           markOop cmp = (markOop) Atomic::cmpxchg_ptr (markOopDesc::INFLATING(), object->mark_addr(), mark) ;
  1266           if (cmp != mark) {
  1267              omRelease (Self, m, true) ;
  1268              continue ;       // Interference -- just retry
  1271           // We've successfully installed INFLATING (0) into the mark-word.
  1272           // This is the only case where 0 will appear in a mark-work.
  1273           // Only the singular thread that successfully swings the mark-word
  1274           // to 0 can perform (or more precisely, complete) inflation.
  1275           //
  1276           // Why do we CAS a 0 into the mark-word instead of just CASing the
  1277           // mark-word from the stack-locked value directly to the new inflated state?
  1278           // Consider what happens when a thread unlocks a stack-locked object.
  1279           // It attempts to use CAS to swing the displaced header value from the
  1280           // on-stack basiclock back into the object header.  Recall also that the
  1281           // header value (hashcode, etc) can reside in (a) the object header, or
  1282           // (b) a displaced header associated with the stack-lock, or (c) a displaced
  1283           // header in an objectMonitor.  The inflate() routine must copy the header
  1284           // value from the basiclock on the owner's stack to the objectMonitor, all
  1285           // the while preserving the hashCode stability invariants.  If the owner
  1286           // decides to release the lock while the value is 0, the unlock will fail
  1287           // and control will eventually pass from slow_exit() to inflate.  The owner
  1288           // will then spin, waiting for the 0 value to disappear.   Put another way,
  1289           // the 0 causes the owner to stall if the owner happens to try to
  1290           // drop the lock (restoring the header from the basiclock to the object)
  1291           // while inflation is in-progress.  This protocol avoids races that might
  1292           // would otherwise permit hashCode values to change or "flicker" for an object.
  1293           // Critically, while object->mark is 0 mark->displaced_mark_helper() is stable.
  1294           // 0 serves as a "BUSY" inflate-in-progress indicator.
  1297           // fetch the displaced mark from the owner's stack.
  1298           // The owner can't die or unwind past the lock while our INFLATING
  1299           // object is in the mark.  Furthermore the owner can't complete
  1300           // an unlock on the object, either.
  1301           markOop dmw = mark->displaced_mark_helper() ;
  1302           assert (dmw->is_neutral(), "invariant") ;
  1304           // Setup monitor fields to proper values -- prepare the monitor
  1305           m->set_header(dmw) ;
  1307           // Optimization: if the mark->locker stack address is associated
  1308           // with this thread we could simply set m->_owner = Self and
  1309           // m->OwnerIsThread = 1. Note that a thread can inflate an object
  1310           // that it has stack-locked -- as might happen in wait() -- directly
  1311           // with CAS.  That is, we can avoid the xchg-NULL .... ST idiom.
  1312           m->set_owner(mark->locker());
  1313           m->set_object(object);
  1314           // TODO-FIXME: assert BasicLock->dhw != 0.
  1316           // Must preserve store ordering. The monitor state must
  1317           // be stable at the time of publishing the monitor address.
  1318           guarantee (object->mark() == markOopDesc::INFLATING(), "invariant") ;
  1319           object->release_set_mark(markOopDesc::encode(m));
  1321           // Hopefully the performance counters are allocated on distinct cache lines
  1322           // to avoid false sharing on MP systems ...
  1323           if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc() ;
  1324           TEVENT(Inflate: overwrite stacklock) ;
  1325           if (TraceMonitorInflation) {
  1326             if (object->is_instance()) {
  1327               ResourceMark rm;
  1328               tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
  1329                 (void *) object, (intptr_t) object->mark(),
  1330                 object->klass()->external_name());
  1333           return m ;
  1336       // CASE: neutral
  1337       // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
  1338       // If we know we're inflating for entry it's better to inflate by swinging a
  1339       // pre-locked objectMonitor pointer into the object header.   A successful
  1340       // CAS inflates the object *and* confers ownership to the inflating thread.
  1341       // In the current implementation we use a 2-step mechanism where we CAS()
  1342       // to inflate and then CAS() again to try to swing _owner from NULL to Self.
  1343       // An inflateTry() method that we could call from fast_enter() and slow_enter()
  1344       // would be useful.
  1346       assert (mark->is_neutral(), "invariant");
  1347       ObjectMonitor * m = omAlloc (Self) ;
  1348       // prepare m for installation - set monitor to initial state
  1349       m->Recycle();
  1350       m->set_header(mark);
  1351       m->set_owner(NULL);
  1352       m->set_object(object);
  1353       m->OwnerIsThread = 1 ;
  1354       m->_recursions   = 0 ;
  1355       m->_Responsible  = NULL ;
  1356       m->_SpinDuration = ObjectMonitor::Knob_SpinLimit ;       // consider: keep metastats by type/class
  1358       if (Atomic::cmpxchg_ptr (markOopDesc::encode(m), object->mark_addr(), mark) != mark) {
  1359           m->set_object (NULL) ;
  1360           m->set_owner  (NULL) ;
  1361           m->OwnerIsThread = 0 ;
  1362           m->Recycle() ;
  1363           omRelease (Self, m, true) ;
  1364           m = NULL ;
  1365           continue ;
  1366           // interference - the markword changed - just retry.
  1367           // The state-transitions are one-way, so there's no chance of
  1368           // live-lock -- "Inflated" is an absorbing state.
  1371       // Hopefully the performance counters are allocated on distinct
  1372       // cache lines to avoid false sharing on MP systems ...
  1373       if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc() ;
  1374       TEVENT(Inflate: overwrite neutral) ;
  1375       if (TraceMonitorInflation) {
  1376         if (object->is_instance()) {
  1377           ResourceMark rm;
  1378           tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
  1379             (void *) object, (intptr_t) object->mark(),
  1380             object->klass()->external_name());
  1383       return m ;
  1387 // Note that we could encounter some performance loss through false-sharing as
  1388 // multiple locks occupy the same $ line.  Padding might be appropriate.
  1391 // Deflate_idle_monitors() is called at all safepoints, immediately
  1392 // after all mutators are stopped, but before any objects have moved.
  1393 // It traverses the list of known monitors, deflating where possible.
  1394 // The scavenged monitor are returned to the monitor free list.
  1395 //
  1396 // Beware that we scavenge at *every* stop-the-world point.
  1397 // Having a large number of monitors in-circulation negatively
  1398 // impacts the performance of some applications (e.g., PointBase).
  1399 // Broadly, we want to minimize the # of monitors in circulation.
  1400 //
  1401 // We have added a flag, MonitorInUseLists, which creates a list
  1402 // of active monitors for each thread. deflate_idle_monitors()
  1403 // only scans the per-thread inuse lists. omAlloc() puts all
  1404 // assigned monitors on the per-thread list. deflate_idle_monitors()
  1405 // returns the non-busy monitors to the global free list.
  1406 // When a thread dies, omFlush() adds the list of active monitors for
  1407 // that thread to a global gOmInUseList acquiring the
  1408 // global list lock. deflate_idle_monitors() acquires the global
  1409 // list lock to scan for non-busy monitors to the global free list.
  1410 // An alternative could have used a single global inuse list. The
  1411 // downside would have been the additional cost of acquiring the global list lock
  1412 // for every omAlloc().
  1413 //
  1414 // Perversely, the heap size -- and thus the STW safepoint rate --
  1415 // typically drives the scavenge rate.  Large heaps can mean infrequent GC,
  1416 // which in turn can mean large(r) numbers of objectmonitors in circulation.
  1417 // This is an unfortunate aspect of this design.
  1418 //
  1420 enum ManifestConstants {
  1421     ClearResponsibleAtSTW   = 0,
  1422     MaximumRecheckInterval  = 1000
  1423 } ;
  1425 // Deflate a single monitor if not in use
  1426 // Return true if deflated, false if in use
  1427 bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj,
  1428                                          ObjectMonitor** FreeHeadp, ObjectMonitor** FreeTailp) {
  1429   bool deflated;
  1430   // Normal case ... The monitor is associated with obj.
  1431   guarantee (obj->mark() == markOopDesc::encode(mid), "invariant") ;
  1432   guarantee (mid == obj->mark()->monitor(), "invariant");
  1433   guarantee (mid->header()->is_neutral(), "invariant");
  1435   if (mid->is_busy()) {
  1436      if (ClearResponsibleAtSTW) mid->_Responsible = NULL ;
  1437      deflated = false;
  1438   } else {
  1439      // Deflate the monitor if it is no longer being used
  1440      // It's idle - scavenge and return to the global free list
  1441      // plain old deflation ...
  1442      TEVENT (deflate_idle_monitors - scavenge1) ;
  1443      if (TraceMonitorInflation) {
  1444        if (obj->is_instance()) {
  1445          ResourceMark rm;
  1446            tty->print_cr("Deflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
  1447                 (void *) obj, (intptr_t) obj->mark(), obj->klass()->external_name());
  1451      // Restore the header back to obj
  1452      obj->release_set_mark(mid->header());
  1453      mid->clear();
  1455      assert (mid->object() == NULL, "invariant") ;
  1457      // Move the object to the working free list defined by FreeHead,FreeTail.
  1458      if (*FreeHeadp == NULL) *FreeHeadp = mid;
  1459      if (*FreeTailp != NULL) {
  1460        ObjectMonitor * prevtail = *FreeTailp;
  1461        assert(prevtail->FreeNext == NULL, "cleaned up deflated?"); // TODO KK
  1462        prevtail->FreeNext = mid;
  1464      *FreeTailp = mid;
  1465      deflated = true;
  1467   return deflated;
  1470 // Caller acquires ListLock
  1471 int ObjectSynchronizer::walk_monitor_list(ObjectMonitor** listheadp,
  1472                                           ObjectMonitor** FreeHeadp, ObjectMonitor** FreeTailp) {
  1473   ObjectMonitor* mid;
  1474   ObjectMonitor* next;
  1475   ObjectMonitor* curmidinuse = NULL;
  1476   int deflatedcount = 0;
  1478   for (mid = *listheadp; mid != NULL; ) {
  1479      oop obj = (oop) mid->object();
  1480      bool deflated = false;
  1481      if (obj != NULL) {
  1482        deflated = deflate_monitor(mid, obj, FreeHeadp, FreeTailp);
  1484      if (deflated) {
  1485        // extract from per-thread in-use-list
  1486        if (mid == *listheadp) {
  1487          *listheadp = mid->FreeNext;
  1488        } else if (curmidinuse != NULL) {
  1489          curmidinuse->FreeNext = mid->FreeNext; // maintain the current thread inuselist
  1491        next = mid->FreeNext;
  1492        mid->FreeNext = NULL;  // This mid is current tail in the FreeHead list
  1493        mid = next;
  1494        deflatedcount++;
  1495      } else {
  1496        curmidinuse = mid;
  1497        mid = mid->FreeNext;
  1500   return deflatedcount;
  1503 void ObjectSynchronizer::deflate_idle_monitors() {
  1504   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
  1505   int nInuse = 0 ;              // currently associated with objects
  1506   int nInCirculation = 0 ;      // extant
  1507   int nScavenged = 0 ;          // reclaimed
  1508   bool deflated = false;
  1510   ObjectMonitor * FreeHead = NULL ;  // Local SLL of scavenged monitors
  1511   ObjectMonitor * FreeTail = NULL ;
  1513   TEVENT (deflate_idle_monitors) ;
  1514   // Prevent omFlush from changing mids in Thread dtor's during deflation
  1515   // And in case the vm thread is acquiring a lock during a safepoint
  1516   // See e.g. 6320749
  1517   Thread::muxAcquire (&ListLock, "scavenge - return") ;
  1519   if (MonitorInUseLists) {
  1520     int inUse = 0;
  1521     for (JavaThread* cur = Threads::first(); cur != NULL; cur = cur->next()) {
  1522       nInCirculation+= cur->omInUseCount;
  1523       int deflatedcount = walk_monitor_list(cur->omInUseList_addr(), &FreeHead, &FreeTail);
  1524       cur->omInUseCount-= deflatedcount;
  1525       // verifyInUse(cur);
  1526       nScavenged += deflatedcount;
  1527       nInuse += cur->omInUseCount;
  1530    // For moribund threads, scan gOmInUseList
  1531    if (gOmInUseList) {
  1532      nInCirculation += gOmInUseCount;
  1533      int deflatedcount = walk_monitor_list((ObjectMonitor **)&gOmInUseList, &FreeHead, &FreeTail);
  1534      gOmInUseCount-= deflatedcount;
  1535      nScavenged += deflatedcount;
  1536      nInuse += gOmInUseCount;
  1539   } else for (ObjectMonitor* block = gBlockList; block != NULL; block = next(block)) {
  1540   // Iterate over all extant monitors - Scavenge all idle monitors.
  1541     assert(block->object() == CHAINMARKER, "must be a block header");
  1542     nInCirculation += _BLOCKSIZE ;
  1543     for (int i = 1 ; i < _BLOCKSIZE; i++) {
  1544       ObjectMonitor* mid = &block[i];
  1545       oop obj = (oop) mid->object();
  1547       if (obj == NULL) {
  1548         // The monitor is not associated with an object.
  1549         // The monitor should either be a thread-specific private
  1550         // free list or the global free list.
  1551         // obj == NULL IMPLIES mid->is_busy() == 0
  1552         guarantee (!mid->is_busy(), "invariant") ;
  1553         continue ;
  1555       deflated = deflate_monitor(mid, obj, &FreeHead, &FreeTail);
  1557       if (deflated) {
  1558         mid->FreeNext = NULL ;
  1559         nScavenged ++ ;
  1560       } else {
  1561         nInuse ++;
  1566   MonitorFreeCount += nScavenged;
  1568   // Consider: audit gFreeList to ensure that MonitorFreeCount and list agree.
  1570   if (ObjectMonitor::Knob_Verbose) {
  1571     ::printf ("Deflate: InCirc=%d InUse=%d Scavenged=%d ForceMonitorScavenge=%d : pop=%d free=%d\n",
  1572         nInCirculation, nInuse, nScavenged, ForceMonitorScavenge,
  1573         MonitorPopulation, MonitorFreeCount) ;
  1574     ::fflush(stdout) ;
  1577   ForceMonitorScavenge = 0;    // Reset
  1579   // Move the scavenged monitors back to the global free list.
  1580   if (FreeHead != NULL) {
  1581      guarantee (FreeTail != NULL && nScavenged > 0, "invariant") ;
  1582      assert (FreeTail->FreeNext == NULL, "invariant") ;
  1583      // constant-time list splice - prepend scavenged segment to gFreeList
  1584      FreeTail->FreeNext = gFreeList ;
  1585      gFreeList = FreeHead ;
  1587   Thread::muxRelease (&ListLock) ;
  1589   if (ObjectMonitor::_sync_Deflations != NULL) ObjectMonitor::_sync_Deflations->inc(nScavenged) ;
  1590   if (ObjectMonitor::_sync_MonExtant  != NULL) ObjectMonitor::_sync_MonExtant ->set_value(nInCirculation);
  1592   // TODO: Add objectMonitor leak detection.
  1593   // Audit/inventory the objectMonitors -- make sure they're all accounted for.
  1594   GVars.stwRandom = os::random() ;
  1595   GVars.stwCycle ++ ;
  1598 // Monitor cleanup on JavaThread::exit
  1600 // Iterate through monitor cache and attempt to release thread's monitors
  1601 // Gives up on a particular monitor if an exception occurs, but continues
  1602 // the overall iteration, swallowing the exception.
  1603 class ReleaseJavaMonitorsClosure: public MonitorClosure {
  1604 private:
  1605   TRAPS;
  1607 public:
  1608   ReleaseJavaMonitorsClosure(Thread* thread) : THREAD(thread) {}
  1609   void do_monitor(ObjectMonitor* mid) {
  1610     if (mid->owner() == THREAD) {
  1611       (void)mid->complete_exit(CHECK);
  1614 };
  1616 // Release all inflated monitors owned by THREAD.  Lightweight monitors are
  1617 // ignored.  This is meant to be called during JNI thread detach which assumes
  1618 // all remaining monitors are heavyweight.  All exceptions are swallowed.
  1619 // Scanning the extant monitor list can be time consuming.
  1620 // A simple optimization is to add a per-thread flag that indicates a thread
  1621 // called jni_monitorenter() during its lifetime.
  1622 //
  1623 // Instead of No_Savepoint_Verifier it might be cheaper to
  1624 // use an idiom of the form:
  1625 //   auto int tmp = SafepointSynchronize::_safepoint_counter ;
  1626 //   <code that must not run at safepoint>
  1627 //   guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ;
  1628 // Since the tests are extremely cheap we could leave them enabled
  1629 // for normal product builds.
  1631 void ObjectSynchronizer::release_monitors_owned_by_thread(TRAPS) {
  1632   assert(THREAD == JavaThread::current(), "must be current Java thread");
  1633   No_Safepoint_Verifier nsv ;
  1634   ReleaseJavaMonitorsClosure rjmc(THREAD);
  1635   Thread::muxAcquire(&ListLock, "release_monitors_owned_by_thread");
  1636   ObjectSynchronizer::monitors_iterate(&rjmc);
  1637   Thread::muxRelease(&ListLock);
  1638   THREAD->clear_pending_exception();
  1641 //------------------------------------------------------------------------------
  1642 // Debugging code
  1644 void ObjectSynchronizer::sanity_checks(const bool verbose,
  1645                                        const uint cache_line_size,
  1646                                        int *error_cnt_ptr,
  1647                                        int *warning_cnt_ptr) {
  1648   u_char *addr_begin      = (u_char*)&GVars;
  1649   u_char *addr_stwRandom  = (u_char*)&GVars.stwRandom;
  1650   u_char *addr_hcSequence = (u_char*)&GVars.hcSequence;
  1652   if (verbose) {
  1653     tty->print_cr("INFO: sizeof(SharedGlobals)=" SIZE_FORMAT,
  1654                   sizeof(SharedGlobals));
  1657   uint offset_stwRandom = (uint)(addr_stwRandom - addr_begin);
  1658   if (verbose) tty->print_cr("INFO: offset(stwRandom)=%u", offset_stwRandom);
  1660   uint offset_hcSequence = (uint)(addr_hcSequence - addr_begin);
  1661   if (verbose) {
  1662     tty->print_cr("INFO: offset(_hcSequence)=%u", offset_hcSequence);
  1665   if (cache_line_size != 0) {
  1666     // We were able to determine the L1 data cache line size so
  1667     // do some cache line specific sanity checks
  1669     if (offset_stwRandom < cache_line_size) {
  1670       tty->print_cr("WARNING: the SharedGlobals.stwRandom field is closer "
  1671                     "to the struct beginning than a cache line which permits "
  1672                     "false sharing.");
  1673       (*warning_cnt_ptr)++;
  1676     if ((offset_hcSequence - offset_stwRandom) < cache_line_size) {
  1677       tty->print_cr("WARNING: the SharedGlobals.stwRandom and "
  1678                     "SharedGlobals.hcSequence fields are closer than a cache "
  1679                     "line which permits false sharing.");
  1680       (*warning_cnt_ptr)++;
  1683     if ((sizeof(SharedGlobals) - offset_hcSequence) < cache_line_size) {
  1684       tty->print_cr("WARNING: the SharedGlobals.hcSequence field is closer "
  1685                     "to the struct end than a cache line which permits false "
  1686                     "sharing.");
  1687       (*warning_cnt_ptr)++;
  1692 #ifndef PRODUCT
  1694 // Verify all monitors in the monitor cache, the verification is weak.
  1695 void ObjectSynchronizer::verify() {
  1696   ObjectMonitor* block = gBlockList;
  1697   ObjectMonitor* mid;
  1698   while (block) {
  1699     assert(block->object() == CHAINMARKER, "must be a block header");
  1700     for (int i = 1; i < _BLOCKSIZE; i++) {
  1701       mid = block + i;
  1702       oop object = (oop) mid->object();
  1703       if (object != NULL) {
  1704         mid->verify();
  1707     block = (ObjectMonitor*) block->FreeNext;
  1711 // Check if monitor belongs to the monitor cache
  1712 // The list is grow-only so it's *relatively* safe to traverse
  1713 // the list of extant blocks without taking a lock.
  1715 int ObjectSynchronizer::verify_objmon_isinpool(ObjectMonitor *monitor) {
  1716   ObjectMonitor* block = gBlockList;
  1718   while (block) {
  1719     assert(block->object() == CHAINMARKER, "must be a block header");
  1720     if (monitor > &block[0] && monitor < &block[_BLOCKSIZE]) {
  1721       address mon = (address) monitor;
  1722       address blk = (address) block;
  1723       size_t diff = mon - blk;
  1724       assert((diff % sizeof(ObjectMonitor)) == 0, "check");
  1725       return 1;
  1727     block = (ObjectMonitor*) block->FreeNext;
  1729   return 0;
  1732 #endif

mercurial