1 /*
   2  * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/vmSymbols.hpp"
  27 #include "memory/resourceArea.hpp"
  28 #include "oops/markOop.hpp"
  29 #include "oops/oop.inline.hpp"
  30 #include "runtime/atomic.hpp"
  31 #include "runtime/handles.inline.hpp"
  32 #include "runtime/interfaceSupport.hpp"
  33 #include "runtime/mutexLocker.hpp"
  34 #include "runtime/objectMonitor.hpp"
  35 #include "runtime/objectMonitor.inline.hpp"
  36 #include "runtime/orderAccess.inline.hpp"
  37 #include "runtime/osThread.hpp"
  38 #include "runtime/stubRoutines.hpp"
  39 #include "runtime/thread.inline.hpp"
  40 #include "services/threadService.hpp"
  41 #include "trace/tracing.hpp"
  42 #include "trace/traceMacros.hpp"
  43 #include "utilities/dtrace.hpp"
  44 #include "utilities/macros.hpp"
  45 #include "utilities/preserveException.hpp"
  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 
  53 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread)                           \
  54   char* bytes = NULL;                                                      \
  55   int len = 0;                                                             \
  56   jlong jtid = SharedRuntime::get_java_tid(thread);                        \
  57   Symbol* klassname = ((oop)obj)->klass()->name();                         \
  58   if (klassname != NULL) {                                                 \
  59     bytes = (char*)klassname->bytes();                                     \
  60     len = klassname->utf8_length();                                        \
  61   }
  62 
  63 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis)            \
  64   {                                                                        \
  65     if (DTraceMonitorProbes) {                                             \
  66       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
  67       HOTSPOT_MONITOR_WAIT(jtid,                                           \
  68                            (monitor), bytes, len, (millis));               \
  69     }                                                                      \
  70   }
  71 
  72 #define HOTSPOT_MONITOR_contended__enter HOTSPOT_MONITOR_CONTENDED_ENTER
  73 #define HOTSPOT_MONITOR_contended__entered HOTSPOT_MONITOR_CONTENDED_ENTERED
  74 #define HOTSPOT_MONITOR_contended__exit HOTSPOT_MONITOR_CONTENDED_EXIT
  75 #define HOTSPOT_MONITOR_notify HOTSPOT_MONITOR_NOTIFY
  76 #define HOTSPOT_MONITOR_notifyAll HOTSPOT_MONITOR_NOTIFYALL
  77 
  78 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread)                  \
  79   {                                                                        \
  80     if (DTraceMonitorProbes) {                                             \
  81       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
  82       HOTSPOT_MONITOR_##probe(jtid,                                        \
  83                               (uintptr_t)(monitor), bytes, len);           \
  84     }                                                                      \
  85   }
  86 
  87 #else //  ndef DTRACE_ENABLED
  88 
  89 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon)    {;}
  90 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon)          {;}
  91 
  92 #endif // ndef DTRACE_ENABLED
  93 
  94 // Tunables ...
  95 // The knob* variables are effectively final.  Once set they should
  96 // never be modified hence.  Consider using __read_mostly with GCC.
  97 
  98 int ObjectMonitor::Knob_ExitRelease = 0;
  99 int ObjectMonitor::Knob_Verbose     = 0;
 100 int ObjectMonitor::Knob_VerifyInUse = 0;
 101 int ObjectMonitor::Knob_VerifyMatch = 0;
 102 int ObjectMonitor::Knob_SpinLimit   = 5000;    // derived by an external tool -
 103 static int Knob_LogSpins            = 0;       // enable jvmstat tally for spins
 104 static int Knob_HandOff             = 0;
 105 static int Knob_ReportSettings      = 0;
 106 
 107 static int Knob_SpinBase            = 0;       // Floor AKA SpinMin
 108 static int Knob_SpinBackOff         = 0;       // spin-loop backoff
 109 static int Knob_CASPenalty          = -1;      // Penalty for failed CAS
 110 static int Knob_OXPenalty           = -1;      // Penalty for observed _owner change
 111 static int Knob_SpinSetSucc         = 1;       // spinners set the _succ field
 112 static int Knob_SpinEarly           = 1;
 113 static int Knob_SuccEnabled         = 1;       // futile wake throttling
 114 static int Knob_SuccRestrict        = 0;       // Limit successors + spinners to at-most-one
 115 static int Knob_MaxSpinners         = -1;      // Should be a function of # CPUs
 116 static int Knob_Bonus               = 100;     // spin success bonus
 117 static int Knob_BonusB              = 100;     // spin success bonus
 118 static int Knob_Penalty             = 200;     // spin failure penalty
 119 static int Knob_Poverty             = 1000;
 120 static int Knob_SpinAfterFutile     = 1;       // Spin after returning from park()
 121 static int Knob_FixedSpin           = 0;
 122 static int Knob_OState              = 3;       // Spinner checks thread state of _owner
 123 static int Knob_UsePause            = 1;
 124 static int Knob_ExitPolicy          = 0;
 125 static int Knob_PreSpin             = 10;      // 20-100 likely better
 126 static int Knob_ResetEvent          = 0;
 127 static int BackOffMask              = 0;
 128 
 129 static int Knob_FastHSSEC           = 0;
 130 static int Knob_MoveNotifyee        = 2;       // notify() - disposition of notifyee
 131 static int Knob_QMode               = 0;       // EntryList-cxq policy - queue discipline
 132 static volatile int InitDone        = 0;
 133 
 134 // -----------------------------------------------------------------------------
 135 // Theory of operations -- Monitors lists, thread residency, etc:
 136 //
 137 // * A thread acquires ownership of a monitor by successfully
 138 //   CAS()ing the _owner field from null to non-null.
 139 //
 140 // * Invariant: A thread appears on at most one monitor list --
 141 //   cxq, EntryList or WaitSet -- at any one time.
 142 //
 143 // * Contending threads "push" themselves onto the cxq with CAS
 144 //   and then spin/park.
 145 //
 146 // * After a contending thread eventually acquires the lock it must
 147 //   dequeue itself from either the EntryList or the cxq.
 148 //
 149 // * The exiting thread identifies and unparks an "heir presumptive"
 150 //   tentative successor thread on the EntryList.  Critically, the
 151 //   exiting thread doesn't unlink the successor thread from the EntryList.
 152 //   After having been unparked, the wakee will recontend for ownership of
 153 //   the monitor.   The successor (wakee) will either acquire the lock or
 154 //   re-park itself.
 155 //
 156 //   Succession is provided for by a policy of competitive handoff.
 157 //   The exiting thread does _not_ grant or pass ownership to the
 158 //   successor thread.  (This is also referred to as "handoff" succession").
 159 //   Instead the exiting thread releases ownership and possibly wakes
 160 //   a successor, so the successor can (re)compete for ownership of the lock.
 161 //   If the EntryList is empty but the cxq is populated the exiting
 162 //   thread will drain the cxq into the EntryList.  It does so by
 163 //   by detaching the cxq (installing null with CAS) and folding
 164 //   the threads from the cxq into the EntryList.  The EntryList is
 165 //   doubly linked, while the cxq is singly linked because of the
 166 //   CAS-based "push" used to enqueue recently arrived threads (RATs).
 167 //
 168 // * Concurrency invariants:
 169 //
 170 //   -- only the monitor owner may access or mutate the EntryList.
 171 //      The mutex property of the monitor itself protects the EntryList
 172 //      from concurrent interference.
 173 //   -- Only the monitor owner may detach the cxq.
 174 //
 175 // * The monitor entry list operations avoid locks, but strictly speaking
 176 //   they're not lock-free.  Enter is lock-free, exit is not.
 177 //   For a description of 'Methods and apparatus providing non-blocking access
 178 //   to a resource,' see U.S. Pat. No. 7844973.
 179 //
 180 // * The cxq can have multiple concurrent "pushers" but only one concurrent
 181 //   detaching thread.  This mechanism is immune from the ABA corruption.
 182 //   More precisely, the CAS-based "push" onto cxq is ABA-oblivious.
 183 //
 184 // * Taken together, the cxq and the EntryList constitute or form a
 185 //   single logical queue of threads stalled trying to acquire the lock.
 186 //   We use two distinct lists to improve the odds of a constant-time
 187 //   dequeue operation after acquisition (in the ::enter() epilogue) and
 188 //   to reduce heat on the list ends.  (c.f. Michael Scott's "2Q" algorithm).
 189 //   A key desideratum is to minimize queue & monitor metadata manipulation
 190 //   that occurs while holding the monitor lock -- that is, we want to
 191 //   minimize monitor lock holds times.  Note that even a small amount of
 192 //   fixed spinning will greatly reduce the # of enqueue-dequeue operations
 193 //   on EntryList|cxq.  That is, spinning relieves contention on the "inner"
 194 //   locks and monitor metadata.
 195 //
 196 //   Cxq points to the set of Recently Arrived Threads attempting entry.
 197 //   Because we push threads onto _cxq with CAS, the RATs must take the form of
 198 //   a singly-linked LIFO.  We drain _cxq into EntryList  at unlock-time when
 199 //   the unlocking thread notices that EntryList is null but _cxq is != null.
 200 //
 201 //   The EntryList is ordered by the prevailing queue discipline and
 202 //   can be organized in any convenient fashion, such as a doubly-linked list or
 203 //   a circular doubly-linked list.  Critically, we want insert and delete operations
 204 //   to operate in constant-time.  If we need a priority queue then something akin
 205 //   to Solaris' sleepq would work nicely.  Viz.,
 206 //   http://agg.eng/ws/on10_nightly/source/usr/src/uts/common/os/sleepq.c.
 207 //   Queue discipline is enforced at ::exit() time, when the unlocking thread
 208 //   drains the cxq into the EntryList, and orders or reorders the threads on the
 209 //   EntryList accordingly.
 210 //
 211 //   Barring "lock barging", this mechanism provides fair cyclic ordering,
 212 //   somewhat similar to an elevator-scan.
 213 //
 214 // * The monitor synchronization subsystem avoids the use of native
 215 //   synchronization primitives except for the narrow platform-specific
 216 //   park-unpark abstraction.  See the comments in os_solaris.cpp regarding
 217 //   the semantics of park-unpark.  Put another way, this monitor implementation
 218 //   depends only on atomic operations and park-unpark.  The monitor subsystem
 219 //   manages all RUNNING->BLOCKED and BLOCKED->READY transitions while the
 220 //   underlying OS manages the READY<->RUN transitions.
 221 //
 222 // * Waiting threads reside on the WaitSet list -- wait() puts
 223 //   the caller onto the WaitSet.
 224 //
 225 // * notify() or notifyAll() simply transfers threads from the WaitSet to
 226 //   either the EntryList or cxq.  Subsequent exit() operations will
 227 //   unpark the notifyee.  Unparking a notifee in notify() is inefficient -
 228 //   it's likely the notifyee would simply impale itself on the lock held
 229 //   by the notifier.
 230 //
 231 // * An interesting alternative is to encode cxq as (List,LockByte) where
 232 //   the LockByte is 0 iff the monitor is owned.  _owner is simply an auxiliary
 233 //   variable, like _recursions, in the scheme.  The threads or Events that form
 234 //   the list would have to be aligned in 256-byte addresses.  A thread would
 235 //   try to acquire the lock or enqueue itself with CAS, but exiting threads
 236 //   could use a 1-0 protocol and simply STB to set the LockByte to 0.
 237 //   Note that is is *not* word-tearing, but it does presume that full-word
 238 //   CAS operations are coherent with intermix with STB operations.  That's true
 239 //   on most common processors.
 240 //
 241 // * See also http://blogs.sun.com/dave
 242 
 243 #define DEFLATER_MARKER reinterpret_cast<void*>(-1)
 244 
 245 // -----------------------------------------------------------------------------
 246 // Enter support
 247 
 248 bool ObjectMonitor::enter(TRAPS) {
 249   // The following code is ordered to check the most common cases first
 250   // and to reduce RTS->RTO cache line upgrades on SPARC and IA32 processors.
 251   Thread * const Self = THREAD;
 252 
 253   void * cur = Atomic::cmpxchg_ptr (Self, &_owner, NULL);
 254   if (cur == NULL) {
 255     // Either ASSERT _recursions == 0 or explicitly set _recursions = 0.
 256     assert(_recursions == 0, "invariant");
 257     assert(_owner == Self, "invariant");
 258     return true;
 259   }
 260 
 261   if (cur == Self) {
 262     // TODO-FIXME: check for integer overflow!  BUGID 6557169.
 263     _recursions++;
 264     return true;
 265   }
 266 
 267   if (Self->is_lock_owned ((address)cur)) {
 268     assert(_recursions == 0, "internal state error");
 269     _recursions = 1;
 270     // Commute owner from a thread-specific on-stack BasicLockObject address to
 271     // a full-fledged "Thread *".
 272     _owner = Self;
 273     return true;
 274   }
 275 
 276   // We've encountered genuine contention.
 277   assert(Self->_Stalled == 0, "invariant");
 278   Self->_Stalled = intptr_t(this);
 279 
 280   // Try one round of spinning *before* enqueueing Self
 281   // and before going through the awkward and expensive state
 282   // transitions.  The following spin is strictly optional ...
 283   // Note that if we acquire the monitor from an initial spin
 284   // we forgo posting JVMTI events and firing DTRACE probes.
 285   if (Knob_SpinEarly && TrySpin (Self) > 0) {
 286     assert(_owner == Self, "invariant");
 287     assert(_recursions == 0, "invariant");
 288     assert(((oop)(object()))->mark() == markOopDesc::encode(this), "invariant");
 289     Self->_Stalled = 0;
 290     return true;
 291   }
 292 
 293   assert(_owner != Self, "invariant");
 294   assert(_succ != Self, "invariant");
 295   assert(Self->is_Java_thread(), "invariant");
 296   JavaThread * jt = (JavaThread *) Self;
 297   assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
 298   assert(jt->thread_state() != _thread_blocked, "invariant");
 299   assert(this->object() != NULL, "invariant");
 300 
 301   // Prevent deflation.  See deflate_idle_monitors(), try_disable_monitor, and is_busy().
 302   // Ensure the object-monitor relationship remains stable while there's contention.
 303   const jint count = Atomic::add(1, &_count);
 304   if (count <= 0 && _owner == DEFLATER_MARKER) {
 305     // Deflation in progress.
 306     // Help deflater thread install the mark word (in case deflater thread is slow).
 307     install_displaced_markword_in_object();
 308     Self->_Stalled = 0;
 309     return false; // Caller should retry. Never mind about _count as this monitor has been deflated.
 310   }
 311   // The deflater thread will not deflate this monitor and the monitor is contended, continue.
 312 
 313   EventJavaMonitorEnter event;
 314 
 315   { // Change java thread status to indicate blocked on monitor enter.
 316     JavaThreadBlockedOnMonitorEnterState jtbmes(jt, this);
 317 
 318     DTRACE_MONITOR_PROBE(contended__enter, this, object(), jt);
 319     if (JvmtiExport::should_post_monitor_contended_enter()) {
 320       JvmtiExport::post_monitor_contended_enter(jt, this);
 321 
 322       // The current thread does not yet own the monitor and does not
 323       // yet appear on any queues that would get it made the successor.
 324       // This means that the JVMTI_EVENT_MONITOR_CONTENDED_ENTER event
 325       // handler cannot accidentally consume an unpark() meant for the
 326       // ParkEvent associated with this ObjectMonitor.
 327     }
 328 
 329     OSThreadContendState osts(Self->osthread());
 330     ThreadBlockInVM tbivm(jt);
 331 
 332     Self->set_current_pending_monitor(this);
 333 
 334     // TODO-FIXME: change the following for(;;) loop to straight-line code.
 335     for (;;) {
 336       jt->set_suspend_equivalent();
 337       // cleared by handle_special_suspend_equivalent_condition()
 338       // or java_suspend_self()
 339 
 340       EnterI(THREAD);
 341 
 342       if (!ExitSuspendEquivalent(jt)) break;
 343 
 344       // We have acquired the contended monitor, but while we were
 345       // waiting another thread suspended us. We don't want to enter
 346       // the monitor while suspended because that would surprise the
 347       // thread that suspended us.
 348       //
 349       _recursions = 0;
 350       _succ = NULL;
 351       exit(false, Self);
 352 
 353       jt->java_suspend_self();
 354     }
 355     Self->set_current_pending_monitor(NULL);
 356 
 357     // We cleared the pending monitor info since we've just gotten past
 358     // the enter-check-for-suspend dance and we now own the monitor free
 359     // and clear, i.e., it is no longer pending. The ThreadBlockInVM
 360     // destructor can go to a safepoint at the end of this block. If we
 361     // do a thread dump during that safepoint, then this thread will show
 362     // as having "-locked" the monitor, but the OS and java.lang.Thread
 363     // states will still report that the thread is blocked trying to
 364     // acquire it.
 365   }
 366 
 367   Atomic::dec(&_count);
 368   Self->_Stalled = 0;
 369 
 370   // Must either set _recursions = 0 or ASSERT _recursions == 0.
 371   assert(_recursions == 0, "invariant");
 372   assert(_owner == Self, "invariant");
 373   assert(_succ != Self, "invariant");
 374   assert(((oop)(object()))->mark() == markOopDesc::encode(this), "invariant");
 375 
 376   // The thread -- now the owner -- is back in vm mode.
 377   // Report the glorious news via TI,DTrace and jvmstat.
 378   // The probe effect is non-trivial.  All the reportage occurs
 379   // while we hold the monitor, increasing the length of the critical
 380   // section.  Amdahl's parallel speedup law comes vividly into play.
 381   //
 382   // Another option might be to aggregate the events (thread local or
 383   // per-monitor aggregation) and defer reporting until a more opportune
 384   // time -- such as next time some thread encounters contention but has
 385   // yet to acquire the lock.  While spinning that thread could
 386   // spinning we could increment JVMStat counters, etc.
 387 
 388   DTRACE_MONITOR_PROBE(contended__entered, this, object(), jt);
 389   if (JvmtiExport::should_post_monitor_contended_entered()) {
 390     JvmtiExport::post_monitor_contended_entered(jt, this);
 391 
 392     // The current thread already owns the monitor and is not going to
 393     // call park() for the remainder of the monitor enter protocol. So
 394     // it doesn't matter if the JVMTI_EVENT_MONITOR_CONTENDED_ENTERED
 395     // event handler consumed an unpark() issued by the thread that
 396     // just exited the monitor.
 397   }
 398 
 399   if (event.should_commit()) {
 400     event.set_monitorClass(((oop)this->object())->klass());
 401     event.set_previousOwner((TYPE_THREAD)_previous_owner_tid);
 402     event.set_address((TYPE_ADDRESS)(uintptr_t)(this->object_addr()));
 403     event.commit();
 404   }
 405 
 406   OM_PERFDATA_OP(ContendedLockAttempts, inc());
 407   return true;
 408 }
 409 
 410 
 411 // Caveat: TryLock() is not necessarily serializing if it returns failure.
 412 // Callers must compensate as needed.
 413 
 414 int ObjectMonitor::TryLock(Thread * Self) {
 415   void * own = _owner;
 416   if (own != NULL) return 0;
 417   if (Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) {
 418     // Either guarantee _recursions == 0 or set _recursions = 0.
 419     assert(_recursions == 0, "invariant");
 420     assert(_owner == Self, "invariant");
 421     return 1;
 422   }
 423   // The lock had been free momentarily, but we lost the race to the lock.
 424   // Interference -- the CAS failed.
 425   // We can either return -1 or retry.
 426   // Retry doesn't make as much sense because the lock was just acquired.
 427   return -1;
 428 }
 429 
 430 // Try disabling this monitor. Returns true iff successful.
 431 // The method will install DEFLATER_MARKER (-1) as the owner of the monitor,
 432 // check _waiters == 0, and make _count negative if it is currently 0. The
 433 // monitor is successfully disabled if _count is negative and this monitor is
 434 // still owned by DEFLATER_MARKER.
 435 //
 436 // All threads trying to acquire the monitor must before parking themselves
 437 // increment _count and check that _owner != DEFLATER_MARKER. If _owner ==
 438 // DEFLATER_MARKER and _count is positive, then a thread can still win the lock
 439 // by atomically installing its thread pointer in _owner.  If _count is
 440 // negative and _owned == DEFLATER_MARKER, then the monitor has been
 441 // successfully disabled and the acquiring threads should help install the
 442 // displaced mark word back into the object and retry acquiring the lock.
 443 //
 444 // A thread wanting to wait on the monitor must increase _waiters while owning the monitor.
 445 bool ObjectMonitor::try_disable_monitor() {
 446   assert(Thread::current()->is_Java_thread(), "precondition");
 447   // We don't want to disable newly allocated monitors as it could result in a endless inflate/deflate cycle.
 448   assert(is_old(), "precondition");
 449 
 450   // Set _owned to DEFLATER_MARKER if monitor is not owned by another thread.
 451   // This forced contending thread through the slow path.
 452   if (!is_busy() && Atomic::cmpxchg_ptr(DEFLATER_MARKER, &_owner, NULL) == NULL) {
 453     // Another thread might still enter the monitor.
 454     // Signal that other threads should retry if the owner is DEFLATER_MARKER by making _count negative.
 455     if (_waiters == 0 && Atomic::cmpxchg(- max_jint, &_count, 0) == 0) {
 456       // ABA problem with _count:
 457       //   Another thread might have acquired this monitor and finished using it.
 458       //   Check owner to see if that happened (no other thread installs DEFLATER_MARKER as owner).
 459       if (_owner == DEFLATER_MARKER) {
 460         // We successfully signalled to all threads entering that they should
 461         // retry.
 462         // Nobody acquired this monitor between installing DEFLATER_MARKER into
 463         // _owner and now (such a thread would have changed _owner).  If any
 464         // thread is now waiting on the monitor, then _waiters must have been
 465         // incremented as it was 0 before. _waiters is changed only when owning
 466         // the monitor, but no other thread can have owned the monitor since we
 467         // installed DEFLATER_MARKER, and thus _waiters must still be 0.
 468         guarantee(_waiters == 0, "Not changed since the previous read");
 469         guarantee(_cxq == NULL, "All contending threads should retry");
 470         guarantee(_EntryList == NULL, "All contending threads should retry");
 471         // Install the old mark word if nobody else has already done it.
 472         install_displaced_markword_in_object();
 473         set_allocation_state(Free);
 474         // Leave this monitor locked to ensure acquiring threads take the slow-path and
 475         // leave _count negative to make them retry.
 476         return true; // Success, lock has been deflated.
 477       }
 478       // We do not own the monitor. Do not deflate.
 479       Atomic::add(max_jint, &_count);
 480     }
 481     // Never mind. Another thread managed to acquire this monitor or there were
 482     // threads waiting.  The threads that saw (or will see) 0 <= _count and
 483     // _owner == DEFLATER_MARKER will compete for ownership and one will
 484     // eventually install itself as owner and subsequently run the exit protocol.
 485   }
 486   assert(0 <= _count, "Nobody else should be make _count negative");
 487   return false;
 488 }
 489 
 490 // Install the displaced mark word of a disabled monitor into the object
 491 // associated with the monitor.
 492 // This method is idempotent and is expected to be executed by both mutators
 493 // wanting to acquire a monitor for an object, mutators wanting to install a
 494 // hashcode in an object, and the thread deflating monitors.
 495 void ObjectMonitor::install_displaced_markword_in_object() {
 496   markOop dmw = header();
 497   assert(dmw->is_neutral() || dmw->hash() == 0 && dmw->is_marked(), "precondition");
 498   if (dmw->hash() == 0 && !dmw->is_marked()) {
 499     // Another thread might update the displaced mark word by computing a hash
 500     // code for the oject or running this method.
 501     // Signal to other threads that the object mark word should be installed
 502     // and read from the object by marking the displaced mark word.
 503     markOop marked_dmw = dmw->set_marked();
 504     assert(marked_dmw->hash() == 0 && marked_dmw->is_marked(), "oops");
 505     dmw = (markOop) Atomic::cmpxchg_ptr(marked_dmw, &_header, dmw);
 506     // If the CAS failed because another thread installed a hash value, then dmw
 507     // will contain the hash and be unmarked. If the CAS failed because another thread
 508     // marked the displaced mark word, then dmw->hash() is zero and dmw is marked.
 509   }
 510   if (dmw->is_marked()) {
 511     assert(dmw->hash() == 0, "invariant");
 512     dmw = dmw->set_unmarked();
 513   }
 514   oop const obj = (oop) object();
 515   // Install displaced mark word if object mark word still points to this monitor.
 516   assert(dmw->is_neutral(), "Must not install non-neutral markword into object");
 517   obj->cas_set_mark(dmw, markOopDesc::encode(this));
 518 }
 519 
 520 #define MAX_RECHECK_INTERVAL 1000
 521 
 522 void ObjectMonitor::EnterI(TRAPS) {
 523   Thread * const Self = THREAD;
 524   assert(Self->is_Java_thread(), "invariant");
 525   assert(((JavaThread *) Self)->thread_state() == _thread_blocked, "invariant");
 526 
 527   // Try the lock - TATAS
 528   if (TryLock (Self) > 0) {
 529     assert(_succ != Self, "invariant");
 530     assert(_owner == Self, "invariant");
 531     assert(_Responsible != Self, "invariant");
 532     return;
 533   }
 534 
 535   if (_owner == DEFLATER_MARKER) {
 536     guarantee(0 < _count, "_owner == DEFLATER_MARKER && _count <= 0 should have been handled by the caller");
 537     // Deflater thread tried to lock this monitor, but it failed to make _count negative and gave up.
 538     // Try to acquire monitor.
 539     if (Atomic::cmpxchg_ptr(Self, &_owner, DEFLATER_MARKER) == DEFLATER_MARKER) {
 540       assert(_succ != Self, "invariant");
 541       assert(_owner == Self, "invariant");
 542       assert(_Responsible != Self, "invariant");
 543       return;
 544     }
 545   }
 546 
 547   DeferredInitialize();
 548 
 549   // We try one round of spinning *before* enqueueing Self.
 550   //
 551   // If the _owner is ready but OFFPROC we could use a YieldTo()
 552   // operation to donate the remainder of this thread's quantum
 553   // to the owner.  This has subtle but beneficial affinity
 554   // effects.
 555 
 556   if (TrySpin (Self) > 0) {
 557     assert(_owner == Self, "invariant");
 558     assert(_succ != Self, "invariant");
 559     assert(_Responsible != Self, "invariant");
 560     return;
 561   }
 562 
 563   // The Spin failed -- Enqueue and park the thread ...
 564   assert(_succ != Self, "invariant");
 565   assert(_owner != Self, "invariant");
 566   assert(_Responsible != Self, "invariant");
 567 
 568   // Enqueue "Self" on ObjectMonitor's _cxq.
 569   //
 570   // Node acts as a proxy for Self.
 571   // As an aside, if were to ever rewrite the synchronization code mostly
 572   // in Java, WaitNodes, ObjectMonitors, and Events would become 1st-class
 573   // Java objects.  This would avoid awkward lifecycle and liveness issues,
 574   // as well as eliminate a subset of ABA issues.
 575   // TODO: eliminate ObjectWaiter and enqueue either Threads or Events.
 576 
 577   ObjectWaiter node(Self);
 578   Self->_ParkEvent->reset();
 579   node._prev   = (ObjectWaiter *) 0xBAD;
 580   node.TState  = ObjectWaiter::TS_CXQ;
 581 
 582   // Push "Self" onto the front of the _cxq.
 583   // Once on cxq/EntryList, Self stays on-queue until it acquires the lock.
 584   // Note that spinning tends to reduce the rate at which threads
 585   // enqueue and dequeue on EntryList|cxq.
 586   ObjectWaiter * nxt;
 587   for (;;) {
 588     node._next = nxt = _cxq;
 589     if (Atomic::cmpxchg_ptr(&node, &_cxq, nxt) == nxt) break;
 590 
 591     // Interference - the CAS failed because _cxq changed.  Just retry.
 592     // As an optional optimization we retry the lock.
 593     if (TryLock (Self) > 0) {
 594       assert(_succ != Self, "invariant");
 595       assert(_owner == Self, "invariant");
 596       assert(_Responsible != Self, "invariant");
 597       return;
 598     }
 599   }
 600 
 601   // Check for cxq|EntryList edge transition to non-null.  This indicates
 602   // the onset of contention.  While contention persists exiting threads
 603   // will use a ST:MEMBAR:LD 1-1 exit protocol.  When contention abates exit
 604   // operations revert to the faster 1-0 mode.  This enter operation may interleave
 605   // (race) a concurrent 1-0 exit operation, resulting in stranding, so we
 606   // arrange for one of the contending thread to use a timed park() operations
 607   // to detect and recover from the race.  (Stranding is form of progress failure
 608   // where the monitor is unlocked but all the contending threads remain parked).
 609   // That is, at least one of the contended threads will periodically poll _owner.
 610   // One of the contending threads will become the designated "Responsible" thread.
 611   // The Responsible thread uses a timed park instead of a normal indefinite park
 612   // operation -- it periodically wakes and checks for and recovers from potential
 613   // strandings admitted by 1-0 exit operations.   We need at most one Responsible
 614   // thread per-monitor at any given moment.  Only threads on cxq|EntryList may
 615   // be responsible for a monitor.
 616   //
 617   // Currently, one of the contended threads takes on the added role of "Responsible".
 618   // A viable alternative would be to use a dedicated "stranding checker" thread
 619   // that periodically iterated over all the threads (or active monitors) and unparked
 620   // successors where there was risk of stranding.  This would help eliminate the
 621   // timer scalability issues we see on some platforms as we'd only have one thread
 622   // -- the checker -- parked on a timer.
 623 
 624   if ((SyncFlags & 16) == 0 && nxt == NULL && _EntryList == NULL) {
 625     // Try to assume the role of responsible thread for the monitor.
 626     // CONSIDER:  ST vs CAS vs { if (Responsible==null) Responsible=Self }
 627     Atomic::cmpxchg_ptr(Self, &_Responsible, NULL);
 628   }
 629 
 630   // The lock might have been released while this thread was occupied queueing
 631   // itself onto _cxq.  To close the race and avoid "stranding" and
 632   // progress-liveness failure we must resample-retry _owner before parking.
 633   // Note the Dekker/Lamport duality: ST cxq; MEMBAR; LD Owner.
 634   // In this case the ST-MEMBAR is accomplished with CAS().
 635   //
 636   // TODO: Defer all thread state transitions until park-time.
 637   // Since state transitions are heavy and inefficient we'd like
 638   // to defer the state transitions until absolutely necessary,
 639   // and in doing so avoid some transitions ...
 640 
 641   TEVENT(Inflated enter - Contention);
 642   int nWakeups = 0;
 643   int recheckInterval = 1;
 644 
 645   for (;;) {
 646 
 647     if (TryLock(Self) > 0) break;
 648     assert(_owner != Self, "invariant");
 649 
 650     if ((SyncFlags & 2) && _Responsible == NULL) {
 651       Atomic::cmpxchg_ptr(Self, &_Responsible, NULL);
 652     }
 653 
 654     // park self
 655     if (_Responsible == Self || (SyncFlags & 1)) {
 656       TEVENT(Inflated enter - park TIMED);
 657       Self->_ParkEvent->park((jlong) recheckInterval);
 658       // Increase the recheckInterval, but clamp the value.
 659       recheckInterval *= 8;
 660       if (recheckInterval > MAX_RECHECK_INTERVAL) {
 661         recheckInterval = MAX_RECHECK_INTERVAL;
 662       }
 663     } else {
 664       TEVENT(Inflated enter - park UNTIMED);
 665       Self->_ParkEvent->park();
 666     }
 667 
 668     if (TryLock(Self) > 0) break;
 669 
 670     if (_owner == DEFLATER_MARKER) {
 671       guarantee(0 < _count, "_owner == DEFLATER_MARKER && _count <= 0 should have been handled by the caller");
 672       // Deflater thread tried to lock this monitor, but it failed to make _count negative and gave up.
 673       // Try to acquire monitor.
 674       if (Atomic::cmpxchg_ptr(Self, &_owner, DEFLATER_MARKER) == DEFLATER_MARKER) {
 675          break;
 676       }
 677     }
 678 
 679     // The lock is still contested.
 680     // Keep a tally of the # of futile wakeups.
 681     // Note that the counter is not protected by a lock or updated by atomics.
 682     // That is by design - we trade "lossy" counters which are exposed to
 683     // races during updates for a lower probe effect.
 684     TEVENT(Inflated enter - Futile wakeup);
 685     // This PerfData object can be used in parallel with a safepoint.
 686     // See the work around in PerfDataManager::destroy().
 687     OM_PERFDATA_OP(FutileWakeups, inc());
 688     ++nWakeups;
 689 
 690     // Assuming this is not a spurious wakeup we'll normally find _succ == Self.
 691     // We can defer clearing _succ until after the spin completes
 692     // TrySpin() must tolerate being called with _succ == Self.
 693     // Try yet another round of adaptive spinning.
 694     if ((Knob_SpinAfterFutile & 1) && TrySpin(Self) > 0) break;
 695 
 696     // We can find that we were unpark()ed and redesignated _succ while
 697     // we were spinning.  That's harmless.  If we iterate and call park(),
 698     // park() will consume the event and return immediately and we'll
 699     // just spin again.  This pattern can repeat, leaving _succ to simply
 700     // spin on a CPU.  Enable Knob_ResetEvent to clear pending unparks().
 701     // Alternately, we can sample fired() here, and if set, forgo spinning
 702     // in the next iteration.
 703 
 704     if ((Knob_ResetEvent & 1) && Self->_ParkEvent->fired()) {
 705       Self->_ParkEvent->reset();
 706       OrderAccess::fence();
 707     }
 708     if (_succ == Self) _succ = NULL;
 709 
 710     // Invariant: after clearing _succ a thread *must* retry _owner before parking.
 711     OrderAccess::fence();
 712   }
 713 
 714   // Egress :
 715   // Self has acquired the lock -- Unlink Self from the cxq or EntryList.
 716   // Normally we'll find Self on the EntryList .
 717   // From the perspective of the lock owner (this thread), the
 718   // EntryList is stable and cxq is prepend-only.
 719   // The head of cxq is volatile but the interior is stable.
 720   // In addition, Self.TState is stable.
 721 
 722   assert(_owner == Self, "invariant");
 723   assert(object() != NULL, "invariant");
 724   // I'd like to write:
 725   //   guarantee (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;
 726   // but as we're at a safepoint that's not safe.
 727 
 728   UnlinkAfterAcquire(Self, &node);
 729   if (_succ == Self) _succ = NULL;
 730 
 731   assert(_succ != Self, "invariant");
 732   if (_Responsible == Self) {
 733     _Responsible = NULL;
 734     OrderAccess::fence(); // Dekker pivot-point
 735 
 736     // We may leave threads on cxq|EntryList without a designated
 737     // "Responsible" thread.  This is benign.  When this thread subsequently
 738     // exits the monitor it can "see" such preexisting "old" threads --
 739     // threads that arrived on the cxq|EntryList before the fence, above --
 740     // by LDing cxq|EntryList.  Newly arrived threads -- that is, threads
 741     // that arrive on cxq after the ST:MEMBAR, above -- will set Responsible
 742     // non-null and elect a new "Responsible" timer thread.
 743     //
 744     // This thread executes:
 745     //    ST Responsible=null; MEMBAR    (in enter epilogue - here)
 746     //    LD cxq|EntryList               (in subsequent exit)
 747     //
 748     // Entering threads in the slow/contended path execute:
 749     //    ST cxq=nonnull; MEMBAR; LD Responsible (in enter prolog)
 750     //    The (ST cxq; MEMBAR) is accomplished with CAS().
 751     //
 752     // The MEMBAR, above, prevents the LD of cxq|EntryList in the subsequent
 753     // exit operation from floating above the ST Responsible=null.
 754   }
 755 
 756   // We've acquired ownership with CAS().
 757   // CAS is serializing -- it has MEMBAR/FENCE-equivalent semantics.
 758   // But since the CAS() this thread may have also stored into _succ,
 759   // EntryList, cxq or Responsible.  These meta-data updates must be
 760   // visible __before this thread subsequently drops the lock.
 761   // Consider what could occur if we didn't enforce this constraint --
 762   // STs to monitor meta-data and user-data could reorder with (become
 763   // visible after) the ST in exit that drops ownership of the lock.
 764   // Some other thread could then acquire the lock, but observe inconsistent
 765   // or old monitor meta-data and heap data.  That violates the JMM.
 766   // To that end, the 1-0 exit() operation must have at least STST|LDST
 767   // "release" barrier semantics.  Specifically, there must be at least a
 768   // STST|LDST barrier in exit() before the ST of null into _owner that drops
 769   // the lock.   The barrier ensures that changes to monitor meta-data and data
 770   // protected by the lock will be visible before we release the lock, and
 771   // therefore before some other thread (CPU) has a chance to acquire the lock.
 772   // See also: http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
 773   //
 774   // Critically, any prior STs to _succ or EntryList must be visible before
 775   // the ST of null into _owner in the *subsequent* (following) corresponding
 776   // monitorexit.  Recall too, that in 1-0 mode monitorexit does not necessarily
 777   // execute a serializing instruction.
 778 
 779   if (SyncFlags & 8) {
 780     OrderAccess::fence();
 781   }
 782   return;
 783 }
 784 
 785 // ReenterI() is a specialized inline form of the latter half of the
 786 // contended slow-path from EnterI().  We use ReenterI() only for
 787 // monitor reentry in wait().
 788 //
 789 // In the future we should reconcile EnterI() and ReenterI(), adding
 790 // Knob_Reset and Knob_SpinAfterFutile support and restructuring the
 791 // loop accordingly.
 792 
 793 void ObjectMonitor::ReenterI(Thread * Self, ObjectWaiter * SelfNode) {
 794   assert(Self != NULL, "invariant");
 795   assert(SelfNode != NULL, "invariant");
 796   assert(SelfNode->_thread == Self, "invariant");
 797   assert(_waiters > 0, "invariant");
 798   assert(((oop)(object()))->mark() == markOopDesc::encode(this), "invariant");
 799   assert(((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant");
 800   JavaThread * jt = (JavaThread *) Self;
 801 
 802   int nWakeups = 0;
 803   for (;;) {
 804     ObjectWaiter::TStates v = SelfNode->TState;
 805     guarantee(v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant");
 806     assert(_owner != Self, "invariant");
 807 
 808     if (TryLock(Self) > 0) break;
 809     if (TrySpin(Self) > 0) break;
 810 
 811     if (_owner == DEFLATER_MARKER) {
 812       guarantee(0 <= _count, "Impossible: _owner == DEFLATER_MARKER && _count < 0, monitor must not be owned by deflater thread here");
 813       if (Atomic::cmpxchg_ptr(Self, &_owner, DEFLATER_MARKER) == DEFLATER_MARKER) {
 814         break;
 815       }
 816     }
 817 
 818     TEVENT(Wait Reentry - parking);
 819 
 820     // State transition wrappers around park() ...
 821     // ReenterI() wisely defers state transitions until
 822     // it's clear we must park the thread.
 823     {
 824       OSThreadContendState osts(Self->osthread());
 825       ThreadBlockInVM tbivm(jt);
 826 
 827       // cleared by handle_special_suspend_equivalent_condition()
 828       // or java_suspend_self()
 829       jt->set_suspend_equivalent();
 830       if (SyncFlags & 1) {
 831         Self->_ParkEvent->park((jlong)MAX_RECHECK_INTERVAL);
 832       } else {
 833         Self->_ParkEvent->park();
 834       }
 835 
 836       // were we externally suspended while we were waiting?
 837       for (;;) {
 838         if (!ExitSuspendEquivalent(jt)) break;
 839         if (_succ == Self) { _succ = NULL; OrderAccess::fence(); }
 840         jt->java_suspend_self();
 841         jt->set_suspend_equivalent();
 842       }
 843     }
 844 
 845     // Try again, but just so we distinguish between futile wakeups and
 846     // successful wakeups.  The following test isn't algorithmically
 847     // necessary, but it helps us maintain sensible statistics.
 848     if (TryLock(Self) > 0) break;
 849 
 850     // The lock is still contested.
 851     // Keep a tally of the # of futile wakeups.
 852     // Note that the counter is not protected by a lock or updated by atomics.
 853     // That is by design - we trade "lossy" counters which are exposed to
 854     // races during updates for a lower probe effect.
 855     TEVENT(Wait Reentry - futile wakeup);
 856     ++nWakeups;
 857 
 858     // Assuming this is not a spurious wakeup we'll normally
 859     // find that _succ == Self.
 860     if (_succ == Self) _succ = NULL;
 861 
 862     // Invariant: after clearing _succ a contending thread
 863     // *must* retry  _owner before parking.
 864     OrderAccess::fence();
 865 
 866     // This PerfData object can be used in parallel with a safepoint.
 867     // See the work around in PerfDataManager::destroy().
 868     OM_PERFDATA_OP(FutileWakeups, inc());
 869   }
 870 
 871   // Self has acquired the lock -- Unlink Self from the cxq or EntryList .
 872   // Normally we'll find Self on the EntryList.
 873   // Unlinking from the EntryList is constant-time and atomic-free.
 874   // From the perspective of the lock owner (this thread), the
 875   // EntryList is stable and cxq is prepend-only.
 876   // The head of cxq is volatile but the interior is stable.
 877   // In addition, Self.TState is stable.
 878 
 879   assert(_owner == Self, "invariant");
 880   assert(((oop)(object()))->mark() == markOopDesc::encode(this), "invariant");
 881   UnlinkAfterAcquire(Self, SelfNode);
 882   if (_succ == Self) _succ = NULL;
 883   assert(_succ != Self, "invariant");
 884   SelfNode->TState = ObjectWaiter::TS_RUN;
 885   OrderAccess::fence();      // see comments at the end of EnterI()
 886 }
 887 
 888 // By convention we unlink a contending thread from EntryList|cxq immediately
 889 // after the thread acquires the lock in ::enter().  Equally, we could defer
 890 // unlinking the thread until ::exit()-time.
 891 
 892 void ObjectMonitor::UnlinkAfterAcquire(Thread *Self, ObjectWaiter *SelfNode) {
 893   assert(_owner == Self, "invariant");
 894   assert(SelfNode->_thread == Self, "invariant");
 895 
 896   if (SelfNode->TState == ObjectWaiter::TS_ENTER) {
 897     // Normal case: remove Self from the DLL EntryList .
 898     // This is a constant-time operation.
 899     ObjectWaiter * nxt = SelfNode->_next;
 900     ObjectWaiter * prv = SelfNode->_prev;
 901     if (nxt != NULL) nxt->_prev = prv;
 902     if (prv != NULL) prv->_next = nxt;
 903     if (SelfNode == _EntryList) _EntryList = nxt;
 904     assert(nxt == NULL || nxt->TState == ObjectWaiter::TS_ENTER, "invariant");
 905     assert(prv == NULL || prv->TState == ObjectWaiter::TS_ENTER, "invariant");
 906     TEVENT(Unlink from EntryList);
 907   } else {
 908     assert(SelfNode->TState == ObjectWaiter::TS_CXQ, "invariant");
 909     // Inopportune interleaving -- Self is still on the cxq.
 910     // This usually means the enqueue of self raced an exiting thread.
 911     // Normally we'll find Self near the front of the cxq, so
 912     // dequeueing is typically fast.  If needbe we can accelerate
 913     // this with some MCS/CHL-like bidirectional list hints and advisory
 914     // back-links so dequeueing from the interior will normally operate
 915     // in constant-time.
 916     // Dequeue Self from either the head (with CAS) or from the interior
 917     // with a linear-time scan and normal non-atomic memory operations.
 918     // CONSIDER: if Self is on the cxq then simply drain cxq into EntryList
 919     // and then unlink Self from EntryList.  We have to drain eventually,
 920     // so it might as well be now.
 921 
 922     ObjectWaiter * v = _cxq;
 923     assert(v != NULL, "invariant");
 924     if (v != SelfNode || Atomic::cmpxchg_ptr (SelfNode->_next, &_cxq, v) != v) {
 925       // The CAS above can fail from interference IFF a "RAT" arrived.
 926       // In that case Self must be in the interior and can no longer be
 927       // at the head of cxq.
 928       if (v == SelfNode) {
 929         assert(_cxq != v, "invariant");
 930         v = _cxq;          // CAS above failed - start scan at head of list
 931       }
 932       ObjectWaiter * p;
 933       ObjectWaiter * q = NULL;
 934       for (p = v; p != NULL && p != SelfNode; p = p->_next) {
 935         q = p;
 936         assert(p->TState == ObjectWaiter::TS_CXQ, "invariant");
 937       }
 938       assert(v != SelfNode, "invariant");
 939       assert(p == SelfNode, "Node not found on cxq");
 940       assert(p != _cxq, "invariant");
 941       assert(q != NULL, "invariant");
 942       assert(q->_next == p, "invariant");
 943       q->_next = p->_next;
 944     }
 945     TEVENT(Unlink from cxq);
 946   }
 947 
 948 #ifdef ASSERT
 949   // Diagnostic hygiene ...
 950   SelfNode->_prev  = (ObjectWaiter *) 0xBAD;
 951   SelfNode->_next  = (ObjectWaiter *) 0xBAD;
 952   SelfNode->TState = ObjectWaiter::TS_RUN;
 953 #endif
 954 }
 955 
 956 // -----------------------------------------------------------------------------
 957 // Exit support
 958 //
 959 // exit()
 960 // ~~~~~~
 961 // Note that the collector can't reclaim the objectMonitor or deflate
 962 // the object out from underneath the thread calling ::exit() as the
 963 // thread calling ::exit() never transitions to a stable state.
 964 // This inhibits GC, which in turn inhibits asynchronous (and
 965 // inopportune) reclamation of "this".
 966 //
 967 // We'd like to assert that: (THREAD->thread_state() != _thread_blocked) ;
 968 // There's one exception to the claim above, however.  EnterI() can call
 969 // exit() to drop a lock if the acquirer has been externally suspended.
 970 // In that case exit() is called with _thread_state as _thread_blocked,
 971 // but the monitor's _count field is > 0, which inhibits reclamation.
 972 //
 973 // 1-0 exit
 974 // ~~~~~~~~
 975 // ::exit() uses a canonical 1-1 idiom with a MEMBAR although some of
 976 // the fast-path operators have been optimized so the common ::exit()
 977 // operation is 1-0, e.g., see macroAssembler_x86.cpp: fast_unlock().
 978 // The code emitted by fast_unlock() elides the usual MEMBAR.  This
 979 // greatly improves latency -- MEMBAR and CAS having considerable local
 980 // latency on modern processors -- but at the cost of "stranding".  Absent the
 981 // MEMBAR, a thread in fast_unlock() can race a thread in the slow
 982 // ::enter() path, resulting in the entering thread being stranding
 983 // and a progress-liveness failure.   Stranding is extremely rare.
 984 // We use timers (timed park operations) & periodic polling to detect
 985 // and recover from stranding.  Potentially stranded threads periodically
 986 // wake up and poll the lock.  See the usage of the _Responsible variable.
 987 //
 988 // The CAS() in enter provides for safety and exclusion, while the CAS or
 989 // MEMBAR in exit provides for progress and avoids stranding.  1-0 locking
 990 // eliminates the CAS/MEMBAR from the exit path, but it admits stranding.
 991 // We detect and recover from stranding with timers.
 992 //
 993 // If a thread transiently strands it'll park until (a) another
 994 // thread acquires the lock and then drops the lock, at which time the
 995 // exiting thread will notice and unpark the stranded thread, or, (b)
 996 // the timer expires.  If the lock is high traffic then the stranding latency
 997 // will be low due to (a).  If the lock is low traffic then the odds of
 998 // stranding are lower, although the worst-case stranding latency
 999 // is longer.  Critically, we don't want to put excessive load in the
1000 // platform's timer subsystem.  We want to minimize both the timer injection
1001 // rate (timers created/sec) as well as the number of timers active at
1002 // any one time.  (more precisely, we want to minimize timer-seconds, which is
1003 // the integral of the # of active timers at any instant over time).
1004 // Both impinge on OS scalability.  Given that, at most one thread parked on
1005 // a monitor will use a timer.
1006 //
1007 // There is also the risk of a futile wake-up. If we drop the lock
1008 // another thread can reacquire the lock immediately, and we can
1009 // then wake a thread unnecessarily. This is benign, and we've
1010 // structured the code so the windows are short and the frequency
1011 // of such futile wakups is low.
1012 
1013 void ObjectMonitor::exit(bool not_suspended, TRAPS) {
1014   Thread * const Self = THREAD;
1015   if (THREAD != _owner) {
1016     if (THREAD->is_lock_owned((address) _owner)) {
1017       // Transmute _owner from a BasicLock pointer to a Thread address.
1018       // We don't need to hold _mutex for this transition.
1019       // Non-null to Non-null is safe as long as all readers can
1020       // tolerate either flavor.
1021       assert(_recursions == 0, "invariant");
1022       _owner = THREAD;
1023       _recursions = 0;
1024     } else {
1025       // Apparent unbalanced locking ...
1026       // Naively we'd like to throw IllegalMonitorStateException.
1027       // As a practical matter we can neither allocate nor throw an
1028       // exception as ::exit() can be called from leaf routines.
1029       // see x86_32.ad Fast_Unlock() and the I1 and I2 properties.
1030       // Upon deeper reflection, however, in a properly run JVM the only
1031       // way we should encounter this situation is in the presence of
1032       // unbalanced JNI locking. TODO: CheckJNICalls.
1033       // See also: CR4414101
1034       TEVENT(Exit - Throw IMSX);
1035       assert(false, "Non-balanced monitor enter/exit! Likely JNI locking");
1036       return;
1037     }
1038   }
1039 
1040   if (_recursions != 0) {
1041     _recursions--;        // this is simple recursive enter
1042     TEVENT(Inflated exit - recursive);
1043     return;
1044   }
1045 
1046   // Invariant: after setting Responsible=null an thread must execute
1047   // a MEMBAR or other serializing instruction before fetching EntryList|cxq.
1048   if ((SyncFlags & 4) == 0) {
1049     _Responsible = NULL;
1050   }
1051 
1052 #if INCLUDE_TRACE
1053   // get the owner's thread id for the MonitorEnter event
1054   // if it is enabled and the thread isn't suspended
1055   if (not_suspended && Tracing::is_event_enabled(TraceJavaMonitorEnterEvent)) {
1056     _previous_owner_tid = THREAD_TRACE_ID(Self);
1057   }
1058 #endif
1059 
1060   for (;;) {
1061     assert(THREAD == _owner, "invariant");
1062 
1063     if (Knob_ExitPolicy == 0) {
1064       // release semantics: prior loads and stores from within the critical section
1065       // must not float (reorder) past the following store that drops the lock.
1066       // On SPARC that requires MEMBAR #loadstore|#storestore.
1067       // But of course in TSO #loadstore|#storestore is not required.
1068       // I'd like to write one of the following:
1069       // A.  OrderAccess::release() ; _owner = NULL
1070       // B.  OrderAccess::loadstore(); OrderAccess::storestore(); _owner = NULL;
1071       // Unfortunately OrderAccess::release() and OrderAccess::loadstore() both
1072       // store into a _dummy variable.  That store is not needed, but can result
1073       // in massive wasteful coherency traffic on classic SMP systems.
1074       // Instead, I use release_store(), which is implemented as just a simple
1075       // ST on x64, x86 and SPARC.
1076       OrderAccess::release_store_ptr(&_owner, NULL);   // drop the lock
1077       OrderAccess::storeload();                        // See if we need to wake a successor
1078       if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != NULL) {
1079         TEVENT(Inflated exit - simple egress);
1080         return;
1081       }
1082       TEVENT(Inflated exit - complex egress);
1083       // Other threads are blocked trying to acquire the lock.
1084 
1085       // Normally the exiting thread is responsible for ensuring succession,
1086       // but if other successors are ready or other entering threads are spinning
1087       // then this thread can simply store NULL into _owner and exit without
1088       // waking a successor.  The existence of spinners or ready successors
1089       // guarantees proper succession (liveness).  Responsibility passes to the
1090       // ready or running successors.  The exiting thread delegates the duty.
1091       // More precisely, if a successor already exists this thread is absolved
1092       // of the responsibility of waking (unparking) one.
1093       //
1094       // The _succ variable is critical to reducing futile wakeup frequency.
1095       // _succ identifies the "heir presumptive" thread that has been made
1096       // ready (unparked) but that has not yet run.  We need only one such
1097       // successor thread to guarantee progress.
1098       // See http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf
1099       // section 3.3 "Futile Wakeup Throttling" for details.
1100       //
1101       // Note that spinners in Enter() also set _succ non-null.
1102       // In the current implementation spinners opportunistically set
1103       // _succ so that exiting threads might avoid waking a successor.
1104       // Another less appealing alternative would be for the exiting thread
1105       // to drop the lock and then spin briefly to see if a spinner managed
1106       // to acquire the lock.  If so, the exiting thread could exit
1107       // immediately without waking a successor, otherwise the exiting
1108       // thread would need to dequeue and wake a successor.
1109       // (Note that we'd need to make the post-drop spin short, but no
1110       // shorter than the worst-case round-trip cache-line migration time.
1111       // The dropped lock needs to become visible to the spinner, and then
1112       // the acquisition of the lock by the spinner must become visible to
1113       // the exiting thread).
1114 
1115       // It appears that an heir-presumptive (successor) must be made ready.
1116       // Only the current lock owner can manipulate the EntryList or
1117       // drain _cxq, so we need to reacquire the lock.  If we fail
1118       // to reacquire the lock the responsibility for ensuring succession
1119       // falls to the new owner.
1120       //
1121       if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) {
1122         return;
1123       }
1124       TEVENT(Exit - Reacquired);
1125     } else {
1126       if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != NULL) {
1127         OrderAccess::release_store_ptr(&_owner, NULL);   // drop the lock
1128         OrderAccess::storeload();
1129         // Ratify the previously observed values.
1130         if (_cxq == NULL || _succ != NULL) {
1131           TEVENT(Inflated exit - simple egress);
1132           return;
1133         }
1134 
1135         // inopportune interleaving -- the exiting thread (this thread)
1136         // in the fast-exit path raced an entering thread in the slow-enter
1137         // path.
1138         // We have two choices:
1139         // A.  Try to reacquire the lock.
1140         //     If the CAS() fails return immediately, otherwise
1141         //     we either restart/rerun the exit operation, or simply
1142         //     fall-through into the code below which wakes a successor.
1143         // B.  If the elements forming the EntryList|cxq are TSM
1144         //     we could simply unpark() the lead thread and return
1145         //     without having set _succ.
1146         if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) {
1147           TEVENT(Inflated exit - reacquired succeeded);
1148           return;
1149         }
1150         TEVENT(Inflated exit - reacquired failed);
1151       } else {
1152         TEVENT(Inflated exit - complex egress);
1153       }
1154     }
1155 
1156     guarantee(_owner == THREAD, "invariant");
1157 
1158     ObjectWaiter * w = NULL;
1159     int QMode = Knob_QMode;
1160 
1161     if (QMode == 2 && _cxq != NULL) {
1162       // QMode == 2 : cxq has precedence over EntryList.
1163       // Try to directly wake a successor from the cxq.
1164       // If successful, the successor will need to unlink itself from cxq.
1165       w = _cxq;
1166       assert(w != NULL, "invariant");
1167       assert(w->TState == ObjectWaiter::TS_CXQ, "Invariant");
1168       ExitEpilog(Self, w);
1169       return;
1170     }
1171 
1172     if (QMode == 3 && _cxq != NULL) {
1173       // Aggressively drain cxq into EntryList at the first opportunity.
1174       // This policy ensure that recently-run threads live at the head of EntryList.
1175       // Drain _cxq into EntryList - bulk transfer.
1176       // First, detach _cxq.
1177       // The following loop is tantamount to: w = swap(&cxq, NULL)
1178       w = _cxq;
1179       for (;;) {
1180         assert(w != NULL, "Invariant");
1181         ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr(NULL, &_cxq, w);
1182         if (u == w) break;
1183         w = u;
1184       }
1185       assert(w != NULL, "invariant");
1186 
1187       ObjectWaiter * q = NULL;
1188       ObjectWaiter * p;
1189       for (p = w; p != NULL; p = p->_next) {
1190         guarantee(p->TState == ObjectWaiter::TS_CXQ, "Invariant");
1191         p->TState = ObjectWaiter::TS_ENTER;
1192         p->_prev = q;
1193         q = p;
1194       }
1195 
1196       // Append the RATs to the EntryList
1197       // TODO: organize EntryList as a CDLL so we can locate the tail in constant-time.
1198       ObjectWaiter * Tail;
1199       for (Tail = _EntryList; Tail != NULL && Tail->_next != NULL;
1200            Tail = Tail->_next)
1201         /* empty */;
1202       if (Tail == NULL) {
1203         _EntryList = w;
1204       } else {
1205         Tail->_next = w;
1206         w->_prev = Tail;
1207       }
1208 
1209       // Fall thru into code that tries to wake a successor from EntryList
1210     }
1211 
1212     if (QMode == 4 && _cxq != NULL) {
1213       // Aggressively drain cxq into EntryList at the first opportunity.
1214       // This policy ensure that recently-run threads live at the head of EntryList.
1215 
1216       // Drain _cxq into EntryList - bulk transfer.
1217       // First, detach _cxq.
1218       // The following loop is tantamount to: w = swap(&cxq, NULL)
1219       w = _cxq;
1220       for (;;) {
1221         assert(w != NULL, "Invariant");
1222         ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr(NULL, &_cxq, w);
1223         if (u == w) break;
1224         w = u;
1225       }
1226       assert(w != NULL, "invariant");
1227 
1228       ObjectWaiter * q = NULL;
1229       ObjectWaiter * p;
1230       for (p = w; p != NULL; p = p->_next) {
1231         guarantee(p->TState == ObjectWaiter::TS_CXQ, "Invariant");
1232         p->TState = ObjectWaiter::TS_ENTER;
1233         p->_prev = q;
1234         q = p;
1235       }
1236 
1237       // Prepend the RATs to the EntryList
1238       if (_EntryList != NULL) {
1239         q->_next = _EntryList;
1240         _EntryList->_prev = q;
1241       }
1242       _EntryList = w;
1243 
1244       // Fall thru into code that tries to wake a successor from EntryList
1245     }
1246 
1247     w = _EntryList;
1248     if (w != NULL) {
1249       // I'd like to write: guarantee (w->_thread != Self).
1250       // But in practice an exiting thread may find itself on the EntryList.
1251       // Let's say thread T1 calls O.wait().  Wait() enqueues T1 on O's waitset and
1252       // then calls exit().  Exit release the lock by setting O._owner to NULL.
1253       // Let's say T1 then stalls.  T2 acquires O and calls O.notify().  The
1254       // notify() operation moves T1 from O's waitset to O's EntryList. T2 then
1255       // release the lock "O".  T2 resumes immediately after the ST of null into
1256       // _owner, above.  T2 notices that the EntryList is populated, so it
1257       // reacquires the lock and then finds itself on the EntryList.
1258       // Given all that, we have to tolerate the circumstance where "w" is
1259       // associated with Self.
1260       assert(w->TState == ObjectWaiter::TS_ENTER, "invariant");
1261       ExitEpilog(Self, w);
1262       return;
1263     }
1264 
1265     // If we find that both _cxq and EntryList are null then just
1266     // re-run the exit protocol from the top.
1267     w = _cxq;
1268     if (w == NULL) continue;
1269 
1270     // Drain _cxq into EntryList - bulk transfer.
1271     // First, detach _cxq.
1272     // The following loop is tantamount to: w = swap(&cxq, NULL)
1273     for (;;) {
1274       assert(w != NULL, "Invariant");
1275       ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr(NULL, &_cxq, w);
1276       if (u == w) break;
1277       w = u;
1278     }
1279     TEVENT(Inflated exit - drain cxq into EntryList);
1280 
1281     assert(w != NULL, "invariant");
1282     assert(_EntryList == NULL, "invariant");
1283 
1284     // Convert the LIFO SLL anchored by _cxq into a DLL.
1285     // The list reorganization step operates in O(LENGTH(w)) time.
1286     // It's critical that this step operate quickly as
1287     // "Self" still holds the outer-lock, restricting parallelism
1288     // and effectively lengthening the critical section.
1289     // Invariant: s chases t chases u.
1290     // TODO-FIXME: consider changing EntryList from a DLL to a CDLL so
1291     // we have faster access to the tail.
1292 
1293     if (QMode == 1) {
1294       // QMode == 1 : drain cxq to EntryList, reversing order
1295       // We also reverse the order of the list.
1296       ObjectWaiter * s = NULL;
1297       ObjectWaiter * t = w;
1298       ObjectWaiter * u = NULL;
1299       while (t != NULL) {
1300         guarantee(t->TState == ObjectWaiter::TS_CXQ, "invariant");
1301         t->TState = ObjectWaiter::TS_ENTER;
1302         u = t->_next;
1303         t->_prev = u;
1304         t->_next = s;
1305         s = t;
1306         t = u;
1307       }
1308       _EntryList  = s;
1309       assert(s != NULL, "invariant");
1310     } else {
1311       // QMode == 0 or QMode == 2
1312       _EntryList = w;
1313       ObjectWaiter * q = NULL;
1314       ObjectWaiter * p;
1315       for (p = w; p != NULL; p = p->_next) {
1316         guarantee(p->TState == ObjectWaiter::TS_CXQ, "Invariant");
1317         p->TState = ObjectWaiter::TS_ENTER;
1318         p->_prev = q;
1319         q = p;
1320       }
1321     }
1322 
1323     // In 1-0 mode we need: ST EntryList; MEMBAR #storestore; ST _owner = NULL
1324     // The MEMBAR is satisfied by the release_store() operation in ExitEpilog().
1325 
1326     // See if we can abdicate to a spinner instead of waking a thread.
1327     // A primary goal of the implementation is to reduce the
1328     // context-switch rate.
1329     if (_succ != NULL) continue;
1330 
1331     w = _EntryList;
1332     if (w != NULL) {
1333       guarantee(w->TState == ObjectWaiter::TS_ENTER, "invariant");
1334       ExitEpilog(Self, w);
1335       return;
1336     }
1337   }
1338 }
1339 
1340 // ExitSuspendEquivalent:
1341 // A faster alternate to handle_special_suspend_equivalent_condition()
1342 //
1343 // handle_special_suspend_equivalent_condition() unconditionally
1344 // acquires the SR_lock.  On some platforms uncontended MutexLocker()
1345 // operations have high latency.  Note that in ::enter() we call HSSEC
1346 // while holding the monitor, so we effectively lengthen the critical sections.
1347 //
1348 // There are a number of possible solutions:
1349 //
1350 // A.  To ameliorate the problem we might also defer state transitions
1351 //     to as late as possible -- just prior to parking.
1352 //     Given that, we'd call HSSEC after having returned from park(),
1353 //     but before attempting to acquire the monitor.  This is only a
1354 //     partial solution.  It avoids calling HSSEC while holding the
1355 //     monitor (good), but it still increases successor reacquisition latency --
1356 //     the interval between unparking a successor and the time the successor
1357 //     resumes and retries the lock.  See ReenterI(), which defers state transitions.
1358 //     If we use this technique we can also avoid EnterI()-exit() loop
1359 //     in ::enter() where we iteratively drop the lock and then attempt
1360 //     to reacquire it after suspending.
1361 //
1362 // B.  In the future we might fold all the suspend bits into a
1363 //     composite per-thread suspend flag and then update it with CAS().
1364 //     Alternately, a Dekker-like mechanism with multiple variables
1365 //     would suffice:
1366 //       ST Self->_suspend_equivalent = false
1367 //       MEMBAR
1368 //       LD Self_>_suspend_flags
1369 //
1370 // UPDATE 2007-10-6: since I've replaced the native Mutex/Monitor subsystem
1371 // with a more efficient implementation, the need to use "FastHSSEC" has
1372 // decreased. - Dave
1373 
1374 
1375 bool ObjectMonitor::ExitSuspendEquivalent(JavaThread * jSelf) {
1376   const int Mode = Knob_FastHSSEC;
1377   if (Mode && !jSelf->is_external_suspend()) {
1378     assert(jSelf->is_suspend_equivalent(), "invariant");
1379     jSelf->clear_suspend_equivalent();
1380     if (2 == Mode) OrderAccess::storeload();
1381     if (!jSelf->is_external_suspend()) return false;
1382     // We raced a suspension -- fall thru into the slow path
1383     TEVENT(ExitSuspendEquivalent - raced);
1384     jSelf->set_suspend_equivalent();
1385   }
1386   return jSelf->handle_special_suspend_equivalent_condition();
1387 }
1388 
1389 
1390 void ObjectMonitor::ExitEpilog(Thread * Self, ObjectWaiter * Wakee) {
1391   assert(_owner == Self, "invariant");
1392 
1393   // Exit protocol:
1394   // 1. ST _succ = wakee
1395   // 2. membar #loadstore|#storestore;
1396   // 2. ST _owner = NULL
1397   // 3. unpark(wakee)
1398 
1399   _succ = Knob_SuccEnabled ? Wakee->_thread : NULL;
1400   ParkEvent * Trigger = Wakee->_event;
1401 
1402   // Hygiene -- once we've set _owner = NULL we can't safely dereference Wakee again.
1403   // The thread associated with Wakee may have grabbed the lock and "Wakee" may be
1404   // out-of-scope (non-extant).
1405   Wakee  = NULL;
1406 
1407   // Drop the lock
1408   OrderAccess::release_store_ptr(&_owner, NULL);
1409   OrderAccess::fence();                               // ST _owner vs LD in unpark()
1410 
1411   if (SafepointSynchronize::do_call_back()) {
1412     TEVENT(unpark before SAFEPOINT);
1413   }
1414 
1415   DTRACE_MONITOR_PROBE(contended__exit, this, object(), Self);
1416   Trigger->unpark();
1417 
1418   // Maintain stats and report events to JVMTI
1419   OM_PERFDATA_OP(Parks, inc());
1420 }
1421 
1422 
1423 // -----------------------------------------------------------------------------
1424 // Class Loader deadlock handling.
1425 //
1426 // complete_exit exits a lock returning recursion count
1427 // complete_exit/reenter operate as a wait without waiting
1428 // complete_exit requires an inflated monitor
1429 // The _owner field is not always the Thread addr even with an
1430 // inflated monitor, e.g. the monitor can be inflated by a non-owning
1431 // thread due to contention.
1432 intptr_t ObjectMonitor::complete_exit(TRAPS) {
1433   Thread * const Self = THREAD;
1434   assert(Self->is_Java_thread(), "Must be Java thread!");
1435   JavaThread *jt = (JavaThread *)THREAD;
1436 
1437   DeferredInitialize();
1438 
1439   if (THREAD != _owner) {
1440     if (THREAD->is_lock_owned ((address)_owner)) {
1441       assert(_recursions == 0, "internal state error");
1442       _owner = THREAD;   // Convert from basiclock addr to Thread addr
1443       _recursions = 0;
1444     }
1445   }
1446 
1447   guarantee(Self == _owner, "complete_exit not owner");
1448   intptr_t save = _recursions; // record the old recursion count
1449   _recursions = 0;        // set the recursion level to be 0
1450   exit(true, Self);           // exit the monitor
1451   guarantee(_owner != Self, "invariant");
1452   return save;
1453 }
1454 
1455 // reenter() enters a lock and sets recursion count
1456 // complete_exit/reenter operate as a wait without waiting
1457 bool ObjectMonitor::reenter(intptr_t recursions, TRAPS) {
1458   Thread * const Self = THREAD;
1459   assert(Self->is_Java_thread(), "Must be Java thread!");
1460   JavaThread *jt = (JavaThread *)THREAD;
1461 
1462   guarantee(_owner != Self, "reenter already owner");
1463   if (!enter(THREAD)) { return false; }      // enter the monitor
1464   guarantee(_recursions == 0, "reenter recursion");
1465   _recursions = recursions;
1466   return true;
1467 }
1468 
1469 
1470 // -----------------------------------------------------------------------------
1471 // A macro is used below because there may already be a pending
1472 // exception which should not abort the execution of the routines
1473 // which use this (which is why we don't put this into check_slow and
1474 // call it with a CHECK argument).
1475 
1476 #define CHECK_OWNER()                                                       \
1477   do {                                                                      \
1478     if (THREAD != _owner) {                                                 \
1479       if (THREAD->is_lock_owned((address) _owner)) {                        \
1480         _owner = THREAD;  /* Convert from basiclock addr to Thread addr */  \
1481         _recursions = 0;                                                    \
1482       } else {                                                              \
1483         TEVENT(Throw IMSX);                                                 \
1484         THROW(vmSymbols::java_lang_IllegalMonitorStateException());         \
1485       }                                                                     \
1486     }                                                                       \
1487   } while (false)
1488 
1489 // check_slow() is a misnomer.  It's called to simply to throw an IMSX exception.
1490 // TODO-FIXME: remove check_slow() -- it's likely dead.
1491 
1492 void ObjectMonitor::check_slow(TRAPS) {
1493   TEVENT(check_slow - throw IMSX);
1494   assert(THREAD != _owner && !THREAD->is_lock_owned((address) _owner), "must not be owner");
1495   THROW_MSG(vmSymbols::java_lang_IllegalMonitorStateException(), "current thread not owner");
1496 }
1497 
1498 static int Adjust(volatile int * adr, int dx) {
1499   int v;
1500   for (v = *adr; Atomic::cmpxchg(v + dx, adr, v) != v; v = *adr) /* empty */;
1501   return v;
1502 }
1503 
1504 // helper method for posting a monitor wait event
1505 void ObjectMonitor::post_monitor_wait_event(EventJavaMonitorWait* event,
1506                                             jlong notifier_tid,
1507                                             jlong timeout,
1508                                             bool timedout) {
1509   assert(event != NULL, "invariant");
1510   event->set_monitorClass(((oop)this->object())->klass());
1511   event->set_timeout(timeout);
1512   event->set_address((TYPE_ADDRESS)this->object_addr());
1513   event->set_notifier(notifier_tid);
1514   event->set_timedOut(timedout);
1515   event->commit();
1516 }
1517 
1518 // -----------------------------------------------------------------------------
1519 // Wait/Notify/NotifyAll
1520 //
1521 // Note: a subset of changes to ObjectMonitor::wait()
1522 // will need to be replicated in complete_exit
1523 void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) {
1524   Thread * const Self = THREAD;
1525   assert(Self->is_Java_thread(), "Must be Java thread!");
1526   JavaThread *jt = (JavaThread *)THREAD;
1527 
1528   DeferredInitialize();
1529 
1530   // Throw IMSX or IEX.
1531   CHECK_OWNER();
1532 
1533   EventJavaMonitorWait event;
1534 
1535   // check for a pending interrupt
1536   if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) {
1537     // post monitor waited event.  Note that this is past-tense, we are done waiting.
1538     if (JvmtiExport::should_post_monitor_waited()) {
1539       // Note: 'false' parameter is passed here because the
1540       // wait was not timed out due to thread interrupt.
1541       JvmtiExport::post_monitor_waited(jt, this, false);
1542 
1543       // In this short circuit of the monitor wait protocol, the
1544       // current thread never drops ownership of the monitor and
1545       // never gets added to the wait queue so the current thread
1546       // cannot be made the successor. This means that the
1547       // JVMTI_EVENT_MONITOR_WAITED event handler cannot accidentally
1548       // consume an unpark() meant for the ParkEvent associated with
1549       // this ObjectMonitor.
1550     }
1551     if (event.should_commit()) {
1552       post_monitor_wait_event(&event, 0, millis, false);
1553     }
1554     TEVENT(Wait - Throw IEX);
1555     THROW(vmSymbols::java_lang_InterruptedException());
1556     return;
1557   }
1558 
1559   TEVENT(Wait);
1560 
1561   assert(Self->_Stalled == 0, "invariant");
1562   Self->_Stalled = intptr_t(this);
1563   jt->set_current_waiting_monitor(this);
1564 
1565   // create a node to be put into the queue
1566   // Critically, after we reset() the event but prior to park(), we must check
1567   // for a pending interrupt.
1568   ObjectWaiter node(Self);
1569   node.TState = ObjectWaiter::TS_WAIT;
1570   Self->_ParkEvent->reset();
1571   OrderAccess::fence();          // ST into Event; membar ; LD interrupted-flag
1572 
1573   // Enter the waiting queue, which is a circular doubly linked list in this case
1574   // but it could be a priority queue or any data structure.
1575   // _WaitSetLock protects the wait queue.  Normally the wait queue is accessed only
1576   // by the the owner of the monitor *except* in the case where park()
1577   // returns because of a timeout of interrupt.  Contention is exceptionally rare
1578   // so we use a simple spin-lock instead of a heavier-weight blocking lock.
1579 
1580   Thread::SpinAcquire(&_WaitSetLock, "WaitSet - add");
1581   AddWaiter(&node);
1582   Thread::SpinRelease(&_WaitSetLock);
1583 
1584   if ((SyncFlags & 4) == 0) {
1585     _Responsible = NULL;
1586   }
1587   intptr_t save = _recursions; // record the old recursion count
1588   _waiters++;                  // increment the number of waiters
1589   _recursions = 0;             // set the recursion level to be 1
1590   exit(true, Self);                    // exit the monitor
1591   guarantee(_owner != Self, "invariant");
1592 
1593   // The thread is on the WaitSet list - now park() it.
1594   // On MP systems it's conceivable that a brief spin before we park
1595   // could be profitable.
1596   //
1597   // TODO-FIXME: change the following logic to a loop of the form
1598   //   while (!timeout && !interrupted && _notified == 0) park()
1599 
1600   int ret = OS_OK;
1601   int WasNotified = 0;
1602   { // State transition wrappers
1603     OSThread* osthread = Self->osthread();
1604     OSThreadWaitState osts(osthread, true);
1605     {
1606       ThreadBlockInVM tbivm(jt);
1607       // Thread is in thread_blocked state and oop access is unsafe.
1608       jt->set_suspend_equivalent();
1609 
1610       if (interruptible && (Thread::is_interrupted(THREAD, false) || HAS_PENDING_EXCEPTION)) {
1611         // Intentionally empty
1612       } else if (node._notified == 0) {
1613         if (millis <= 0) {
1614           Self->_ParkEvent->park();
1615         } else {
1616           ret = Self->_ParkEvent->park(millis);
1617         }
1618       }
1619 
1620       // were we externally suspended while we were waiting?
1621       if (ExitSuspendEquivalent (jt)) {
1622         // TODO-FIXME: add -- if succ == Self then succ = null.
1623         jt->java_suspend_self();
1624       }
1625 
1626     } // Exit thread safepoint: transition _thread_blocked -> _thread_in_vm
1627 
1628     // Node may be on the WaitSet, the EntryList (or cxq), or in transition
1629     // from the WaitSet to the EntryList.
1630     // See if we need to remove Node from the WaitSet.
1631     // We use double-checked locking to avoid grabbing _WaitSetLock
1632     // if the thread is not on the wait queue.
1633     //
1634     // Note that we don't need a fence before the fetch of TState.
1635     // In the worst case we'll fetch a old-stale value of TS_WAIT previously
1636     // written by the is thread. (perhaps the fetch might even be satisfied
1637     // by a look-aside into the processor's own store buffer, although given
1638     // the length of the code path between the prior ST and this load that's
1639     // highly unlikely).  If the following LD fetches a stale TS_WAIT value
1640     // then we'll acquire the lock and then re-fetch a fresh TState value.
1641     // That is, we fail toward safety.
1642 
1643     if (node.TState == ObjectWaiter::TS_WAIT) {
1644       Thread::SpinAcquire(&_WaitSetLock, "WaitSet - unlink");
1645       if (node.TState == ObjectWaiter::TS_WAIT) {
1646         DequeueSpecificWaiter(&node);       // unlink from WaitSet
1647         assert(node._notified == 0, "invariant");
1648         node.TState = ObjectWaiter::TS_RUN;
1649       }
1650       Thread::SpinRelease(&_WaitSetLock);
1651     }
1652 
1653     // The thread is now either on off-list (TS_RUN),
1654     // on the EntryList (TS_ENTER), or on the cxq (TS_CXQ).
1655     // The Node's TState variable is stable from the perspective of this thread.
1656     // No other threads will asynchronously modify TState.
1657     guarantee(node.TState != ObjectWaiter::TS_WAIT, "invariant");
1658     OrderAccess::loadload();
1659     if (_succ == Self) _succ = NULL;
1660     WasNotified = node._notified;
1661 
1662     // Reentry phase -- reacquire the monitor.
1663     // re-enter contended monitor after object.wait().
1664     // retain OBJECT_WAIT state until re-enter successfully completes
1665     // Thread state is thread_in_vm and oop access is again safe,
1666     // although the raw address of the object may have changed.
1667     // (Don't cache naked oops over safepoints, of course).
1668 
1669     // post monitor waited event. Note that this is past-tense, we are done waiting.
1670     if (JvmtiExport::should_post_monitor_waited()) {
1671       JvmtiExport::post_monitor_waited(jt, this, ret == OS_TIMEOUT);
1672 
1673       if (node._notified != 0 && _succ == Self) {
1674         // In this part of the monitor wait-notify-reenter protocol it
1675         // is possible (and normal) for another thread to do a fastpath
1676         // monitor enter-exit while this thread is still trying to get
1677         // to the reenter portion of the protocol.
1678         //
1679         // The ObjectMonitor was notified and the current thread is
1680         // the successor which also means that an unpark() has already
1681         // been done. The JVMTI_EVENT_MONITOR_WAITED event handler can
1682         // consume the unpark() that was done when the successor was
1683         // set because the same ParkEvent is shared between Java
1684         // monitors and JVM/TI RawMonitors (for now).
1685         //
1686         // We redo the unpark() to ensure forward progress, i.e., we
1687         // don't want all pending threads hanging (parked) with none
1688         // entering the unlocked monitor.
1689         node._event->unpark();
1690       }
1691     }
1692 
1693     if (event.should_commit()) {
1694       post_monitor_wait_event(&event, node._notifier_tid, millis, ret == OS_TIMEOUT);
1695     }
1696 
1697     OrderAccess::fence();
1698 
1699     assert(Self->_Stalled != 0, "invariant");
1700     Self->_Stalled = 0;
1701 
1702     assert(_owner != Self, "invariant");
1703     ObjectWaiter::TStates v = node.TState;
1704     if (v == ObjectWaiter::TS_RUN) {
1705       DEBUG_ONLY(const bool success = ) enter(Self);
1706       assert(success, "enter signalled that we should retry, but monitor should not be deflated as waiters > 0");
1707     } else {
1708       guarantee(v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant");
1709       ReenterI(Self, &node);
1710       node.wait_reenter_end(this);
1711     }
1712 
1713     // Self has reacquired the lock.
1714     // Lifecycle - the node representing Self must not appear on any queues.
1715     // Node is about to go out-of-scope, but even if it were immortal we wouldn't
1716     // want residual elements associated with this thread left on any lists.
1717     guarantee(node.TState == ObjectWaiter::TS_RUN, "invariant");
1718     assert(_owner == Self, "invariant");
1719     assert(_succ != Self, "invariant");
1720   } // OSThreadWaitState()
1721 
1722   jt->set_current_waiting_monitor(NULL);
1723 
1724   guarantee(_recursions == 0, "invariant");
1725   _recursions = save;     // restore the old recursion count
1726   _waiters--;             // decrement the number of waiters
1727 
1728   // Verify a few postconditions
1729   assert(_owner == Self, "invariant");
1730   assert(_succ != Self, "invariant");
1731   assert(((oop)(object()))->mark() == markOopDesc::encode(this), "invariant");
1732 
1733   if (SyncFlags & 32) {
1734     OrderAccess::fence();
1735   }
1736 
1737   // check if the notification happened
1738   if (!WasNotified) {
1739     // no, it could be timeout or Thread.interrupt() or both
1740     // check for interrupt event, otherwise it is timeout
1741     if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) {
1742       TEVENT(Wait - throw IEX from epilog);
1743       THROW(vmSymbols::java_lang_InterruptedException());
1744     }
1745   }
1746 
1747   // NOTE: Spurious wake up will be consider as timeout.
1748   // Monitor notify has precedence over thread interrupt.
1749 }
1750 
1751 
1752 // Consider:
1753 // If the lock is cool (cxq == null && succ == null) and we're on an MP system
1754 // then instead of transferring a thread from the WaitSet to the EntryList
1755 // we might just dequeue a thread from the WaitSet and directly unpark() it.
1756 
1757 void ObjectMonitor::INotify(Thread * Self) {
1758   const int policy = Knob_MoveNotifyee;
1759 
1760   Thread::SpinAcquire(&_WaitSetLock, "WaitSet - notify");
1761   ObjectWaiter * iterator = DequeueWaiter();
1762   if (iterator != NULL) {
1763     TEVENT(Notify1 - Transfer);
1764     guarantee(iterator->TState == ObjectWaiter::TS_WAIT, "invariant");
1765     guarantee(iterator->_notified == 0, "invariant");
1766     // Disposition - what might we do with iterator ?
1767     // a.  add it directly to the EntryList - either tail (policy == 1)
1768     //     or head (policy == 0).
1769     // b.  push it onto the front of the _cxq (policy == 2).
1770     // For now we use (b).
1771     if (policy != 4) {
1772       iterator->TState = ObjectWaiter::TS_ENTER;
1773     }
1774     iterator->_notified = 1;
1775     iterator->_notifier_tid = THREAD_TRACE_ID(Self);
1776 
1777     ObjectWaiter * list = _EntryList;
1778     if (list != NULL) {
1779       assert(list->_prev == NULL, "invariant");
1780       assert(list->TState == ObjectWaiter::TS_ENTER, "invariant");
1781       assert(list != iterator, "invariant");
1782     }
1783 
1784     if (policy == 0) {       // prepend to EntryList
1785       if (list == NULL) {
1786         iterator->_next = iterator->_prev = NULL;
1787         _EntryList = iterator;
1788       } else {
1789         list->_prev = iterator;
1790         iterator->_next = list;
1791         iterator->_prev = NULL;
1792         _EntryList = iterator;
1793       }
1794     } else if (policy == 1) {      // append to EntryList
1795       if (list == NULL) {
1796         iterator->_next = iterator->_prev = NULL;
1797         _EntryList = iterator;
1798       } else {
1799         // CONSIDER:  finding the tail currently requires a linear-time walk of
1800         // the EntryList.  We can make tail access constant-time by converting to
1801         // a CDLL instead of using our current DLL.
1802         ObjectWaiter * tail;
1803         for (tail = list; tail->_next != NULL; tail = tail->_next) /* empty */;
1804         assert(tail != NULL && tail->_next == NULL, "invariant");
1805         tail->_next = iterator;
1806         iterator->_prev = tail;
1807         iterator->_next = NULL;
1808       }
1809     } else if (policy == 2) {      // prepend to cxq
1810       if (list == NULL) {
1811         iterator->_next = iterator->_prev = NULL;
1812         _EntryList = iterator;
1813       } else {
1814         iterator->TState = ObjectWaiter::TS_CXQ;
1815         for (;;) {
1816           ObjectWaiter * front = _cxq;
1817           iterator->_next = front;
1818           if (Atomic::cmpxchg_ptr(iterator, &_cxq, front) == front) {
1819             break;
1820           }
1821         }
1822       }
1823     } else if (policy == 3) {      // append to cxq
1824       iterator->TState = ObjectWaiter::TS_CXQ;
1825       for (;;) {
1826         ObjectWaiter * tail = _cxq;
1827         if (tail == NULL) {
1828           iterator->_next = NULL;
1829           if (Atomic::cmpxchg_ptr(iterator, &_cxq, NULL) == NULL) {
1830             break;
1831           }
1832         } else {
1833           while (tail->_next != NULL) tail = tail->_next;
1834           tail->_next = iterator;
1835           iterator->_prev = tail;
1836           iterator->_next = NULL;
1837           break;
1838         }
1839       }
1840     } else {
1841       ParkEvent * ev = iterator->_event;
1842       iterator->TState = ObjectWaiter::TS_RUN;
1843       OrderAccess::fence();
1844       ev->unpark();
1845     }
1846 
1847     // _WaitSetLock protects the wait queue, not the EntryList.  We could
1848     // move the add-to-EntryList operation, above, outside the critical section
1849     // protected by _WaitSetLock.  In practice that's not useful.  With the
1850     // exception of  wait() timeouts and interrupts the monitor owner
1851     // is the only thread that grabs _WaitSetLock.  There's almost no contention
1852     // on _WaitSetLock so it's not profitable to reduce the length of the
1853     // critical section.
1854 
1855     if (policy < 4) {
1856       iterator->wait_reenter_begin(this);
1857     }
1858   }
1859   Thread::SpinRelease(&_WaitSetLock);
1860 }
1861 
1862 // Consider: a not-uncommon synchronization bug is to use notify() when
1863 // notifyAll() is more appropriate, potentially resulting in stranded
1864 // threads; this is one example of a lost wakeup. A useful diagnostic
1865 // option is to force all notify() operations to behave as notifyAll().
1866 //
1867 // Note: We can also detect many such problems with a "minimum wait".
1868 // When the "minimum wait" is set to a small non-zero timeout value
1869 // and the program does not hang whereas it did absent "minimum wait",
1870 // that suggests a lost wakeup bug. The '-XX:SyncFlags=1' option uses
1871 // a "minimum wait" for all park() operations; see the recheckInterval
1872 // variable and MAX_RECHECK_INTERVAL.
1873 
1874 void ObjectMonitor::notify(TRAPS) {
1875   CHECK_OWNER();
1876   if (_WaitSet == NULL) {
1877     TEVENT(Empty-Notify);
1878     return;
1879   }
1880   DTRACE_MONITOR_PROBE(notify, this, object(), THREAD);
1881   INotify(THREAD);
1882   OM_PERFDATA_OP(Notifications, inc(1));
1883 }
1884 
1885 
1886 // The current implementation of notifyAll() transfers the waiters one-at-a-time
1887 // from the waitset to the EntryList. This could be done more efficiently with a
1888 // single bulk transfer but in practice it's not time-critical. Beware too,
1889 // that in prepend-mode we invert the order of the waiters. Let's say that the
1890 // waitset is "ABCD" and the EntryList is "XYZ". After a notifyAll() in prepend
1891 // mode the waitset will be empty and the EntryList will be "DCBAXYZ".
1892 
1893 void ObjectMonitor::notifyAll(TRAPS) {
1894   CHECK_OWNER();
1895   if (_WaitSet == NULL) {
1896     TEVENT(Empty-NotifyAll);
1897     return;
1898   }
1899 
1900   DTRACE_MONITOR_PROBE(notifyAll, this, object(), THREAD);
1901   int tally = 0;
1902   while (_WaitSet != NULL) {
1903     tally++;
1904     INotify(THREAD);
1905   }
1906 
1907   OM_PERFDATA_OP(Notifications, inc(tally));
1908 }
1909 
1910 // -----------------------------------------------------------------------------
1911 // Adaptive Spinning Support
1912 //
1913 // Adaptive spin-then-block - rational spinning
1914 //
1915 // Note that we spin "globally" on _owner with a classic SMP-polite TATAS
1916 // algorithm.  On high order SMP systems it would be better to start with
1917 // a brief global spin and then revert to spinning locally.  In the spirit of MCS/CLH,
1918 // a contending thread could enqueue itself on the cxq and then spin locally
1919 // on a thread-specific variable such as its ParkEvent._Event flag.
1920 // That's left as an exercise for the reader.  Note that global spinning is
1921 // not problematic on Niagara, as the L2 cache serves the interconnect and
1922 // has both low latency and massive bandwidth.
1923 //
1924 // Broadly, we can fix the spin frequency -- that is, the % of contended lock
1925 // acquisition attempts where we opt to spin --  at 100% and vary the spin count
1926 // (duration) or we can fix the count at approximately the duration of
1927 // a context switch and vary the frequency.   Of course we could also
1928 // vary both satisfying K == Frequency * Duration, where K is adaptive by monitor.
1929 // For a description of 'Adaptive spin-then-block mutual exclusion in
1930 // multi-threaded processing,' see U.S. Pat. No. 8046758.
1931 //
1932 // This implementation varies the duration "D", where D varies with
1933 // the success rate of recent spin attempts. (D is capped at approximately
1934 // length of a round-trip context switch).  The success rate for recent
1935 // spin attempts is a good predictor of the success rate of future spin
1936 // attempts.  The mechanism adapts automatically to varying critical
1937 // section length (lock modality), system load and degree of parallelism.
1938 // D is maintained per-monitor in _SpinDuration and is initialized
1939 // optimistically.  Spin frequency is fixed at 100%.
1940 //
1941 // Note that _SpinDuration is volatile, but we update it without locks
1942 // or atomics.  The code is designed so that _SpinDuration stays within
1943 // a reasonable range even in the presence of races.  The arithmetic
1944 // operations on _SpinDuration are closed over the domain of legal values,
1945 // so at worst a race will install and older but still legal value.
1946 // At the very worst this introduces some apparent non-determinism.
1947 // We might spin when we shouldn't or vice-versa, but since the spin
1948 // count are relatively short, even in the worst case, the effect is harmless.
1949 //
1950 // Care must be taken that a low "D" value does not become an
1951 // an absorbing state.  Transient spinning failures -- when spinning
1952 // is overall profitable -- should not cause the system to converge
1953 // on low "D" values.  We want spinning to be stable and predictable
1954 // and fairly responsive to change and at the same time we don't want
1955 // it to oscillate, become metastable, be "too" non-deterministic,
1956 // or converge on or enter undesirable stable absorbing states.
1957 //
1958 // We implement a feedback-based control system -- using past behavior
1959 // to predict future behavior.  We face two issues: (a) if the
1960 // input signal is random then the spin predictor won't provide optimal
1961 // results, and (b) if the signal frequency is too high then the control
1962 // system, which has some natural response lag, will "chase" the signal.
1963 // (b) can arise from multimodal lock hold times.  Transient preemption
1964 // can also result in apparent bimodal lock hold times.
1965 // Although sub-optimal, neither condition is particularly harmful, as
1966 // in the worst-case we'll spin when we shouldn't or vice-versa.
1967 // The maximum spin duration is rather short so the failure modes aren't bad.
1968 // To be conservative, I've tuned the gain in system to bias toward
1969 // _not spinning.  Relatedly, the system can sometimes enter a mode where it
1970 // "rings" or oscillates between spinning and not spinning.  This happens
1971 // when spinning is just on the cusp of profitability, however, so the
1972 // situation is not dire.  The state is benign -- there's no need to add
1973 // hysteresis control to damp the transition rate between spinning and
1974 // not spinning.
1975 
1976 // Spinning: Fixed frequency (100%), vary duration
1977 int ObjectMonitor::TrySpin(Thread * Self) {
1978   // Dumb, brutal spin.  Good for comparative measurements against adaptive spinning.
1979   int ctr = Knob_FixedSpin;
1980   if (ctr != 0) {
1981     while (--ctr >= 0) {
1982       if (TryLock(Self) > 0) return 1;
1983       SpinPause();
1984     }
1985     return 0;
1986   }
1987 
1988   for (ctr = Knob_PreSpin + 1; --ctr >= 0;) {
1989     if (TryLock(Self) > 0) {
1990       // Increase _SpinDuration ...
1991       // Note that we don't clamp SpinDuration precisely at SpinLimit.
1992       // Raising _SpurDuration to the poverty line is key.
1993       int x = _SpinDuration;
1994       if (x < Knob_SpinLimit) {
1995         if (x < Knob_Poverty) x = Knob_Poverty;
1996         _SpinDuration = x + Knob_BonusB;
1997       }
1998       return 1;
1999     }
2000     SpinPause();
2001   }
2002 
2003   // Admission control - verify preconditions for spinning
2004   //
2005   // We always spin a little bit, just to prevent _SpinDuration == 0 from
2006   // becoming an absorbing state.  Put another way, we spin briefly to
2007   // sample, just in case the system load, parallelism, contention, or lock
2008   // modality changed.
2009   //
2010   // Consider the following alternative:
2011   // Periodically set _SpinDuration = _SpinLimit and try a long/full
2012   // spin attempt.  "Periodically" might mean after a tally of
2013   // the # of failed spin attempts (or iterations) reaches some threshold.
2014   // This takes us into the realm of 1-out-of-N spinning, where we
2015   // hold the duration constant but vary the frequency.
2016 
2017   ctr = _SpinDuration;
2018   if (ctr < Knob_SpinBase) ctr = Knob_SpinBase;
2019   if (ctr <= 0) return 0;
2020 
2021   if (Knob_SuccRestrict && _succ != NULL) return 0;
2022   if (Knob_OState && NotRunnable (Self, (Thread *) _owner)) {
2023     TEVENT(Spin abort - notrunnable [TOP]);
2024     return 0;
2025   }
2026 
2027   int MaxSpin = Knob_MaxSpinners;
2028   if (MaxSpin >= 0) {
2029     if (_Spinner > MaxSpin) {
2030       TEVENT(Spin abort -- too many spinners);
2031       return 0;
2032     }
2033     // Slightly racy, but benign ...
2034     Adjust(&_Spinner, 1);
2035   }
2036 
2037   // We're good to spin ... spin ingress.
2038   // CONSIDER: use Prefetch::write() to avoid RTS->RTO upgrades
2039   // when preparing to LD...CAS _owner, etc and the CAS is likely
2040   // to succeed.
2041   int hits    = 0;
2042   int msk     = 0;
2043   int caspty  = Knob_CASPenalty;
2044   int oxpty   = Knob_OXPenalty;
2045   int sss     = Knob_SpinSetSucc;
2046   if (sss && _succ == NULL) _succ = Self;
2047   Thread * prv = NULL;
2048 
2049   // There are three ways to exit the following loop:
2050   // 1.  A successful spin where this thread has acquired the lock.
2051   // 2.  Spin failure with prejudice
2052   // 3.  Spin failure without prejudice
2053 
2054   while (--ctr >= 0) {
2055 
2056     // Periodic polling -- Check for pending GC
2057     // Threads may spin while they're unsafe.
2058     // We don't want spinning threads to delay the JVM from reaching
2059     // a stop-the-world safepoint or to steal cycles from GC.
2060     // If we detect a pending safepoint we abort in order that
2061     // (a) this thread, if unsafe, doesn't delay the safepoint, and (b)
2062     // this thread, if safe, doesn't steal cycles from GC.
2063     // This is in keeping with the "no loitering in runtime" rule.
2064     // We periodically check to see if there's a safepoint pending.
2065     if ((ctr & 0xFF) == 0) {
2066       if (SafepointSynchronize::do_call_back()) {
2067         TEVENT(Spin: safepoint);
2068         goto Abort;           // abrupt spin egress
2069       }
2070       if (Knob_UsePause & 1) SpinPause();
2071     }
2072 
2073     if (Knob_UsePause & 2) SpinPause();
2074 
2075     // Exponential back-off ...  Stay off the bus to reduce coherency traffic.
2076     // This is useful on classic SMP systems, but is of less utility on
2077     // N1-style CMT platforms.
2078     //
2079     // Trade-off: lock acquisition latency vs coherency bandwidth.
2080     // Lock hold times are typically short.  A histogram
2081     // of successful spin attempts shows that we usually acquire
2082     // the lock early in the spin.  That suggests we want to
2083     // sample _owner frequently in the early phase of the spin,
2084     // but then back-off and sample less frequently as the spin
2085     // progresses.  The back-off makes a good citizen on SMP big
2086     // SMP systems.  Oversampling _owner can consume excessive
2087     // coherency bandwidth.  Relatedly, if we _oversample _owner we
2088     // can inadvertently interfere with the the ST m->owner=null.
2089     // executed by the lock owner.
2090     if (ctr & msk) continue;
2091     ++hits;
2092     if ((hits & 0xF) == 0) {
2093       // The 0xF, above, corresponds to the exponent.
2094       // Consider: (msk+1)|msk
2095       msk = ((msk << 2)|3) & BackOffMask;
2096     }
2097 
2098     // Probe _owner with TATAS
2099     // If this thread observes the monitor transition or flicker
2100     // from locked to unlocked to locked, then the odds that this
2101     // thread will acquire the lock in this spin attempt go down
2102     // considerably.  The same argument applies if the CAS fails
2103     // or if we observe _owner change from one non-null value to
2104     // another non-null value.   In such cases we might abort
2105     // the spin without prejudice or apply a "penalty" to the
2106     // spin count-down variable "ctr", reducing it by 100, say.
2107 
2108     Thread * ox = (Thread *) _owner;
2109     if (ox == NULL) {
2110       ox = (Thread *) Atomic::cmpxchg_ptr(Self, &_owner, NULL);
2111       if (ox == NULL) {
2112         // The CAS succeeded -- this thread acquired ownership
2113         // Take care of some bookkeeping to exit spin state.
2114         if (sss && _succ == Self) {
2115           _succ = NULL;
2116         }
2117         if (MaxSpin > 0) Adjust(&_Spinner, -1);
2118 
2119         // Increase _SpinDuration :
2120         // The spin was successful (profitable) so we tend toward
2121         // longer spin attempts in the future.
2122         // CONSIDER: factor "ctr" into the _SpinDuration adjustment.
2123         // If we acquired the lock early in the spin cycle it
2124         // makes sense to increase _SpinDuration proportionally.
2125         // Note that we don't clamp SpinDuration precisely at SpinLimit.
2126         int x = _SpinDuration;
2127         if (x < Knob_SpinLimit) {
2128           if (x < Knob_Poverty) x = Knob_Poverty;
2129           _SpinDuration = x + Knob_Bonus;
2130         }
2131         return 1;
2132       }
2133 
2134       // The CAS failed ... we can take any of the following actions:
2135       // * penalize: ctr -= Knob_CASPenalty
2136       // * exit spin with prejudice -- goto Abort;
2137       // * exit spin without prejudice.
2138       // * Since CAS is high-latency, retry again immediately.
2139       prv = ox;
2140       TEVENT(Spin: cas failed);
2141       if (caspty == -2) break;
2142       if (caspty == -1) goto Abort;
2143       ctr -= caspty;
2144       continue;
2145     }
2146 
2147     // Did lock ownership change hands ?
2148     if (ox != prv && prv != NULL) {
2149       TEVENT(spin: Owner changed)
2150       if (oxpty == -2) break;
2151       if (oxpty == -1) goto Abort;
2152       ctr -= oxpty;
2153     }
2154     prv = ox;
2155 
2156     // Abort the spin if the owner is not executing.
2157     // The owner must be executing in order to drop the lock.
2158     // Spinning while the owner is OFFPROC is idiocy.
2159     // Consider: ctr -= RunnablePenalty ;
2160     if (Knob_OState && NotRunnable (Self, ox)) {
2161       TEVENT(Spin abort - notrunnable);
2162       goto Abort;
2163     }
2164     if (sss && _succ == NULL) _succ = Self;
2165   }
2166 
2167   // Spin failed with prejudice -- reduce _SpinDuration.
2168   // TODO: Use an AIMD-like policy to adjust _SpinDuration.
2169   // AIMD is globally stable.
2170   TEVENT(Spin failure);
2171   {
2172     int x = _SpinDuration;
2173     if (x > 0) {
2174       // Consider an AIMD scheme like: x -= (x >> 3) + 100
2175       // This is globally sample and tends to damp the response.
2176       x -= Knob_Penalty;
2177       if (x < 0) x = 0;
2178       _SpinDuration = x;
2179     }
2180   }
2181 
2182  Abort:
2183   if (MaxSpin >= 0) Adjust(&_Spinner, -1);
2184   if (sss && _succ == Self) {
2185     _succ = NULL;
2186     // Invariant: after setting succ=null a contending thread
2187     // must recheck-retry _owner before parking.  This usually happens
2188     // in the normal usage of TrySpin(), but it's safest
2189     // to make TrySpin() as foolproof as possible.
2190     OrderAccess::fence();
2191     if (TryLock(Self) > 0) return 1;
2192   }
2193   return 0;
2194 }
2195 
2196 // NotRunnable() -- informed spinning
2197 //
2198 // Don't bother spinning if the owner is not eligible to drop the lock.
2199 // Peek at the owner's schedctl.sc_state and Thread._thread_values and
2200 // spin only if the owner thread is _thread_in_Java or _thread_in_vm.
2201 // The thread must be runnable in order to drop the lock in timely fashion.
2202 // If the _owner is not runnable then spinning will not likely be
2203 // successful (profitable).
2204 //
2205 // Beware -- the thread referenced by _owner could have died
2206 // so a simply fetch from _owner->_thread_state might trap.
2207 // Instead, we use SafeFetchXX() to safely LD _owner->_thread_state.
2208 // Because of the lifecycle issues the schedctl and _thread_state values
2209 // observed by NotRunnable() might be garbage.  NotRunnable must
2210 // tolerate this and consider the observed _thread_state value
2211 // as advisory.
2212 //
2213 // Beware too, that _owner is sometimes a BasicLock address and sometimes
2214 // a thread pointer.
2215 // Alternately, we might tag the type (thread pointer vs basiclock pointer)
2216 // with the LSB of _owner.  Another option would be to probablistically probe
2217 // the putative _owner->TypeTag value.
2218 //
2219 // Checking _thread_state isn't perfect.  Even if the thread is
2220 // in_java it might be blocked on a page-fault or have been preempted
2221 // and sitting on a ready/dispatch queue.  _thread state in conjunction
2222 // with schedctl.sc_state gives us a good picture of what the
2223 // thread is doing, however.
2224 //
2225 // TODO: check schedctl.sc_state.
2226 // We'll need to use SafeFetch32() to read from the schedctl block.
2227 // See RFE #5004247 and http://sac.sfbay.sun.com/Archives/CaseLog/arc/PSARC/2005/351/
2228 //
2229 // The return value from NotRunnable() is *advisory* -- the
2230 // result is based on sampling and is not necessarily coherent.
2231 // The caller must tolerate false-negative and false-positive errors.
2232 // Spinning, in general, is probabilistic anyway.
2233 
2234 
2235 int ObjectMonitor::NotRunnable(Thread * Self, Thread * ox) {
2236   // Check ox->TypeTag == 2BAD.
2237   if (ox == NULL) return 0;
2238 
2239   // Avoid transitive spinning ...
2240   // Say T1 spins or blocks trying to acquire L.  T1._Stalled is set to L.
2241   // Immediately after T1 acquires L it's possible that T2, also
2242   // spinning on L, will see L.Owner=T1 and T1._Stalled=L.
2243   // This occurs transiently after T1 acquired L but before
2244   // T1 managed to clear T1.Stalled.  T2 does not need to abort
2245   // its spin in this circumstance.
2246   intptr_t BlockedOn = SafeFetchN((intptr_t *) &ox->_Stalled, intptr_t(1));
2247 
2248   if (BlockedOn == 1) return 1;
2249   if (BlockedOn != 0) {
2250     return BlockedOn != intptr_t(this) && _owner == ox;
2251   }
2252 
2253   assert(sizeof(((JavaThread *)ox)->_thread_state == sizeof(int)), "invariant");
2254   int jst = SafeFetch32((int *) &((JavaThread *) ox)->_thread_state, -1);;
2255   // consider also: jst != _thread_in_Java -- but that's overspecific.
2256   return jst == _thread_blocked || jst == _thread_in_native;
2257 }
2258 
2259 
2260 // -----------------------------------------------------------------------------
2261 // WaitSet management ...
2262 
2263 ObjectWaiter::ObjectWaiter(Thread* thread) {
2264   _next     = NULL;
2265   _prev     = NULL;
2266   _notified = 0;
2267   TState    = TS_RUN;
2268   _thread   = thread;
2269   _event    = thread->_ParkEvent;
2270   _active   = false;
2271   assert(_event != NULL, "invariant");
2272 }
2273 
2274 void ObjectWaiter::wait_reenter_begin(ObjectMonitor * const mon) {
2275   JavaThread *jt = (JavaThread *)this->_thread;
2276   _active = JavaThreadBlockedOnMonitorEnterState::wait_reenter_begin(jt, mon);
2277 }
2278 
2279 void ObjectWaiter::wait_reenter_end(ObjectMonitor * const mon) {
2280   JavaThread *jt = (JavaThread *)this->_thread;
2281   JavaThreadBlockedOnMonitorEnterState::wait_reenter_end(jt, _active);
2282 }
2283 
2284 inline void ObjectMonitor::AddWaiter(ObjectWaiter* node) {
2285   assert(node != NULL, "should not add NULL node");
2286   assert(node->_prev == NULL, "node already in list");
2287   assert(node->_next == NULL, "node already in list");
2288   // put node at end of queue (circular doubly linked list)
2289   if (_WaitSet == NULL) {
2290     _WaitSet = node;
2291     node->_prev = node;
2292     node->_next = node;
2293   } else {
2294     ObjectWaiter* head = _WaitSet;
2295     ObjectWaiter* tail = head->_prev;
2296     assert(tail->_next == head, "invariant check");
2297     tail->_next = node;
2298     head->_prev = node;
2299     node->_next = head;
2300     node->_prev = tail;
2301   }
2302 }
2303 
2304 inline ObjectWaiter* ObjectMonitor::DequeueWaiter() {
2305   // dequeue the very first waiter
2306   ObjectWaiter* waiter = _WaitSet;
2307   if (waiter) {
2308     DequeueSpecificWaiter(waiter);
2309   }
2310   return waiter;
2311 }
2312 
2313 inline void ObjectMonitor::DequeueSpecificWaiter(ObjectWaiter* node) {
2314   assert(node != NULL, "should not dequeue NULL node");
2315   assert(node->_prev != NULL, "node already removed from list");
2316   assert(node->_next != NULL, "node already removed from list");
2317   // when the waiter has woken up because of interrupt,
2318   // timeout or other spurious wake-up, dequeue the
2319   // waiter from waiting list
2320   ObjectWaiter* next = node->_next;
2321   if (next == node) {
2322     assert(node->_prev == node, "invariant check");
2323     _WaitSet = NULL;
2324   } else {
2325     ObjectWaiter* prev = node->_prev;
2326     assert(prev->_next == node, "invariant check");
2327     assert(next->_prev == node, "invariant check");
2328     next->_prev = prev;
2329     prev->_next = next;
2330     if (_WaitSet == node) {
2331       _WaitSet = next;
2332     }
2333   }
2334   node->_next = NULL;
2335   node->_prev = NULL;
2336 }
2337 
2338 // -----------------------------------------------------------------------------
2339 // PerfData support
2340 PerfCounter * ObjectMonitor::_sync_ContendedLockAttempts       = NULL;
2341 PerfCounter * ObjectMonitor::_sync_FutileWakeups               = NULL;
2342 PerfCounter * ObjectMonitor::_sync_Parks                       = NULL;
2343 PerfCounter * ObjectMonitor::_sync_EmptyNotifications          = NULL;
2344 PerfCounter * ObjectMonitor::_sync_Notifications               = NULL;
2345 PerfCounter * ObjectMonitor::_sync_PrivateA                    = NULL;
2346 PerfCounter * ObjectMonitor::_sync_PrivateB                    = NULL;
2347 PerfCounter * ObjectMonitor::_sync_SlowExit                    = NULL;
2348 PerfCounter * ObjectMonitor::_sync_SlowEnter                   = NULL;
2349 PerfCounter * ObjectMonitor::_sync_SlowNotify                  = NULL;
2350 PerfCounter * ObjectMonitor::_sync_SlowNotifyAll               = NULL;
2351 PerfCounter * ObjectMonitor::_sync_FailedSpins                 = NULL;
2352 PerfCounter * ObjectMonitor::_sync_SuccessfulSpins             = NULL;
2353 PerfCounter * ObjectMonitor::_sync_MonInCirculation            = NULL;
2354 PerfCounter * ObjectMonitor::_sync_MonScavenged                = NULL;
2355 PerfCounter * ObjectMonitor::_sync_Inflations                  = NULL;
2356 PerfCounter * ObjectMonitor::_sync_Deflations                  = NULL;
2357 PerfLongVariable * ObjectMonitor::_sync_MonExtant              = NULL;
2358 
2359 // One-shot global initialization for the sync subsystem.
2360 // We could also defer initialization and initialize on-demand
2361 // the first time we call inflate().  Initialization would
2362 // be protected - like so many things - by the MonitorCache_lock.
2363 
2364 void ObjectMonitor::Initialize() {
2365   static int InitializationCompleted = 0;
2366   assert(InitializationCompleted == 0, "invariant");
2367   InitializationCompleted = 1;
2368   if (UsePerfData) {
2369     EXCEPTION_MARK;
2370 #define NEWPERFCOUNTER(n)                                                \
2371   {                                                                      \
2372     n = PerfDataManager::create_counter(SUN_RT, #n, PerfData::U_Events,  \
2373                                         CHECK);                          \
2374   }
2375 #define NEWPERFVARIABLE(n)                                                \
2376   {                                                                       \
2377     n = PerfDataManager::create_variable(SUN_RT, #n, PerfData::U_Events,  \
2378                                          CHECK);                          \
2379   }
2380     NEWPERFCOUNTER(_sync_Inflations);
2381     NEWPERFCOUNTER(_sync_Deflations);
2382     NEWPERFCOUNTER(_sync_ContendedLockAttempts);
2383     NEWPERFCOUNTER(_sync_FutileWakeups);
2384     NEWPERFCOUNTER(_sync_Parks);
2385     NEWPERFCOUNTER(_sync_EmptyNotifications);
2386     NEWPERFCOUNTER(_sync_Notifications);
2387     NEWPERFCOUNTER(_sync_SlowEnter);
2388     NEWPERFCOUNTER(_sync_SlowExit);
2389     NEWPERFCOUNTER(_sync_SlowNotify);
2390     NEWPERFCOUNTER(_sync_SlowNotifyAll);
2391     NEWPERFCOUNTER(_sync_FailedSpins);
2392     NEWPERFCOUNTER(_sync_SuccessfulSpins);
2393     NEWPERFCOUNTER(_sync_PrivateA);
2394     NEWPERFCOUNTER(_sync_PrivateB);
2395     NEWPERFCOUNTER(_sync_MonInCirculation);
2396     NEWPERFCOUNTER(_sync_MonScavenged);
2397     NEWPERFVARIABLE(_sync_MonExtant);
2398 #undef NEWPERFCOUNTER
2399 #undef NEWPERFVARIABLE
2400   }
2401 }
2402 
2403 static char * kvGet(char * kvList, const char * Key) {
2404   if (kvList == NULL) return NULL;
2405   size_t n = strlen(Key);
2406   char * Search;
2407   for (Search = kvList; *Search; Search += strlen(Search) + 1) {
2408     if (strncmp (Search, Key, n) == 0) {
2409       if (Search[n] == '=') return Search + n + 1;
2410       if (Search[n] == 0)   return(char *) "1";
2411     }
2412   }
2413   return NULL;
2414 }
2415 
2416 static int kvGetInt(char * kvList, const char * Key, int Default) {
2417   char * v = kvGet(kvList, Key);
2418   int rslt = v ? ::strtol(v, NULL, 0) : Default;
2419   if (Knob_ReportSettings && v != NULL) {
2420     tty->print_cr("INFO: SyncKnob: %s %d(%d)", Key, rslt, Default) ;
2421     tty->flush();
2422   }
2423   return rslt;
2424 }
2425 
2426 void ObjectMonitor::DeferredInitialize() {
2427   if (InitDone > 0) return;
2428   if (Atomic::cmpxchg (-1, &InitDone, 0) != 0) {
2429     while (InitDone != 1) /* empty */;
2430     return;
2431   }
2432 
2433   // One-shot global initialization ...
2434   // The initialization is idempotent, so we don't need locks.
2435   // In the future consider doing this via os::init_2().
2436   // SyncKnobs consist of <Key>=<Value> pairs in the style
2437   // of environment variables.  Start by converting ':' to NUL.
2438 
2439   if (SyncKnobs == NULL) SyncKnobs = "";
2440 
2441   size_t sz = strlen(SyncKnobs);
2442   char * knobs = (char *) malloc(sz + 2);
2443   if (knobs == NULL) {
2444     vm_exit_out_of_memory(sz + 2, OOM_MALLOC_ERROR, "Parse SyncKnobs");
2445     guarantee(0, "invariant");
2446   }
2447   strcpy(knobs, SyncKnobs);
2448   knobs[sz+1] = 0;
2449   for (char * p = knobs; *p; p++) {
2450     if (*p == ':') *p = 0;
2451   }
2452 
2453   #define SETKNOB(x) { Knob_##x = kvGetInt(knobs, #x, Knob_##x); }
2454   SETKNOB(ReportSettings);
2455   SETKNOB(ExitRelease);
2456   SETKNOB(Verbose);
2457   SETKNOB(VerifyInUse);
2458   SETKNOB(VerifyMatch);
2459   SETKNOB(FixedSpin);
2460   SETKNOB(SpinLimit);
2461   SETKNOB(SpinBase);
2462   SETKNOB(SpinBackOff);
2463   SETKNOB(CASPenalty);
2464   SETKNOB(OXPenalty);
2465   SETKNOB(LogSpins);
2466   SETKNOB(SpinSetSucc);
2467   SETKNOB(SuccEnabled);
2468   SETKNOB(SuccRestrict);
2469   SETKNOB(Penalty);
2470   SETKNOB(Bonus);
2471   SETKNOB(BonusB);
2472   SETKNOB(Poverty);
2473   SETKNOB(SpinAfterFutile);
2474   SETKNOB(UsePause);
2475   SETKNOB(SpinEarly);
2476   SETKNOB(OState);
2477   SETKNOB(MaxSpinners);
2478   SETKNOB(PreSpin);
2479   SETKNOB(ExitPolicy);
2480   SETKNOB(QMode);
2481   SETKNOB(ResetEvent);
2482   SETKNOB(MoveNotifyee);
2483   SETKNOB(FastHSSEC);
2484   #undef SETKNOB
2485 
2486   if (Knob_Verbose) {
2487     sanity_checks();
2488   }
2489 
2490   if (os::is_MP()) {
2491     BackOffMask = (1 << Knob_SpinBackOff) - 1;
2492     if (Knob_ReportSettings) {
2493       tty->print_cr("INFO: BackOffMask=0x%X", BackOffMask);
2494     }
2495     // CONSIDER: BackOffMask = ROUNDUP_NEXT_POWER2 (ncpus-1)
2496   } else {
2497     Knob_SpinLimit = 0;
2498     Knob_SpinBase  = 0;
2499     Knob_PreSpin   = 0;
2500     Knob_FixedSpin = -1;
2501   }
2502 
2503   if (Knob_LogSpins == 0) {
2504     ObjectMonitor::_sync_FailedSpins = NULL;
2505   }
2506 
2507   free(knobs);
2508   OrderAccess::fence();
2509   InitDone = 1;
2510 }
2511 
2512 void ObjectMonitor::sanity_checks() {
2513   int error_cnt = 0;
2514   int warning_cnt = 0;
2515   bool verbose = Knob_Verbose != 0 NOT_PRODUCT(|| VerboseInternalVMTests);
2516 
2517   if (verbose) {
2518     tty->print_cr("INFO: sizeof(ObjectMonitor)=" SIZE_FORMAT,
2519                   sizeof(ObjectMonitor));
2520     tty->print_cr("INFO: sizeof(PaddedEnd<ObjectMonitor>)=" SIZE_FORMAT,
2521                   sizeof(PaddedEnd<ObjectMonitor>));
2522   }
2523 
2524   uint cache_line_size = VM_Version::L1_data_cache_line_size();
2525   if (verbose) {
2526     tty->print_cr("INFO: L1_data_cache_line_size=%u", cache_line_size);
2527   }
2528 
2529   ObjectMonitor dummy;
2530   u_char *addr_begin  = (u_char*)&dummy;
2531   u_char *addr_header = (u_char*)&dummy._header;
2532   u_char *addr_owner  = (u_char*)&dummy._owner;
2533 
2534   uint offset_header = (uint)(addr_header - addr_begin);
2535   if (verbose) tty->print_cr("INFO: offset(_header)=%u", offset_header);
2536 
2537   uint offset_owner = (uint)(addr_owner - addr_begin);
2538   if (verbose) tty->print_cr("INFO: offset(_owner)=%u", offset_owner);
2539 
2540   if ((uint)(addr_header - addr_begin) != 0) {
2541     tty->print_cr("ERROR: offset(_header) must be zero (0).");
2542     error_cnt++;
2543   }
2544 
2545   if (cache_line_size != 0) {
2546     // We were able to determine the L1 data cache line size so
2547     // do some cache line specific sanity checks
2548 
2549     if ((offset_owner - offset_header) < cache_line_size) {
2550       tty->print_cr("WARNING: the _header and _owner fields are closer "
2551                     "than a cache line which permits false sharing.");
2552       warning_cnt++;
2553     }
2554 
2555     if ((sizeof(PaddedEnd<ObjectMonitor>) % cache_line_size) != 0) {
2556       tty->print_cr("WARNING: PaddedEnd<ObjectMonitor> size is not a "
2557                     "multiple of a cache line which permits false sharing.");
2558       warning_cnt++;
2559     }
2560   }
2561 
2562   ObjectSynchronizer::sanity_checks(verbose, cache_line_size, &error_cnt,
2563                                     &warning_cnt);
2564 
2565   if (verbose || error_cnt != 0 || warning_cnt != 0) {
2566     tty->print_cr("INFO: error_cnt=%d", error_cnt);
2567     tty->print_cr("INFO: warning_cnt=%d", warning_cnt);
2568   }
2569 
2570   guarantee(error_cnt == 0,
2571             "Fatal error(s) found in ObjectMonitor::sanity_checks()");
2572 }
2573 
2574 #ifndef PRODUCT
2575 void ObjectMonitor_test() {
2576   ObjectMonitor::sanity_checks();
2577 }
2578 #endif