src/share/vm/runtime/synchronizer.cpp
author andrew
Fri May 28 11:23:44 2010 +0100 (23 months ago)
changeset 1568 d2f6f71320bd
parent 15471be129f955bf
parent 1567193a468093fa
child 1958b69c41ea1764
permissions -rw-r--r--
Merge
        1 /*
        2  * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
        3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
        4  *
        5  * This code is free software; you can redistribute it and/or modify it
        6  * under the terms of the GNU General Public License version 2 only, as
        7  * published by the Free Software Foundation.
        8  *
        9  * This code is distributed in the hope that it will be useful, but WITHOUT
       10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       12  * version 2 for more details (a copy is included in the LICENSE file that
       13  * accompanied this code).
       14  *
       15  * You should have received a copy of the GNU General Public License version
       16  * 2 along with this work; if not, write to the Free Software Foundation,
       17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       18  *
       19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       20  * or visit www.oracle.com if you need additional information or have any
       21  * questions.
       22  *
       23  */
       24 
       25 # include "incls/_precompiled.incl"
       26 # include "incls/_synchronizer.cpp.incl"
       27 
       28 #if defined(__GNUC__) && !defined(IA64)
       29   // Need to inhibit inlining for older versions of GCC to avoid build-time failures
       30   #define ATTR __attribute__((noinline))
       31 #else
       32   #define ATTR
       33 #endif
       34 
       35 // Native markword accessors for synchronization and hashCode().
       36 //
       37 // The "core" versions of monitor enter and exit reside in this file.
       38 // The interpreter and compilers contain specialized transliterated
       39 // variants of the enter-exit fast-path operations.  See i486.ad fast_lock(),
       40 // for instance.  If you make changes here, make sure to modify the
       41 // interpreter, and both C1 and C2 fast-path inline locking code emission.
       42 //
       43 // TODO: merge the objectMonitor and synchronizer classes.
       44 //
       45 // -----------------------------------------------------------------------------
       46 
       47 #ifdef DTRACE_ENABLED
       48 
       49 // Only bother with this argument setup if dtrace is available
       50 // TODO-FIXME: probes should not fire when caller is _blocked.  assert() accordingly.
       51 
       52 HS_DTRACE_PROBE_DECL5(hotspot, monitor__wait,
       53   jlong, uintptr_t, char*, int, long);
       54 HS_DTRACE_PROBE_DECL4(hotspot, monitor__waited,
       55   jlong, uintptr_t, char*, int);
       56 HS_DTRACE_PROBE_DECL4(hotspot, monitor__notify,
       57   jlong, uintptr_t, char*, int);
       58 HS_DTRACE_PROBE_DECL4(hotspot, monitor__notifyAll,
       59   jlong, uintptr_t, char*, int);
       60 HS_DTRACE_PROBE_DECL4(hotspot, monitor__contended__enter,
       61   jlong, uintptr_t, char*, int);
       62 HS_DTRACE_PROBE_DECL4(hotspot, monitor__contended__entered,
       63   jlong, uintptr_t, char*, int);
       64 HS_DTRACE_PROBE_DECL4(hotspot, monitor__contended__exit,
       65   jlong, uintptr_t, char*, int);
       66 
       67 #define DTRACE_MONITOR_PROBE_COMMON(klassOop, thread)                      \
       68   char* bytes = NULL;                                                      \
       69   int len = 0;                                                             \
       70   jlong jtid = SharedRuntime::get_java_tid(thread);                        \
       71   symbolOop klassname = ((oop)(klassOop))->klass()->klass_part()->name();  \
       72   if (klassname != NULL) {                                                 \
       73     bytes = (char*)klassname->bytes();                                     \
       74     len = klassname->utf8_length();                                        \
       75   }
       76 
       77 #define DTRACE_MONITOR_WAIT_PROBE(monitor, klassOop, thread, millis)       \
       78   {                                                                        \
       79     if (DTraceMonitorProbes) {                                            \
       80       DTRACE_MONITOR_PROBE_COMMON(klassOop, thread);                       \
       81       HS_DTRACE_PROBE5(hotspot, monitor__wait, jtid,                       \
       82                        (monitor), bytes, len, (millis));                   \
       83     }                                                                      \
       84   }
       85 
       86 #define DTRACE_MONITOR_PROBE(probe, monitor, klassOop, thread)             \
       87   {                                                                        \
       88     if (DTraceMonitorProbes) {                                            \
       89       DTRACE_MONITOR_PROBE_COMMON(klassOop, thread);                       \
       90       HS_DTRACE_PROBE4(hotspot, monitor__##probe, jtid,                    \
       91                        (uintptr_t)(monitor), bytes, len);                  \
       92     }                                                                      \
       93   }
       94 
       95 #else //  ndef DTRACE_ENABLED
       96 
       97 #define DTRACE_MONITOR_WAIT_PROBE(klassOop, thread, millis, mon)    {;}
       98 #define DTRACE_MONITOR_PROBE(probe, klassOop, thread, mon)          {;}
       99 
      100 #endif // ndef DTRACE_ENABLED
      101 
      102 // ObjectWaiter serves as a "proxy" or surrogate thread.
      103 // TODO-FIXME: Eliminate ObjectWaiter and use the thread-specific
      104 // ParkEvent instead.  Beware, however, that the JVMTI code
      105 // knows about ObjectWaiters, so we'll have to reconcile that code.
      106 // See next_waiter(), first_waiter(), etc.
      107 
      108 class ObjectWaiter : public StackObj {
      109  public:
      110   enum TStates { TS_UNDEF, TS_READY, TS_RUN, TS_WAIT, TS_ENTER, TS_CXQ } ;
      111   enum Sorted  { PREPEND, APPEND, SORTED } ;
      112   ObjectWaiter * volatile _next;
      113   ObjectWaiter * volatile _prev;
      114   Thread*       _thread;
      115   ParkEvent *   _event;
      116   volatile int  _notified ;
      117   volatile TStates TState ;
      118   Sorted        _Sorted ;           // List placement disposition
      119   bool          _active ;           // Contention monitoring is enabled
      120  public:
      121   ObjectWaiter(Thread* thread) {
      122     _next     = NULL;
      123     _prev     = NULL;
      124     _notified = 0;
      125     TState    = TS_RUN ;
      126     _thread   = thread;
      127     _event    = thread->_ParkEvent ;
      128     _active   = false;
      129     assert (_event != NULL, "invariant") ;
      130   }
      131 
      132   void wait_reenter_begin(ObjectMonitor *mon) {
      133     JavaThread *jt = (JavaThread *)this->_thread;
      134     _active = JavaThreadBlockedOnMonitorEnterState::wait_reenter_begin(jt, mon);
      135   }
      136 
      137   void wait_reenter_end(ObjectMonitor *mon) {
      138     JavaThread *jt = (JavaThread *)this->_thread;
      139     JavaThreadBlockedOnMonitorEnterState::wait_reenter_end(jt, _active);
      140   }
      141 };
      142 
      143 enum ManifestConstants {
      144     ClearResponsibleAtSTW   = 0,
      145     MaximumRecheckInterval  = 1000
      146 } ;
      147 
      148 
      149 #undef TEVENT
      150 #define TEVENT(nom) {if (SyncVerbose) FEVENT(nom); }
      151 
      152 #define FEVENT(nom) { static volatile int ctr = 0 ; int v = ++ctr ; if ((v & (v-1)) == 0) { ::printf (#nom " : %d \n", v); ::fflush(stdout); }}
      153 
      154 #undef  TEVENT
      155 #define TEVENT(nom) {;}
      156 
      157 // Performance concern:
      158 // OrderAccess::storestore() calls release() which STs 0 into the global volatile
      159 // OrderAccess::Dummy variable.  This store is unnecessary for correctness.
      160 // Many threads STing into a common location causes considerable cache migration
      161 // or "sloshing" on large SMP system.  As such, I avoid using OrderAccess::storestore()
      162 // until it's repaired.  In some cases OrderAccess::fence() -- which incurs local
      163 // latency on the executing processor -- is a better choice as it scales on SMP
      164 // systems.  See http://blogs.sun.com/dave/entry/biased_locking_in_hotspot for a
      165 // discussion of coherency costs.  Note that all our current reference platforms
      166 // provide strong ST-ST order, so the issue is moot on IA32, x64, and SPARC.
      167 //
      168 // As a general policy we use "volatile" to control compiler-based reordering
      169 // and explicit fences (barriers) to control for architectural reordering performed
      170 // by the CPU(s) or platform.
      171 
      172 static int  MBFence (int x) { OrderAccess::fence(); return x; }
      173 
      174 struct SharedGlobals {
      175     // These are highly shared mostly-read variables.
      176     // To avoid false-sharing they need to be the sole occupants of a $ line.
      177     double padPrefix [8];
      178     volatile int stwRandom ;
      179     volatile int stwCycle ;
      180 
      181     // Hot RW variables -- Sequester to avoid false-sharing
      182     double padSuffix [16];
      183     volatile int hcSequence ;
      184     double padFinal [8] ;
      185 } ;
      186 
      187 static SharedGlobals GVars ;
      188 static int MonitorScavengeThreshold = 1000000 ;
      189 static volatile int ForceMonitorScavenge = 0 ; // Scavenge required and pending
      190 
      191 // Tunables ...
      192 // The knob* variables are effectively final.  Once set they should
      193 // never be modified hence.  Consider using __read_mostly with GCC.
      194 
      195 static int Knob_LogSpins           = 0 ;       // enable jvmstat tally for spins
      196 static int Knob_HandOff            = 0 ;
      197 static int Knob_Verbose            = 0 ;
      198 static int Knob_ReportSettings     = 0 ;
      199 
      200 static int Knob_SpinLimit          = 5000 ;    // derived by an external tool -
      201 static int Knob_SpinBase           = 0 ;       // Floor AKA SpinMin
      202 static int Knob_SpinBackOff        = 0 ;       // spin-loop backoff
      203 static int Knob_CASPenalty         = -1 ;      // Penalty for failed CAS
      204 static int Knob_OXPenalty          = -1 ;      // Penalty for observed _owner change
      205 static int Knob_SpinSetSucc        = 1 ;       // spinners set the _succ field
      206 static int Knob_SpinEarly          = 1 ;
      207 static int Knob_SuccEnabled        = 1 ;       // futile wake throttling
      208 static int Knob_SuccRestrict       = 0 ;       // Limit successors + spinners to at-most-one
      209 static int Knob_MaxSpinners        = -1 ;      // Should be a function of # CPUs
      210 static int Knob_Bonus              = 100 ;     // spin success bonus
      211 static int Knob_BonusB             = 100 ;     // spin success bonus
      212 static int Knob_Penalty            = 200 ;     // spin failure penalty
      213 static int Knob_Poverty            = 1000 ;
      214 static int Knob_SpinAfterFutile    = 1 ;       // Spin after returning from park()
      215 static int Knob_FixedSpin          = 0 ;
      216 static int Knob_OState             = 3 ;       // Spinner checks thread state of _owner
      217 static int Knob_UsePause           = 1 ;
      218 static int Knob_ExitPolicy         = 0 ;
      219 static int Knob_PreSpin            = 10 ;      // 20-100 likely better
      220 static int Knob_ResetEvent         = 0 ;
      221 static int BackOffMask             = 0 ;
      222 
      223 static int Knob_FastHSSEC          = 0 ;
      224 static int Knob_MoveNotifyee       = 2 ;       // notify() - disposition of notifyee
      225 static int Knob_QMode              = 0 ;       // EntryList-cxq policy - queue discipline
      226 static volatile int InitDone       = 0 ;
      227 
      228 
      229 // hashCode() generation :
      230 //
      231 // Possibilities:
      232 // * MD5Digest of {obj,stwRandom}
      233 // * CRC32 of {obj,stwRandom} or any linear-feedback shift register function.
      234 // * A DES- or AES-style SBox[] mechanism
      235 // * One of the Phi-based schemes, such as:
      236 //   2654435761 = 2^32 * Phi (golden ratio)
      237 //   HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stwRandom ;
      238 // * A variation of Marsaglia's shift-xor RNG scheme.
      239 // * (obj ^ stwRandom) is appealing, but can result
      240 //   in undesirable regularity in the hashCode values of adjacent objects
      241 //   (objects allocated back-to-back, in particular).  This could potentially
      242 //   result in hashtable collisions and reduced hashtable efficiency.
      243 //   There are simple ways to "diffuse" the middle address bits over the
      244 //   generated hashCode values:
      245 //
      246 
      247 static inline intptr_t get_next_hash(Thread * Self, oop obj) {
      248   intptr_t value = 0 ;
      249   if (hashCode == 0) {
      250      // This form uses an unguarded global Park-Miller RNG,
      251      // so it's possible for two threads to race and generate the same RNG.
      252      // On MP system we'll have lots of RW access to a global, so the
      253      // mechanism induces lots of coherency traffic.
      254      value = os::random() ;
      255   } else
      256   if (hashCode == 1) {
      257      // This variation has the property of being stable (idempotent)
      258      // between STW operations.  This can be useful in some of the 1-0
      259      // synchronization schemes.
      260      intptr_t addrBits = intptr_t(obj) >> 3 ;
      261      value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom ;
      262   } else
      263   if (hashCode == 2) {
      264      value = 1 ;            // for sensitivity testing
      265   } else
      266   if (hashCode == 3) {
      267      value = ++GVars.hcSequence ;
      268   } else
      269   if (hashCode == 4) {
      270      value = intptr_t(obj) ;
      271   } else {
      272      // Marsaglia's xor-shift scheme with thread-specific state
      273      // This is probably the best overall implementation -- we'll
      274      // likely make this the default in future releases.
      275      unsigned t = Self->_hashStateX ;
      276      t ^= (t << 11) ;
      277      Self->_hashStateX = Self->_hashStateY ;
      278      Self->_hashStateY = Self->_hashStateZ ;
      279      Self->_hashStateZ = Self->_hashStateW ;
      280      unsigned v = Self->_hashStateW ;
      281      v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)) ;
      282      Self->_hashStateW = v ;
      283      value = v ;
      284   }
      285 
      286   value &= markOopDesc::hash_mask;
      287   if (value == 0) value = 0xBAD ;
      288   assert (value != markOopDesc::no_hash, "invariant") ;
      289   TEVENT (hashCode: GENERATE) ;
      290   return value;
      291 }
      292 
      293 void BasicLock::print_on(outputStream* st) const {
      294   st->print("monitor");
      295 }
      296 
      297 void BasicLock::move_to(oop obj, BasicLock* dest) {
      298   // Check to see if we need to inflate the lock. This is only needed
      299   // if an object is locked using "this" lightweight monitor. In that
      300   // case, the displaced_header() is unlocked, because the
      301   // displaced_header() contains the header for the originally unlocked
      302   // object. However the object could have already been inflated. But it
      303   // does not matter, the inflation will just a no-op. For other cases,
      304   // the displaced header will be either 0x0 or 0x3, which are location
      305   // independent, therefore the BasicLock is free to move.
      306   //
      307   // During OSR we may need to relocate a BasicLock (which contains a
      308   // displaced word) from a location in an interpreter frame to a
      309   // new location in a compiled frame.  "this" refers to the source
      310   // basiclock in the interpreter frame.  "dest" refers to the destination
      311   // basiclock in the new compiled frame.  We *always* inflate in move_to().
      312   // The always-Inflate policy works properly, but in 1.5.0 it can sometimes
      313   // cause performance problems in code that makes heavy use of a small # of
      314   // uncontended locks.   (We'd inflate during OSR, and then sync performance
      315   // would subsequently plummet because the thread would be forced thru the slow-path).
      316   // This problem has been made largely moot on IA32 by inlining the inflated fast-path
      317   // operations in Fast_Lock and Fast_Unlock in i486.ad.
      318   //
      319   // Note that there is a way to safely swing the object's markword from
      320   // one stack location to another.  This avoids inflation.  Obviously,
      321   // we need to ensure that both locations refer to the current thread's stack.
      322   // There are some subtle concurrency issues, however, and since the benefit is
      323   // is small (given the support for inflated fast-path locking in the fast_lock, etc)
      324   // we'll leave that optimization for another time.
      325 
      326   if (displaced_header()->is_neutral()) {
      327     ObjectSynchronizer::inflate_helper(obj);
      328     // WARNING: We can not put check here, because the inflation
      329     // will not update the displaced header. Once BasicLock is inflated,
      330     // no one should ever look at its content.
      331   } else {
      332     // Typically the displaced header will be 0 (recursive stack lock) or
      333     // unused_mark.  Naively we'd like to assert that the displaced mark
      334     // value is either 0, neutral, or 3.  But with the advent of the
      335     // store-before-CAS avoidance in fast_lock/compiler_lock_object
      336     // we can find any flavor mark in the displaced mark.
      337   }
      338 // [RGV] The next line appears to do nothing!
      339   intptr_t dh = (intptr_t) displaced_header();
      340   dest->set_displaced_header(displaced_header());
      341 }
      342 
      343 // -----------------------------------------------------------------------------
      344 
      345 // standard constructor, allows locking failures
      346 ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool doLock) {
      347   _dolock = doLock;
      348   _thread = thread;
      349   debug_only(if (StrictSafepointChecks) _thread->check_for_valid_safepoint_state(false);)
      350   _obj = obj;
      351 
      352   if (_dolock) {
      353     TEVENT (ObjectLocker) ;
      354 
      355     ObjectSynchronizer::fast_enter(_obj, &_lock, false, _thread);
      356   }
      357 }
      358 
      359 ObjectLocker::~ObjectLocker() {
      360   if (_dolock) {
      361     ObjectSynchronizer::fast_exit(_obj(), &_lock, _thread);
      362   }
      363 }
      364 
      365 // -----------------------------------------------------------------------------
      366 
      367 
      368 PerfCounter * ObjectSynchronizer::_sync_Inflations                  = NULL ;
      369 PerfCounter * ObjectSynchronizer::_sync_Deflations                  = NULL ;
      370 PerfCounter * ObjectSynchronizer::_sync_ContendedLockAttempts       = NULL ;
      371 PerfCounter * ObjectSynchronizer::_sync_FutileWakeups               = NULL ;
      372 PerfCounter * ObjectSynchronizer::_sync_Parks                       = NULL ;
      373 PerfCounter * ObjectSynchronizer::_sync_EmptyNotifications          = NULL ;
      374 PerfCounter * ObjectSynchronizer::_sync_Notifications               = NULL ;
      375 PerfCounter * ObjectSynchronizer::_sync_PrivateA                    = NULL ;
      376 PerfCounter * ObjectSynchronizer::_sync_PrivateB                    = NULL ;
      377 PerfCounter * ObjectSynchronizer::_sync_SlowExit                    = NULL ;
      378 PerfCounter * ObjectSynchronizer::_sync_SlowEnter                   = NULL ;
      379 PerfCounter * ObjectSynchronizer::_sync_SlowNotify                  = NULL ;
      380 PerfCounter * ObjectSynchronizer::_sync_SlowNotifyAll               = NULL ;
      381 PerfCounter * ObjectSynchronizer::_sync_FailedSpins                 = NULL ;
      382 PerfCounter * ObjectSynchronizer::_sync_SuccessfulSpins             = NULL ;
      383 PerfCounter * ObjectSynchronizer::_sync_MonInCirculation            = NULL ;
      384 PerfCounter * ObjectSynchronizer::_sync_MonScavenged                = NULL ;
      385 PerfLongVariable * ObjectSynchronizer::_sync_MonExtant              = NULL ;
      386 
      387 // One-shot global initialization for the sync subsystem.
      388 // We could also defer initialization and initialize on-demand
      389 // the first time we call inflate().  Initialization would
      390 // be protected - like so many things - by the MonitorCache_lock.
      391 
      392 void ObjectSynchronizer::Initialize () {
      393   static int InitializationCompleted = 0 ;
      394   assert (InitializationCompleted == 0, "invariant") ;
      395   InitializationCompleted = 1 ;
      396   if (UsePerfData) {
      397       EXCEPTION_MARK ;
      398       #define NEWPERFCOUNTER(n)   {n = PerfDataManager::create_counter(SUN_RT, #n, PerfData::U_Events,CHECK); }
      399       #define NEWPERFVARIABLE(n)  {n = PerfDataManager::create_variable(SUN_RT, #n, PerfData::U_Events,CHECK); }
      400       NEWPERFCOUNTER(_sync_Inflations) ;
      401       NEWPERFCOUNTER(_sync_Deflations) ;
      402       NEWPERFCOUNTER(_sync_ContendedLockAttempts) ;
      403       NEWPERFCOUNTER(_sync_FutileWakeups) ;
      404       NEWPERFCOUNTER(_sync_Parks) ;
      405       NEWPERFCOUNTER(_sync_EmptyNotifications) ;
      406       NEWPERFCOUNTER(_sync_Notifications) ;
      407       NEWPERFCOUNTER(_sync_SlowEnter) ;
      408       NEWPERFCOUNTER(_sync_SlowExit) ;
      409       NEWPERFCOUNTER(_sync_SlowNotify) ;
      410       NEWPERFCOUNTER(_sync_SlowNotifyAll) ;
      411       NEWPERFCOUNTER(_sync_FailedSpins) ;
      412       NEWPERFCOUNTER(_sync_SuccessfulSpins) ;
      413       NEWPERFCOUNTER(_sync_PrivateA) ;
      414       NEWPERFCOUNTER(_sync_PrivateB) ;
      415       NEWPERFCOUNTER(_sync_MonInCirculation) ;
      416       NEWPERFCOUNTER(_sync_MonScavenged) ;
      417       NEWPERFVARIABLE(_sync_MonExtant) ;
      418       #undef NEWPERFCOUNTER
      419   }
      420 }
      421 
      422 // Compile-time asserts
      423 // When possible, it's better to catch errors deterministically at
      424 // compile-time than at runtime.  The down-side to using compile-time
      425 // asserts is that error message -- often something about negative array
      426 // indices -- is opaque.
      427 
      428 #define CTASSERT(x) { int tag[1-(2*!(x))]; printf ("Tag @" INTPTR_FORMAT "\n", (intptr_t)tag); }
      429 
      430 void ObjectMonitor::ctAsserts() {
      431   CTASSERT(offset_of (ObjectMonitor, _header) == 0);
      432 }
      433 
      434 static int Adjust (volatile int * adr, int dx) {
      435   int v ;
      436   for (v = *adr ; Atomic::cmpxchg (v + dx, adr, v) != v; v = *adr) ;
      437   return v ;
      438 }
      439 
      440 // Ad-hoc mutual exclusion primitives: SpinLock and Mux
      441 //
      442 // We employ SpinLocks _only for low-contention, fixed-length
      443 // short-duration critical sections where we're concerned
      444 // about native mutex_t or HotSpot Mutex:: latency.
      445 // The mux construct provides a spin-then-block mutual exclusion
      446 // mechanism.
      447 //
      448 // Testing has shown that contention on the ListLock guarding gFreeList
      449 // is common.  If we implement ListLock as a simple SpinLock it's common
      450 // for the JVM to devolve to yielding with little progress.  This is true
      451 // despite the fact that the critical sections protected by ListLock are
      452 // extremely short.
      453 //
      454 // TODO-FIXME: ListLock should be of type SpinLock.
      455 // We should make this a 1st-class type, integrated into the lock
      456 // hierarchy as leaf-locks.  Critically, the SpinLock structure
      457 // should have sufficient padding to avoid false-sharing and excessive
      458 // cache-coherency traffic.
      459 
      460 
      461 typedef volatile int SpinLockT ;
      462 
      463 void Thread::SpinAcquire (volatile int * adr, const char * LockName) {
      464   if (Atomic::cmpxchg (1, adr, 0) == 0) {
      465      return ;   // normal fast-path return
      466   }
      467 
      468   // Slow-path : We've encountered contention -- Spin/Yield/Block strategy.
      469   TEVENT (SpinAcquire - ctx) ;
      470   int ctr = 0 ;
      471   int Yields = 0 ;
      472   for (;;) {
      473      while (*adr != 0) {
      474         ++ctr ;
      475         if ((ctr & 0xFFF) == 0 || !os::is_MP()) {
      476            if (Yields > 5) {
      477              // Consider using a simple NakedSleep() instead.
      478              // Then SpinAcquire could be called by non-JVM threads
      479              Thread::current()->_ParkEvent->park(1) ;
      480            } else {
      481              os::NakedYield() ;
      482              ++Yields ;
      483            }
      484         } else {
      485            SpinPause() ;
      486         }
      487      }
      488      if (Atomic::cmpxchg (1, adr, 0) == 0) return ;
      489   }
      490 }
      491 
      492 void Thread::SpinRelease (volatile int * adr) {
      493   assert (*adr != 0, "invariant") ;
      494   OrderAccess::fence() ;      // guarantee at least release consistency.
      495   // Roach-motel semantics.
      496   // It's safe if subsequent LDs and STs float "up" into the critical section,
      497   // but prior LDs and STs within the critical section can't be allowed
      498   // to reorder or float past the ST that releases the lock.
      499   *adr = 0 ;
      500 }
      501 
      502 // muxAcquire and muxRelease:
      503 //
      504 // *  muxAcquire and muxRelease support a single-word lock-word construct.
      505 //    The LSB of the word is set IFF the lock is held.
      506 //    The remainder of the word points to the head of a singly-linked list
      507 //    of threads blocked on the lock.
      508 //
      509 // *  The current implementation of muxAcquire-muxRelease uses its own
      510 //    dedicated Thread._MuxEvent instance.  If we're interested in
      511 //    minimizing the peak number of extant ParkEvent instances then
      512 //    we could eliminate _MuxEvent and "borrow" _ParkEvent as long
      513 //    as certain invariants were satisfied.  Specifically, care would need
      514 //    to be taken with regards to consuming unpark() "permits".
      515 //    A safe rule of thumb is that a thread would never call muxAcquire()
      516 //    if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently
      517 //    park().  Otherwise the _ParkEvent park() operation in muxAcquire() could
      518 //    consume an unpark() permit intended for monitorenter, for instance.
      519 //    One way around this would be to widen the restricted-range semaphore
      520 //    implemented in park().  Another alternative would be to provide
      521 //    multiple instances of the PlatformEvent() for each thread.  One
      522 //    instance would be dedicated to muxAcquire-muxRelease, for instance.
      523 //
      524 // *  Usage:
      525 //    -- Only as leaf locks
      526 //    -- for short-term locking only as muxAcquire does not perform
      527 //       thread state transitions.
      528 //
      529 // Alternatives:
      530 // *  We could implement muxAcquire and muxRelease with MCS or CLH locks
      531 //    but with parking or spin-then-park instead of pure spinning.
      532 // *  Use Taura-Oyama-Yonenzawa locks.
      533 // *  It's possible to construct a 1-0 lock if we encode the lockword as
      534 //    (List,LockByte).  Acquire will CAS the full lockword while Release
      535 //    will STB 0 into the LockByte.  The 1-0 scheme admits stranding, so
      536 //    acquiring threads use timers (ParkTimed) to detect and recover from
      537 //    the stranding window.  Thread/Node structures must be aligned on 256-byte
      538 //    boundaries by using placement-new.
      539 // *  Augment MCS with advisory back-link fields maintained with CAS().
      540 //    Pictorially:  LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner.
      541 //    The validity of the backlinks must be ratified before we trust the value.
      542 //    If the backlinks are invalid the exiting thread must back-track through the
      543 //    the forward links, which are always trustworthy.
      544 // *  Add a successor indication.  The LockWord is currently encoded as
      545 //    (List, LOCKBIT:1).  We could also add a SUCCBIT or an explicit _succ variable
      546 //    to provide the usual futile-wakeup optimization.
      547 //    See RTStt for details.
      548 // *  Consider schedctl.sc_nopreempt to cover the critical section.
      549 //
      550 
      551 
      552 typedef volatile intptr_t MutexT ;      // Mux Lock-word
      553 enum MuxBits { LOCKBIT = 1 } ;
      554 
      555 void Thread::muxAcquire (volatile intptr_t * Lock, const char * LockName) {
      556   intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ;
      557   if (w == 0) return ;
      558   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
      559      return ;
      560   }
      561 
      562   TEVENT (muxAcquire - Contention) ;
      563   ParkEvent * const Self = Thread::current()->_MuxEvent ;
      564   assert ((intptr_t(Self) & LOCKBIT) == 0, "invariant") ;
      565   for (;;) {
      566      int its = (os::is_MP() ? 100 : 0) + 1 ;
      567 
      568      // Optional spin phase: spin-then-park strategy
      569      while (--its >= 0) {
      570        w = *Lock ;
      571        if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
      572           return ;
      573        }
      574      }
      575 
      576      Self->reset() ;
      577      Self->OnList = intptr_t(Lock) ;
      578      // The following fence() isn't _strictly necessary as the subsequent
      579      // CAS() both serializes execution and ratifies the fetched *Lock value.
      580      OrderAccess::fence();
      581      for (;;) {
      582         w = *Lock ;
      583         if ((w & LOCKBIT) == 0) {
      584             if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
      585                 Self->OnList = 0 ;   // hygiene - allows stronger asserts
      586                 return ;
      587             }
      588             continue ;      // Interference -- *Lock changed -- Just retry
      589         }
      590         assert (w & LOCKBIT, "invariant") ;
      591         Self->ListNext = (ParkEvent *) (w & ~LOCKBIT );
      592         if (Atomic::cmpxchg_ptr (intptr_t(Self)|LOCKBIT, Lock, w) == w) break ;
      593      }
      594 
      595      while (Self->OnList != 0) {
      596         Self->park() ;
      597      }
      598   }
      599 }
      600 
      601 void Thread::muxAcquireW (volatile intptr_t * Lock, ParkEvent * ev) {
      602   intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ;
      603   if (w == 0) return ;
      604   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
      605     return ;
      606   }
      607 
      608   TEVENT (muxAcquire - Contention) ;
      609   ParkEvent * ReleaseAfter = NULL ;
      610   if (ev == NULL) {
      611     ev = ReleaseAfter = ParkEvent::Allocate (NULL) ;
      612   }
      613   assert ((intptr_t(ev) & LOCKBIT) == 0, "invariant") ;
      614   for (;;) {
      615     guarantee (ev->OnList == 0, "invariant") ;
      616     int its = (os::is_MP() ? 100 : 0) + 1 ;
      617 
      618     // Optional spin phase: spin-then-park strategy
      619     while (--its >= 0) {
      620       w = *Lock ;
      621       if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
      622         if (ReleaseAfter != NULL) {
      623           ParkEvent::Release (ReleaseAfter) ;
      624         }
      625         return ;
      626       }
      627     }
      628 
      629     ev->reset() ;
      630     ev->OnList = intptr_t(Lock) ;
      631     // The following fence() isn't _strictly necessary as the subsequent
      632     // CAS() both serializes execution and ratifies the fetched *Lock value.
      633     OrderAccess::fence();
      634     for (;;) {
      635       w = *Lock ;
      636       if ((w & LOCKBIT) == 0) {
      637         if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
      638           ev->OnList = 0 ;
      639           // We call ::Release while holding the outer lock, thus
      640           // artificially lengthening the critical section.
      641           // Consider deferring the ::Release() until the subsequent unlock(),
      642           // after we've dropped the outer lock.
      643           if (ReleaseAfter != NULL) {
      644             ParkEvent::Release (ReleaseAfter) ;
      645           }
      646           return ;
      647         }
      648         continue ;      // Interference -- *Lock changed -- Just retry
      649       }
      650       assert (w & LOCKBIT, "invariant") ;
      651       ev->ListNext = (ParkEvent *) (w & ~LOCKBIT );
      652       if (Atomic::cmpxchg_ptr (intptr_t(ev)|LOCKBIT, Lock, w) == w) break ;
      653     }
      654 
      655     while (ev->OnList != 0) {
      656       ev->park() ;
      657     }
      658   }
      659 }
      660 
      661 // Release() must extract a successor from the list and then wake that thread.
      662 // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme
      663 // similar to that used by ParkEvent::Allocate() and ::Release().  DMR-based
      664 // Release() would :
      665 // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list.
      666 // (B) Extract a successor from the private list "in-hand"
      667 // (C) attempt to CAS() the residual back into *Lock over null.
      668 //     If there were any newly arrived threads and the CAS() would fail.
      669 //     In that case Release() would detach the RATs, re-merge the list in-hand
      670 //     with the RATs and repeat as needed.  Alternately, Release() might
      671 //     detach and extract a successor, but then pass the residual list to the wakee.
      672 //     The wakee would be responsible for reattaching and remerging before it
      673 //     competed for the lock.
      674 //
      675 // Both "pop" and DMR are immune from ABA corruption -- there can be
      676 // multiple concurrent pushers, but only one popper or detacher.
      677 // This implementation pops from the head of the list.  This is unfair,
      678 // but tends to provide excellent throughput as hot threads remain hot.
      679 // (We wake recently run threads first).
      680 
      681 void Thread::muxRelease (volatile intptr_t * Lock)  {
      682   for (;;) {
      683     const intptr_t w = Atomic::cmpxchg_ptr (0, Lock, LOCKBIT) ;
      684     assert (w & LOCKBIT, "invariant") ;
      685     if (w == LOCKBIT) return ;
      686     ParkEvent * List = (ParkEvent *) (w & ~LOCKBIT) ;
      687     assert (List != NULL, "invariant") ;
      688     assert (List->OnList == intptr_t(Lock), "invariant") ;
      689     ParkEvent * nxt = List->ListNext ;
      690 
      691     // The following CAS() releases the lock and pops the head element.
      692     if (Atomic::cmpxchg_ptr (intptr_t(nxt), Lock, w) != w) {
      693       continue ;
      694     }
      695     List->OnList = 0 ;
      696     OrderAccess::fence() ;
      697     List->unpark () ;
      698     return ;
      699   }
      700 }
      701 
      702 // ObjectMonitor Lifecycle
      703 // -----------------------
      704 // Inflation unlinks monitors from the global gFreeList and
      705 // associates them with objects.  Deflation -- which occurs at
      706 // STW-time -- disassociates idle monitors from objects.  Such
      707 // scavenged monitors are returned to the gFreeList.
      708 //
      709 // The global list is protected by ListLock.  All the critical sections
      710 // are short and operate in constant-time.
      711 //
      712 // ObjectMonitors reside in type-stable memory (TSM) and are immortal.
      713 //
      714 // Lifecycle:
      715 // --   unassigned and on the global free list
      716 // --   unassigned and on a thread's private omFreeList
      717 // --   assigned to an object.  The object is inflated and the mark refers
      718 //      to the objectmonitor.
      719 //
      720 // TODO-FIXME:
      721 //
      722 // *  We currently protect the gFreeList with a simple lock.
      723 //    An alternate lock-free scheme would be to pop elements from the gFreeList
      724 //    with CAS.  This would be safe from ABA corruption as long we only
      725 //    recycled previously appearing elements onto the list in deflate_idle_monitors()
      726 //    at STW-time.  Completely new elements could always be pushed onto the gFreeList
      727 //    with CAS.  Elements that appeared previously on the list could only
      728 //    be installed at STW-time.
      729 //
      730 // *  For efficiency and to help reduce the store-before-CAS penalty
      731 //    the objectmonitors on gFreeList or local free lists should be ready to install
      732 //    with the exception of _header and _object.  _object can be set after inflation.
      733 //    In particular, keep all objectMonitors on a thread's private list in ready-to-install
      734 //    state with m.Owner set properly.
      735 //
      736 // *  We could all diffuse contention by using multiple global (FreeList, Lock)
      737 //    pairs -- threads could use trylock() and a cyclic-scan strategy to search for
      738 //    an unlocked free list.
      739 //
      740 // *  Add lifecycle tags and assert()s.
      741 //
      742 // *  Be more consistent about when we clear an objectmonitor's fields:
      743 //    A.  After extracting the objectmonitor from a free list.
      744 //    B.  After adding an objectmonitor to a free list.
      745 //
      746 
      747 ObjectMonitor * ObjectSynchronizer::gBlockList = NULL ;
      748 ObjectMonitor * volatile ObjectSynchronizer::gFreeList  = NULL ;
      749 static volatile intptr_t ListLock = 0 ;      // protects global monitor free-list cache
      750 static volatile int MonitorFreeCount  = 0 ;      // # on gFreeList
      751 static volatile int MonitorPopulation = 0 ;      // # Extant -- in circulation
      752 #define CHAINMARKER ((oop)-1)
      753 
      754 // Constraining monitor pool growth via MonitorBound ...
      755 //
      756 // The monitor pool is grow-only.  We scavenge at STW safepoint-time, but the
      757 // the rate of scavenging is driven primarily by GC.  As such,  we can find
      758 // an inordinate number of monitors in circulation.
      759 // To avoid that scenario we can artificially induce a STW safepoint
      760 // if the pool appears to be growing past some reasonable bound.
      761 // Generally we favor time in space-time tradeoffs, but as there's no
      762 // natural back-pressure on the # of extant monitors we need to impose some
      763 // type of limit.  Beware that if MonitorBound is set to too low a value
      764 // we could just loop. In addition, if MonitorBound is set to a low value
      765 // we'll incur more safepoints, which are harmful to performance.
      766 // See also: GuaranteedSafepointInterval
      767 //
      768 // As noted elsewhere, the correct long-term solution is to deflate at
      769 // monitorexit-time, in which case the number of inflated objects is bounded
      770 // by the number of threads.  That policy obviates the need for scavenging at
      771 // STW safepoint time.   As an aside, scavenging can be time-consuming when the
      772 // # of extant monitors is large.   Unfortunately there's a day-1 assumption baked
      773 // into much HotSpot code that the object::monitor relationship, once established
      774 // or observed, will remain stable except over potential safepoints.
      775 //
      776 // We can use either a blocking synchronous VM operation or an async VM operation.
      777 // -- If we use a blocking VM operation :
      778 //    Calls to ScavengeCheck() should be inserted only into 'safe' locations in paths
      779 //    that lead to ::inflate() or ::omAlloc().
      780 //    Even though the safepoint will not directly induce GC, a GC might
      781 //    piggyback on the safepoint operation, so the caller should hold no naked oops.
      782 //    Furthermore, monitor::object relationships are NOT necessarily stable over this call
      783 //    unless the caller has made provisions to "pin" the object to the monitor, say
      784 //    by incrementing the monitor's _count field.
      785 // -- If we use a non-blocking asynchronous VM operation :
      786 //    the constraints above don't apply.  The safepoint will fire in the future
      787 //    at a more convenient time.  On the other hand the latency between posting and
      788 //    running the safepoint introduces or admits "slop" or laxity during which the
      789 //    monitor population can climb further above the threshold.  The monitor population,
      790 //    however, tends to converge asymptotically over time to a count that's slightly
      791 //    above the target value specified by MonitorBound.   That is, we avoid unbounded
      792 //    growth, albeit with some imprecision.
      793 //
      794 // The current implementation uses asynchronous VM operations.
      795 //
      796 // Ideally we'd check if (MonitorPopulation > MonitorBound) in omAlloc()
      797 // immediately before trying to grow the global list via allocation.
      798 // If the predicate was true then we'd induce a synchronous safepoint, wait
      799 // for the safepoint to complete, and then again to allocate from the global
      800 // free list.  This approach is much simpler and precise, admitting no "slop".
      801 // Unfortunately we can't safely safepoint in the midst of omAlloc(), so
      802 // instead we use asynchronous safepoints.
      803 
      804 static void InduceScavenge (Thread * Self, const char * Whence) {
      805   // Induce STW safepoint to trim monitors
      806   // Ultimately, this results in a call to deflate_idle_monitors() in the near future.
      807   // More precisely, trigger an asynchronous STW safepoint as the number
      808   // of active monitors passes the specified threshold.
      809   // TODO: assert thread state is reasonable
      810 
      811   if (ForceMonitorScavenge == 0 && Atomic::xchg (1, &ForceMonitorScavenge) == 0) {
      812     if (Knob_Verbose) {
      813       ::printf ("Monitor scavenge - Induced STW @%s (%d)\n", Whence, ForceMonitorScavenge) ;
      814       ::fflush(stdout) ;
      815     }
      816     // Induce a 'null' safepoint to scavenge monitors
      817     // Must VM_Operation instance be heap allocated as the op will be enqueue and posted
      818     // to the VMthread and have a lifespan longer than that of this activation record.
      819     // The VMThread will delete the op when completed.
      820     VMThread::execute (new VM_ForceAsyncSafepoint()) ;
      821 
      822     if (Knob_Verbose) {
      823       ::printf ("Monitor scavenge - STW posted @%s (%d)\n", Whence, ForceMonitorScavenge) ;
      824       ::fflush(stdout) ;
      825     }
      826   }
      827 }
      828 
      829 ObjectMonitor * ATTR ObjectSynchronizer::omAlloc (Thread * Self) {
      830     // A large MAXPRIVATE value reduces both list lock contention
      831     // and list coherency traffic, but also tends to increase the
      832     // number of objectMonitors in circulation as well as the STW
      833     // scavenge costs.  As usual, we lean toward time in space-time
      834     // tradeoffs.
      835     const int MAXPRIVATE = 1024 ;
      836     for (;;) {
      837         ObjectMonitor * m ;
      838 
      839         // 1: try to allocate from the thread's local omFreeList.
      840         // Threads will attempt to allocate first from their local list, then
      841         // from the global list, and only after those attempts fail will the thread
      842         // attempt to instantiate new monitors.   Thread-local free lists take
      843         // heat off the ListLock and improve allocation latency, as well as reducing
      844         // coherency traffic on the shared global list.
      845         m = Self->omFreeList ;
      846         if (m != NULL) {
      847            Self->omFreeList = m->FreeNext ;
      848            Self->omFreeCount -- ;
      849            // CONSIDER: set m->FreeNext = BAD -- diagnostic hygiene
      850            guarantee (m->object() == NULL, "invariant") ;
      851            if (MonitorInUseLists) {
      852              m->FreeNext = Self->omInUseList;
      853              Self->omInUseList = m;
      854              Self->omInUseCount ++;
      855            }
      856            return m ;
      857         }
      858 
      859         // 2: try to allocate from the global gFreeList
      860         // CONSIDER: use muxTry() instead of muxAcquire().
      861         // If the muxTry() fails then drop immediately into case 3.
      862         // If we're using thread-local free lists then try
      863         // to reprovision the caller's free list.
      864         if (gFreeList != NULL) {
      865             // Reprovision the thread's omFreeList.
      866             // Use bulk transfers to reduce the allocation rate and heat
      867             // on various locks.
      868             Thread::muxAcquire (&ListLock, "omAlloc") ;
      869             for (int i = Self->omFreeProvision; --i >= 0 && gFreeList != NULL; ) {
      870                 MonitorFreeCount --;
      871                 ObjectMonitor * take = gFreeList ;
      872                 gFreeList = take->FreeNext ;
      873                 guarantee (take->object() == NULL, "invariant") ;
      874                 guarantee (!take->is_busy(), "invariant") ;
      875                 take->Recycle() ;
      876                 omRelease (Self, take) ;
      877             }
      878             Thread::muxRelease (&ListLock) ;
      879             Self->omFreeProvision += 1 + (Self->omFreeProvision/2) ;
      880             if (Self->omFreeProvision > MAXPRIVATE ) Self->omFreeProvision = MAXPRIVATE ;
      881             TEVENT (omFirst - reprovision) ;
      882             continue ;
      883 
      884             const int mx = MonitorBound ;
      885             if (mx > 0 && (MonitorPopulation-MonitorFreeCount) > mx) {
      886               // We can't safely induce a STW safepoint from omAlloc() as our thread
      887               // state may not be appropriate for such activities and callers may hold
      888               // naked oops, so instead we defer the action.
      889               InduceScavenge (Self, "omAlloc") ;
      890             }
      891             continue;
      892         }
      893 
      894         // 3: allocate a block of new ObjectMonitors
      895         // Both the local and global free lists are empty -- resort to malloc().
      896         // In the current implementation objectMonitors are TSM - immortal.
      897         assert (_BLOCKSIZE > 1, "invariant") ;
      898         ObjectMonitor * temp = new ObjectMonitor[_BLOCKSIZE];
      899 
      900         // NOTE: (almost) no way to recover if allocation failed.
      901         // We might be able to induce a STW safepoint and scavenge enough
      902         // objectMonitors to permit progress.
      903         if (temp == NULL) {
      904             vm_exit_out_of_memory (sizeof (ObjectMonitor[_BLOCKSIZE]), "Allocate ObjectMonitors") ;
      905         }
      906 
      907         // Format the block.
      908         // initialize the linked list, each monitor points to its next
      909         // forming the single linked free list, the very first monitor
      910         // will points to next block, which forms the block list.
      911         // The trick of using the 1st element in the block as gBlockList
      912         // linkage should be reconsidered.  A better implementation would
      913         // look like: class Block { Block * next; int N; ObjectMonitor Body [N] ; }
      914 
      915         for (int i = 1; i < _BLOCKSIZE ; i++) {
      916            temp[i].FreeNext = &temp[i+1];
      917         }
      918 
      919         // terminate the last monitor as the end of list
      920         temp[_BLOCKSIZE - 1].FreeNext = NULL ;
      921 
      922         // Element [0] is reserved for global list linkage
      923         temp[0].set_object(CHAINMARKER);
      924 
      925         // Consider carving out this thread's current request from the
      926         // block in hand.  This avoids some lock traffic and redundant
      927         // list activity.
      928 
      929         // Acquire the ListLock to manipulate BlockList and FreeList.
      930         // An Oyama-Taura-Yonezawa scheme might be more efficient.
      931         Thread::muxAcquire (&ListLock, "omAlloc [2]") ;
      932         MonitorPopulation += _BLOCKSIZE-1;
      933         MonitorFreeCount += _BLOCKSIZE-1;
      934 
      935         // Add the new block to the list of extant blocks (gBlockList).
      936         // The very first objectMonitor in a block is reserved and dedicated.
      937         // It serves as blocklist "next" linkage.
      938         temp[0].FreeNext = gBlockList;
      939         gBlockList = temp;
      940 
      941         // Add the new string of objectMonitors to the global free list
      942         temp[_BLOCKSIZE - 1].FreeNext = gFreeList ;
      943         gFreeList = temp + 1;
      944         Thread::muxRelease (&ListLock) ;
      945         TEVENT (Allocate block of monitors) ;
      946     }
      947 }
      948 
      949 // Place "m" on the caller's private per-thread omFreeList.
      950 // In practice there's no need to clamp or limit the number of
      951 // monitors on a thread's omFreeList as the only time we'll call
      952 // omRelease is to return a monitor to the free list after a CAS
      953 // attempt failed.  This doesn't allow unbounded #s of monitors to
      954 // accumulate on a thread's free list.
      955 //
      956 // In the future the usage of omRelease() might change and monitors
      957 // could migrate between free lists.  In that case to avoid excessive
      958 // accumulation we could  limit omCount to (omProvision*2), otherwise return
      959 // the objectMonitor to the global list.  We should drain (return) in reasonable chunks.
      960 // That is, *not* one-at-a-time.
      961 
      962 
      963 void ObjectSynchronizer::omRelease (Thread * Self, ObjectMonitor * m) {
      964     guarantee (m->object() == NULL, "invariant") ;
      965     m->FreeNext = Self->omFreeList ;
      966     Self->omFreeList = m ;
      967     Self->omFreeCount ++ ;
      968 }
      969 
      970 // Return the monitors of a moribund thread's local free list to
      971 // the global free list.  Typically a thread calls omFlush() when
      972 // it's dying.  We could also consider having the VM thread steal
      973 // monitors from threads that have not run java code over a few
      974 // consecutive STW safepoints.  Relatedly, we might decay
      975 // omFreeProvision at STW safepoints.
      976 //
      977 // We currently call omFlush() from the Thread:: dtor _after the thread
      978 // has been excised from the thread list and is no longer a mutator.
      979 // That means that omFlush() can run concurrently with a safepoint and
      980 // the scavenge operator.  Calling omFlush() from JavaThread::exit() might
      981 // be a better choice as we could safely reason that that the JVM is
      982 // not at a safepoint at the time of the call, and thus there could
      983 // be not inopportune interleavings between omFlush() and the scavenge
      984 // operator.
      985 
      986 void ObjectSynchronizer::omFlush (Thread * Self) {
      987     ObjectMonitor * List = Self->omFreeList ;  // Null-terminated SLL
      988     Self->omFreeList = NULL ;
      989     if (List == NULL) return ;
      990     ObjectMonitor * Tail = NULL ;
      991     ObjectMonitor * s ;
      992     int Tally = 0;
      993     for (s = List ; s != NULL ; s = s->FreeNext) {
      994         Tally ++ ;
      995         Tail = s ;
      996         guarantee (s->object() == NULL, "invariant") ;
      997         guarantee (!s->is_busy(), "invariant") ;
      998         s->set_owner (NULL) ;   // redundant but good hygiene
      999         TEVENT (omFlush - Move one) ;
     1000     }
     1001 
     1002     guarantee (Tail != NULL && List != NULL, "invariant") ;
     1003     Thread::muxAcquire (&ListLock, "omFlush") ;
     1004     Tail->FreeNext = gFreeList ;
     1005     gFreeList = List ;
     1006     MonitorFreeCount += Tally;
     1007     Thread::muxRelease (&ListLock) ;
     1008     TEVENT (omFlush) ;
     1009 }
     1010 
     1011 
     1012 // Get the next block in the block list.
     1013 static inline ObjectMonitor* next(ObjectMonitor* block) {
     1014   assert(block->object() == CHAINMARKER, "must be a block header");
     1015   block = block->FreeNext ;
     1016   assert(block == NULL || block->object() == CHAINMARKER, "must be a block header");
     1017   return block;
     1018 }
     1019 
     1020 // Fast path code shared by multiple functions
     1021 ObjectMonitor* ObjectSynchronizer::inflate_helper(oop obj) {
     1022   markOop mark = obj->mark();
     1023   if (mark->has_monitor()) {
     1024     assert(ObjectSynchronizer::verify_objmon_isinpool(mark->monitor()), "monitor is invalid");
     1025     assert(mark->monitor()->header()->is_neutral(), "monitor must record a good object header");
     1026     return mark->monitor();
     1027   }
     1028   return ObjectSynchronizer::inflate(Thread::current(), obj);
     1029 }
     1030 
     1031 // Note that we could encounter some performance loss through false-sharing as
     1032 // multiple locks occupy the same $ line.  Padding might be appropriate.
     1033 
     1034 #define NINFLATIONLOCKS 256
     1035 static volatile intptr_t InflationLocks [NINFLATIONLOCKS] ;
     1036 
     1037 static markOop ReadStableMark (oop obj) {
     1038   markOop mark = obj->mark() ;
     1039   if (!mark->is_being_inflated()) {
     1040     return mark ;       // normal fast-path return
     1041   }
     1042 
     1043   int its = 0 ;
     1044   for (;;) {
     1045     markOop mark = obj->mark() ;
     1046     if (!mark->is_being_inflated()) {
     1047       return mark ;    // normal fast-path return
     1048     }
     1049 
     1050     // The object is being inflated by some other thread.
     1051     // The caller of ReadStableMark() must wait for inflation to complete.
     1052     // Avoid live-lock
     1053     // TODO: consider calling SafepointSynchronize::do_call_back() while
     1054     // spinning to see if there's a safepoint pending.  If so, immediately
     1055     // yielding or blocking would be appropriate.  Avoid spinning while
     1056     // there is a safepoint pending.
     1057     // TODO: add inflation contention performance counters.
     1058     // TODO: restrict the aggregate number of spinners.
     1059 
     1060     ++its ;
     1061     if (its > 10000 || !os::is_MP()) {
     1062        if (its & 1) {
     1063          os::NakedYield() ;
     1064          TEVENT (Inflate: INFLATING - yield) ;
     1065        } else {
     1066          // Note that the following code attenuates the livelock problem but is not
     1067          // a complete remedy.  A more complete solution would require that the inflating
     1068          // thread hold the associated inflation lock.  The following code simply restricts
     1069          // the number of spinners to at most one.  We'll have N-2 threads blocked
     1070          // on the inflationlock, 1 thread holding the inflation lock and using
     1071          // a yield/park strategy, and 1 thread in the midst of inflation.
     1072          // A more refined approach would be to change the encoding of INFLATING
     1073          // to allow encapsulation of a native thread pointer.  Threads waiting for
     1074          // inflation to complete would use CAS to push themselves onto a singly linked
     1075          // list rooted at the markword.  Once enqueued, they'd loop, checking a per-thread flag
     1076          // and calling park().  When inflation was complete the thread that accomplished inflation
     1077          // would detach the list and set the markword to inflated with a single CAS and
     1078          // then for each thread on the list, set the flag and unpark() the thread.
     1079          // This is conceptually similar to muxAcquire-muxRelease, except that muxRelease
     1080          // wakes at most one thread whereas we need to wake the entire list.
     1081          int ix = (intptr_t(obj) >> 5) & (NINFLATIONLOCKS-1) ;
     1082          int YieldThenBlock = 0 ;
     1083          assert (ix >= 0 && ix < NINFLATIONLOCKS, "invariant") ;
     1084          assert ((NINFLATIONLOCKS & (NINFLATIONLOCKS-1)) == 0, "invariant") ;
     1085          Thread::muxAcquire (InflationLocks + ix, "InflationLock") ;
     1086          while (obj->mark() == markOopDesc::INFLATING()) {
     1087            // Beware: NakedYield() is advisory and has almost no effect on some platforms
     1088            // so we periodically call Self->_ParkEvent->park(1).
     1089            // We use a mixed spin/yield/block mechanism.
     1090            if ((YieldThenBlock++) >= 16) {
     1091               Thread::current()->_ParkEvent->park(1) ;
     1092            } else {
     1093               os::NakedYield() ;
     1094            }
     1095          }
     1096          Thread::muxRelease (InflationLocks + ix ) ;
     1097          TEVENT (Inflate: INFLATING - yield/park) ;
     1098        }
     1099     } else {
     1100        SpinPause() ;       // SMP-polite spinning
     1101     }
     1102   }
     1103 }
     1104 
     1105 ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) {
     1106   // Inflate mutates the heap ...
     1107   // Relaxing assertion for bug 6320749.
     1108   assert (Universe::verify_in_progress() ||
     1109           !SafepointSynchronize::is_at_safepoint(), "invariant") ;
     1110 
     1111   for (;;) {
     1112       const markOop mark = object->mark() ;
     1113       assert (!mark->has_bias_pattern(), "invariant") ;
     1114 
     1115       // The mark can be in one of the following states:
     1116       // *  Inflated     - just return
     1117       // *  Stack-locked - coerce it to inflated
     1118       // *  INFLATING    - busy wait for conversion to complete
     1119       // *  Neutral      - aggressively inflate the object.
     1120       // *  BIASED       - Illegal.  We should never see this
     1121 
     1122       // CASE: inflated
     1123       if (mark->has_monitor()) {
     1124           ObjectMonitor * inf = mark->monitor() ;
     1125           assert (inf->header()->is_neutral(), "invariant");
     1126           assert (inf->object() == object, "invariant") ;
     1127           assert (ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid");
     1128           return inf ;
     1129       }
     1130 
     1131       // CASE: inflation in progress - inflating over a stack-lock.
     1132       // Some other thread is converting from stack-locked to inflated.
     1133       // Only that thread can complete inflation -- other threads must wait.
     1134       // The INFLATING value is transient.
     1135       // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
     1136       // We could always eliminate polling by parking the thread on some auxiliary list.
     1137       if (mark == markOopDesc::INFLATING()) {
     1138          TEVENT (Inflate: spin while INFLATING) ;
     1139          ReadStableMark(object) ;
     1140          continue ;
     1141       }
     1142 
     1143       // CASE: stack-locked
     1144       // Could be stack-locked either by this thread or by some other thread.
     1145       //
     1146       // Note that we allocate the objectmonitor speculatively, _before_ attempting
     1147       // to install INFLATING into the mark word.  We originally installed INFLATING,
     1148       // allocated the objectmonitor, and then finally STed the address of the
     1149       // objectmonitor into the mark.  This was correct, but artificially lengthened
     1150       // the interval in which INFLATED appeared in the mark, thus increasing
     1151       // the odds of inflation contention.
     1152       //
     1153       // We now use per-thread private objectmonitor free lists.
     1154       // These list are reprovisioned from the global free list outside the
     1155       // critical INFLATING...ST interval.  A thread can transfer
     1156       // multiple objectmonitors en-mass from the global free list to its local free list.
     1157       // This reduces coherency traffic and lock contention on the global free list.
     1158       // Using such local free lists, it doesn't matter if the omAlloc() call appears
     1159       // before or after the CAS(INFLATING) operation.
     1160       // See the comments in omAlloc().
     1161 
     1162       if (mark->has_locker()) {
     1163           ObjectMonitor * m = omAlloc (Self) ;
     1164           // Optimistically prepare the objectmonitor - anticipate successful CAS
     1165           // We do this before the CAS in order to minimize the length of time
     1166           // in which INFLATING appears in the mark.
     1167           m->Recycle();
     1168           m->FreeNext      = NULL ;
     1169           m->_Responsible  = NULL ;
     1170           m->OwnerIsThread = 0 ;
     1171           m->_recursions   = 0 ;
     1172           m->_SpinDuration = Knob_SpinLimit ;   // Consider: maintain by type/class
     1173 
     1174           markOop cmp = (markOop) Atomic::cmpxchg_ptr (markOopDesc::INFLATING(), object->mark_addr(), mark) ;
     1175           if (cmp != mark) {
     1176              omRelease (Self, m) ;
     1177              continue ;       // Interference -- just retry
     1178           }
     1179 
     1180           // We've successfully installed INFLATING (0) into the mark-word.
     1181           // This is the only case where 0 will appear in a mark-work.
     1182           // Only the singular thread that successfully swings the mark-word
     1183           // to 0 can perform (or more precisely, complete) inflation.
     1184           //
     1185           // Why do we CAS a 0 into the mark-word instead of just CASing the
     1186           // mark-word from the stack-locked value directly to the new inflated state?
     1187           // Consider what happens when a thread unlocks a stack-locked object.
     1188           // It attempts to use CAS to swing the displaced header value from the
     1189           // on-stack basiclock back into the object header.  Recall also that the
     1190           // header value (hashcode, etc) can reside in (a) the object header, or
     1191           // (b) a displaced header associated with the stack-lock, or (c) a displaced
     1192           // header in an objectMonitor.  The inflate() routine must copy the header
     1193           // value from the basiclock on the owner's stack to the objectMonitor, all
     1194           // the while preserving the hashCode stability invariants.  If the owner
     1195           // decides to release the lock while the value is 0, the unlock will fail
     1196           // and control will eventually pass from slow_exit() to inflate.  The owner
     1197           // will then spin, waiting for the 0 value to disappear.   Put another way,
     1198           // the 0 causes the owner to stall if the owner happens to try to
     1199           // drop the lock (restoring the header from the basiclock to the object)
     1200           // while inflation is in-progress.  This protocol avoids races that might
     1201           // would otherwise permit hashCode values to change or "flicker" for an object.
     1202           // Critically, while object->mark is 0 mark->displaced_mark_helper() is stable.
     1203           // 0 serves as a "BUSY" inflate-in-progress indicator.
     1204 
     1205 
     1206           // fetch the displaced mark from the owner's stack.
     1207           // The owner can't die or unwind past the lock while our INFLATING
     1208           // object is in the mark.  Furthermore the owner can't complete
     1209           // an unlock on the object, either.
     1210           markOop dmw = mark->displaced_mark_helper() ;
     1211           assert (dmw->is_neutral(), "invariant") ;
     1212 
     1213           // Setup monitor fields to proper values -- prepare the monitor
     1214           m->set_header(dmw) ;
     1215 
     1216           // Optimization: if the mark->locker stack address is associated
     1217           // with this thread we could simply set m->_owner = Self and
     1218           // m->OwnerIsThread = 1. Note that a thread can inflate an object
     1219           // that it has stack-locked -- as might happen in wait() -- directly
     1220           // with CAS.  That is, we can avoid the xchg-NULL .... ST idiom.
     1221           m->set_owner(mark->locker());
     1222           m->set_object(object);
     1223           // TODO-FIXME: assert BasicLock->dhw != 0.
     1224 
     1225           // Must preserve store ordering. The monitor state must
     1226           // be stable at the time of publishing the monitor address.
     1227           guarantee (object->mark() == markOopDesc::INFLATING(), "invariant") ;
     1228           object->release_set_mark(markOopDesc::encode(m));
     1229 
     1230           // Hopefully the performance counters are allocated on distinct cache lines
     1231           // to avoid false sharing on MP systems ...
     1232           if (_sync_Inflations != NULL) _sync_Inflations->inc() ;
     1233           TEVENT(Inflate: overwrite stacklock) ;
     1234           if (TraceMonitorInflation) {
     1235             if (object->is_instance()) {
     1236               ResourceMark rm;
     1237               tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
     1238                 (intptr_t) object, (intptr_t) object->mark(),
     1239                 Klass::cast(object->klass())->external_name());
     1240             }
     1241           }
     1242           return m ;
     1243       }
     1244 
     1245       // CASE: neutral
     1246       // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
     1247       // If we know we're inflating for entry it's better to inflate by swinging a
     1248       // pre-locked objectMonitor pointer into the object header.   A successful
     1249       // CAS inflates the object *and* confers ownership to the inflating thread.
     1250       // In the current implementation we use a 2-step mechanism where we CAS()
     1251       // to inflate and then CAS() again to try to swing _owner from NULL to Self.
     1252       // An inflateTry() method that we could call from fast_enter() and slow_enter()
     1253       // would be useful.
     1254 
     1255       assert (mark->is_neutral(), "invariant");
     1256       ObjectMonitor * m = omAlloc (Self) ;
     1257       // prepare m for installation - set monitor to initial state
     1258       m->Recycle();
     1259       m->set_header(mark);
     1260       m->set_owner(NULL);
     1261       m->set_object(object);
     1262       m->OwnerIsThread = 1 ;
     1263       m->_recursions   = 0 ;
     1264       m->FreeNext      = NULL ;
     1265       m->_Responsible  = NULL ;
     1266       m->_SpinDuration = Knob_SpinLimit ;       // consider: keep metastats by type/class
     1267 
     1268       if (Atomic::cmpxchg_ptr (markOopDesc::encode(m), object->mark_addr(), mark) != mark) {
     1269           m->set_object (NULL) ;
     1270           m->set_owner  (NULL) ;
     1271           m->OwnerIsThread = 0 ;
     1272           m->Recycle() ;
     1273           omRelease (Self, m) ;
     1274           m = NULL ;
     1275           continue ;
     1276           // interference - the markword changed - just retry.
     1277           // The state-transitions are one-way, so there's no chance of
     1278           // live-lock -- "Inflated" is an absorbing state.
     1279       }
     1280 
     1281       // Hopefully the performance counters are allocated on distinct
     1282       // cache lines to avoid false sharing on MP systems ...
     1283       if (_sync_Inflations != NULL) _sync_Inflations->inc() ;
     1284       TEVENT(Inflate: overwrite neutral) ;
     1285       if (TraceMonitorInflation) {
     1286         if (object->is_instance()) {
     1287           ResourceMark rm;
     1288           tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
     1289             (intptr_t) object, (intptr_t) object->mark(),
     1290             Klass::cast(object->klass())->external_name());
     1291         }
     1292       }
     1293       return m ;
     1294   }
     1295 }
     1296 
     1297 
     1298 // This the fast monitor enter. The interpreter and compiler use
     1299 // some assembly copies of this code. Make sure update those code
     1300 // if the following function is changed. The implementation is
     1301 // extremely sensitive to race condition. Be careful.
     1302 
     1303 void ObjectSynchronizer::fast_enter(Handle obj, BasicLock* lock, bool attempt_rebias, TRAPS) {
     1304  if (UseBiasedLocking) {
     1305     if (!SafepointSynchronize::is_at_safepoint()) {
     1306       BiasedLocking::Condition cond = BiasedLocking::revoke_and_rebias(obj, attempt_rebias, THREAD);
     1307       if (cond == BiasedLocking::BIAS_REVOKED_AND_REBIASED) {
     1308         return;
     1309       }
     1310     } else {
     1311       assert(!attempt_rebias, "can not rebias toward VM thread");
     1312       BiasedLocking::revoke_at_safepoint(obj);
     1313     }
     1314     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
     1315  }
     1316 
     1317  slow_enter (obj, lock, THREAD) ;
     1318 }
     1319 
     1320 void ObjectSynchronizer::fast_exit(oop object, BasicLock* lock, TRAPS) {
     1321   assert(!object->mark()->has_bias_pattern(), "should not see bias pattern here");
     1322   // if displaced header is null, the previous enter is recursive enter, no-op
     1323   markOop dhw = lock->displaced_header();
     1324   markOop mark ;
     1325   if (dhw == NULL) {
     1326      // Recursive stack-lock.
     1327      // Diagnostics -- Could be: stack-locked, inflating, inflated.
     1328      mark = object->mark() ;
     1329      assert (!mark->is_neutral(), "invariant") ;
     1330      if (mark->has_locker() && mark != markOopDesc::INFLATING()) {
     1331         assert(THREAD->is_lock_owned((address)mark->locker()), "invariant") ;
     1332      }
     1333      if (mark->has_monitor()) {
     1334         ObjectMonitor * m = mark->monitor() ;
     1335         assert(((oop)(m->object()))->mark() == mark, "invariant") ;
     1336         assert(m->is_entered(THREAD), "invariant") ;
     1337      }
     1338      return ;
     1339   }
     1340 
     1341   mark = object->mark() ;
     1342 
     1343   // If the object is stack-locked by the current thread, try to
     1344   // swing the displaced header from the box back to the mark.
     1345   if (mark == (markOop) lock) {
     1346      assert (dhw->is_neutral(), "invariant") ;
     1347      if ((markOop) Atomic::cmpxchg_ptr (dhw, object->mark_addr(), mark) == mark) {
     1348         TEVENT (fast_exit: release stacklock) ;
     1349         return;
     1350      }
     1351   }
     1352 
     1353   ObjectSynchronizer::inflate(THREAD, object)->exit (THREAD) ;
     1354 }
     1355 
     1356 // This routine is used to handle interpreter/compiler slow case
     1357 // We don't need to use fast path here, because it must have been
     1358 // failed in the interpreter/compiler code.
     1359 void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) {
     1360   markOop mark = obj->mark();
     1361   assert(!mark->has_bias_pattern(), "should not see bias pattern here");
     1362 
     1363   if (mark->is_neutral()) {
     1364     // Anticipate successful CAS -- the ST of the displaced mark must
     1365     // be visible <= the ST performed by the CAS.
     1366     lock->set_displaced_header(mark);
     1367     if (mark == (markOop) Atomic::cmpxchg_ptr(lock, obj()->mark_addr(), mark)) {
     1368       TEVENT (slow_enter: release stacklock) ;
     1369       return ;
     1370     }
     1371     // Fall through to inflate() ...
     1372   } else
     1373   if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
     1374     assert(lock != mark->locker(), "must not re-lock the same lock");
     1375     assert(lock != (BasicLock*)obj->mark(), "don't relock with same BasicLock");
     1376     lock->set_displaced_header(NULL);
     1377     return;
     1378   }
     1379 
     1380 #if 0
     1381   // The following optimization isn't particularly useful.
     1382   if (mark->has_monitor() && mark->monitor()->is_entered(THREAD)) {
     1383     lock->set_displaced_header (NULL) ;
     1384     return ;
     1385   }
     1386 #endif
     1387 
     1388   // The object header will never be displaced to this lock,
     1389   // so it does not matter what the value is, except that it
     1390   // must be non-zero to avoid looking like a re-entrant lock,
     1391   // and must not look locked either.
     1392   lock->set_displaced_header(markOopDesc::unused_mark());
     1393   ObjectSynchronizer::inflate(THREAD, obj())->enter(THREAD);
     1394 }
     1395 
     1396 // This routine is used to handle interpreter/compiler slow case
     1397 // We don't need to use fast path here, because it must have
     1398 // failed in the interpreter/compiler code. Simply use the heavy
     1399 // weight monitor should be ok, unless someone find otherwise.
     1400 void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) {
     1401   fast_exit (object, lock, THREAD) ;
     1402 }
     1403 
     1404 // NOTE: must use heavy weight monitor to handle jni monitor enter
     1405 void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) { // possible entry from jni enter
     1406   // the current locking is from JNI instead of Java code
     1407   TEVENT (jni_enter) ;
     1408   if (UseBiasedLocking) {
     1409     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
     1410     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
     1411   }
     1412   THREAD->set_current_pending_monitor_is_from_java(false);
     1413   ObjectSynchronizer::inflate(THREAD, obj())->enter(THREAD);
     1414   THREAD->set_current_pending_monitor_is_from_java(true);
     1415 }
     1416 
     1417 // NOTE: must use heavy weight monitor to handle jni monitor enter
     1418 bool ObjectSynchronizer::jni_try_enter(Handle obj, Thread* THREAD) {
     1419   if (UseBiasedLocking) {
     1420     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
     1421     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
     1422   }
     1423 
     1424   ObjectMonitor* monitor = ObjectSynchronizer::inflate_helper(obj());
     1425   return monitor->try_enter(THREAD);
     1426 }
     1427 
     1428 
     1429 // NOTE: must use heavy weight monitor to handle jni monitor exit
     1430 void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) {
     1431   TEVENT (jni_exit) ;
     1432   if (UseBiasedLocking) {
     1433     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
     1434   }
     1435   assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
     1436 
     1437   ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj);
     1438   // If this thread has locked the object, exit the monitor.  Note:  can't use
     1439   // monitor->check(CHECK); must exit even if an exception is pending.
     1440   if (monitor->check(THREAD)) {
     1441      monitor->exit(THREAD);
     1442   }
     1443 }
     1444 
     1445 // complete_exit()/reenter() are used to wait on a nested lock
     1446 // i.e. to give up an outer lock completely and then re-enter
     1447 // Used when holding nested locks - lock acquisition order: lock1 then lock2
     1448 //  1) complete_exit lock1 - saving recursion count
     1449 //  2) wait on lock2
     1450 //  3) when notified on lock2, unlock lock2
     1451 //  4) reenter lock1 with original recursion count
     1452 //  5) lock lock2
     1453 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
     1454 intptr_t ObjectSynchronizer::complete_exit(Handle obj, TRAPS) {
     1455   TEVENT (complete_exit) ;
     1456   if (UseBiasedLocking) {
     1457     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
     1458     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
     1459   }
     1460 
     1461   ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj());
     1462 
     1463   return monitor->complete_exit(THREAD);
     1464 }
     1465 
     1466 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
     1467 void ObjectSynchronizer::reenter(Handle obj, intptr_t recursion, TRAPS) {
     1468   TEVENT (reenter) ;
     1469   if (UseBiasedLocking) {
     1470     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
     1471     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
     1472   }
     1473 
     1474   ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj());
     1475 
     1476   monitor->reenter(recursion, THREAD);
     1477 }
     1478 
     1479 // This exists only as a workaround of dtrace bug 6254741
     1480 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) {
     1481   DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
     1482   return 0;
     1483 }
     1484 
     1485 // NOTE: must use heavy weight monitor to handle wait()
     1486 void ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
     1487   if (UseBiasedLocking) {
     1488     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
     1489     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
     1490   }
     1491   if (millis < 0) {
     1492     TEVENT (wait - throw IAX) ;
     1493     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
     1494   }
     1495   ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj());
     1496   DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis);
     1497   monitor->wait(millis, true, THREAD);
     1498 
     1499   /* This dummy call is in place to get around dtrace bug 6254741.  Once
     1500      that's fixed we can uncomment the following line and remove the call */
     1501   // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
     1502   dtrace_waited_probe(monitor, obj, THREAD);
     1503 }
     1504 
     1505 void ObjectSynchronizer::waitUninterruptibly (Handle obj, jlong millis, TRAPS) {
     1506   if (UseBiasedLocking) {
     1507     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
     1508     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
     1509   }
     1510   if (millis < 0) {
     1511     TEVENT (wait - throw IAX) ;
     1512     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
     1513   }
     1514   ObjectSynchronizer::inflate(THREAD, obj()) -> wait(millis, false, THREAD) ;
     1515 }
     1516 
     1517 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
     1518  if (UseBiasedLocking) {
     1519     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
     1520     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
     1521   }
     1522 
     1523   markOop mark = obj->mark();
     1524   if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
     1525     return;
     1526   }
     1527   ObjectSynchronizer::inflate(THREAD, obj())->notify(THREAD);
     1528 }
     1529 
     1530 // NOTE: see comment of notify()
     1531 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
     1532   if (UseBiasedLocking) {
     1533     BiasedLocking::revoke_and_rebias(obj, false, THREAD);
     1534     assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
     1535   }
     1536 
     1537   markOop mark = obj->mark();
     1538   if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
     1539     return;
     1540   }
     1541   ObjectSynchronizer::inflate(THREAD, obj())->notifyAll(THREAD);
     1542 }
     1543 
     1544 intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) {
     1545   if (UseBiasedLocking) {
     1546     // NOTE: many places throughout the JVM do not expect a safepoint
     1547     // to be taken here, in particular most operations on perm gen
     1548     // objects. However, we only ever bias Java instances and all of
     1549     // the call sites of identity_hash that might revoke biases have
     1550     // been checked to make sure they can handle a safepoint. The
     1551     // added check of the bias pattern is to avoid useless calls to
     1552     // thread-local storage.
     1553     if (obj->mark()->has_bias_pattern()) {
     1554       // Box and unbox the raw reference just in case we cause a STW safepoint.
     1555       Handle hobj (Self, obj) ;
     1556       // Relaxing assertion for bug 6320749.
     1557       assert (Universe::verify_in_progress() ||
     1558               !SafepointSynchronize::is_at_safepoint(),
     1559              "biases should not be seen by VM thread here");
     1560       BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current());
     1561       obj = hobj() ;
     1562       assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
     1563     }
     1564   }
     1565 
     1566   // hashCode() is a heap mutator ...
     1567   // Relaxing assertion for bug 6320749.
     1568   assert (Universe::verify_in_progress() ||
     1569           !SafepointSynchronize::is_at_safepoint(), "invariant") ;
     1570   assert (Universe::verify_in_progress() ||
     1571           Self->is_Java_thread() , "invariant") ;
     1572   assert (Universe::verify_in_progress() ||
     1573          ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant") ;
     1574 
     1575   ObjectMonitor* monitor = NULL;
     1576   markOop temp, test;
     1577   intptr_t hash;
     1578   markOop mark = ReadStableMark (obj);
     1579 
     1580   // object should remain ineligible for biased locking
     1581   assert (!mark->has_bias_pattern(), "invariant") ;
     1582 
     1583   if (mark->is_neutral()) {
     1584     hash = mark->hash();              // this is a normal header
     1585     if (hash) {                       // if it has hash, just return it
     1586       return hash;
     1587     }
     1588     hash = get_next_hash(Self, obj);  // allocate a new hash code
     1589     temp = mark->copy_set_hash(hash); // merge the hash code into header
     1590     // use (machine word version) atomic operation to install the hash
     1591     test = (markOop) Atomic::cmpxchg_ptr(temp, obj->mark_addr(), mark);
     1592     if (test == mark) {
     1593       return hash;
     1594     }
     1595     // If atomic operation failed, we must inflate the header
     1596     // into heavy weight monitor. We could add more code here
     1597     // for fast path, but it does not worth the complexity.
     1598   } else if (mark->has_monitor()) {
     1599     monitor = mark->monitor();
     1600     temp = monitor->header();
     1601     assert (temp->is_neutral(), "invariant") ;
     1602     hash = temp->hash();
     1603     if (hash) {
     1604       return hash;
     1605     }
     1606     // Skip to the following code to reduce code size
     1607   } else if (Self->is_lock_owned((address)mark->locker())) {
     1608     temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned
     1609     assert (temp->is_neutral(), "invariant") ;
     1610     hash = temp->hash();              // by current thread, check if the displaced
     1611     if (hash) {                       // header contains hash code
     1612       return hash;
     1613     }
     1614     // WARNING:
     1615     //   The displaced header is strictly immutable.
     1616     // It can NOT be changed in ANY cases. So we have
     1617     // to inflate the header into heavyweight monitor
     1618     // even the current thread owns the lock. The reason
     1619     // is the BasicLock (stack slot) will be asynchronously
     1620     // read by other threads during the inflate() function.
     1621     // Any change to stack may not propagate to other threads
     1622     // correctly.
     1623   }
     1624 
     1625   // Inflate the monitor to set hash code
     1626   monitor = ObjectSynchronizer::inflate(Self, obj);
     1627   // Load displaced header and check it has hash code
     1628   mark = monitor->header();
     1629   assert (mark->is_neutral(), "invariant") ;
     1630   hash = mark->hash();
     1631   if (hash == 0) {
     1632     hash = get_next_hash(Self, obj);
     1633     temp = mark->copy_set_hash(hash); // merge hash code into header
     1634     assert (temp->is_neutral(), "invariant") ;
     1635     test = (markOop) Atomic::cmpxchg_ptr(temp, monitor, mark);
     1636     if (test != mark) {
     1637       // The only update to the header in the monitor (outside GC)
     1638       // is install the hash code. If someone add new usage of
     1639       // displaced header, please update this code
     1640       hash = test->hash();
     1641       assert (test->is_neutral(), "invariant") ;
     1642       assert (hash != 0, "Trivial unexpected object/monitor header usage.");
     1643     }
     1644   }
     1645   // We finally get the hash
     1646   return hash;
     1647 }
     1648 
     1649 // Deprecated -- use FastHashCode() instead.
     1650 
     1651 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) {
     1652   return FastHashCode (Thread::current(), obj()) ;
     1653 }
     1654 
     1655 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread,
     1656                                                    Handle h_obj) {
     1657   if (UseBiasedLocking) {
     1658     BiasedLocking::revoke_and_rebias(h_obj, false, thread);
     1659     assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
     1660   }
     1661 
     1662   assert(thread == JavaThread::current(), "Can only be called on current thread");
     1663   oop obj = h_obj();
     1664 
     1665   markOop mark = ReadStableMark (obj) ;
     1666 
     1667   // Uncontended case, header points to stack
     1668   if (mark->has_locker()) {
     1669     return thread->is_lock_owned((address)mark->locker());
     1670   }
     1671   // Contended case, header points to ObjectMonitor (tagged pointer)
     1672   if (mark->has_monitor()) {
     1673     ObjectMonitor* monitor = mark->monitor();
     1674     return monitor->is_entered(thread) != 0 ;
     1675   }
     1676   // Unlocked case, header in place
     1677   assert(mark->is_neutral(), "sanity check");
     1678   return false;
     1679 }
     1680 
     1681 // Be aware of this method could revoke bias of the lock object.
     1682 // This method querys the ownership of the lock handle specified by 'h_obj'.
     1683 // If the current thread owns the lock, it returns owner_self. If no
     1684 // thread owns the lock, it returns owner_none. Otherwise, it will return
     1685 // ower_other.
     1686 ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership
     1687 (JavaThread *self, Handle h_obj) {
     1688   // The caller must beware this method can revoke bias, and
     1689   // revocation can result in a safepoint.
     1690   assert (!SafepointSynchronize::is_at_safepoint(), "invariant") ;
     1691   assert (self->thread_state() != _thread_blocked , "invariant") ;
     1692 
     1693   // Possible mark states: neutral, biased, stack-locked, inflated
     1694 
     1695   if (UseBiasedLocking && h_obj()->mark()->has_bias_pattern()) {
     1696     // CASE: biased
     1697     BiasedLocking::revoke_and_rebias(h_obj, false, self);
     1698     assert(!h_obj->mark()->has_bias_pattern(),
     1699            "biases should be revoked by now");
     1700   }
     1701 
     1702   assert(self == JavaThread::current(), "Can only be called on current thread");
     1703   oop obj = h_obj();
     1704   markOop mark = ReadStableMark (obj) ;
     1705 
     1706   // CASE: stack-locked.  Mark points to a BasicLock on the owner's stack.
     1707   if (mark->has_locker()) {
     1708     return self->is_lock_owned((address)mark->locker()) ?
     1709       owner_self : owner_other;
     1710   }
     1711 
     1712   // CASE: inflated. Mark (tagged pointer) points to an objectMonitor.
     1713   // The Object:ObjectMonitor relationship is stable as long as we're
     1714   // not at a safepoint.
     1715   if (mark->has_monitor()) {
     1716     void * owner = mark->monitor()->_owner ;
     1717     if (owner == NULL) return owner_none ;
     1718     return (owner == self ||
     1719             self->is_lock_owned((address)owner)) ? owner_self : owner_other;
     1720   }
     1721 
     1722   // CASE: neutral
     1723   assert(mark->is_neutral(), "sanity check");
     1724   return owner_none ;           // it's unlocked
     1725 }
     1726 
     1727 // FIXME: jvmti should call this
     1728 JavaThread* ObjectSynchronizer::get_lock_owner(Handle h_obj, bool doLock) {
     1729   if (UseBiasedLocking) {
     1730     if (SafepointSynchronize::is_at_safepoint()) {
     1731       BiasedLocking::revoke_at_safepoint(h_obj);
     1732     } else {
     1733       BiasedLocking::revoke_and_rebias(h_obj, false, JavaThread::current());
     1734     }
     1735     assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
     1736   }
     1737 
     1738   oop obj = h_obj();
     1739   address owner = NULL;
     1740 
     1741   markOop mark = ReadStableMark (obj) ;
     1742 
     1743   // Uncontended case, header points to stack
     1744   if (mark->has_locker()) {
     1745     owner = (address) mark->locker();
     1746   }
     1747 
     1748   // Contended case, header points to ObjectMonitor (tagged pointer)
     1749   if (mark->has_monitor()) {
     1750     ObjectMonitor* monitor = mark->monitor();
     1751     assert(monitor != NULL, "monitor should be non-null");
     1752     owner = (address) monitor->owner();
     1753   }
     1754 
     1755   if (owner != NULL) {
     1756     return Threads::owning_thread_from_monitor_owner(owner, doLock);
     1757   }
     1758 
     1759   // Unlocked case, header in place
     1760   // Cannot have assertion since this object may have been
     1761   // locked by another thread when reaching here.
     1762   // assert(mark->is_neutral(), "sanity check");
     1763 
     1764   return NULL;
     1765 }
     1766 
     1767 // Iterate through monitor cache and attempt to release thread's monitors
     1768 // Gives up on a particular monitor if an exception occurs, but continues
     1769 // the overall iteration, swallowing the exception.
     1770 class ReleaseJavaMonitorsClosure: public MonitorClosure {
     1771 private:
     1772   TRAPS;
     1773 
     1774 public:
     1775   ReleaseJavaMonitorsClosure(Thread* thread) : THREAD(thread) {}
     1776   void do_monitor(ObjectMonitor* mid) {
     1777     if (mid->owner() == THREAD) {
     1778       (void)mid->complete_exit(CHECK);
     1779     }
     1780   }
     1781 };
     1782 
     1783 // Release all inflated monitors owned by THREAD.  Lightweight monitors are
     1784 // ignored.  This is meant to be called during JNI thread detach which assumes
     1785 // all remaining monitors are heavyweight.  All exceptions are swallowed.
     1786 // Scanning the extant monitor list can be time consuming.
     1787 // A simple optimization is to add a per-thread flag that indicates a thread
     1788 // called jni_monitorenter() during its lifetime.
     1789 //
     1790 // Instead of No_Savepoint_Verifier it might be cheaper to
     1791 // use an idiom of the form:
     1792 //   auto int tmp = SafepointSynchronize::_safepoint_counter ;
     1793 //   <code that must not run at safepoint>
     1794 //   guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ;
     1795 // Since the tests are extremely cheap we could leave them enabled
     1796 // for normal product builds.
     1797 
     1798 void ObjectSynchronizer::release_monitors_owned_by_thread(TRAPS) {
     1799   assert(THREAD == JavaThread::current(), "must be current Java thread");
     1800   No_Safepoint_Verifier nsv ;
     1801   ReleaseJavaMonitorsClosure rjmc(THREAD);
     1802   Thread::muxAcquire(&ListLock, "release_monitors_owned_by_thread");
     1803   ObjectSynchronizer::monitors_iterate(&rjmc);
     1804   Thread::muxRelease(&ListLock);
     1805   THREAD->clear_pending_exception();
     1806 }
     1807 
     1808 // Visitors ...
     1809 
     1810 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure) {
     1811   ObjectMonitor* block = gBlockList;
     1812   ObjectMonitor* mid;
     1813   while (block) {
     1814     assert(block->object() == CHAINMARKER, "must be a block header");
     1815     for (int i = _BLOCKSIZE - 1; i > 0; i--) {
     1816       mid = block + i;
     1817       oop object = (oop) mid->object();
     1818       if (object != NULL) {
     1819         closure->do_monitor(mid);
     1820       }
     1821     }
     1822     block = (ObjectMonitor*) block->FreeNext;
     1823   }
     1824 }
     1825 
     1826 void ObjectSynchronizer::oops_do(OopClosure* f) {
     1827   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
     1828   for (ObjectMonitor* block = gBlockList; block != NULL; block = next(block)) {
     1829     assert(block->object() == CHAINMARKER, "must be a block header");
     1830     for (int i = 1; i < _BLOCKSIZE; i++) {
     1831       ObjectMonitor* mid = &block[i];
     1832       if (mid->object() != NULL) {
     1833         f->do_oop((oop*)mid->object_addr());
     1834       }
     1835     }
     1836   }
     1837 }
     1838 
     1839 // Deflate_idle_monitors() is called at all safepoints, immediately
     1840 // after all mutators are stopped, but before any objects have moved.
     1841 // It traverses the list of known monitors, deflating where possible.
     1842 // The scavenged monitor are returned to the monitor free list.
     1843 //
     1844 // Beware that we scavenge at *every* stop-the-world point.
     1845 // Having a large number of monitors in-circulation negatively
     1846 // impacts the performance of some applications (e.g., PointBase).
     1847 // Broadly, we want to minimize the # of monitors in circulation.
     1848 //
     1849 // We have added a flag, MonitorInUseLists, which creates a list
     1850 // of active monitors for each thread. deflate_idle_monitors()
     1851 // only scans the per-thread inuse lists. omAlloc() puts all
     1852 // assigned monitors on the per-thread list. deflate_idle_monitors()
     1853 // returns the non-busy monitors to the global free list.
     1854 // An alternative could have used a single global inuse list. The
     1855 // downside would have been the additional cost of acquiring the global list lock
     1856 // for every omAlloc().
     1857 //
     1858 // Perversely, the heap size -- and thus the STW safepoint rate --
     1859 // typically drives the scavenge rate.  Large heaps can mean infrequent GC,
     1860 // which in turn can mean large(r) numbers of objectmonitors in circulation.
     1861 // This is an unfortunate aspect of this design.
     1862 //
     1863 // Another refinement would be to refrain from calling deflate_idle_monitors()
     1864 // except at stop-the-world points associated with garbage collections.
     1865 //
     1866 // An even better solution would be to deflate on-the-fly, aggressively,
     1867 // at monitorexit-time as is done in EVM's metalock or Relaxed Locks.
     1868 
     1869 // Deflate a single monitor if not in use
     1870 // Return true if deflated, false if in use
     1871 bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj,
     1872                                          ObjectMonitor** FreeHeadp, ObjectMonitor** FreeTailp) {
     1873   bool deflated;
     1874     // Normal case ... The monitor is associated with obj.
     1875     guarantee (obj->mark() == markOopDesc::encode(mid), "invariant") ;
     1876     guarantee (mid == obj->mark()->monitor(), "invariant");
     1877     guarantee (mid->header()->is_neutral(), "invariant");
     1878 
     1879     if (mid->is_busy()) {
     1880        if (ClearResponsibleAtSTW) mid->_Responsible = NULL ;
     1881        deflated = false;
     1882     } else {
     1883        // Deflate the monitor if it is no longer being used
     1884        // It's idle - scavenge and return to the global free list
     1885        // plain old deflation ...
     1886        TEVENT (deflate_idle_monitors - scavenge1) ;
     1887        if (TraceMonitorInflation) {
     1888          if (obj->is_instance()) {
     1889            ResourceMark rm;
     1890              tty->print_cr("Deflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
     1891                   (intptr_t) obj, (intptr_t) obj->mark(), Klass::cast(obj->klass())->external_name());
     1892          }
     1893        }
     1894 
     1895        // Restore the header back to obj
     1896        obj->release_set_mark(mid->header());
     1897        mid->clear();
     1898 
     1899        assert (mid->object() == NULL, "invariant") ;
     1900 
     1901        // Move the object to the working free list defined by FreeHead,FreeTail.
     1902        if (*FreeHeadp == NULL) *FreeHeadp = mid;
     1903        if (*FreeTailp != NULL) {
     1904          ObjectMonitor * prevtail = *FreeTailp;
     1905          prevtail->FreeNext = mid;
     1906        }
     1907        *FreeTailp = mid;
     1908        deflated = true;
     1909     }
     1910     return deflated;
     1911 }
     1912 
     1913 void ObjectSynchronizer::deflate_idle_monitors() {
     1914   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
     1915   int nInuse = 0 ;              // currently associated with objects
     1916   int nInCirculation = 0 ;      // extant
     1917   int nScavenged = 0 ;          // reclaimed
     1918   bool deflated = false;
     1919 
     1920   ObjectMonitor * FreeHead = NULL ;  // Local SLL of scavenged monitors
     1921   ObjectMonitor * FreeTail = NULL ;
     1922 
     1923   TEVENT (deflate_idle_monitors) ;
     1924   // Prevent omFlush from changing mids in Thread dtor's during deflation
     1925   // And in case the vm thread is acquiring a lock during a safepoint
     1926   // See e.g. 6320749
     1927   Thread::muxAcquire (&ListLock, "scavenge - return") ;
     1928 
     1929   if (MonitorInUseLists) {
     1930     ObjectMonitor* mid;
     1931     ObjectMonitor* next;
     1932     ObjectMonitor* curmidinuse;
     1933     for (JavaThread* cur = Threads::first(); cur != NULL; cur = cur->next()) {
     1934       curmidinuse = NULL;
     1935       for (mid = cur->omInUseList; mid != NULL; ) {
     1936         oop obj = (oop) mid->object();
     1937         deflated = false;
     1938         if (obj != NULL) {
     1939           deflated = deflate_monitor(mid, obj, &FreeHead, &FreeTail);
     1940         }
     1941         if (deflated) {
     1942           // extract from per-thread in-use-list
     1943           if (mid == cur->omInUseList) {
     1944             cur->omInUseList = mid->FreeNext;
     1945           } else if (curmidinuse != NULL) {
     1946             curmidinuse->FreeNext = mid->FreeNext; // maintain the current thread inuselist
     1947           }
     1948           next = mid->FreeNext;
     1949           mid->FreeNext = NULL;  // This mid is current tail in the FreeHead list
     1950           mid = next;
     1951           cur->omInUseCount--;
     1952           nScavenged ++ ;
     1953         } else {
     1954           curmidinuse = mid;
     1955           mid = mid->FreeNext;
     1956           nInuse ++;
     1957         }
     1958      }
     1959    }
     1960   } else for (ObjectMonitor* block = gBlockList; block != NULL; block = next(block)) {
     1961   // Iterate over all extant monitors - Scavenge all idle monitors.
     1962     assert(block->object() == CHAINMARKER, "must be a block header");
     1963     nInCirculation += _BLOCKSIZE ;
     1964     for (int i = 1 ; i < _BLOCKSIZE; i++) {
     1965       ObjectMonitor* mid = &block[i];
     1966       oop obj = (oop) mid->object();
     1967 
     1968       if (obj == NULL) {
     1969         // The monitor is not associated with an object.
     1970         // The monitor should either be a thread-specific private
     1971         // free list or the global free list.
     1972         // obj == NULL IMPLIES mid->is_busy() == 0
     1973         guarantee (!mid->is_busy(), "invariant") ;
     1974         continue ;
     1975       }
     1976       deflated = deflate_monitor(mid, obj, &FreeHead, &FreeTail);
     1977 
     1978       if (deflated) {
     1979          mid->FreeNext = NULL ;
     1980          nScavenged ++ ;
     1981       } else {
     1982          nInuse ++;
     1983       }
     1984     }
     1985   }
     1986 
     1987   MonitorFreeCount += nScavenged;
     1988 
     1989   // Consider: audit gFreeList to ensure that MonitorFreeCount and list agree.
     1990 
     1991   if (Knob_Verbose) {
     1992     ::printf ("Deflate: InCirc=%d InUse=%d Scavenged=%d ForceMonitorScavenge=%d : pop=%d free=%d\n",
     1993         nInCirculation, nInuse, nScavenged, ForceMonitorScavenge,
     1994         MonitorPopulation, MonitorFreeCount) ;
     1995     ::fflush(stdout) ;
     1996   }
     1997 
     1998   ForceMonitorScavenge = 0;    // Reset
     1999 
     2000   // Move the scavenged monitors back to the global free list.
     2001   if (FreeHead != NULL) {
     2002      guarantee (FreeTail != NULL && nScavenged > 0, "invariant") ;
     2003      assert (FreeTail->FreeNext == NULL, "invariant") ;
     2004      // constant-time list splice - prepend scavenged segment to gFreeList
     2005      FreeTail->FreeNext = gFreeList ;
     2006      gFreeList = FreeHead ;
     2007   }
     2008   Thread::muxRelease (&ListLock) ;
     2009 
     2010   if (_sync_Deflations != NULL) _sync_Deflations->inc(nScavenged) ;
     2011   if (_sync_MonExtant  != NULL) _sync_MonExtant ->set_value(nInCirculation);
     2012 
     2013   // TODO: Add objectMonitor leak detection.
     2014   // Audit/inventory the objectMonitors -- make sure they're all accounted for.
     2015   GVars.stwRandom = os::random() ;
     2016   GVars.stwCycle ++ ;
     2017 }
     2018 
     2019 // A macro is used below because there may already be a pending
     2020 // exception which should not abort the execution of the routines
     2021 // which use this (which is why we don't put this into check_slow and
     2022 // call it with a CHECK argument).
     2023 
     2024 #define CHECK_OWNER()                                                             \
     2025   do {                                                                            \
     2026     if (THREAD != _owner) {                                                       \
     2027       if (THREAD->is_lock_owned((address) _owner)) {                              \
     2028         _owner = THREAD ;  /* Convert from basiclock addr to Thread addr */       \
     2029         _recursions = 0;                                                          \
     2030         OwnerIsThread = 1 ;                                                       \
     2031       } else {                                                                    \
     2032         TEVENT (Throw IMSX) ;                                                     \
     2033         THROW(vmSymbols::java_lang_IllegalMonitorStateException());               \
     2034       }                                                                           \
     2035     }                                                                             \
     2036   } while (false)
     2037 
     2038 // TODO-FIXME: eliminate ObjectWaiters.  Replace this visitor/enumerator
     2039 // interface with a simple FirstWaitingThread(), NextWaitingThread() interface.
     2040 
     2041 ObjectWaiter* ObjectMonitor::first_waiter() {
     2042   return _WaitSet;
     2043 }
     2044 
     2045 ObjectWaiter* ObjectMonitor::next_waiter(ObjectWaiter* o) {
     2046   return o->_next;
     2047 }
     2048 
     2049 Thread* ObjectMonitor::thread_of_waiter(ObjectWaiter* o) {
     2050   return o->_thread;
     2051 }
     2052 
     2053 // initialize the monitor, exception the semaphore, all other fields
     2054 // are simple integers or pointers
     2055 ObjectMonitor::ObjectMonitor() {
     2056   _header       = NULL;
     2057   _count        = 0;
     2058   _waiters      = 0,
     2059   _recursions   = 0;
     2060   _object       = NULL;
     2061   _owner        = NULL;
     2062   _WaitSet      = NULL;
     2063   _WaitSetLock  = 0 ;
     2064   _Responsible  = NULL ;
     2065   _succ         = NULL ;
     2066   _cxq          = NULL ;
     2067   FreeNext      = NULL ;
     2068   _EntryList    = NULL ;
     2069   _SpinFreq     = 0 ;
     2070   _SpinClock    = 0 ;
     2071   OwnerIsThread = 0 ;
     2072 }
     2073 
     2074 ObjectMonitor::~ObjectMonitor() {
     2075    // TODO: Add asserts ...
     2076    // _cxq == 0 _succ == NULL _owner == NULL _waiters == 0
     2077    // _count == 0 _EntryList  == NULL etc
     2078 }
     2079 
     2080 intptr_t ObjectMonitor::is_busy() const {
     2081   // TODO-FIXME: merge _count and _waiters.
     2082   // TODO-FIXME: assert _owner == null implies _recursions = 0
     2083   // TODO-FIXME: assert _WaitSet != null implies _count > 0
     2084   return _count|_waiters|intptr_t(_owner)|intptr_t(_cxq)|intptr_t(_EntryList ) ;
     2085 }
     2086 
     2087 void ObjectMonitor::Recycle () {
     2088   // TODO: add stronger asserts ...
     2089   // _cxq == 0 _succ == NULL _owner == NULL _waiters == 0
     2090   // _count == 0 EntryList  == NULL
     2091   // _recursions == 0 _WaitSet == NULL
     2092   // TODO: assert (is_busy()|_recursions) == 0
     2093   _succ          = NULL ;
     2094   _EntryList     = NULL ;
     2095   _cxq           = NULL ;
     2096   _WaitSet       = NULL ;
     2097   _recursions    = 0 ;
     2098   _SpinFreq      = 0 ;
     2099   _SpinClock     = 0 ;
     2100   OwnerIsThread  = 0 ;
     2101 }
     2102 
     2103 // WaitSet management ...
     2104 
     2105 inline void ObjectMonitor::AddWaiter(ObjectWaiter* node) {
     2106   assert(node != NULL, "should not dequeue NULL node");
     2107   assert(node->_prev == NULL, "node already in list");
     2108   assert(node->_next == NULL, "node already in list");
     2109   // put node at end of queue (circular doubly linked list)
     2110   if (_WaitSet == NULL) {
     2111     _WaitSet = node;
     2112     node->_prev = node;
     2113     node->_next = node;
     2114   } else {
     2115     ObjectWaiter* head = _WaitSet ;
     2116     ObjectWaiter* tail = head->_prev;
     2117     assert(tail->_next == head, "invariant check");
     2118     tail->_next = node;
     2119     head->_prev = node;
     2120     node->_next = head;
     2121     node->_prev = tail;
     2122   }
     2123 }
     2124 
     2125 inline ObjectWaiter* ObjectMonitor::DequeueWaiter() {
     2126   // dequeue the very first waiter
     2127   ObjectWaiter* waiter = _WaitSet;
     2128   if (waiter) {
     2129     DequeueSpecificWaiter(waiter);
     2130   }
     2131   return waiter;
     2132 }
     2133 
     2134 inline void ObjectMonitor::DequeueSpecificWaiter(ObjectWaiter* node) {
     2135   assert(node != NULL, "should not dequeue NULL node");
     2136   assert(node->_prev != NULL, "node already removed from list");
     2137   assert(node->_next != NULL, "node already removed from list");
     2138   // when the waiter has woken up because of interrupt,
     2139   // timeout or other spurious wake-up, dequeue the
     2140   // waiter from waiting list
     2141   ObjectWaiter* next = node->_next;
     2142   if (next == node) {
     2143     assert(node->_prev == node, "invariant check");
     2144     _WaitSet = NULL;
     2145   } else {
     2146     ObjectWaiter* prev = node->_prev;
     2147     assert(prev->_next == node, "invariant check");
     2148     assert(next->_prev == node, "invariant check");
     2149     next->_prev = prev;
     2150     prev->_next = next;
     2151     if (_WaitSet == node) {
     2152       _WaitSet = next;
     2153     }
     2154   }
     2155   node->_next = NULL;
     2156   node->_prev = NULL;
     2157 }
     2158 
     2159 static char * kvGet (char * kvList, const char * Key) {
     2160     if (kvList == NULL) return NULL ;
     2161     size_t n = strlen (Key) ;
     2162     char * Search ;
     2163     for (Search = kvList ; *Search ; Search += strlen(Search) + 1) {
     2164         if (strncmp (Search, Key, n) == 0) {
     2165             if (Search[n] == '=') return Search + n + 1 ;
     2166             if (Search[n] == 0)   return (char *) "1" ;
     2167         }
     2168     }
     2169     return NULL ;
     2170 }
     2171 
     2172 static int kvGetInt (char * kvList, const char * Key, int Default) {
     2173     char * v = kvGet (kvList, Key) ;
     2174     int rslt = v ? ::strtol (v, NULL, 0) : Default ;
     2175     if (Knob_ReportSettings && v != NULL) {
     2176         ::printf ("  SyncKnob: %s %d(%d)\n", Key, rslt, Default) ;
     2177         ::fflush (stdout) ;
     2178     }
     2179     return rslt ;
     2180 }
     2181 
     2182 // By convention we unlink a contending thread from EntryList|cxq immediately
     2183 // after the thread acquires the lock in ::enter().  Equally, we could defer
     2184 // unlinking the thread until ::exit()-time.
     2185 
     2186 void ObjectMonitor::UnlinkAfterAcquire (Thread * Self, ObjectWaiter * SelfNode)
     2187 {
     2188     assert (_owner == Self, "invariant") ;
     2189     assert (SelfNode->_thread == Self, "invariant") ;
     2190 
     2191     if (SelfNode->TState == ObjectWaiter::TS_ENTER) {
     2192         // Normal case: remove Self from the DLL EntryList .
     2193         // This is a constant-time operation.
     2194         ObjectWaiter * nxt = SelfNode->_next ;
     2195         ObjectWaiter * prv = SelfNode->_prev ;
     2196         if (nxt != NULL) nxt->_prev = prv ;
     2197         if (prv != NULL) prv->_next = nxt ;
     2198         if (SelfNode == _EntryList ) _EntryList = nxt ;
     2199         assert (nxt == NULL || nxt->TState == ObjectWaiter::TS_ENTER, "invariant") ;
     2200         assert (prv == NULL || prv->TState == ObjectWaiter::TS_ENTER, "invariant") ;
     2201         TEVENT (Unlink from EntryList) ;
     2202     } else {
     2203         guarantee (SelfNode->TState == ObjectWaiter::TS_CXQ, "invariant") ;
     2204         // Inopportune interleaving -- Self is still on the cxq.
     2205         // This usually means the enqueue of self raced an exiting thread.
     2206         // Normally we'll find Self near the front of the cxq, so
     2207         // dequeueing is typically fast.  If needbe we can accelerate
     2208         // this with some MCS/CHL-like bidirectional list hints and advisory
     2209         // back-links so dequeueing from the interior will normally operate
     2210         // in constant-time.
     2211         // Dequeue Self from either the head (with CAS) or from the interior
     2212         // with a linear-time scan and normal non-atomic memory operations.
     2213         // CONSIDER: if Self is on the cxq then simply drain cxq into EntryList
     2214         // and then unlink Self from EntryList.  We have to drain eventually,
     2215         // so it might as well be now.
     2216 
     2217         ObjectWaiter * v = _cxq ;
     2218         assert (v != NULL, "invariant") ;
     2219         if (v != SelfNode || Atomic::cmpxchg_ptr (SelfNode->_next, &_cxq, v) != v) {
     2220             // The CAS above can fail from interference IFF a "RAT" arrived.
     2221             // In that case Self must be in the interior and can no longer be
     2222             // at the head of cxq.
     2223             if (v == SelfNode) {
     2224                 assert (_cxq != v, "invariant") ;
     2225                 v = _cxq ;          // CAS above failed - start scan at head of list
     2226             }
     2227             ObjectWaiter * p ;
     2228             ObjectWaiter * q = NULL ;
     2229             for (p = v ; p != NULL && p != SelfNode; p = p->_next) {
     2230                 q = p ;
     2231                 assert (p->TState == ObjectWaiter::TS_CXQ, "invariant") ;
     2232             }
     2233             assert (v != SelfNode,  "invariant") ;
     2234             assert (p == SelfNode,  "Node not found on cxq") ;
     2235             assert (p != _cxq,      "invariant") ;
     2236             assert (q != NULL,      "invariant") ;
     2237             assert (q->_next == p,  "invariant") ;
     2238             q->_next = p->_next ;
     2239         }
     2240         TEVENT (Unlink from cxq) ;
     2241     }
     2242 
     2243     // Diagnostic hygiene ...
     2244     SelfNode->_prev  = (ObjectWaiter *) 0xBAD ;
     2245     SelfNode->_next  = (ObjectWaiter *) 0xBAD ;
     2246     SelfNode->TState = ObjectWaiter::TS_RUN ;
     2247 }
     2248 
     2249 // Caveat: TryLock() is not necessarily serializing if it returns failure.
     2250 // Callers must compensate as needed.
     2251 
     2252 int ObjectMonitor::TryLock (Thread * Self) {
     2253    for (;;) {
     2254       void * own = _owner ;
     2255       if (own != NULL) return 0 ;
     2256       if (Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) {
     2257          // Either guarantee _recursions == 0 or set _recursions = 0.
     2258          assert (_recursions == 0, "invariant") ;
     2259          assert (_owner == Self, "invariant") ;
     2260          // CONSIDER: set or assert that OwnerIsThread == 1
     2261          return 1 ;
     2262       }
     2263       // The lock had been free momentarily, but we lost the race to the lock.
     2264       // Interference -- the CAS failed.
     2265       // We can either return -1 or retry.
     2266       // Retry doesn't make as much sense because the lock was just acquired.
     2267       if (true) return -1 ;
     2268    }
     2269 }
     2270 
     2271 // NotRunnable() -- informed spinning
     2272 //
     2273 // Don't bother spinning if the owner is not eligible to drop the lock.
     2274 // Peek at the owner's schedctl.sc_state and Thread._thread_values and
     2275 // spin only if the owner thread is _thread_in_Java or _thread_in_vm.
     2276 // The thread must be runnable in order to drop the lock in timely fashion.
     2277 // If the _owner is not runnable then spinning will not likely be
     2278 // successful (profitable).
     2279 //
     2280 // Beware -- the thread referenced by _owner could have died
     2281 // so a simply fetch from _owner->_thread_state might trap.
     2282 // Instead, we use SafeFetchXX() to safely LD _owner->_thread_state.
     2283 // Because of the lifecycle issues the schedctl and _thread_state values
     2284 // observed by NotRunnable() might be garbage.  NotRunnable must
     2285 // tolerate this and consider the observed _thread_state value
     2286 // as advisory.
     2287 //
     2288 // Beware too, that _owner is sometimes a BasicLock address and sometimes
     2289 // a thread pointer.  We differentiate the two cases with OwnerIsThread.
     2290 // Alternately, we might tag the type (thread pointer vs basiclock pointer)
     2291 // with the LSB of _owner.  Another option would be to probablistically probe
     2292 // the putative _owner->TypeTag value.
     2293 //
     2294 // Checking _thread_state isn't perfect.  Even if the thread is
     2295 // in_java it might be blocked on a page-fault or have been preempted
     2296 // and sitting on a ready/dispatch queue.  _thread state in conjunction
     2297 // with schedctl.sc_state gives us a good picture of what the
     2298 // thread is doing, however.
     2299 //
     2300 // TODO: check schedctl.sc_state.
     2301 // We'll need to use SafeFetch32() to read from the schedctl block.
     2302 // See RFE #5004247 and http://sac.sfbay.sun.com/Archives/CaseLog/arc/PSARC/2005/351/
     2303 //
     2304 // The return value from NotRunnable() is *advisory* -- the
     2305 // result is based on sampling and is not necessarily coherent.
     2306 // The caller must tolerate false-negative and false-positive errors.
     2307 // Spinning, in general, is probabilistic anyway.
     2308 
     2309 
     2310 int ObjectMonitor::NotRunnable (Thread * Self, Thread * ox) {
     2311     // Check either OwnerIsThread or ox->TypeTag == 2BAD.
     2312     if (!OwnerIsThread) return 0 ;
     2313 
     2314     if (ox == NULL) return 0 ;
     2315 
     2316     // Avoid transitive spinning ...
     2317     // Say T1 spins or blocks trying to acquire L.  T1._Stalled is set to L.
     2318     // Immediately after T1 acquires L it's possible that T2, also
     2319     // spinning on L, will see L.Owner=T1 and T1._Stalled=L.
     2320     // This occurs transiently after T1 acquired L but before
     2321     // T1 managed to clear T1.Stalled.  T2 does not need to abort
     2322     // its spin in this circumstance.
     2323     intptr_t BlockedOn = SafeFetchN ((intptr_t *) &ox->_Stalled, intptr_t(1)) ;
     2324 
     2325     if (BlockedOn == 1) return 1 ;
     2326     if (BlockedOn != 0) {
     2327       return BlockedOn != intptr_t(this) && _owner == ox ;
     2328     }
     2329 
     2330     assert (sizeof(((JavaThread *)ox)->_thread_state == sizeof(int)), "invariant") ;
     2331     int jst = SafeFetch32 ((int *) &((JavaThread *) ox)->_thread_state, -1) ; ;
     2332     // consider also: jst != _thread_in_Java -- but that's overspecific.
     2333     return jst == _thread_blocked || jst == _thread_in_native ;
     2334 }
     2335 
     2336 
     2337 // Adaptive spin-then-block - rational spinning
     2338 //
     2339 // Note that we spin "globally" on _owner with a classic SMP-polite TATAS
     2340 // algorithm.  On high order SMP systems it would be better to start with
     2341 // a brief global spin and then revert to spinning locally.  In the spirit of MCS/CLH,
     2342 // a contending thread could enqueue itself on the cxq and then spin locally
     2343 // on a thread-specific variable such as its ParkEvent._Event flag.
     2344 // That's left as an exercise for the reader.  Note that global spinning is
     2345 // not problematic on Niagara, as the L2$ serves the interconnect and has both
     2346 // low latency and massive bandwidth.
     2347 //
     2348 // Broadly, we can fix the spin frequency -- that is, the % of contended lock
     2349 // acquisition attempts where we opt to spin --  at 100% and vary the spin count
     2350 // (duration) or we can fix the count at approximately the duration of
     2351 // a context switch and vary the frequency.   Of course we could also
     2352 // vary both satisfying K == Frequency * Duration, where K is adaptive by monitor.
     2353 // See http://j2se.east/~dice/PERSIST/040824-AdaptiveSpinning.html.
     2354 //
     2355 // This implementation varies the duration "D", where D varies with
     2356 // the success rate of recent spin attempts. (D is capped at approximately
     2357 // length of a round-trip context switch).  The success rate for recent
     2358 // spin attempts is a good predictor of the success rate of future spin
     2359 // attempts.  The mechanism adapts automatically to varying critical
     2360 // section length (lock modality), system load and degree of parallelism.
     2361 // D is maintained per-monitor in _SpinDuration and is initialized
     2362 // optimistically.  Spin frequency is fixed at 100%.
     2363 //
     2364 // Note that _SpinDuration is volatile, but we update it without locks
     2365 // or atomics.  The code is designed so that _SpinDuration stays within
     2366 // a reasonable range even in the presence of races.  The arithmetic
     2367 // operations on _SpinDuration are closed over the domain of legal values,
     2368 // so at worst a race will install and older but still legal value.
     2369 // At the very worst this introduces some apparent non-determinism.
     2370 // We might spin when we shouldn't or vice-versa, but since the spin
     2371 // count are relatively short, even in the worst case, the effect is harmless.
     2372 //
     2373 // Care must be taken that a low "D" value does not become an
     2374 // an absorbing state.  Transient spinning failures -- when spinning
     2375 // is overall profitable -- should not cause the system to converge
     2376 // on low "D" values.  We want spinning to be stable and predictable
     2377 // and fairly responsive to change and at the same time we don't want
     2378 // it to oscillate, become metastable, be "too" non-deterministic,
     2379 // or converge on or enter undesirable stable absorbing states.
     2380 //
     2381 // We implement a feedback-based control system -- using past behavior
     2382 // to predict future behavior.  We face two issues: (a) if the
     2383 // input signal is random then the spin predictor won't provide optimal
     2384 // results, and (b) if the signal frequency is too high then the control
     2385 // system, which has some natural response lag, will "chase" the signal.
     2386 // (b) can arise from multimodal lock hold times.  Transient preemption
     2387 // can also result in apparent bimodal lock hold times.
     2388 // Although sub-optimal, neither condition is particularly harmful, as
     2389 // in the worst-case we'll spin when we shouldn't or vice-versa.
     2390 // The maximum spin duration is rather short so the failure modes aren't bad.
     2391 // To be conservative, I've tuned the gain in system to bias toward
     2392 // _not spinning.  Relatedly, the system can sometimes enter a mode where it
     2393 // "rings" or oscillates between spinning and not spinning.  This happens
     2394 // when spinning is just on the cusp of profitability, however, so the
     2395 // situation is not dire.  The state is benign -- there's no need to add
     2396 // hysteresis control to damp the transition rate between spinning and
     2397 // not spinning.
     2398 //
     2399 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     2400 //
     2401 // Spin-then-block strategies ...
     2402 //
     2403 // Thoughts on ways to improve spinning :
     2404 //
     2405 // *  Periodically call {psr_}getloadavg() while spinning, and
     2406 //    permit unbounded spinning if the load average is <
     2407 //    the number of processors.  Beware, however, that getloadavg()
     2408 //    is exceptionally fast on solaris (about 1/10 the cost of a full
     2409 //    spin cycle, but quite expensive on linux.  Beware also, that
     2410 //    multiple JVMs could "ring" or oscillate in a feedback loop.
     2411 //    Sufficient damping would solve that problem.
     2412 //
     2413 // *  We currently use spin loops with iteration counters to approximate
     2414 //    spinning for some interval.  Given the availability of high-precision
     2415 //    time sources such as gethrtime(), %TICK, %STICK, RDTSC, etc., we should
     2416 //    someday reimplement the spin loops to duration-based instead of iteration-based.
     2417 //
     2418 // *  Don't spin if there are more than N = (CPUs/2) threads
     2419 //        currently spinning on the monitor (or globally).
     2420 //    That is, limit the number of concurrent spinners.
     2421 //    We might also limit the # of spinners in the JVM, globally.
     2422 //
     2423 // *  If a spinning thread observes _owner change hands it should
     2424 //    abort the spin (and park immediately) or at least debit
     2425 //    the spin counter by a large "penalty".
     2426 //
     2427 // *  Classically, the spin count is either K*(CPUs-1) or is a
     2428 //        simple constant that approximates the length of a context switch.
     2429 //    We currently use a value -- computed by a special utility -- that
     2430 //    approximates round-trip context switch times.
     2431 //
     2432 // *  Normally schedctl_start()/_stop() is used to advise the kernel
     2433 //    to avoid preempting threads that are running in short, bounded
     2434 //    critical sections.  We could use the schedctl hooks in an inverted
     2435 //    sense -- spinners would set the nopreempt flag, but poll the preempt
     2436 //    pending flag.  If a spinner observed a pending preemption it'd immediately
     2437 //    abort the spin and park.   As such, the schedctl service acts as
     2438 //    a preemption warning mechanism.
     2439 //
     2440 // *  In lieu of spinning, if the system is running below saturation
     2441 //    (that is, loadavg() << #cpus), we can instead suppress futile
     2442 //    wakeup throttling, or even wake more than one successor at exit-time.
     2443 //    The net effect is largely equivalent to spinning.  In both cases,
     2444 //    contending threads go ONPROC and opportunistically attempt to acquire
     2445 //    the lock, decreasing lock handover latency at the expense of wasted
     2446 //    cycles and context switching.
     2447 //
     2448 // *  We might to spin less after we've parked as the thread will
     2449 //    have less $ and TLB affinity with the processor.
     2450 //    Likewise, we might spin less if we come ONPROC on a different
     2451 //    processor or after a long period (>> rechose_interval).
     2452 //
     2453 // *  A table-driven state machine similar to Solaris' dispadmin scheduling
     2454 //    tables might be a better design.  Instead of encoding information in
     2455 //    _SpinDuration, _SpinFreq and _SpinClock we'd just use explicit,
     2456 //    discrete states.   Success or failure during a spin would drive
     2457 //    state transitions, and each state node would contain a spin count.
     2458 //
     2459 // *  If the processor is operating in a mode intended to conserve power
     2460 //    (such as Intel's SpeedStep) or to reduce thermal output (thermal
     2461 //    step-down mode) then the Java synchronization subsystem should
     2462 //    forgo spinning.
     2463 //
     2464 // *  The minimum spin duration should be approximately the worst-case
     2465 //    store propagation latency on the platform.  That is, the time
     2466 //    it takes a store on CPU A to become visible on CPU B, where A and
     2467 //    B are "distant".
     2468 //
     2469 // *  We might want to factor a thread's priority in the spin policy.
     2470 //    Threads with a higher priority might spin for slightly longer.
     2471 //    Similarly, if we use back-off in the TATAS loop, lower priority
     2472 //    threads might back-off longer.  We don't currently use a
     2473 //    thread's priority when placing it on the entry queue.  We may
     2474 //    want to consider doing so in future releases.
     2475 //
     2476 // *  We might transiently drop a thread's scheduling priority while it spins.
     2477 //    SCHED_BATCH on linux and FX scheduling class at priority=0 on Solaris
     2478 //    would suffice.  We could even consider letting the thread spin indefinitely at
     2479 //    a depressed or "idle" priority.  This brings up fairness issues, however --
     2480 //    in a saturated system a thread would with a reduced priority could languish
     2481 //    for extended periods on the ready queue.
     2482 //
     2483 // *  While spinning try to use the otherwise wasted time to help the VM make
     2484 //    progress:
     2485 //
     2486 //    -- YieldTo() the owner, if the owner is OFFPROC but ready
     2487 //       Done our remaining quantum directly to the ready thread.
     2488 //       This helps "push" the lock owner through the critical section.
     2489 //       It also tends to improve affinity/locality as the lock
     2490 //       "migrates" less frequently between CPUs.
     2491 //    -- Walk our own stack in anticipation of blocking.  Memoize the roots.
     2492 //    -- Perform strand checking for other thread.  Unpark potential strandees.
     2493 //    -- Help GC: trace or mark -- this would need to be a bounded unit of work.
     2494 //       Unfortunately this will pollute our $ and TLBs.  Recall that we
     2495 //       spin to avoid context switching -- context switching has an
     2496 //       immediate cost in latency, a disruptive cost to other strands on a CMT
     2497 //       processor, and an amortized cost because of the D$ and TLB cache
     2498 //       reload transient when the thread comes back ONPROC and repopulates
     2499 //       $s and TLBs.
     2500 //    -- call getloadavg() to see if the system is saturated.  It'd probably
     2501 //       make sense to call getloadavg() half way through the spin.
     2502 //       If the system isn't at full capacity the we'd simply reset
     2503 //       the spin counter to and extend the spin attempt.
     2504 //    -- Doug points out that we should use the same "helping" policy
     2505 //       in thread.yield().
     2506 //
     2507 // *  Try MONITOR-MWAIT on systems that support those instructions.
     2508 //
     2509 // *  The spin statistics that drive spin decisions & frequency are
     2510 //    maintained in the objectmonitor structure so if we deflate and reinflate
     2511 //    we lose spin state.  In practice this is not usually a concern
     2512 //    as the default spin state after inflation is aggressive (optimistic)
     2513 //    and tends toward spinning.  So in the worst case for a lock where
     2514 //    spinning is not profitable we may spin unnecessarily for a brief
     2515 //    period.  But then again, if a lock is contended it'll tend not to deflate
     2516 //    in the first place.
     2517 
     2518 
     2519 intptr_t ObjectMonitor::SpinCallbackArgument = 0 ;
     2520 int (*ObjectMonitor::SpinCallbackFunction)(intptr_t, int) = NULL ;
     2521 
     2522 // Spinning: Fixed frequency (100%), vary duration
     2523 
     2524 int ObjectMonitor::TrySpin_VaryDuration (Thread * Self) {
     2525 
     2526     // Dumb, brutal spin.  Good for comparative measurements against adaptive spinning.
     2527     int ctr = Knob_FixedSpin ;
     2528     if (ctr != 0) {
     2529         while (--ctr >= 0) {
     2530             if (TryLock (Self) > 0) return 1 ;
     2531             SpinPause () ;
     2532         }
     2533         return 0 ;
     2534     }
     2535 
     2536     for (ctr = Knob_PreSpin + 1; --ctr >= 0 ; ) {
     2537       if (TryLock(Self) > 0) {
     2538         // Increase _SpinDuration ...
     2539         // Note that we don't clamp SpinDuration precisely at SpinLimit.
     2540         // Raising _SpurDuration to the poverty line is key.
     2541         int x = _SpinDuration ;
     2542         if (x < Knob_SpinLimit) {
     2543            if (x < Knob_Poverty) x = Knob_Poverty ;
     2544            _SpinDuration = x + Knob_BonusB ;
     2545         }
     2546         return 1 ;
     2547       }
     2548       SpinPause () ;
     2549     }
     2550 
     2551     // Admission control - verify preconditions for spinning
     2552     //
     2553     // We always spin a little bit, just to prevent _SpinDuration == 0 from
     2554     // becoming an absorbing state.  Put another way, we spin briefly to
     2555     // sample, just in case the system load, parallelism, contention, or lock
     2556     // modality changed.
     2557     //
     2558     // Consider the following alternative:
     2559     // Periodically set _SpinDuration = _SpinLimit and try a long/full
     2560     // spin attempt.  "Periodically" might mean after a tally of
     2561     // the # of failed spin attempts (or iterations) reaches some threshold.
     2562     // This takes us into the realm of 1-out-of-N spinning, where we
     2563     // hold the duration constant but vary the frequency.
     2564 
     2565     ctr = _SpinDuration  ;
     2566     if (ctr < Knob_SpinBase) ctr = Knob_SpinBase ;
     2567     if (ctr <= 0) return 0 ;
     2568 
     2569     if (Knob_SuccRestrict && _succ != NULL) return 0 ;
     2570     if (Knob_OState && NotRunnable (Self, (Thread *) _owner)) {
     2571        TEVENT (Spin abort - notrunnable [TOP]);
     2572        return 0 ;
     2573     }
     2574 
     2575     int MaxSpin = Knob_MaxSpinners ;
     2576     if (MaxSpin >= 0) {
     2577        if (_Spinner > MaxSpin) {
     2578           TEVENT (Spin abort -- too many spinners) ;
     2579           return 0 ;
     2580        }
     2581        // Slighty racy, but benign ...
     2582        Adjust (&_Spinner, 1) ;
     2583     }
     2584 
     2585     // We're good to spin ... spin ingress.
     2586     // CONSIDER: use Prefetch::write() to avoid RTS->RTO upgrades
     2587     // when preparing to LD...CAS _owner, etc and the CAS is likely
     2588     // to succeed.
     2589     int hits    = 0 ;
     2590     int msk     = 0 ;
     2591     int caspty  = Knob_CASPenalty ;
     2592     int oxpty   = Knob_OXPenalty ;
     2593     int sss     = Knob_SpinSetSucc ;
     2594     if (sss && _succ == NULL ) _succ = Self ;
     2595     Thread * prv = NULL ;
     2596 
     2597     // There are three ways to exit the following loop:
     2598     // 1.  A successful spin where this thread has acquired the lock.
     2599     // 2.  Spin failure with prejudice
     2600     // 3.  Spin failure without prejudice
     2601 
     2602     while (--ctr >= 0) {
     2603 
     2604       // Periodic polling -- Check for pending GC
     2605       // Threads may spin while they're unsafe.
     2606       // We don't want spinning threads to delay the JVM from reaching
     2607       // a stop-the-world safepoint or to steal cycles from GC.
     2608       // If we detect a pending safepoint we abort in order that
     2609       // (a) this thread, if unsafe, doesn't delay the safepoint, and (b)
     2610       // this thread, if safe, doesn't steal cycles from GC.
     2611       // This is in keeping with the "no loitering in runtime" rule.
     2612       // We periodically check to see if there's a safepoint pending.
     2613       if ((ctr & 0xFF) == 0) {
     2614          if (SafepointSynchronize::do_call_back()) {
     2615             TEVENT (Spin: safepoint) ;
     2616             goto Abort ;           // abrupt spin egress
     2617          }
     2618          if (Knob_UsePause & 1) SpinPause () ;
     2619 
     2620          int (*scb)(intptr_t,int) = SpinCallbackFunction ;
     2621          if (hits > 50 && scb != NULL) {
     2622             int abend = (*scb)(SpinCallbackArgument, 0) ;
     2623          }
     2624       }
     2625 
     2626       if (Knob_UsePause & 2) SpinPause() ;
     2627 
     2628       // Exponential back-off ...  Stay off the bus to reduce coherency traffic.
     2629       // This is useful on classic SMP systems, but is of less utility on
     2630       // N1-style CMT platforms.
     2631       //
     2632       // Trade-off: lock acquisition latency vs coherency bandwidth.
     2633       // Lock hold times are typically short.  A histogram
     2634       // of successful spin attempts shows that we usually acquire
     2635       // the lock early in the spin.  That suggests we want to
     2636       // sample _owner frequently in the early phase of the spin,
     2637       // but then back-off and sample less frequently as the spin
     2638       // progresses.  The back-off makes a good citizen on SMP big
     2639       // SMP systems.  Oversampling _owner can consume excessive
     2640       // coherency bandwidth.  Relatedly, if we _oversample _owner we
     2641       // can inadvertently interfere with the the ST m->owner=null.
     2642       // executed by the lock owner.
     2643       if (ctr & msk) continue ;
     2644       ++hits ;
     2645       if ((hits & 0xF) == 0) {
     2646         // The 0xF, above, corresponds to the exponent.
     2647         // Consider: (msk+1)|msk
     2648         msk = ((msk << 2)|3) & BackOffMask ;
     2649       }
     2650 
     2651       // Probe _owner with TATAS
     2652       // If this thread observes the monitor transition or flicker
     2653       // from locked to unlocked to locked, then the odds that this
     2654       // thread will acquire the lock in this spin attempt go down
     2655       // considerably.  The same argument applies if the CAS fails
     2656       // or if we observe _owner change from one non-null value to
     2657       // another non-null value.   In such cases we might abort
     2658       // the spin without prejudice or apply a "penalty" to the
     2659       // spin count-down variable "ctr", reducing it by 100, say.
     2660 
     2661       Thread * ox = (Thread *) _owner ;
     2662       if (ox == NULL) {
     2663          ox = (Thread *) Atomic::cmpxchg_ptr (Self, &_owner, NULL) ;
     2664          if (ox == NULL) {
     2665             // The CAS succeeded -- this thread acquired ownership
     2666             // Take care of some bookkeeping to exit spin state.
     2667             if (sss && _succ == Self) {
     2668                _succ = NULL ;
     2669             }
     2670             if (MaxSpin > 0) Adjust (&_Spinner, -1) ;
     2671 
     2672             // Increase _SpinDuration :
     2673             // The spin was successful (profitable) so we tend toward
     2674             // longer spin attempts in the future.
     2675             // CONSIDER: factor "ctr" into the _SpinDuration adjustment.
     2676             // If we acquired the lock early in the spin cycle it
     2677             // makes sense to increase _SpinDuration proportionally.
     2678             // Note that we don't clamp SpinDuration precisely at SpinLimit.
     2679             int x = _SpinDuration ;
     2680             if (x < Knob_SpinLimit) {
     2681                 if (x < Knob_Poverty) x = Knob_Poverty ;
     2682                 _SpinDuration = x + Knob_Bonus ;
     2683             }
     2684             return 1 ;
     2685          }
     2686 
     2687          // The CAS failed ... we can take any of the following actions:
     2688          // * penalize: ctr -= Knob_CASPenalty
     2689          // * exit spin with prejudice -- goto Abort;
     2690          // * exit spin without prejudice.
     2691          // * Since CAS is high-latency, retry again immediately.
     2692          prv = ox ;
     2693          TEVENT (Spin: cas failed) ;
     2694          if (caspty == -2) break ;
     2695          if (caspty == -1) goto Abort ;
     2696          ctr -= caspty ;
     2697          continue ;
     2698       }
     2699 
     2700       // Did lock ownership change hands ?
     2701       if (ox != prv && prv != NULL ) {
     2702           TEVENT (spin: Owner changed)
     2703           if (oxpty == -2) break ;
     2704           if (oxpty == -1) goto Abort ;
     2705           ctr -= oxpty ;
     2706       }
     2707       prv = ox ;
     2708 
     2709       // Abort the spin if the owner is not executing.
     2710       // The owner must be executing in order to drop the lock.
     2711       // Spinning while the owner is OFFPROC is idiocy.
     2712       // Consider: ctr -= RunnablePenalty ;
     2713       if (Knob_OState && NotRunnable (Self, ox)) {
     2714          TEVENT (Spin abort - notrunnable);
     2715          goto Abort ;
     2716       }
     2717       if (sss && _succ == NULL ) _succ = Self ;
     2718    }
     2719 
     2720    // Spin failed with prejudice -- reduce _SpinDuration.
     2721    // TODO: Use an AIMD-like policy to adjust _SpinDuration.
     2722    // AIMD is globally stable.
     2723    TEVENT (Spin failure) ;
     2724    {
     2725      int x = _SpinDuration ;
     2726      if (x > 0) {
     2727         // Consider an AIMD scheme like: x -= (x >> 3) + 100
     2728         // This is globally sample and tends to damp the response.
     2729         x -= Knob_Penalty ;
     2730         if (x < 0) x = 0 ;
     2731         _SpinDuration = x ;
     2732      }
     2733    }
     2734 
     2735  Abort:
     2736    if (MaxSpin >= 0) Adjust (&_Spinner, -1) ;
     2737    if (sss && _succ == Self) {
     2738       _succ = NULL ;
     2739       // Invariant: after setting succ=null a contending thread
     2740       // must recheck-retry _owner before parking.  This usually happens
     2741       // in the normal usage of TrySpin(), but it's safest
     2742       // to make TrySpin() as foolproof as possible.
     2743       OrderAccess::fence() ;
     2744       if (TryLock(Self) > 0) return 1 ;
     2745    }
     2746    return 0 ;
     2747 }
     2748 
     2749 #define TrySpin TrySpin_VaryDuration
     2750 
     2751 static void DeferredInitialize () {
     2752   if (InitDone > 0) return ;
     2753   if (Atomic::cmpxchg (-1, &InitDone, 0) != 0) {
     2754       while (InitDone != 1) ;
     2755       return ;
     2756   }
     2757 
     2758   // One-shot global initialization ...
     2759   // The initialization is idempotent, so we don't need locks.
     2760   // In the future consider doing this via os::init_2().
     2761   // SyncKnobs consist of <Key>=<Value> pairs in the style
     2762   // of environment variables.  Start by converting ':' to NUL.
     2763 
     2764   if (SyncKnobs == NULL) SyncKnobs = "" ;
     2765 
     2766   size_t sz = strlen (SyncKnobs) ;
     2767   char * knobs = (char *) malloc (sz + 2) ;
     2768   if (knobs == NULL) {
     2769      vm_exit_out_of_memory (sz + 2, "Parse SyncKnobs") ;
     2770      guarantee (0, "invariant") ;
     2771   }
     2772   strcpy (knobs, SyncKnobs) ;
     2773   knobs[sz+1] = 0 ;
     2774   for (char * p = knobs ; *p ; p++) {
     2775      if (*p == ':') *p = 0 ;
     2776   }
     2777 
     2778   #define SETKNOB(x) { Knob_##x = kvGetInt (knobs, #x, Knob_##x); }
     2779   SETKNOB(ReportSettings) ;
     2780   SETKNOB(Verbose) ;
     2781   SETKNOB(FixedSpin) ;
     2782   SETKNOB(SpinLimit) ;
     2783   SETKNOB(SpinBase) ;
     2784   SETKNOB(SpinBackOff);
     2785   SETKNOB(CASPenalty) ;
     2786   SETKNOB(OXPenalty) ;
     2787   SETKNOB(LogSpins) ;
     2788   SETKNOB(SpinSetSucc) ;
     2789   SETKNOB(SuccEnabled) ;
     2790   SETKNOB(SuccRestrict) ;
     2791   SETKNOB(Penalty) ;
     2792   SETKNOB(Bonus) ;
     2793   SETKNOB(BonusB) ;
     2794   SETKNOB(Poverty) ;
     2795   SETKNOB(SpinAfterFutile) ;
     2796   SETKNOB(UsePause) ;
     2797   SETKNOB(SpinEarly) ;
     2798   SETKNOB(OState) ;
     2799   SETKNOB(MaxSpinners) ;
     2800   SETKNOB(PreSpin) ;
     2801   SETKNOB(ExitPolicy) ;
     2802   SETKNOB(QMode);
     2803   SETKNOB(ResetEvent) ;
     2804   SETKNOB(MoveNotifyee) ;
     2805   SETKNOB(FastHSSEC) ;
     2806   #undef SETKNOB
     2807 
     2808   if (os::is_MP()) {
     2809      BackOffMask = (1 << Knob_SpinBackOff) - 1 ;
     2810      if (Knob_ReportSettings) ::printf ("BackOffMask=%X\n", BackOffMask) ;
     2811      // CONSIDER: BackOffMask = ROUNDUP_NEXT_POWER2 (ncpus-1)
     2812   } else {
     2813      Knob_SpinLimit = 0 ;
     2814      Knob_SpinBase  = 0 ;
     2815      Knob_PreSpin   = 0 ;
     2816      Knob_FixedSpin = -1 ;
     2817   }
     2818 
     2819   if (Knob_LogSpins == 0) {
     2820      ObjectSynchronizer::_sync_FailedSpins = NULL ;
     2821   }
     2822 
     2823   free (knobs) ;
     2824   OrderAccess::fence() ;
     2825   InitDone = 1 ;
     2826 }
     2827 
     2828 // Theory of operations -- Monitors lists, thread residency, etc:
     2829 //
     2830 // * A thread acquires ownership of a monitor by successfully
     2831 //   CAS()ing the _owner field from null to non-null.
     2832 //
     2833 // * Invariant: A thread appears on at most one monitor list --
     2834 //   cxq, EntryList or WaitSet -- at any one time.
     2835 //
     2836 // * Contending threads "push" themselves onto the cxq with CAS
     2837 //   and then spin/park.
     2838 //
     2839 // * After a contending thread eventually acquires the lock it must
     2840 //   dequeue itself from either the EntryList or the cxq.
     2841 //
     2842 // * The exiting thread identifies and unparks an "heir presumptive"
     2843 //   tentative successor thread on the EntryList.  Critically, the
     2844 //   exiting thread doesn't unlink the successor thread from the EntryList.
     2845 //   After having been unparked, the wakee will recontend for ownership of
     2846 //   the monitor.   The successor (wakee) will either acquire the lock or
     2847 //   re-park itself.
     2848 //
     2849 //   Succession is provided for by a policy of competitive handoff.
     2850 //   The exiting thread does _not_ grant or pass ownership to the
     2851 //   successor thread.  (This is also referred to as "handoff" succession").
     2852 //   Instead the exiting thread releases ownership and possibly wakes
     2853 //   a successor, so the successor can (re)compete for ownership of the lock.
     2854 //   If the EntryList is empty but the cxq is populated the exiting
     2855 //   thread will drain the cxq into the EntryList.  It does so by
     2856 //   by detaching the cxq (installing null with CAS) and folding
     2857 //   the threads from the cxq into the EntryList.  The EntryList is
     2858 //   doubly linked, while the cxq is singly linked because of the
     2859 //   CAS-based "push" used to enqueue recently arrived threads (RATs).
     2860 //
     2861 // * Concurrency invariants:
     2862 //
     2863 //   -- only the monitor owner may access or mutate the EntryList.
     2864 //      The mutex property of the monitor itself protects the EntryList
     2865 //      from concurrent interference.
     2866 //   -- Only the monitor owner may detach the cxq.
     2867 //
     2868 // * The monitor entry list operations avoid locks, but strictly speaking
     2869 //   they're not lock-free.  Enter is lock-free, exit is not.
     2870 //   See http://j2se.east/~dice/PERSIST/040825-LockFreeQueues.html
     2871 //
     2872 // * The cxq can have multiple concurrent "pushers" but only one concurrent
     2873 //   detaching thread.  This mechanism is immune from the ABA corruption.
     2874 //   More precisely, the CAS-based "push" onto cxq is ABA-oblivious.
     2875 //
     2876 // * Taken together, the cxq and the EntryList constitute or form a
     2877 //   single logical queue of threads stalled trying to acquire the lock.
     2878 //   We use two distinct lists to improve the odds of a constant-time
     2879 //   dequeue operation after acquisition (in the ::enter() epilog) and
     2880 //   to reduce heat on the list ends.  (c.f. Michael Scott's "2Q" algorithm).
     2881 //   A key desideratum is to minimize queue & monitor metadata manipulation
     2882 //   that occurs while holding the monitor lock -- that is, we want to
     2883 //   minimize monitor lock holds times.  Note that even a small amount of
     2884 //   fixed spinning will greatly reduce the # of enqueue-dequeue operations
     2885 //   on EntryList|cxq.  That is, spinning relieves contention on the "inner"
     2886 //   locks and monitor metadata.
     2887 //
     2888 //   Cxq points to the the set of Recently Arrived Threads attempting entry.
     2889 //   Because we push threads onto _cxq with CAS, the RATs must take the form of
     2890 //   a singly-linked LIFO.  We drain _cxq into EntryList  at unlock-time when
     2891 //   the unlocking thread notices that EntryList is null but _cxq is != null.
     2892 //
     2893 //   The EntryList is ordered by the prevailing queue discipline and
     2894 //   can be organized in any convenient fashion, such as a doubly-linked list or
     2895 //   a circular doubly-linked list.  Critically, we want insert and delete operations
     2896 //   to operate in constant-time.  If we need a priority queue then something akin
     2897 //   to Solaris' sleepq would work nicely.  Viz.,
     2898 //   http://agg.eng/ws/on10_nightly/source/usr/src/uts/common/os/sleepq.c.
     2899 //   Queue discipline is enforced at ::exit() time, when the unlocking thread
     2900 //   drains the cxq into the EntryList, and orders or reorders the threads on the
     2901 //   EntryList accordingly.
     2902 //
     2903 //   Barring "lock barging", this mechanism provides fair cyclic ordering,
     2904 //   somewhat similar to an elevator-scan.
     2905 //
     2906 // * The monitor synchronization subsystem avoids the use of native
     2907 //   synchronization primitives except for the narrow platform-specific
     2908 //   park-unpark abstraction.  See the comments in os_solaris.cpp regarding
     2909 //   the semantics of park-unpark.  Put another way, this monitor implementation
     2910 //   depends only on atomic operations and park-unpark.  The monitor subsystem
     2911 //   manages all RUNNING->BLOCKED and BLOCKED->READY transitions while the
     2912 //   underlying OS manages the READY<->RUN transitions.
     2913 //
     2914 // * Waiting threads reside on the WaitSet list -- wait() puts
     2915 //   the caller onto the WaitSet.
     2916 //
     2917 // * notify() or notifyAll() simply transfers threads from the WaitSet to
     2918 //   either the EntryList or cxq.  Subsequent exit() operations will
     2919 //   unpark the notifyee.  Unparking a notifee in notify() is inefficient -
     2920 //   it's likely the notifyee would simply impale itself on the lock held
     2921 //   by the notifier.
     2922 //
     2923 // * An interesting alternative is to encode cxq as (List,LockByte) where
     2924 //   the LockByte is 0 iff the monitor is owned.  _owner is simply an auxiliary
     2925 //   variable, like _recursions, in the scheme.  The threads or Events that form
     2926 //   the list would have to be aligned in 256-byte addresses.  A thread would
     2927 //   try to acquire the lock or enqueue itself with CAS, but exiting threads
     2928 //   could use a 1-0 protocol and simply STB to set the LockByte to 0.
     2929 //   Note that is is *not* word-tearing, but it does presume that full-word
     2930 //   CAS operations are coherent with intermix with STB operations.  That's true
     2931 //   on most common processors.
     2932 //
     2933 // * See also http://blogs.sun.com/dave
     2934 
     2935 
     2936 void ATTR ObjectMonitor::EnterI (TRAPS) {
     2937     Thread * Self = THREAD ;
     2938     assert (Self->is_Java_thread(), "invariant") ;
     2939     assert (((JavaThread *) Self)->thread_state() == _thread_blocked   , "invariant") ;
     2940 
     2941     // Try the lock - TATAS
     2942     if (TryLock (Self) > 0) {
     2943         assert (_succ != Self              , "invariant") ;
     2944         assert (_owner == Self             , "invariant") ;
     2945         assert (_Responsible != Self       , "invariant") ;
     2946         return ;
     2947     }
     2948 
     2949     DeferredInitialize () ;
     2950 
     2951     // We try one round of spinning *before* enqueueing Self.
     2952     //
     2953     // If the _owner is ready but OFFPROC we could use a YieldTo()
     2954     // operation to donate the remainder of this thread's quantum
     2955     // to the owner.  This has subtle but beneficial affinity
     2956     // effects.
     2957 
     2958     if (TrySpin (Self) > 0) {
     2959         assert (_owner == Self        , "invariant") ;
     2960         assert (_succ != Self         , "invariant") ;
     2961         assert (_Responsible != Self  , "invariant") ;
     2962         return ;
     2963     }
     2964 
     2965     // The Spin failed -- Enqueue and park the thread ...
     2966     assert (_succ  != Self            , "invariant") ;
     2967     assert (_owner != Self            , "invariant") ;
     2968     assert (_Responsible != Self      , "invariant") ;
     2969 
     2970     // Enqueue "Self" on ObjectMonitor's _cxq.
     2971     //
     2972     // Node acts as a proxy for Self.
     2973     // As an aside, if were to ever rewrite the synchronization code mostly
     2974     // in Java, WaitNodes, ObjectMonitors, and Events would become 1st-class
     2975     // Java objects.  This would avoid awkward lifecycle and liveness issues,
     2976     // as well as eliminate a subset of ABA issues.
     2977     // TODO: eliminate ObjectWaiter and enqueue either Threads or Events.
     2978     //
     2979 
     2980     ObjectWaiter node(Self) ;
     2981     Self->_ParkEvent->reset() ;
     2982     node._prev   = (ObjectWaiter *) 0xBAD ;
     2983     node.TState  = ObjectWaiter::TS_CXQ ;
     2984 
     2985     // Push "Self" onto the front of the _cxq.
     2986     // Once on cxq/EntryList, Self stays on-queue until it acquires the lock.
     2987     // Note that spinning tends to reduce the rate at which threads
     2988     // enqueue and dequeue on EntryList|cxq.
     2989     ObjectWaiter * nxt ;
     2990     for (;;) {
     2991         node._next = nxt = _cxq ;
     2992         if (Atomic::cmpxchg_ptr (&node, &_cxq, nxt) == nxt) break ;
     2993 
     2994         // Interference - the CAS failed because _cxq changed.  Just retry.
     2995         // As an optional optimization we retry the lock.
     2996         if (TryLock (Self) > 0) {
     2997             assert (_succ != Self         , "invariant") ;
     2998             assert (_owner == Self        , "invariant") ;
     2999             assert (_Responsible != Self  , "invariant") ;
     3000             return ;
     3001         }
     3002     }
     3003 
     3004     // Check for cxq|EntryList edge transition to non-null.  This indicates
     3005     // the onset of contention.  While contention persists exiting threads
     3006     // will use a ST:MEMBAR:LD 1-1 exit protocol.  When contention abates exit
     3007     // operations revert to the faster 1-0 mode.  This enter operation may interleave
     3008     // (race) a concurrent 1-0 exit operation, resulting in stranding, so we
     3009     // arrange for one of the contending thread to use a timed park() operations
     3010     // to detect and recover from the race.  (Stranding is form of progress failure
     3011     // where the monitor is unlocked but all the contending threads remain parked).
     3012     // That is, at least one of the contended threads will periodically poll _owner.
     3013     // One of the contending threads will become the designated "Responsible" thread.
     3014     // The Responsible thread uses a timed park instead of a normal indefinite park
     3015     // operation -- it periodically wakes and checks for and recovers from potential
     3016     // strandings admitted by 1-0 exit operations.   We need at most one Responsible
     3017     // thread per-monitor at any given moment.  Only threads on cxq|EntryList may
     3018     // be responsible for a monitor.
     3019     //
     3020     // Currently, one of the contended threads takes on the added role of "Responsible".
     3021     // A viable alternative would be to use a dedicated "stranding checker" thread
     3022     // that periodically iterated over all the threads (or active monitors) and unparked
     3023     // successors where there was risk of stranding.  This would help eliminate the
     3024     // timer scalability issues we see on some platforms as we'd only have one thread
     3025     // -- the checker -- parked on a timer.
     3026 
     3027     if ((SyncFlags & 16) == 0 && nxt == NULL && _EntryList == NULL) {
     3028         // Try to assume the role of responsible thread for the monitor.
     3029         // CONSIDER:  ST vs CAS vs { if (Responsible==null) Responsible=Self }
     3030         Atomic::cmpxchg_ptr (Self, &_Responsible, NULL) ;
     3031     }
     3032 
     3033     // The lock have been released while this thread was occupied queueing
     3034     // itself onto _cxq.  To close the race and avoid "stranding" and
     3035     // progress-liveness failure we must resample-retry _owner before parking.
     3036     // Note the Dekker/Lamport duality: ST cxq; MEMBAR; LD Owner.
     3037     // In this case the ST-MEMBAR is accomplished with CAS().
     3038     //
     3039     // TODO: Defer all thread state transitions until park-time.
     3040     // Since state transitions are heavy and inefficient we'd like
     3041     // to defer the state transitions until absolutely necessary,
     3042     // and in doing so avoid some transitions ...
     3043 
     3044     TEVENT (Inflated enter - Contention) ;
     3045     int nWakeups = 0 ;
     3046     int RecheckInterval = 1 ;
     3047 
     3048     for (;;) {
     3049 
     3050         if (TryLock (Self) > 0) break ;
     3051         assert (_owner != Self, "invariant") ;
     3052 
     3053         if ((SyncFlags & 2) && _Responsible == NULL) {
     3054            Atomic::cmpxchg_ptr (Self, &_Responsible, NULL) ;
     3055         }
     3056 
     3057         // park self
     3058         if (_Responsible == Self || (SyncFlags & 1)) {
     3059             TEVENT (Inflated enter - park TIMED) ;
     3060             Self->_ParkEvent->park ((jlong) RecheckInterval) ;
     3061             // Increase the RecheckInterval, but clamp the value.
     3062             RecheckInterval *= 8 ;
     3063             if (RecheckInterval > 1000) RecheckInterval = 1000 ;
     3064         } else {
     3065             TEVENT (Inflated enter - park UNTIMED) ;
     3066             Self->_ParkEvent->park() ;
     3067         }
     3068 
     3069         if (TryLock(Self) > 0) break ;
     3070 
     3071         // The lock is still contested.
     3072         // Keep a tally of the # of futile wakeups.
     3073         // Note that the counter is not protected by a lock or updated by atomics.
     3074         // That is by design - we trade "lossy" counters which are exposed to
     3075         // races during updates for a lower probe effect.
     3076         TEVENT (Inflated enter - Futile wakeup) ;
     3077         if (ObjectSynchronizer::_sync_FutileWakeups != NULL) {
     3078            ObjectSynchronizer::_sync_FutileWakeups->inc() ;
     3079         }
     3080         ++ nWakeups ;
     3081 
     3082         // Assuming this is not a spurious wakeup we'll normally find _succ == Self.
     3083         // We can defer clearing _succ until after the spin completes
     3084         // TrySpin() must tolerate being called with _succ == Self.
     3085         // Try yet another round of adaptive spinning.
     3086         if ((Knob_SpinAfterFutile & 1) && TrySpin (Self) > 0) break ;
     3087 
     3088         // We can find that we were unpark()ed and redesignated _succ while
     3089         // we were spinning.  That's harmless.  If we iterate and call park(),
     3090         // park() will consume the event and return immediately and we'll
     3091         // just spin again.  This pattern can repeat, leaving _succ to simply
     3092         // spin on a CPU.  Enable Knob_ResetEvent to clear pending unparks().
     3093         // Alternately, we can sample fired() here, and if set, forgo spinning
     3094         // in the next iteration.
     3095 
     3096         if ((Knob_ResetEvent & 1) && Self->_ParkEvent->fired()) {
     3097            Self->_ParkEvent->reset() ;
     3098            OrderAccess::fence() ;
     3099         }
     3100         if (_succ == Self) _succ = NULL ;
     3101 
     3102         // Invariant: after clearing _succ a thread *must* retry _owner before parking.
     3103         OrderAccess::fence() ;
     3104     }
     3105 
     3106     // Egress :
     3107     // Self has acquired the lock -- Unlink Self from the cxq or EntryList.
     3108     // Normally we'll find Self on the EntryList .
     3109     // From the perspective of the lock owner (this thread), the
     3110     // EntryList is stable and cxq is prepend-only.
     3111     // The head of cxq is volatile but the interior is stable.
     3112     // In addition, Self.TState is stable.
     3113 
     3114     assert (_owner == Self      , "invariant") ;
     3115     assert (object() != NULL    , "invariant") ;
     3116     // I'd like to write:
     3117     //   guarantee (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;
     3118     // but as we're at a safepoint that's not safe.
     3119 
     3120     UnlinkAfterAcquire (Self, &node) ;
     3121     if (_succ == Self) _succ = NULL ;
     3122 
     3123     assert (_succ != Self, "invariant") ;
     3124     if (_Responsible == Self) {
     3125         _Responsible = NULL ;
     3126         // Dekker pivot-point.
     3127         // Consider OrderAccess::storeload() here
     3128 
     3129         // We may leave threads on cxq|EntryList without a designated
     3130         // "Responsible" thread.  This is benign.  When this thread subsequently
     3131         // exits the monitor it can "see" such preexisting "old" threads --
     3132         // threads that arrived on the cxq|EntryList before the fence, above --
     3133         // by LDing cxq|EntryList.  Newly arrived threads -- that is, threads
     3134         // that arrive on cxq after the ST:MEMBAR, above -- will set Responsible
     3135         // non-null and elect a new "Responsible" timer thread.
     3136         //
     3137         // This thread executes:
     3138         //    ST Responsible=null; MEMBAR    (in enter epilog - here)
     3139         //    LD cxq|EntryList               (in subsequent exit)
     3140         //
     3141         // Entering threads in the slow/contended path execute:
     3142         //    ST cxq=nonnull; MEMBAR; LD Responsible (in enter prolog)
     3143         //    The (ST cxq; MEMBAR) is accomplished with CAS().
     3144         //
     3145         // The MEMBAR, above, prevents the LD of cxq|EntryList in the subsequent
     3146         // exit operation from floating above the ST Responsible=null.
     3147         //
     3148         // In *practice* however, EnterI() is always followed by some atomic
     3149         // operation such as the decrement of _count in ::enter().  Those atomics
     3150         // obviate the need for the explicit MEMBAR, above.
     3151     }
     3152 
     3153     // We've acquired ownership with CAS().
     3154     // CAS is serializing -- it has MEMBAR/FENCE-equivalent semantics.
     3155     // But since the CAS() this thread may have also stored into _succ,
     3156     // EntryList, cxq or Responsible.  These meta-data updates must be
     3157     // visible __before this thread subsequently drops the lock.
     3158     // Consider what could occur if we didn't enforce this constraint --
     3159     // STs to monitor meta-data and user-data could reorder with (become
     3160     // visible after) the ST in exit that drops ownership of the lock.
     3161     // Some other thread could then acquire the lock, but observe inconsistent
     3162     // or old monitor meta-data and heap data.  That violates the JMM.
     3163     // To that end, the 1-0 exit() operation must have at least STST|LDST
     3164     // "release" barrier semantics.  Specifically, there must be at least a
     3165     // STST|LDST barrier in exit() before the ST of null into _owner that drops
     3166     // the lock.   The barrier ensures that changes to monitor meta-data and data
     3167     // protected by the lock will be visible before we release the lock, and
     3168     // therefore before some other thread (CPU) has a chance to acquire the lock.
     3169     // See also: http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
     3170     //
     3171     // Critically, any prior STs to _succ or EntryList must be visible before
     3172     // the ST of null into _owner in the *subsequent* (following) corresponding
     3173     // monitorexit.  Recall too, that in 1-0 mode monitorexit does not necessarily
     3174     // execute a serializing instruction.
     3175 
     3176     if (SyncFlags & 8) {
     3177        OrderAccess::fence() ;
     3178     }
     3179     return ;
     3180 }
     3181 
     3182 // ExitSuspendEquivalent:
     3183 // A faster alternate to handle_special_suspend_equivalent_condition()
     3184 //
     3185 // handle_special_suspend_equivalent_condition() unconditionally
     3186 // acquires the SR_lock.  On some platforms uncontended MutexLocker()
     3187 // operations have high latency.  Note that in ::enter() we call HSSEC
     3188 // while holding the monitor, so we effectively lengthen the critical sections.
     3189 //
     3190 // There are a number of possible solutions:
     3191 //
     3192 // A.  To ameliorate the problem we might also defer state transitions
     3193 //     to as late as possible -- just prior to parking.
     3194 //     Given that, we'd call HSSEC after having returned from park(),
     3195 //     but before attempting to acquire the monitor.  This is only a
     3196 //     partial solution.  It avoids calling HSSEC while holding the
     3197 //     monitor (good), but it still increases successor reacquisition latency --
     3198 //     the interval between unparking a successor and the time the successor
     3199 //     resumes and retries the lock.  See ReenterI(), which defers state transitions.
     3200 //     If we use this technique we can also avoid EnterI()-exit() loop
     3201 //     in ::enter() where we iteratively drop the lock and then attempt
     3202 //     to reacquire it after suspending.
     3203 //
     3204 // B.  In the future we might fold all the suspend bits into a
     3205 //     composite per-thread suspend flag and then update it with CAS().
     3206 //     Alternately, a Dekker-like mechanism with multiple variables
     3207 //     would suffice:
     3208 //       ST Self->_suspend_equivalent = false
     3209 //       MEMBAR
     3210 //       LD Self_>_suspend_flags
     3211 //
     3212 
     3213 
     3214 bool ObjectMonitor::ExitSuspendEquivalent (JavaThread * jSelf) {
     3215    int Mode = Knob_FastHSSEC ;
     3216    if (Mode && !jSelf->is_external_suspend()) {
     3217       assert (jSelf->is_suspend_equivalent(), "invariant") ;
     3218       jSelf->clear_suspend_equivalent() ;
     3219       if (2 == Mode) OrderAccess::storeload() ;
     3220       if (!jSelf->is_external_suspend()) return false ;
     3221       // We raced a suspension -- fall thru into the slow path
     3222       TEVENT (ExitSuspendEquivalent - raced) ;
     3223       jSelf->set_suspend_equivalent() ;
     3224    }
     3225    return jSelf->handle_special_suspend_equivalent_condition() ;
     3226 }
     3227 
     3228 
     3229 // ReenterI() is a specialized inline form of the latter half of the
     3230 // contended slow-path from EnterI().  We use ReenterI() only for
     3231 // monitor reentry in wait().
     3232 //
     3233 // In the future we should reconcile EnterI() and ReenterI(), adding
     3234 // Knob_Reset and Knob_SpinAfterFutile support and restructuring the
     3235 // loop accordingly.
     3236 
     3237 void ATTR ObjectMonitor::ReenterI (Thread * Self, ObjectWaiter * SelfNode) {
     3238     assert (Self != NULL                , "invariant") ;
     3239     assert (SelfNode != NULL            , "invariant") ;
     3240     assert (SelfNode->_thread == Self   , "invariant") ;
     3241     assert (_waiters > 0                , "invariant") ;
     3242     assert (((oop)(object()))->mark() == markOopDesc::encode(this) , "invariant") ;
     3243     assert (((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant") ;
     3244     JavaThread * jt = (JavaThread *) Self ;
     3245 
     3246     int nWakeups = 0 ;
     3247     for (;;) {
     3248         ObjectWaiter::TStates v = SelfNode->TState ;
     3249         guarantee (v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant") ;
     3250         assert    (_owner != Self, "invariant") ;
     3251 
     3252         if (TryLock (Self) > 0) break ;
     3253         if (TrySpin (Self) > 0) break ;
     3254 
     3255         TEVENT (Wait Reentry - parking) ;
     3256 
     3257         // State transition wrappers around park() ...
     3258         // ReenterI() wisely defers state transitions until
     3259         // it's clear we must park the thread.
     3260         {
     3261            OSThreadContendState osts(Self->osthread());
     3262            ThreadBlockInVM tbivm(jt);
     3263 
     3264            // cleared by handle_special_suspend_equivalent_condition()
     3265            // or java_suspend_self()
     3266            jt->set_suspend_equivalent();
     3267            if (SyncFlags & 1) {
     3268               Self->_ParkEvent->park ((jlong)1000) ;
     3269            } else {
     3270               Self->_ParkEvent->park () ;
     3271            }
     3272 
     3273            // were we externally suspended while we were waiting?
     3274            for (;;) {
     3275               if (!ExitSuspendEquivalent (jt)) break ;
     3276               if (_succ == Self) { _succ = NULL; OrderAccess::fence(); }
     3277               jt->java_suspend_self();
     3278               jt->set_suspend_equivalent();
     3279            }
     3280         }
     3281 
     3282         // Try again, but just so we distinguish between futile wakeups and
     3283         // successful wakeups.  The following test isn't algorithmically
     3284         // necessary, but it helps us maintain sensible statistics.
     3285         if (TryLock(Self) > 0) break ;
     3286 
     3287         // The lock is still contested.
     3288         // Keep a tally of the # of futile wakeups.
     3289         // Note that the counter is not protected by a lock or updated by atomics.
     3290         // That is by design - we trade "lossy" counters which are exposed to
     3291         // races during updates for a lower probe effect.
     3292         TEVENT (Wait Reentry - futile wakeup) ;
     3293         ++ nWakeups ;
     3294 
     3295         // Assuming this is not a spurious wakeup we'll normally
     3296         // find that _succ == Self.
     3297         if (_succ == Self) _succ = NULL ;
     3298 
     3299         // Invariant: after clearing _succ a contending thread
     3300         // *must* retry  _owner before parking.
     3301         OrderAccess::fence() ;
     3302 
     3303         if (ObjectSynchronizer::_sync_FutileWakeups != NULL) {
     3304           ObjectSynchronizer::_sync_FutileWakeups->inc() ;
     3305         }
     3306     }
     3307 
     3308     // Self has acquired the lock -- Unlink Self from the cxq or EntryList .
     3309     // Normally we'll find Self on the EntryList.
     3310     // Unlinking from the EntryList is constant-time and atomic-free.
     3311     // From the perspective of the lock owner (this thread), the
     3312     // EntryList is stable and cxq is prepend-only.
     3313     // The head of cxq is volatile but the interior is stable.
     3314     // In addition, Self.TState is stable.
     3315 
     3316     assert (_owner == Self, "invariant") ;
     3317     assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;
     3318     UnlinkAfterAcquire (Self, SelfNode) ;
     3319     if (_succ == Self) _succ = NULL ;
     3320     assert (_succ != Self, "invariant") ;
     3321     SelfNode->TState = ObjectWaiter::TS_RUN ;
     3322     OrderAccess::fence() ;      // see comments at the end of EnterI()
     3323 }
     3324 
     3325 bool ObjectMonitor::try_enter(Thread* THREAD) {
     3326   if (THREAD != _owner) {
     3327     if (THREAD->is_lock_owned ((address)_owner)) {
     3328        assert(_recursions == 0, "internal state error");
     3329        _owner = THREAD ;
     3330        _recursions = 1 ;
     3331        OwnerIsThread = 1 ;
     3332        return true;
     3333     }
     3334     if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) {
     3335       return false;
     3336     }
     3337     return true;
     3338   } else {
     3339     _recursions++;
     3340     return true;
     3341   }
     3342 }
     3343 
     3344 void ATTR ObjectMonitor::enter(TRAPS) {
     3345   // The following code is ordered to check the most common cases first
     3346   // and to reduce RTS->RTO cache line upgrades on SPARC and IA32 processors.
     3347   Thread * const Self = THREAD ;
     3348   void * cur ;
     3349 
     3350   cur = Atomic::cmpxchg_ptr (Self, &_owner, NULL) ;
     3351   if (cur == NULL) {
     3352      // Either ASSERT _recursions == 0 or explicitly set _recursions = 0.
     3353      assert (_recursions == 0   , "invariant") ;
     3354      assert (_owner      == Self, "invariant") ;
     3355      // CONSIDER: set or assert OwnerIsThread == 1
     3356      return ;
     3357   }
     3358 
     3359   if (cur == Self) {
     3360      // TODO-FIXME: check for integer overflow!  BUGID 6557169.
     3361      _recursions ++ ;
     3362      return ;
     3363   }
     3364 
     3365   if (Self->is_lock_owned ((address)cur)) {
     3366     assert (_recursions == 0, "internal state error");
     3367     _recursions = 1 ;
     3368     // Commute owner from a thread-specific on-stack BasicLockObject address to
     3369     // a full-fledged "Thread *".
     3370     _owner = Self ;
     3371     OwnerIsThread = 1 ;
     3372     return ;
     3373   }
     3374 
     3375   // We've encountered genuine contention.
     3376   assert (Self->_Stalled == 0, "invariant") ;
     3377   Self->_Stalled = intptr_t(this) ;
     3378 
     3379   // Try one round of spinning *before* enqueueing Self
     3380   // and before going through the awkward and expensive state
     3381   // transitions.  The following spin is strictly optional ...
     3382   // Note that if we acquire the monitor from an initial spin
     3383   // we forgo posting JVMTI events and firing DTRACE probes.
     3384   if (Knob_SpinEarly && TrySpin (Self) > 0) {
     3385      assert (_owner == Self      , "invariant") ;
     3386      assert (_recursions == 0    , "invariant") ;
     3387      assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;
     3388      Self->_Stalled = 0 ;
     3389      return ;
     3390   }
     3391 
     3392   assert (_owner != Self          , "invariant") ;
     3393   assert (_succ  != Self          , "invariant") ;
     3394   assert (Self->is_Java_thread()  , "invariant") ;
     3395   JavaThread * jt = (JavaThread *) Self ;
     3396   assert (!SafepointSynchronize::is_at_safepoint(), "invariant") ;
     3397   assert (jt->thread_state() != _thread_blocked   , "invariant") ;
     3398   assert (this->object() != NULL  , "invariant") ;
     3399   assert (_count >= 0, "invariant") ;
     3400 
     3401   // Prevent deflation at STW-time.  See deflate_idle_monitors() and is_busy().
     3402   // Ensure the object-monitor relationship remains stable while there's contention.
     3403   Atomic::inc_ptr(&_count);
     3404 
     3405   { // Change java thread status to indicate blocked on monitor enter.
     3406     JavaThreadBlockedOnMonitorEnterState jtbmes(jt, this);
     3407 
     3408     DTRACE_MONITOR_PROBE(contended__enter, this, object(), jt);
     3409     if (JvmtiExport::should_post_monitor_contended_enter()) {
     3410       JvmtiExport::post_monitor_contended_enter(jt, this);
     3411     }
     3412 
     3413     OSThreadContendState osts(Self->osthread());
     3414     ThreadBlockInVM tbivm(jt);
     3415 
     3416     Self->set_current_pending_monitor(this);
     3417 
     3418     // TODO-FIXME: change the following for(;;) loop to straight-line code.
     3419     for (;;) {
     3420       jt->set_suspend_equivalent();
     3421       // cleared by handle_special_suspend_equivalent_condition()
     3422       // or java_suspend_self()
     3423 
     3424       EnterI (THREAD) ;
     3425 
     3426       if (!ExitSuspendEquivalent(jt)) break ;
     3427 
     3428       //
     3429       // We have acquired the contended monitor, but while we were
     3430       // waiting another thread suspended us. We don't want to enter
     3431       // the monitor while suspended because that would surprise the
     3432       // thread that suspended us.
     3433       //
     3434           _recursions = 0 ;
     3435       _succ = NULL ;
     3436       exit (Self) ;
     3437 
     3438       jt->java_suspend_self();
     3439     }
     3440     Self->set_current_pending_monitor(NULL);
     3441   }
     3442 
     3443   Atomic::dec_ptr(&_count);
     3444   assert (_count >= 0, "invariant") ;
     3445   Self->_Stalled = 0 ;
     3446 
     3447   // Must either set _recursions = 0 or ASSERT _recursions == 0.
     3448   assert (_recursions == 0     , "invariant") ;
     3449   assert (_owner == Self       , "invariant") ;
     3450   assert (_succ  != Self       , "invariant") ;
     3451   assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;
     3452 
     3453   // The thread -- now the owner -- is back in vm mode.
     3454   // Report the glorious news via TI,DTrace and jvmstat.
     3455   // The probe effect is non-trivial.  All the reportage occurs
     3456   // while we hold the monitor, increasing the length of the critical
     3457   // section.  Amdahl's parallel speedup law comes vividly into play.
     3458   //
     3459   // Another option might be to aggregate the events (thread local or
     3460   // per-monitor aggregation) and defer reporting until a more opportune
     3461   // time -- such as next time some thread encounters contention but has
     3462   // yet to acquire the lock.  While spinning that thread could
     3463   // spinning we could increment JVMStat counters, etc.
     3464 
     3465   DTRACE_MONITOR_PROBE(contended__entered, this, object(), jt);
     3466   if (JvmtiExport::should_post_monitor_contended_entered()) {
     3467     JvmtiExport::post_monitor_contended_entered(jt, this);
     3468   }
     3469   if (ObjectSynchronizer::_sync_ContendedLockAttempts != NULL) {
     3470      ObjectSynchronizer::_sync_ContendedLockAttempts->inc() ;
     3471   }
     3472 }
     3473 
     3474 void ObjectMonitor::ExitEpilog (Thread * Self, ObjectWaiter * Wakee) {
     3475    assert (_owner == Self, "invariant") ;
     3476 
     3477    // Exit protocol:
     3478    // 1. ST _succ = wakee
     3479    // 2. membar #loadstore|#storestore;
     3480    // 2. ST _owner = NULL
     3481    // 3. unpark(wakee)
     3482 
     3483    _succ = Knob_SuccEnabled ? Wakee->_thread : NULL ;
     3484    ParkEvent * Trigger = Wakee->_event ;
     3485 
     3486    // Hygiene -- once we've set _owner = NULL we can't safely dereference Wakee again.
     3487    // The thread associated with Wakee may have grabbed the lock and "Wakee" may be
     3488    // out-of-scope (non-extant).
     3489    Wakee  = NULL ;
     3490 
     3491    // Drop the lock
     3492    OrderAccess::release_store_ptr (&_owner, NULL) ;
     3493    OrderAccess::fence() ;                               // ST _owner vs LD in unpark()
     3494 
     3495    // TODO-FIXME:
     3496    // If there's a safepoint pending the best policy would be to
     3497    // get _this thread to a safepoint and only wake the successor
     3498    // after the safepoint completed.  monitorexit uses a "leaf"
     3499    // state transition, however, so this thread can't become
     3500    // safe at this point in time.  (Its stack isn't walkable).
     3501    // The next best thing is to defer waking the successor by
     3502    // adding to a list of thread to be unparked after at the
     3503    // end of the forthcoming STW).
     3504    if (SafepointSynchronize::do_call_back()) {
     3505       TEVENT (unpark before SAFEPOINT) ;
     3506    }
     3507 
     3508    // Possible optimizations ...
     3509    //
     3510    // * Consider: set Wakee->UnparkTime = timeNow()
     3511    //   When the thread wakes up it'll compute (timeNow() - Self->UnparkTime()).
     3512    //   By measuring recent ONPROC latency we can approximate the
     3513    //   system load.  In turn, we can feed that information back
     3514    //   into the spinning & succession policies.
     3515    //   (ONPROC latency correlates strongly with load).
     3516    //
     3517    // * Pull affinity:
     3518    //   If the wakee is cold then transiently setting it's affinity
     3519    //   to the current CPU is a good idea.
     3520    //   See http://j2se.east/~dice/PERSIST/050624-PullAffinity.txt
     3521    DTRACE_MONITOR_PROBE(contended__exit, this, object(), Self);
     3522    Trigger->unpark() ;
     3523 
     3524    // Maintain stats and report events to JVMTI
     3525    if (ObjectSynchronizer::_sync_Parks != NULL) {
     3526       ObjectSynchronizer::_sync_Parks->inc() ;
     3527    }
     3528 }
     3529 
     3530 
     3531 // exit()
     3532 // ~~~~~~
     3533 // Note that the collector can't reclaim the objectMonitor or deflate
     3534 // the object out from underneath the thread calling ::exit() as the
     3535 // thread calling ::exit() never transitions to a stable state.
     3536 // This inhibits GC, which in turn inhibits asynchronous (and
     3537 // inopportune) reclamation of "this".
     3538 //
     3539 // We'd like to assert that: (THREAD->thread_state() != _thread_blocked) ;
     3540 // There's one exception to the claim above, however.  EnterI() can call
     3541 // exit() to drop a lock if the acquirer has been externally suspended.
     3542 // In that case exit() is called with _thread_state as _thread_blocked,
     3543 // but the monitor's _count field is > 0, which inhibits reclamation.
     3544 //
     3545 // 1-0 exit
     3546 // ~~~~~~~~
     3547 // ::exit() uses a canonical 1-1 idiom with a MEMBAR although some of
     3548 // the fast-path operators have been optimized so the common ::exit()
     3549 // operation is 1-0.  See i486.ad fast_unlock(), for instance.
     3550 // The code emitted by fast_unlock() elides the usual MEMBAR.  This
     3551 // greatly improves latency -- MEMBAR and CAS having considerable local
     3552 // latency on modern processors -- but at the cost of "stranding".  Absent the
     3553 // MEMBAR, a thread in fast_unlock() can race a thread in the slow
     3554 // ::enter() path, resulting in the entering thread being stranding
     3555 // and a progress-liveness failure.   Stranding is extremely rare.
     3556 // We use timers (timed park operations) & periodic polling to detect
     3557 // and recover from stranding.  Potentially stranded threads periodically
     3558 // wake up and poll the lock.  See the usage of the _Responsible variable.
     3559 //
     3560 // The CAS() in enter provides for safety and exclusion, while the CAS or
     3561 // MEMBAR in exit provides for progress and avoids stranding.  1-0 locking
     3562 // eliminates the CAS/MEMBAR from the exist path, but it admits stranding.
     3563 // We detect and recover from stranding with timers.
     3564 //
     3565 // If a thread transiently strands it'll park until (a) another
     3566 // thread acquires the lock and then drops the lock, at which time the
     3567 // exiting thread will notice and unpark the stranded thread, or, (b)
     3568 // the timer expires.  If the lock is high traffic then the stranding latency
     3569 // will be low due to (a).  If the lock is low traffic then the odds of
     3570 // stranding are lower, although the worst-case stranding latency
     3571 // is longer.  Critically, we don't want to put excessive load in the
     3572 // platform's timer subsystem.  We want to minimize both the timer injection
     3573 // rate (timers created/sec) as well as the number of timers active at
     3574 // any one time.  (more precisely, we want to minimize timer-seconds, which is
     3575 // the integral of the # of active timers at any instant over time).
     3576 // Both impinge on OS scalability.  Given that, at most one thread parked on
     3577 // a monitor will use a timer.
     3578 
     3579 void ATTR ObjectMonitor::exit(TRAPS) {
     3580    Thread * Self = THREAD ;
     3581    if (THREAD != _owner) {
     3582      if (THREAD->is_lock_owned((address) _owner)) {
     3583        // Transmute _owner from a BasicLock pointer to a Thread address.
     3584        // We don't need to hold _mutex for this transition.
     3585        // Non-null to Non-null is safe as long as all readers can
     3586        // tolerate either flavor.
     3587        assert (_recursions == 0, "invariant") ;
     3588        _owner = THREAD ;
     3589        _recursions = 0 ;
     3590        OwnerIsThread = 1 ;
     3591      } else {
     3592        // NOTE: we need to handle unbalanced monitor enter/exit
     3593        // in native code by throwing an exception.
     3594        // TODO: Throw an IllegalMonitorStateException ?
     3595        TEVENT (Exit - Throw IMSX) ;
     3596        assert(false, "Non-balanced monitor enter/exit!");
     3597        if (false) {
     3598           THROW(vmSymbols::java_lang_IllegalMonitorStateException());
     3599        }
     3600        return;
     3601      }
     3602    }
     3603 
     3604    if (_recursions != 0) {
     3605      _recursions--;        // this is simple recursive enter
     3606      TEVENT (Inflated exit - recursive) ;
     3607      return ;
     3608    }
     3609 
     3610    // Invariant: after setting Responsible=null an thread must execute
     3611    // a MEMBAR or other serializing instruction before fetching EntryList|cxq.
     3612    if ((SyncFlags & 4) == 0) {
     3613       _Responsible = NULL ;
     3614    }
     3615 
     3616    for (;;) {
     3617       assert (THREAD == _owner, "invariant") ;
     3618 
     3619       // Fast-path monitor exit:
     3620       //
     3621       // Observe the Dekker/Lamport duality:
     3622       // A thread in ::exit() executes:
     3623       //   ST Owner=null; MEMBAR; LD EntryList|cxq.
     3624       // A thread in the contended ::enter() path executes the complementary:
     3625       //   ST EntryList|cxq = nonnull; MEMBAR; LD Owner.
     3626       //
     3627       // Note that there's a benign race in the exit path.  We can drop the
     3628       // lock, another thread can reacquire the lock immediately, and we can
     3629       // then wake a thread unnecessarily (yet another flavor of futile wakeup).
     3630       // This is benign, and we've structured the code so the windows are short
     3631       // and the frequency of such futile wakeups is low.
     3632       //
     3633       // We could eliminate the race by encoding both the "LOCKED" state and
     3634       // the queue head in a single word.  Exit would then use either CAS to
     3635       // clear the LOCKED bit/byte.  This precludes the desirable 1-0 optimization,
     3636       // however.
     3637       //
     3638       // Possible fast-path ::exit() optimization:
     3639       // The current fast-path exit implementation fetches both cxq and EntryList.
     3640       // See also i486.ad fast_unlock().  Testing has shown that two LDs
     3641       // isn't measurably slower than a single LD on any platforms.
     3642       // Still, we could reduce the 2 LDs to one or zero by one of the following:
     3643       //
     3644       // - Use _count instead of cxq|EntryList
     3645       //   We intend to eliminate _count, however, when we switch
     3646       //   to on-the-fly deflation in ::exit() as is used in
     3647       //   Metalocks and RelaxedLocks.
     3648       //
     3649       // - Establish the invariant that cxq == null implies EntryList == null.
     3650       //   set cxq == EMPTY (1) to encode the state where cxq is empty
     3651       //   by EntryList != null.  EMPTY is a distinguished value.
     3652       //   The fast-path exit() would fetch cxq but not EntryList.
     3653       //
     3654       // - Encode succ as follows:
     3655       //   succ = t :  Thread t is the successor -- t is ready or is spinning.
     3656       //               Exiting thread does not need to wake a successor.
     3657       //   succ = 0 :  No successor required -> (EntryList|cxq) == null
     3658       //               Exiting thread does not need to wake a successor
     3659       //   succ = 1 :  Successor required    -> (EntryList|cxq) != null and
     3660       //               logically succ == null.
     3661       //               Exiting thread must wake a successor.
     3662       //
     3663       //   The 1-1 fast-exit path would appear as :
     3664       //     _owner = null ; membar ;
     3665       //     if (_succ == 1 && CAS (&_owner, null, Self) == null) goto SlowPath
     3666       //     goto FastPathDone ;
     3667       //
     3668       //   and the 1-0 fast-exit path would appear as:
     3669       //      if (_succ == 1) goto SlowPath
     3670       //      Owner = null ;
     3671       //      goto FastPathDone
     3672       //
     3673       // - Encode the LSB of _owner as 1 to indicate that exit()
     3674       //   must use the slow-path and make a successor ready.
     3675       //   (_owner & 1) == 0 IFF succ != null || (EntryList|cxq) == null
     3676       //   (_owner & 1) == 0 IFF succ == null && (EntryList|cxq) != null (obviously)
     3677       //   The 1-0 fast exit path would read:
     3678       //      if (_owner != Self) goto SlowPath
     3679       //      _owner = null
     3680       //      goto FastPathDone
     3681 
     3682       if (Knob_ExitPolicy == 0) {
     3683          // release semantics: prior loads and stores from within the critical section
     3684          // must not float (reorder) past the following store that drops the lock.
     3685          // On SPARC that requires MEMBAR #loadstore|#storestore.
     3686          // But of course in TSO #loadstore|#storestore is not required.
     3687          // I'd like to write one of the following:
     3688          // A.  OrderAccess::release() ; _owner = NULL
     3689          // B.  OrderAccess::loadstore(); OrderAccess::storestore(); _owner = NULL;
     3690          // Unfortunately OrderAccess::release() and OrderAccess::loadstore() both
     3691          // store into a _dummy variable.  That store is not needed, but can result
     3692          // in massive wasteful coherency traffic on classic SMP systems.
     3693          // Instead, I use release_store(), which is implemented as just a simple
     3694          // ST on x64, x86 and SPARC.
     3695          OrderAccess::release_store_ptr (&_owner, NULL) ;   // drop the lock
     3696          OrderAccess::storeload() ;                         // See if we need to wake a successor
     3697          if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != NULL) {
     3698             TEVENT (Inflated exit - simple egress) ;
     3699             return ;
     3700          }
     3701          TEVENT (Inflated exit - complex egress) ;
     3702 
     3703          // Normally the exiting thread is responsible for ensuring succession,
     3704          // but if other successors are ready or other entering threads are spinning
     3705          // then this thread can simply store NULL into _owner and exit without
     3706          // waking a successor.  The existence of spinners or ready successors
     3707          // guarantees proper succession (liveness).  Responsibility passes to the
     3708          // ready or running successors.  The exiting thread delegates the duty.
     3709          // More precisely, if a successor already exists this thread is absolved
     3710          // of the responsibility of waking (unparking) one.
     3711          //
     3712          // The _succ variable is critical to reducing futile wakeup frequency.
     3713          // _succ identifies the "heir presumptive" thread that has been made
     3714          // ready (unparked) but that has not yet run.  We need only one such
     3715          // successor thread to guarantee progress.
     3716          // See http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf
     3717          // section 3.3 "Futile Wakeup Throttling" for details.
     3718          //
     3719          // Note that spinners in Enter() also set _succ non-null.
     3720          // In the current implementation spinners opportunistically set
     3721          // _succ so that exiting threads might avoid waking a successor.
     3722          // Another less appealing alternative would be for the exiting thread
     3723          // to drop the lock and then spin briefly to see if a spinner managed
     3724          // to acquire the lock.  If so, the exiting thread could exit
     3725          // immediately without waking a successor, otherwise the exiting
     3726          // thread would need to dequeue and wake a successor.
     3727          // (Note that we'd need to make the post-drop spin short, but no
     3728          // shorter than the worst-case round-trip cache-line migration time.
     3729          // The dropped lock needs to become visible to the spinner, and then
     3730          // the acquisition of the lock by the spinner must become visible to
     3731          // the exiting thread).
     3732          //
     3733 
     3734          // It appears that an heir-presumptive (successor) must be made ready.
     3735          // Only the current lock owner can manipulate the EntryList or
     3736          // drain _cxq, so we need to reacquire the lock.  If we fail
     3737          // to reacquire the lock the responsibility for ensuring succession
     3738          // falls to the new owner.
     3739          //
     3740          if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) {
     3741             return ;
     3742          }
     3743          TEVENT (Exit - Reacquired) ;
     3744       } else {
     3745          if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != NULL) {
     3746             OrderAccess::release_store_ptr (&_owner, NULL) ;   // drop the lock
     3747             OrderAccess::storeload() ;
     3748             // Ratify the previously observed values.
     3749             if (_cxq == NULL || _succ != NULL) {
     3750                 TEVENT (Inflated exit - simple egress) ;
     3751                 return ;
     3752             }
     3753 
     3754             // inopportune interleaving -- the exiting thread (this thread)
     3755             // in the fast-exit path raced an entering thread in the slow-enter
     3756             // path.
     3757             // We have two choices:
     3758             // A.  Try to reacquire the lock.
     3759             //     If the CAS() fails return immediately, otherwise
     3760             //     we either restart/rerun the exit operation, or simply
     3761             //     fall-through into the code below which wakes a successor.
     3762             // B.  If the elements forming the EntryList|cxq are TSM
     3763             //     we could simply unpark() the lead thread and return
     3764             //     without having set _succ.
     3765             if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) {
     3766                TEVENT (Inflated exit - reacquired succeeded) ;
     3767                return ;
     3768             }
     3769             TEVENT (Inflated exit - reacquired failed) ;
     3770          } else {
     3771             TEVENT (Inflated exit - complex egress) ;
     3772          }
     3773       }
     3774 
     3775       guarantee (_owner == THREAD, "invariant") ;
     3776 
     3777       // Select an appropriate successor ("heir presumptive") from the EntryList
     3778       // and make it ready.  Generally we just wake the head of EntryList .
     3779       // There's no algorithmic constraint that we use the head - it's just
     3780       // a policy decision.   Note that the thread at head of the EntryList
     3781       // remains at the head until it acquires the lock.  This means we'll
     3782       // repeatedly wake the same thread until it manages to grab the lock.
     3783       // This is generally a good policy - if we're seeing lots of futile wakeups
     3784       // at least we're waking/rewaking a thread that's like to be hot or warm
     3785       // (have residual D$ and TLB affinity).
     3786       //
     3787       // "Wakeup locality" optimization:
     3788       // http://j2se.east/~dice/PERSIST/040825-WakeLocality.txt
     3789       // In the future we'll try to bias the selection mechanism
     3790       // to preferentially pick a thread that recently ran on
     3791       // a processor element that shares cache with the CPU on which
     3792       // the exiting thread is running.   We need access to Solaris'
     3793       // schedctl.sc_cpu to make that work.
     3794       //
     3795       ObjectWaiter * w = NULL ;
     3796       int QMode = Knob_QMode ;
     3797 
     3798       if (QMode == 2 && _cxq != NULL) {
     3799           // QMode == 2 : cxq has precedence over EntryList.
     3800           // Try to directly wake a successor from the cxq.
     3801           // If successful, the successor will need to unlink itself from cxq.
     3802           w = _cxq ;
     3803           assert (w != NULL, "invariant") ;
     3804           assert (w->TState == ObjectWaiter::TS_CXQ, "Invariant") ;
     3805           ExitEpilog (Self, w) ;
     3806           return ;
     3807       }
     3808 
     3809       if (QMode == 3 && _cxq != NULL) {
     3810           // Aggressively drain cxq into EntryList at the first opportunity.
     3811           // This policy ensure that recently-run threads live at the head of EntryList.
     3812           // Drain _cxq into EntryList - bulk transfer.
     3813           // First, detach _cxq.
     3814           // The following loop is tantamount to: w = swap (&cxq, NULL)
     3815           w = _cxq ;
     3816           for (;;) {
     3817              assert (w != NULL, "Invariant") ;
     3818              ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ;
     3819              if (u == w) break ;
     3820              w = u ;
     3821           }
     3822           assert (w != NULL              , "invariant") ;
     3823 
     3824           ObjectWaiter * q = NULL ;
     3825           ObjectWaiter * p ;
     3826           for (p = w ; p != NULL ; p = p->_next) {
     3827               guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ;
     3828               p->TState = ObjectWaiter::TS_ENTER ;
     3829               p->_prev = q ;
     3830               q = p ;
     3831           }
     3832 
     3833           // Append the RATs to the EntryList
     3834           // TODO: organize EntryList as a CDLL so we can locate the tail in constant-time.
     3835           ObjectWaiter * Tail ;
     3836           for (Tail = _EntryList ; Tail != NULL && Tail->_next != NULL ; Tail = Tail->_next) ;
     3837           if (Tail == NULL) {
     3838               _EntryList = w ;
     3839           } else {
     3840               Tail->_next = w ;
     3841               w->_prev = Tail ;
     3842           }
     3843 
     3844           // Fall thru into code that tries to wake a successor from EntryList
     3845       }
     3846 
     3847       if (QMode == 4 && _cxq != NULL) {
     3848           // Aggressively drain cxq into EntryList at the first opportunity.
     3849           // This policy ensure that recently-run threads live at the head of EntryList.
     3850 
     3851           // Drain _cxq into EntryList - bulk transfer.
     3852           // First, detach _cxq.
     3853           // The following loop is tantamount to: w = swap (&cxq, NULL)
     3854           w = _cxq ;
     3855           for (;;) {
     3856              assert (w != NULL, "Invariant") ;
     3857              ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ;
     3858              if (u == w) break ;
     3859              w = u ;
     3860           }
     3861           assert (w != NULL              , "invariant") ;
     3862 
     3863           ObjectWaiter * q = NULL ;
     3864           ObjectWaiter * p ;
     3865           for (p = w ; p != NULL ; p = p->_next) {
     3866               guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ;
     3867               p->TState = ObjectWaiter::TS_ENTER ;
     3868               p->_prev = q ;
     3869               q = p ;
     3870           }
     3871 
     3872           // Prepend the RATs to the EntryList
     3873           if (_EntryList != NULL) {
     3874               q->_next = _EntryList ;
     3875               _EntryList->_prev = q ;
     3876           }
     3877           _EntryList = w ;
     3878 
     3879           // Fall thru into code that tries to wake a successor from EntryList
     3880       }
     3881 
     3882       w = _EntryList  ;
     3883       if (w != NULL) {
     3884           // I'd like to write: guarantee (w->_thread != Self).
     3885           // But in practice an exiting thread may find itself on the EntryList.
     3886           // Lets say thread T1 calls O.wait().  Wait() enqueues T1 on O's waitset and
     3887           // then calls exit().  Exit release the lock by setting O._owner to NULL.
     3888           // Lets say T1 then stalls.  T2 acquires O and calls O.notify().  The
     3889           // notify() operation moves T1 from O's waitset to O's EntryList. T2 then
     3890           // release the lock "O".  T2 resumes immediately after the ST of null into
     3891           // _owner, above.  T2 notices that the EntryList is populated, so it
     3892           // reacquires the lock and then finds itself on the EntryList.
     3893           // Given all that, we have to tolerate the circumstance where "w" is
     3894           // associated with Self.
     3895           assert (w->TState == ObjectWaiter::TS_ENTER, "invariant") ;
     3896           ExitEpilog (Self, w) ;
     3897           return ;
     3898       }
     3899 
     3900       // If we find that both _cxq and EntryList are null then just
     3901       // re-run the exit protocol from the top.
     3902       w = _cxq ;
     3903       if (w == NULL) continue ;
     3904 
     3905       // Drain _cxq into EntryList - bulk transfer.
     3906       // First, detach _cxq.
     3907       // The following loop is tantamount to: w = swap (&cxq, NULL)
     3908       for (;;) {
     3909           assert (w != NULL, "Invariant") ;
     3910           ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ;
     3911           if (u == w) break ;
     3912           w = u ;
     3913       }
     3914       TEVENT (Inflated exit - drain cxq into EntryList) ;
     3915 
     3916       assert (w != NULL              , "invariant") ;
     3917       assert (_EntryList  == NULL    , "invariant") ;
     3918 
     3919       // Convert the LIFO SLL anchored by _cxq into a DLL.
     3920       // The list reorganization step operates in O(LENGTH(w)) time.
     3921       // It's critical that this step operate quickly as
     3922       // "Self" still holds the outer-lock, restricting parallelism
     3923       // and effectively lengthening the critical section.
     3924       // Invariant: s chases t chases u.
     3925       // TODO-FIXME: consider changing EntryList from a DLL to a CDLL so
     3926       // we have faster access to the tail.
     3927 
     3928       if (QMode == 1) {
     3929          // QMode == 1 : drain cxq to EntryList, reversing order
     3930          // We also reverse the order of the list.
     3931          ObjectWaiter * s = NULL ;
     3932          ObjectWaiter * t = w ;
     3933          ObjectWaiter * u = NULL ;
     3934          while (t != NULL) {
     3935              guarantee (t->TState == ObjectWaiter::TS_CXQ, "invariant") ;
     3936              t->TState = ObjectWaiter::TS_ENTER ;
     3937              u = t->_next ;
     3938              t->_prev = u ;
     3939              t->_next = s ;
     3940              s = t;
     3941              t = u ;
     3942          }
     3943          _EntryList  = s ;
     3944          assert (s != NULL, "invariant") ;
     3945       } else {
     3946          // QMode == 0 or QMode == 2
     3947          _EntryList = w ;
     3948          ObjectWaiter * q = NULL ;
     3949          ObjectWaiter * p ;
     3950          for (p = w ; p != NULL ; p = p->_next) {
     3951              guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ;
     3952              p->TState = ObjectWaiter::TS_ENTER ;
     3953              p->_prev = q ;
     3954              q = p ;
     3955          }
     3956       }
     3957 
     3958       // In 1-0 mode we need: ST EntryList; MEMBAR #storestore; ST _owner = NULL
     3959       // The MEMBAR is satisfied by the release_store() operation in ExitEpilog().
     3960 
     3961       // See if we can abdicate to a spinner instead of waking a thread.
     3962       // A primary goal of the implementation is to reduce the
     3963       // context-switch rate.
     3964       if (_succ != NULL) continue;
     3965 
     3966       w = _EntryList  ;
     3967       if (w != NULL) {
     3968           guarantee (w->TState == ObjectWaiter::TS_ENTER, "invariant") ;
     3969           ExitEpilog (Self, w) ;
     3970           return ;
     3971       }
     3972    }
     3973 }
     3974 // complete_exit exits a lock returning recursion count
     3975 // complete_exit/reenter operate as a wait without waiting
     3976 // complete_exit requires an inflated monitor
     3977 // The _owner field is not always the Thread addr even with an
     3978 // inflated monitor, e.g. the monitor can be inflated by a non-owning
     3979 // thread due to contention.
     3980 intptr_t ObjectMonitor::complete_exit(TRAPS) {
     3981    Thread * const Self = THREAD;
     3982    assert(Self->is_Java_thread(), "Must be Java thread!");
     3983    JavaThread *jt = (JavaThread *)THREAD;
     3984 
     3985    DeferredInitialize();
     3986 
     3987    if (THREAD != _owner) {
     3988     if (THREAD->is_lock_owned ((address)_owner)) {
     3989        assert(_recursions == 0, "internal state error");
     3990        _owner = THREAD ;   /* Convert from basiclock addr to Thread addr */
     3991        _recursions = 0 ;
     3992        OwnerIsThread = 1 ;
     3993     }
     3994    }
     3995 
     3996    guarantee(Self == _owner, "complete_exit not owner");
     3997    intptr_t save = _recursions; // record the old recursion count
     3998    _recursions = 0;        // set the recursion level to be 0
     3999    exit (Self) ;           // exit the monitor
     4000    guarantee (_owner != Self, "invariant");
     4001    return save;
     4002 }
     4003 
     4004 // reenter() enters a lock and sets recursion count
     4005 // complete_exit/reenter operate as a wait without waiting
     4006 void ObjectMonitor::reenter(intptr_t recursions, TRAPS) {
     4007    Thread * const Self = THREAD;
     4008    assert(Self->is_Java_thread(), "Must be Java thread!");
     4009    JavaThread *jt = (JavaThread *)THREAD;
     4010 
     4011    guarantee(_owner != Self, "reenter already owner");
     4012    enter (THREAD);       // enter the monitor
     4013    guarantee (_recursions == 0, "reenter recursion");
     4014    _recursions = recursions;
     4015    return;
     4016 }
     4017 
     4018 // Note: a subset of changes to ObjectMonitor::wait()
     4019 // will need to be replicated in complete_exit above
     4020 void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) {
     4021    Thread * const Self = THREAD ;
     4022    assert(Self->is_Java_thread(), "Must be Java thread!");
     4023    JavaThread *jt = (JavaThread *)THREAD;
     4024 
     4025    DeferredInitialize () ;
     4026 
     4027    // Throw IMSX or IEX.
     4028    CHECK_OWNER();
     4029 
     4030    // check for a pending interrupt
     4031    if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) {
     4032      // post monitor waited event.  Note that this is past-tense, we are done waiting.
     4033      if (JvmtiExport::should_post_monitor_waited()) {
     4034         // Note: 'false' parameter is passed here because the
     4035         // wait was not timed out due to thread interrupt.
     4036         JvmtiExport::post_monitor_waited(jt, this, false);
     4037      }
     4038      TEVENT (Wait - Throw IEX) ;
     4039      THROW(vmSymbols::java_lang_InterruptedException());
     4040      return ;
     4041    }
     4042    TEVENT (Wait) ;
     4043 
     4044    assert (Self->_Stalled == 0, "invariant") ;
     4045    Self->_Stalled = intptr_t(this) ;
     4046    jt->set_current_waiting_monitor(this);
     4047 
     4048    // create a node to be put into the queue
     4049    // Critically, after we reset() the event but prior to park(), we must check
     4050    // for a pending interrupt.
     4051    ObjectWaiter node(Self);
     4052    node.TState = ObjectWaiter::TS_WAIT ;
     4053    Self->_ParkEvent->reset() ;
     4054    OrderAccess::fence();          // ST into Event; membar ; LD interrupted-flag
     4055 
     4056    // Enter the waiting queue, which is a circular doubly linked list in this case
     4057    // but it could be a priority queue or any data structure.
     4058    // _WaitSetLock protects the wait queue.  Normally the wait queue is accessed only
     4059    // by the the owner of the monitor *except* in the case where park()
     4060    // returns because of a timeout of interrupt.  Contention is exceptionally rare
     4061    // so we use a simple spin-lock instead of a heavier-weight blocking lock.
     4062 
     4063    Thread::SpinAcquire (&_WaitSetLock, "WaitSet - add") ;
     4064    AddWaiter (&node) ;
     4065    Thread::SpinRelease (&_WaitSetLock) ;
     4066 
     4067    if ((SyncFlags & 4) == 0) {
     4068       _Responsible = NULL ;
     4069    }
     4070    intptr_t save = _recursions; // record the old recursion count
     4071    _waiters++;                  // increment the number of waiters
     4072    _recursions = 0;             // set the recursion level to be 1
     4073    exit (Self) ;                    // exit the monitor
     4074    guarantee (_owner != Self, "invariant") ;
     4075 
     4076    // As soon as the ObjectMonitor's ownership is dropped in the exit()
     4077    // call above, another thread can enter() the ObjectMonitor, do the
     4078    // notify(), and exit() the ObjectMonitor. If the other thread's
     4079    // exit() call chooses this thread as the successor and the unpark()
     4080    // call happens to occur while this thread is posting a
     4081    // MONITOR_CONTENDED_EXIT event, then we run the risk of the event
     4082    // handler using RawMonitors and consuming the unpark().
     4083    //
     4084    // To avoid the problem, we re-post the event. This does no harm
     4085    // even if the original unpark() was not consumed because we are the
     4086    // chosen successor for this monitor.
     4087    if (node._notified != 0 && _succ == Self) {
     4088       node._event->unpark();
     4089    }
     4090 
     4091    // The thread is on the WaitSet list - now park() it.
     4092    // On MP systems it's conceivable that a brief spin before we park
     4093    // could be profitable.
     4094    //
     4095    // TODO-FIXME: change the following logic to a loop of the form
     4096    //   while (!timeout && !interrupted && _notified == 0) park()
     4097 
     4098    int ret = OS_OK ;
     4099    int WasNotified = 0 ;
     4100    { // State transition wrappers
     4101      OSThread* osthread = Self->osthread();
     4102      OSThreadWaitState osts(osthread, true);
     4103      {
     4104        ThreadBlockInVM tbivm(jt);
     4105        // Thread is in thread_blocked state and oop access is unsafe.
     4106        jt->set_suspend_equivalent();
     4107 
     4108        if (interruptible && (Thread::is_interrupted(THREAD, false) || HAS_PENDING_EXCEPTION)) {
     4109            // Intentionally empty
     4110        } else
     4111        if (node._notified == 0) {
     4112          if (millis <= 0) {
     4113             Self->_ParkEvent->park () ;
     4114          } else {
     4115             ret = Self->_ParkEvent->park (millis) ;
     4116          }
     4117        }
     4118 
     4119        // were we externally suspended while we were waiting?
     4120        if (ExitSuspendEquivalent (jt)) {
     4121           // TODO-FIXME: add -- if succ == Self then succ = null.
     4122           jt->java_suspend_self();
     4123        }
     4124 
     4125      } // Exit thread safepoint: transition _thread_blocked -> _thread_in_vm
     4126 
     4127 
     4128      // Node may be on the WaitSet, the EntryList (or cxq), or in transition
     4129      // from the WaitSet to the EntryList.
     4130      // See if we need to remove Node from the WaitSet.
     4131      // We use double-checked locking to avoid grabbing _WaitSetLock
     4132      // if the thread is not on the wait queue.
     4133      //
     4134      // Note that we don't need a fence before the fetch of TState.
     4135      // In the worst case we'll fetch a old-stale value of TS_WAIT previously
     4136      // written by the is thread. (perhaps the fetch might even be satisfied
     4137      // by a look-aside into the processor's own store buffer, although given
     4138      // the length of the code path between the prior ST and this load that's
     4139      // highly unlikely).  If the following LD fetches a stale TS_WAIT value
     4140      // then we'll acquire the lock and then re-fetch a fresh TState value.
     4141      // That is, we fail toward safety.
     4142 
     4143      if (node.TState == ObjectWaiter::TS_WAIT) {
     4144          Thread::SpinAcquire (&_WaitSetLock, "WaitSet - unlink") ;
     4145          if (node.TState == ObjectWaiter::TS_WAIT) {
     4146             DequeueSpecificWaiter (&node) ;       // unlink from WaitSet
     4147             assert(node._notified == 0, "invariant");
     4148             node.TState = ObjectWaiter::TS_RUN ;
     4149          }
     4150          Thread::SpinRelease (&_WaitSetLock) ;
     4151      }
     4152 
     4153      // The thread is now either on off-list (TS_RUN),
     4154      // on the EntryList (TS_ENTER), or on the cxq (TS_CXQ).
     4155      // The Node's TState variable is stable from the perspective of this thread.
     4156      // No other threads will asynchronously modify TState.
     4157      guarantee (node.TState != ObjectWaiter::TS_WAIT, "invariant") ;
     4158      OrderAccess::loadload() ;
     4159      if (_succ == Self) _succ = NULL ;
     4160      WasNotified = node._notified ;
     4161 
     4162      // Reentry phase -- reacquire the monitor.
     4163      // re-enter contended monitor after object.wait().
     4164      // retain OBJECT_WAIT state until re-enter successfully completes
     4165      // Thread state is thread_in_vm and oop access is again safe,
     4166      // although the raw address of the object may have changed.
     4167      // (Don't cache naked oops over safepoints, of course).
     4168 
     4169      // post monitor waited event. Note that this is past-tense, we are done waiting.
     4170      if (JvmtiExport::should_post_monitor_waited()) {
     4171        JvmtiExport::post_monitor_waited(jt, this, ret == OS_TIMEOUT);
     4172      }
     4173      OrderAccess::fence() ;
     4174 
     4175      assert (Self->_Stalled != 0, "invariant") ;
     4176      Self->_Stalled = 0 ;
     4177 
     4178      assert (_owner != Self, "invariant") ;
     4179      ObjectWaiter::TStates v = node.TState ;
     4180      if (v == ObjectWaiter::TS_RUN) {
     4181          enter (Self) ;
     4182      } else {
     4183          guarantee (v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant") ;
     4184          ReenterI (Self, &node) ;
     4185          node.wait_reenter_end(this);
     4186      }
     4187 
     4188      // Self has reacquired the lock.
     4189      // Lifecycle - the node representing Self must not appear on any queues.
     4190      // Node is about to go out-of-scope, but even if it were immortal we wouldn't
     4191      // want residual elements associated with this thread left on any lists.
     4192      guarantee (node.TState == ObjectWaiter::TS_RUN, "invariant") ;
     4193      assert    (_owner == Self, "invariant") ;
     4194      assert    (_succ != Self , "invariant") ;
     4195    } // OSThreadWaitState()
     4196 
     4197    jt->set_current_waiting_monitor(NULL);
     4198 
     4199    guarantee (_recursions == 0, "invariant") ;
     4200    _recursions = save;     // restore the old recursion count
     4201    _waiters--;             // decrement the number of waiters
     4202 
     4203    // Verify a few postconditions
     4204    assert (_owner == Self       , "invariant") ;
     4205    assert (_succ  != Self       , "invariant") ;
     4206    assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;
     4207 
     4208    if (SyncFlags & 32) {
     4209       OrderAccess::fence() ;
     4210    }
     4211 
     4212    // check if the notification happened
     4213    if (!WasNotified) {
     4214      // no, it could be timeout or Thread.interrupt() or both
     4215      // check for interrupt event, otherwise it is timeout
     4216      if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) {
     4217        TEVENT (Wait - throw IEX from epilog) ;
     4218        THROW(vmSymbols::java_lang_InterruptedException());
     4219      }
     4220    }
     4221 
     4222    // NOTE: Spurious wake up will be consider as timeout.
     4223    // Monitor notify has precedence over thread interrupt.
     4224 }
     4225 
     4226 
     4227 // Consider:
     4228 // If the lock is cool (cxq == null && succ == null) and we're on an MP system
     4229 // then instead of transferring a thread from the WaitSet to the EntryList
     4230 // we might just dequeue a thread from the WaitSet and directly unpark() it.
     4231 
     4232 void ObjectMonitor::notify(TRAPS) {
     4233   CHECK_OWNER();
     4234   if (_WaitSet == NULL) {
     4235      TEVENT (Empty-Notify) ;
     4236      return ;
     4237   }
     4238   DTRACE_MONITOR_PROBE(notify, this, object(), THREAD);
     4239 
     4240   int Policy = Knob_MoveNotifyee ;
     4241 
     4242   Thread::SpinAcquire (&_WaitSetLock, "WaitSet - notify") ;
     4243   ObjectWaiter * iterator = DequeueWaiter() ;
     4244   if (iterator != NULL) {
     4245      TEVENT (Notify1 - Transfer) ;
     4246      guarantee (iterator->TState == ObjectWaiter::TS_WAIT, "invariant") ;
     4247      guarantee (iterator->_notified == 0, "invariant") ;
     4248      // Disposition - what might we do with iterator ?
     4249      // a.  add it directly to the EntryList - either tail or head.
     4250      // b.  push it onto the front of the _cxq.
     4251      // For now we use (a).
     4252      if (Policy != 4) {
     4253         iterator->TState = ObjectWaiter::TS_ENTER ;
     4254      }
     4255      iterator->_notified = 1 ;
     4256 
     4257      ObjectWaiter * List = _EntryList ;
     4258      if (List != NULL) {
     4259         assert (List->_prev == NULL, "invariant") ;
     4260         assert (List->TState == ObjectWaiter::TS_ENTER, "invariant") ;
     4261         assert (List != iterator, "invariant") ;
     4262      }
     4263 
     4264      if (Policy == 0) {       // prepend to EntryList
     4265          if (List == NULL) {
     4266              iterator->_next = iterator->_prev = NULL ;
     4267              _EntryList = iterator ;
     4268          } else {
     4269              List->_prev = iterator ;
     4270              iterator->_next = List ;
     4271              iterator->_prev = NULL ;
     4272              _EntryList = iterator ;
     4273         }
     4274      } else
     4275      if (Policy == 1) {      // append to EntryList
     4276          if (List == NULL) {
     4277              iterator->_next = iterator->_prev = NULL ;
     4278              _EntryList = iterator ;
     4279          } else {
     4280             // CONSIDER:  finding the tail currently requires a linear-time walk of
     4281             // the EntryList.  We can make tail access constant-time by converting to
     4282             // a CDLL instead of using our current DLL.
     4283             ObjectWaiter * Tail ;
     4284             for (Tail = List ; Tail->_next != NULL ; Tail = Tail->_next) ;
     4285             assert (Tail != NULL && Tail->_next == NULL, "invariant") ;
     4286             Tail->_next = iterator ;
     4287             iterator->_prev = Tail ;
     4288             iterator->_next = NULL ;
     4289         }
     4290      } else
     4291      if (Policy == 2) {      // prepend to cxq
     4292          // prepend to cxq
     4293          if (List == NULL) {
     4294              iterator->_next = iterator->_prev = NULL ;
     4295              _EntryList = iterator ;
     4296          } else {
     4297             iterator->TState = ObjectWaiter::TS_CXQ ;
     4298             for (;;) {
     4299                 ObjectWaiter * Front = _cxq ;
     4300                 iterator->_next = Front ;
     4301                 if (Atomic::cmpxchg_ptr (iterator, &_cxq, Front) == Front) {
     4302                     break ;
     4303                 }
     4304             }
     4305          }
     4306      } else
     4307      if (Policy == 3) {      // append to cxq
     4308         iterator->TState = ObjectWaiter::TS_CXQ ;
     4309         for (;;) {
     4310             ObjectWaiter * Tail ;
     4311             Tail = _cxq ;
     4312             if (Tail == NULL) {
     4313                 iterator->_next = NULL ;
     4314                 if (Atomic::cmpxchg_ptr (iterator, &_cxq, NULL) == NULL) {
     4315                    break ;
     4316                 }
     4317             } else {
     4318                 while (Tail->_next != NULL) Tail = Tail->_next ;
     4319                 Tail->_next = iterator ;
     4320                 iterator->_prev = Tail ;
     4321                 iterator->_next = NULL ;
     4322                 break ;
     4323             }
     4324         }
     4325      } else {
     4326         ParkEvent * ev = iterator->_event ;
     4327         iterator->TState = ObjectWaiter::TS_RUN ;
     4328         OrderAccess::fence() ;
     4329         ev->unpark() ;
     4330      }
     4331 
     4332      if (Policy < 4) {
     4333        iterator->wait_reenter_begin(this);
     4334      }
     4335 
     4336      // _WaitSetLock protects the wait queue, not the EntryList.  We could
     4337      // move the add-to-EntryList operation, above, outside the critical section
     4338      // protected by _WaitSetLock.  In practice that's not useful.  With the
     4339      // exception of  wait() timeouts and interrupts the monitor owner
     4340      // is the only thread that grabs _WaitSetLock.  There's almost no contention
     4341      // on _WaitSetLock so it's not profitable to reduce the length of the
     4342      // critical section.
     4343   }
     4344 
     4345   Thread::SpinRelease (&_WaitSetLock) ;
     4346 
     4347   if (iterator != NULL && ObjectSynchronizer::_sync_Notifications != NULL) {
     4348      ObjectSynchronizer::_sync_Notifications->inc() ;
     4349   }
     4350 }
     4351 
     4352 
     4353 void ObjectMonitor::notifyAll(TRAPS) {
     4354   CHECK_OWNER();
     4355   ObjectWaiter* iterator;
     4356   if (_WaitSet == NULL) {
     4357       TEVENT (Empty-NotifyAll) ;
     4358       return ;
     4359   }
     4360   DTRACE_MONITOR_PROBE(notifyAll, this, object(), THREAD);
     4361 
     4362   int Policy = Knob_MoveNotifyee ;
     4363   int Tally = 0 ;
     4364   Thread::SpinAcquire (&_WaitSetLock, "WaitSet - notifyall") ;
     4365 
     4366   for (;;) {
     4367      iterator = DequeueWaiter () ;
     4368      if (iterator == NULL) break ;
     4369      TEVENT (NotifyAll - Transfer1) ;
     4370      ++Tally ;
     4371 
     4372      // Disposition - what might we do with iterator ?
     4373      // a.  add it directly to the EntryList - either tail or head.
     4374      // b.  push it onto the front of the _cxq.
     4375      // For now we use (a).
     4376      //
     4377      // TODO-FIXME: currently notifyAll() transfers the waiters one-at-a-time from the waitset
     4378      // to the EntryList.  This could be done more efficiently with a single bulk transfer,
     4379      // but in practice it's not time-critical.  Beware too, that in prepend-mode we invert the
     4380      // order of the waiters.  Lets say that the waitset is "ABCD" and the EntryList is "XYZ".
     4381      // After a notifyAll() in prepend mode the waitset will be empty and the EntryList will
     4382      // be "DCBAXYZ".
     4383 
     4384      guarantee (iterator->TState == ObjectWaiter::TS_WAIT, "invariant") ;
     4385      guarantee (iterator->_notified == 0, "invariant") ;
     4386      iterator->_notified = 1 ;
     4387      if (Policy != 4) {
     4388         iterator->TState = ObjectWaiter::TS_ENTER ;
     4389      }
     4390 
     4391      ObjectWaiter * List = _EntryList ;
     4392      if (List != NULL) {
     4393         assert (List->_prev == NULL, "invariant") ;
     4394         assert (List->TState == ObjectWaiter::TS_ENTER, "invariant") ;
     4395         assert (List != iterator, "invariant") ;
     4396      }
     4397 
     4398      if (Policy == 0) {       // prepend to EntryList
     4399          if (List == NULL) {
     4400              iterator->_next = iterator->_prev = NULL ;
     4401              _EntryList = iterator ;
     4402          } else {
     4403              List->_prev = iterator ;
     4404              iterator->_next = List ;
     4405              iterator->_prev = NULL ;
     4406              _EntryList = iterator ;
     4407         }
     4408      } else
     4409      if (Policy == 1) {      // append to EntryList
     4410          if (List == NULL) {
     4411              iterator->_next = iterator->_prev = NULL ;
     4412              _EntryList = iterator ;
     4413          } else {
     4414             // CONSIDER:  finding the tail currently requires a linear-time walk of
     4415             // the EntryList.  We can make tail access constant-time by converting to
     4416             // a CDLL instead of using our current DLL.
     4417             ObjectWaiter * Tail ;
     4418             for (Tail = List ; Tail->_next != NULL ; Tail = Tail->_next) ;
     4419             assert (Tail != NULL && Tail->_next == NULL, "invariant") ;
     4420             Tail->_next = iterator ;
     4421             iterator->_prev = Tail ;
     4422             iterator->_next = NULL ;
     4423         }
     4424      } else
     4425      if (Policy == 2) {      // prepend to cxq
     4426          // prepend to cxq
     4427          iterator->TState = ObjectWaiter::TS_CXQ ;
     4428          for (;;) {
     4429              ObjectWaiter * Front = _cxq ;
     4430              iterator->_next = Front ;
     4431              if (Atomic::cmpxchg_ptr (iterator, &_cxq, Front) == Front) {
     4432                  break ;
     4433              }
     4434          }
     4435      } else
     4436      if (Policy == 3) {      // append to cxq
     4437         iterator->TState = ObjectWaiter::TS_CXQ ;
     4438         for (;;) {
     4439             ObjectWaiter * Tail ;
     4440             Tail = _cxq ;
     4441             if (Tail == NULL) {
     4442                 iterator->_next = NULL ;
     4443                 if (Atomic::cmpxchg_ptr (iterator, &_cxq, NULL) == NULL) {
     4444                    break ;
     4445                 }
     4446             } else {
     4447                 while (Tail->_next != NULL) Tail = Tail->_next ;
     4448                 Tail->_next = iterator ;
     4449                 iterator->_prev = Tail ;
     4450                 iterator->_next = NULL ;
     4451                 break ;
     4452             }
     4453         }
     4454      } else {
     4455         ParkEvent * ev = iterator->_event ;
     4456         iterator->TState = ObjectWaiter::TS_RUN ;
     4457         OrderAccess::fence() ;
     4458         ev->unpark() ;
     4459      }
     4460 
     4461      if (Policy < 4) {
     4462        iterator->wait_reenter_begin(this);
     4463      }
     4464 
     4465      // _WaitSetLock protects the wait queue, not the EntryList.  We could
     4466      // move the add-to-EntryList operation, above, outside the critical section
     4467      // protected by _WaitSetLock.  In practice that's not useful.  With the
     4468      // exception of  wait() timeouts and interrupts the monitor owner
     4469      // is the only thread that grabs _WaitSetLock.  There's almost no contention
     4470      // on _WaitSetLock so it's not profitable to reduce the length of the
     4471      // critical section.
     4472   }
     4473 
     4474   Thread::SpinRelease (&_WaitSetLock) ;
     4475 
     4476   if (Tally != 0 && ObjectSynchronizer::_sync_Notifications != NULL) {
     4477      ObjectSynchronizer::_sync_Notifications->inc(Tally) ;
     4478   }
     4479 }
     4480 
     4481 // check_slow() is a misnomer.  It's called to simply to throw an IMSX exception.
     4482 // TODO-FIXME: remove check_slow() -- it's likely dead.
     4483 
     4484 void ObjectMonitor::check_slow(TRAPS) {
     4485   TEVENT (check_slow - throw IMSX) ;
     4486   assert(THREAD != _owner && !THREAD->is_lock_owned((address) _owner), "must not be owner");
     4487   THROW_MSG(vmSymbols::java_lang_IllegalMonitorStateException(), "current thread not owner");
     4488 }
     4489 
     4490 
     4491 // -------------------------------------------------------------------------
     4492 // The raw monitor subsystem is entirely distinct from normal
     4493 // java-synchronization or jni-synchronization.  raw monitors are not
     4494 // associated with objects.  They can be implemented in any manner
     4495 // that makes sense.  The original implementors decided to piggy-back
     4496 // the raw-monitor implementation on the existing Java objectMonitor mechanism.
     4497 // This flaw needs to fixed.  We should reimplement raw monitors as sui-generis.
     4498 // Specifically, we should not implement raw monitors via java monitors.
     4499 // Time permitting, we should disentangle and deconvolve the two implementations
     4500 // and move the resulting raw monitor implementation over to the JVMTI directories.
     4501 // Ideally, the raw monitor implementation would be built on top of
     4502 // park-unpark and nothing else.
     4503 //
     4504 // raw monitors are used mainly by JVMTI
     4505 // The raw monitor implementation borrows the ObjectMonitor structure,
     4506 // but the operators are degenerate and extremely simple.
     4507 //
     4508 // Mixed use of a single objectMonitor instance -- as both a raw monitor
     4509 // and a normal java monitor -- is not permissible.
     4510 //
     4511 // Note that we use the single RawMonitor_lock to protect queue operations for
     4512 // _all_ raw monitors.  This is a scalability impediment, but since raw monitor usage
     4513 // is deprecated and rare, this is not of concern.  The RawMonitor_lock can not
     4514 // be held indefinitely.  The critical sections must be short and bounded.
     4515 //
     4516 // -------------------------------------------------------------------------
     4517 
     4518 int ObjectMonitor::SimpleEnter (Thread * Self) {
     4519   for (;;) {
     4520     if (Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) {
     4521        return OS_OK ;
     4522     }
     4523 
     4524     ObjectWaiter Node (Self) ;
     4525     Self->_ParkEvent->reset() ;     // strictly optional
     4526     Node.TState = ObjectWaiter::TS_ENTER ;
     4527 
     4528     RawMonitor_lock->lock_without_safepoint_check() ;
     4529     Node._next  = _EntryList ;
     4530     _EntryList  = &Node ;
     4531     OrderAccess::fence() ;
     4532     if (_owner == NULL && Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) {
     4533         _EntryList = Node._next ;
     4534         RawMonitor_lock->unlock() ;
     4535         return OS_OK ;
     4536     }
     4537     RawMonitor_lock->unlock() ;
     4538     while (Node.TState == ObjectWaiter::TS_ENTER) {
     4539        Self->_ParkEvent->park() ;
     4540     }
     4541   }
     4542 }
     4543 
     4544 int ObjectMonitor::SimpleExit (Thread * Self) {
     4545   guarantee (_owner == Self, "invariant") ;
     4546   OrderAccess::release_store_ptr (&_owner, NULL) ;
     4547   OrderAccess::fence() ;
     4548   if (_EntryList == NULL) return OS_OK ;
     4549   ObjectWaiter * w ;
     4550 
     4551   RawMonitor_lock->lock_without_safepoint_check() ;
     4552   w = _EntryList ;
     4553   if (w != NULL) {
     4554       _EntryList = w->_next ;
     4555   }
     4556   RawMonitor_lock->unlock() ;
     4557   if (w != NULL) {
     4558       guarantee (w ->TState == ObjectWaiter::TS_ENTER, "invariant") ;
     4559       ParkEvent * ev = w->_event ;
     4560       w->TState = ObjectWaiter::TS_RUN ;
     4561       OrderAccess::fence() ;
     4562       ev->unpark() ;
     4563   }
     4564   return OS_OK ;
     4565 }
     4566 
     4567 int ObjectMonitor::SimpleWait (Thread * Self, jlong millis) {
     4568   guarantee (_owner == Self  , "invariant") ;
     4569   guarantee (_recursions == 0, "invariant") ;
     4570 
     4571   ObjectWaiter Node (Self) ;
     4572   Node._notified = 0 ;
     4573   Node.TState    = ObjectWaiter::TS_WAIT ;
     4574 
     4575   RawMonitor_lock->lock_without_safepoint_check() ;
     4576   Node._next     = _WaitSet ;
     4577   _WaitSet       = &Node ;
     4578   RawMonitor_lock->unlock() ;
     4579 
     4580   SimpleExit (Self) ;
     4581   guarantee (_owner != Self, "invariant") ;
     4582 
     4583   int ret = OS_OK ;
     4584   if (millis <= 0) {
     4585     Self->_ParkEvent->park();
     4586   } else {
     4587     ret = Self->_ParkEvent->park(millis);
     4588   }
     4589 
     4590   // If thread still resides on the waitset then unlink it.
     4591   // Double-checked locking -- the usage is safe in this context
     4592   // as we TState is volatile and the lock-unlock operators are
     4593   // serializing (barrier-equivalent).
     4594 
     4595   if (Node.TState == ObjectWaiter::TS_WAIT) {
     4596     RawMonitor_lock->lock_without_safepoint_check() ;
     4597     if (Node.TState == ObjectWaiter::TS_WAIT) {
     4598       // Simple O(n) unlink, but performance isn't critical here.
     4599       ObjectWaiter * p ;
     4600       ObjectWaiter * q = NULL ;
     4601       for (p = _WaitSet ; p != &Node; p = p->_next) {
     4602          q = p ;
     4603       }
     4604       guarantee (p == &Node, "invariant") ;
     4605       if (q == NULL) {
     4606         guarantee (p == _WaitSet, "invariant") ;
     4607         _WaitSet = p->_next ;
     4608       } else {
     4609         guarantee (p == q->_next, "invariant") ;
     4610         q->_next = p->_next ;
     4611       }
     4612       Node.TState = ObjectWaiter::TS_RUN ;
     4613     }
     4614     RawMonitor_lock->unlock() ;
     4615   }
     4616 
     4617   guarantee (Node.TState == ObjectWaiter::TS_RUN, "invariant") ;
     4618   SimpleEnter (Self) ;
     4619 
     4620   guarantee (_owner == Self, "invariant") ;
     4621   guarantee (_recursions == 0, "invariant") ;
     4622   return ret ;
     4623 }
     4624 
     4625 int ObjectMonitor::SimpleNotify (Thread * Self, bool All) {
     4626   guarantee (_owner == Self, "invariant") ;
     4627   if (_WaitSet == NULL) return OS_OK ;
     4628 
     4629   // We have two options:
     4630   // A. Transfer the threads from the WaitSet to the EntryList
     4631   // B. Remove the thread from the WaitSet and unpark() it.
     4632   //
     4633   // We use (B), which is crude and results in lots of futile
     4634   // context switching.  In particular (B) induces lots of contention.
     4635 
     4636   ParkEvent * ev = NULL ;       // consider using a small auto array ...
     4637   RawMonitor_lock->lock_without_safepoint_check() ;
     4638   for (;;) {
     4639       ObjectWaiter * w = _WaitSet ;
     4640       if (w == NULL) break ;
     4641       _WaitSet = w->_next ;
     4642       if (ev != NULL) { ev->unpark(); ev = NULL; }
     4643       ev = w->_event ;
     4644       OrderAccess::loadstore() ;
     4645       w->TState = ObjectWaiter::TS_RUN ;
     4646       OrderAccess::storeload();
     4647       if (!All) break ;
     4648   }
     4649   RawMonitor_lock->unlock() ;
     4650   if (ev != NULL) ev->unpark();
     4651   return OS_OK ;
     4652 }
     4653 
     4654 // Any JavaThread will enter here with state _thread_blocked
     4655 int ObjectMonitor::raw_enter(TRAPS) {
     4656   TEVENT (raw_enter) ;
     4657   void * Contended ;
     4658 
     4659   // don't enter raw monitor if thread is being externally suspended, it will
     4660   // surprise the suspender if a "suspended" thread can still enter monitor
     4661   JavaThread * jt = (JavaThread *)THREAD;
     4662   if (THREAD->is_Java_thread()) {
     4663     jt->SR_lock()->lock_without_safepoint_check();
     4664     while (jt->is_external_suspend()) {
     4665       jt->SR_lock()->unlock();
     4666       jt->java_suspend_self();
     4667       jt->SR_lock()->lock_without_safepoint_check();
     4668     }
     4669     // guarded by SR_lock to avoid racing with new external suspend requests.
     4670     Contended = Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) ;
     4671     jt->SR_lock()->unlock();
     4672   } else {
     4673     Contended = Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) ;
     4674   }
     4675 
     4676   if (Contended == THREAD) {
     4677      _recursions ++ ;
     4678      return OM_OK ;
     4679   }
     4680 
     4681   if (Contended == NULL) {
     4682      guarantee (_owner == THREAD, "invariant") ;
     4683      guarantee (_recursions == 0, "invariant") ;
     4684      return OM_OK ;
     4685   }
     4686 
     4687   THREAD->set_current_pending_monitor(this);
     4688 
     4689   if (!THREAD->is_Java_thread()) {
     4690      // No other non-Java threads besides VM thread would acquire
     4691      // a raw monitor.
     4692      assert(THREAD->is_VM_thread(), "must be VM thread");
     4693      SimpleEnter (THREAD) ;
     4694    } else {
     4695      guarantee (jt->thread_state() == _thread_blocked, "invariant") ;
     4696      for (;;) {
     4697        jt->set_suspend_equivalent();
     4698        // cleared by handle_special_suspend_equivalent_condition() or
     4699        // java_suspend_self()
     4700        SimpleEnter (THREAD) ;
     4701 
     4702        // were we externally suspended while we were waiting?
     4703        if (!jt->handle_special_suspend_equivalent_condition()) break ;
     4704 
     4705        // This thread was externally suspended
     4706        //
     4707        // This logic isn't needed for JVMTI raw monitors,
     4708        // but doesn't hurt just in case the suspend rules change. This
     4709            // logic is needed for the ObjectMonitor.wait() reentry phase.
     4710            // We have reentered the contended monitor, but while we were
     4711            // waiting another thread suspended us. We don't want to reenter
     4712            // the monitor while suspended because that would surprise the
     4713            // thread that suspended us.
     4714            //
     4715            // Drop the lock -
     4716        SimpleExit (THREAD) ;
     4717 
     4718            jt->java_suspend_self();
     4719          }
     4720 
     4721      assert(_owner == THREAD, "Fatal error with monitor owner!");
     4722      assert(_recursions == 0, "Fatal error with monitor recursions!");
     4723   }
     4724 
     4725   THREAD->set_current_pending_monitor(NULL);
     4726   guarantee (_recursions == 0, "invariant") ;
     4727   return OM_OK;
     4728 }
     4729 
     4730 // Used mainly for JVMTI raw monitor implementation
     4731 // Also used for ObjectMonitor::wait().
     4732 int ObjectMonitor::raw_exit(TRAPS) {
     4733   TEVENT (raw_exit) ;
     4734   if (THREAD != _owner) {
     4735     return OM_ILLEGAL_MONITOR_STATE;
     4736   }
     4737   if (_recursions > 0) {
     4738     --_recursions ;
     4739     return OM_OK ;
     4740   }
     4741 
     4742   void * List = _EntryList ;
     4743   SimpleExit (THREAD) ;
     4744 
     4745   return OM_OK;
     4746 }
     4747 
     4748 // Used for JVMTI raw monitor implementation.
     4749 // All JavaThreads will enter here with state _thread_blocked
     4750 
     4751 int ObjectMonitor::raw_wait(jlong millis, bool interruptible, TRAPS) {
     4752   TEVENT (raw_wait) ;
     4753   if (THREAD != _owner) {
     4754     return OM_ILLEGAL_MONITOR_STATE;
     4755   }
     4756 
     4757   // To avoid spurious wakeups we reset the parkevent -- This is strictly optional.
     4758   // The caller must be able to tolerate spurious returns from raw_wait().
     4759   THREAD->_ParkEvent->reset() ;
     4760   OrderAccess::fence() ;
     4761 
     4762   // check interrupt event
     4763   if (interruptible && Thread::is_interrupted(THREAD, true)) {
     4764     return OM_INTERRUPTED;
     4765   }
     4766 
     4767   intptr_t save = _recursions ;
     4768   _recursions = 0 ;
     4769   _waiters ++ ;
     4770   if (THREAD->is_Java_thread()) {
     4771     guarantee (((JavaThread *) THREAD)->thread_state() == _thread_blocked, "invariant") ;
     4772     ((JavaThread *)THREAD)->set_suspend_equivalent();
     4773   }
     4774   int rv = SimpleWait (THREAD, millis) ;
     4775   _recursions = save ;
     4776   _waiters -- ;
     4777 
     4778   guarantee (THREAD == _owner, "invariant") ;
     4779   if (THREAD->is_Java_thread()) {
     4780      JavaThread * jSelf = (JavaThread *) THREAD ;
     4781      for (;;) {
     4782         if (!jSelf->handle_special_suspend_equivalent_condition()) break ;
     4783         SimpleExit (THREAD) ;
     4784         jSelf->java_suspend_self();
     4785         SimpleEnter (THREAD) ;
     4786         jSelf->set_suspend_equivalent() ;
     4787      }
     4788   }
     4789   guarantee (THREAD == _owner, "invariant") ;
     4790 
     4791   if (interruptible && Thread::is_interrupted(THREAD, true)) {
     4792     return OM_INTERRUPTED;
     4793   }
     4794   return OM_OK ;
     4795 }
     4796 
     4797 int ObjectMonitor::raw_notify(TRAPS) {
     4798   TEVENT (raw_notify) ;
     4799   if (THREAD != _owner) {
     4800     return OM_ILLEGAL_MONITOR_STATE;
     4801   }
     4802   SimpleNotify (THREAD, false) ;
     4803   return OM_OK;
     4804 }
     4805 
     4806 int ObjectMonitor::raw_notifyAll(TRAPS) {
     4807   TEVENT (raw_notifyAll) ;
     4808   if (THREAD != _owner) {
     4809     return OM_ILLEGAL_MONITOR_STATE;
     4810   }
     4811   SimpleNotify (THREAD, true) ;
     4812   return OM_OK;
     4813 }
     4814 
     4815 #ifndef PRODUCT
     4816 void ObjectMonitor::verify() {
     4817 }
     4818 
     4819 void ObjectMonitor::print() {
     4820 }
     4821 #endif
     4822 
     4823 //------------------------------------------------------------------------------
     4824 // Non-product code
     4825 
     4826 #ifndef PRODUCT
     4827 
     4828 void ObjectSynchronizer::trace_locking(Handle locking_obj, bool is_compiled,
     4829                                        bool is_method, bool is_locking) {
     4830   // Don't know what to do here
     4831 }
     4832 
     4833 // Verify all monitors in the monitor cache, the verification is weak.
     4834 void ObjectSynchronizer::verify() {
     4835   ObjectMonitor* block = gBlockList;
     4836   ObjectMonitor* mid;
     4837   while (block) {
     4838     assert(block->object() == CHAINMARKER, "must be a block header");
     4839     for (int i = 1; i < _BLOCKSIZE; i++) {
     4840       mid = block + i;
     4841       oop object = (oop) mid->object();
     4842       if (object != NULL) {
     4843         mid->verify();
     4844       }
     4845     }
     4846     block = (ObjectMonitor*) block->FreeNext;
     4847   }
     4848 }
     4849 
     4850 // Check if monitor belongs to the monitor cache
     4851 // The list is grow-only so it's *relatively* safe to traverse
     4852 // the list of extant blocks without taking a lock.
     4853 
     4854 int ObjectSynchronizer::verify_objmon_isinpool(ObjectMonitor *monitor) {
     4855   ObjectMonitor* block = gBlockList;
     4856 
     4857   while (block) {
     4858     assert(block->object() == CHAINMARKER, "must be a block header");
     4859     if (monitor > &block[0] && monitor < &block[_BLOCKSIZE]) {
     4860       address mon = (address) monitor;
     4861       address blk = (address) block;
     4862       size_t diff = mon - blk;
     4863       assert((diff % sizeof(ObjectMonitor)) == 0, "check");
     4864       return 1;
     4865     }
     4866     block = (ObjectMonitor*) block->FreeNext;
     4867   }
     4868   return 0;
     4869 }
     4870 
     4871 #endif