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