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