src/share/vm/runtime/synchronizer.cpp

Mon, 12 Aug 2019 18:30:40 +0300

author
apetushkov
date
Mon, 12 Aug 2019 18:30:40 +0300
changeset 9858
b985cbb00e68
parent 8729
402618d5afc9
child 9892
9a4141de094d
permissions
-rw-r--r--

8223147: JFR Backport
8199712: Flight Recorder
8203346: JFR: Inconsistent signature of jfr_add_string_constant
8195817: JFR.stop should require name of recording
8195818: JFR.start should increase autogenerated name by one
8195819: Remove recording=x from jcmd JFR.check output
8203921: JFR thread sampling is missing fixes from JDK-8194552
8203929: Limit amount of data for JFR.dump
8203664: JFR start failure after AppCDS archive created with JFR StartFlightRecording
8003209: JFR events for network utilization
8207392: [PPC64] Implement JFR profiling
8202835: jfr/event/os/TestSystemProcess.java fails on missing events
Summary: Backport JFR from JDK11. Initial integration
Reviewed-by: neugens

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

mercurial