mutex.cpp revision 6402:2377269bd73d
1
2/*
3 * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 *
24 */
25
26#include "precompiled.hpp"
27#include "runtime/mutex.hpp"
28#include "runtime/orderAccess.inline.hpp"
29#include "runtime/osThread.hpp"
30#include "runtime/thread.inline.hpp"
31#include "utilities/events.hpp"
32#ifdef TARGET_OS_FAMILY_linux
33# include "mutex_linux.inline.hpp"
34#endif
35#ifdef TARGET_OS_FAMILY_solaris
36# include "mutex_solaris.inline.hpp"
37#endif
38#ifdef TARGET_OS_FAMILY_windows
39# include "mutex_windows.inline.hpp"
40#endif
41#ifdef TARGET_OS_FAMILY_bsd
42# include "mutex_bsd.inline.hpp"
43#endif
44
45// o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o
46//
47// Native Monitor-Mutex locking - theory of operations
48//
49// * Native Monitors are completely unrelated to Java-level monitors,
50//   although the "back-end" slow-path implementations share a common lineage.
51//   See objectMonitor:: in synchronizer.cpp.
52//   Native Monitors do *not* support nesting or recursion but otherwise
53//   they're basically Hoare-flavor monitors.
54//
55// * A thread acquires ownership of a Monitor/Mutex by CASing the LockByte
56//   in the _LockWord from zero to non-zero.  Note that the _Owner field
57//   is advisory and is used only to verify that the thread calling unlock()
58//   is indeed the last thread to have acquired the lock.
59//
60// * Contending threads "push" themselves onto the front of the contention
61//   queue -- called the cxq -- with CAS and then spin/park.
62//   The _LockWord contains the LockByte as well as the pointer to the head
63//   of the cxq.  Colocating the LockByte with the cxq precludes certain races.
64//
65// * Using a separately addressable LockByte allows for CAS:MEMBAR or CAS:0
66//   idioms.  We currently use MEMBAR in the uncontended unlock() path, as
67//   MEMBAR often has less latency than CAS.  If warranted, we could switch to
68//   a CAS:0 mode, using timers to close the resultant race, as is done
69//   with Java Monitors in synchronizer.cpp.
70//
71//   See the following for a discussion of the relative cost of atomics (CAS)
72//   MEMBAR, and ways to eliminate such instructions from the common-case paths:
73//   -- http://blogs.sun.com/dave/entry/biased_locking_in_hotspot
74//   -- http://blogs.sun.com/dave/resource/MustangSync.pdf
75//   -- http://blogs.sun.com/dave/resource/synchronization-public2.pdf
76//   -- synchronizer.cpp
77//
78// * Overall goals - desiderata
79//   1. Minimize context switching
80//   2. Minimize lock migration
81//   3. Minimize CPI -- affinity and locality
82//   4. Minimize the execution of high-latency instructions such as CAS or MEMBAR
83//   5. Minimize outer lock hold times
84//   6. Behave gracefully on a loaded system
85//
86// * Thread flow and list residency:
87//
88//   Contention queue --> EntryList --> OnDeck --> Owner --> !Owner
89//   [..resident on monitor list..]
90//   [...........contending..................]
91//
92//   -- The contention queue (cxq) contains recently-arrived threads (RATs).
93//      Threads on the cxq eventually drain into the EntryList.
94//   -- Invariant: a thread appears on at most one list -- cxq, EntryList
95//      or WaitSet -- at any one time.
96//   -- For a given monitor there can be at most one "OnDeck" thread at any
97//      given time but if needbe this particular invariant could be relaxed.
98//
99// * The WaitSet and EntryList linked lists are composed of ParkEvents.
100//   I use ParkEvent instead of threads as ParkEvents are immortal and
101//   type-stable, meaning we can safely unpark() a possibly stale
102//   list element in the unlock()-path.  (That's benign).
103//
104// * Succession policy - providing for progress:
105//
106//   As necessary, the unlock()ing thread identifies, unlinks, and unparks
107//   an "heir presumptive" tentative successor thread from the EntryList.
108//   This becomes the so-called "OnDeck" thread, of which there can be only
109//   one at any given time for a given monitor.  The wakee will recontend
110//   for ownership of monitor.
111//
112//   Succession is provided for by a policy of competitive handoff.
113//   The exiting thread does _not_ grant or pass ownership to the
114//   successor thread.  (This is also referred to as "handoff" succession").
115//   Instead the exiting thread releases ownership and possibly wakes
116//   a successor, so the successor can (re)compete for ownership of the lock.
117//
118//   Competitive handoff provides excellent overall throughput at the expense
119//   of short-term fairness.  If fairness is a concern then one remedy might
120//   be to add an AcquireCounter field to the monitor.  After a thread acquires
121//   the lock it will decrement the AcquireCounter field.  When the count
122//   reaches 0 the thread would reset the AcquireCounter variable, abdicate
123//   the lock directly to some thread on the EntryList, and then move itself to the
124//   tail of the EntryList.
125//
126//   But in practice most threads engage or otherwise participate in resource
127//   bounded producer-consumer relationships, so lock domination is not usually
128//   a practical concern.  Recall too, that in general it's easier to construct
129//   a fair lock from a fast lock, but not vice-versa.
130//
131// * The cxq can have multiple concurrent "pushers" but only one concurrent
132//   detaching thread.  This mechanism is immune from the ABA corruption.
133//   More precisely, the CAS-based "push" onto cxq is ABA-oblivious.
134//   We use OnDeck as a pseudo-lock to enforce the at-most-one detaching
135//   thread constraint.
136//
137// * Taken together, the cxq and the EntryList constitute or form a
138//   single logical queue of threads stalled trying to acquire the lock.
139//   We use two distinct lists to reduce heat on the list ends.
140//   Threads in lock() enqueue onto cxq while threads in unlock() will
141//   dequeue from the EntryList.  (c.f. Michael Scott's "2Q" algorithm).
142//   A key desideratum is to minimize queue & monitor metadata manipulation
143//   that occurs while holding the "outer" monitor lock -- that is, we want to
144//   minimize monitor lock holds times.
145//
146//   The EntryList is ordered by the prevailing queue discipline and
147//   can be organized in any convenient fashion, such as a doubly-linked list or
148//   a circular doubly-linked list.  If we need a priority queue then something akin
149//   to Solaris' sleepq would work nicely.  Viz.,
150//   -- http://agg.eng/ws/on10_nightly/source/usr/src/uts/common/os/sleepq.c.
151//   -- http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/uts/common/os/sleepq.c
152//   Queue discipline is enforced at ::unlock() time, when the unlocking thread
153//   drains the cxq into the EntryList, and orders or reorders the threads on the
154//   EntryList accordingly.
155//
156//   Barring "lock barging", this mechanism provides fair cyclic ordering,
157//   somewhat similar to an elevator-scan.
158//
159// * OnDeck
160//   --  For a given monitor there can be at most one OnDeck thread at any given
161//       instant.  The OnDeck thread is contending for the lock, but has been
162//       unlinked from the EntryList and cxq by some previous unlock() operations.
163//       Once a thread has been designated the OnDeck thread it will remain so
164//       until it manages to acquire the lock -- being OnDeck is a stable property.
165//   --  Threads on the EntryList or cxq are _not allowed to attempt lock acquisition.
166//   --  OnDeck also serves as an "inner lock" as follows.  Threads in unlock() will, after
167//       having cleared the LockByte and dropped the outer lock,  attempt to "trylock"
168//       OnDeck by CASing the field from null to non-null.  If successful, that thread
169//       is then responsible for progress and succession and can use CAS to detach and
170//       drain the cxq into the EntryList.  By convention, only this thread, the holder of
171//       the OnDeck inner lock, can manipulate the EntryList or detach and drain the
172//       RATs on the cxq into the EntryList.  This avoids ABA corruption on the cxq as
173//       we allow multiple concurrent "push" operations but restrict detach concurrency
174//       to at most one thread.  Having selected and detached a successor, the thread then
175//       changes the OnDeck to refer to that successor, and then unparks the successor.
176//       That successor will eventually acquire the lock and clear OnDeck.  Beware
177//       that the OnDeck usage as a lock is asymmetric.  A thread in unlock() transiently
178//       "acquires" OnDeck, performs queue manipulations, passes OnDeck to some successor,
179//       and then the successor eventually "drops" OnDeck.  Note that there's never
180//       any sense of contention on the inner lock, however.  Threads never contend
181//       or wait for the inner lock.
182//   --  OnDeck provides for futile wakeup throttling a described in section 3.3 of
183//       See http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf
184//       In a sense, OnDeck subsumes the ObjectMonitor _Succ and ObjectWaiter
185//       TState fields found in Java-level objectMonitors.  (See synchronizer.cpp).
186//
187// * Waiting threads reside on the WaitSet list -- wait() puts
188//   the caller onto the WaitSet.  Notify() or notifyAll() simply
189//   transfers threads from the WaitSet to either the EntryList or cxq.
190//   Subsequent unlock() operations will eventually unpark the notifyee.
191//   Unparking a notifee in notify() proper is inefficient - if we were to do so
192//   it's likely the notifyee would simply impale itself on the lock held
193//   by the notifier.
194//
195// * The mechanism is obstruction-free in that if the holder of the transient
196//   OnDeck lock in unlock() is preempted or otherwise stalls, other threads
197//   can still acquire and release the outer lock and continue to make progress.
198//   At worst, waking of already blocked contending threads may be delayed,
199//   but nothing worse.  (We only use "trylock" operations on the inner OnDeck
200//   lock).
201//
202// * Note that thread-local storage must be initialized before a thread
203//   uses Native monitors or mutexes.  The native monitor-mutex subsystem
204//   depends on Thread::current().
205//
206// * The monitor synchronization subsystem avoids the use of native
207//   synchronization primitives except for the narrow platform-specific
208//   park-unpark abstraction.  See the comments in os_solaris.cpp regarding
209//   the semantics of park-unpark.  Put another way, this monitor implementation
210//   depends only on atomic operations and park-unpark.  The monitor subsystem
211//   manages all RUNNING->BLOCKED and BLOCKED->READY transitions while the
212//   underlying OS manages the READY<->RUN transitions.
213//
214// * The memory consistency model provide by lock()-unlock() is at least as
215//   strong or stronger than the Java Memory model defined by JSR-133.
216//   That is, we guarantee at least entry consistency, if not stronger.
217//   See http://g.oswego.edu/dl/jmm/cookbook.html.
218//
219// * Thread:: currently contains a set of purpose-specific ParkEvents:
220//   _MutexEvent, _ParkEvent, etc.  A better approach might be to do away with
221//   the purpose-specific ParkEvents and instead implement a general per-thread
222//   stack of available ParkEvents which we could provision on-demand.  The
223//   stack acts as a local cache to avoid excessive calls to ParkEvent::Allocate()
224//   and ::Release().  A thread would simply pop an element from the local stack before it
225//   enqueued or park()ed.  When the contention was over the thread would
226//   push the no-longer-needed ParkEvent back onto its stack.
227//
228// * A slightly reduced form of ILock() and IUnlock() have been partially
229//   model-checked (Murphi) for safety and progress at T=1,2,3 and 4.
230//   It'd be interesting to see if TLA/TLC could be useful as well.
231//
232// * Mutex-Monitor is a low-level "leaf" subsystem.  That is, the monitor
233//   code should never call other code in the JVM that might itself need to
234//   acquire monitors or mutexes.  That's true *except* in the case of the
235//   ThreadBlockInVM state transition wrappers.  The ThreadBlockInVM DTOR handles
236//   mutator reentry (ingress) by checking for a pending safepoint in which case it will
237//   call SafepointSynchronize::block(), which in turn may call Safepoint_lock->lock(), etc.
238//   In that particular case a call to lock() for a given Monitor can end up recursively
239//   calling lock() on another monitor.   While distasteful, this is largely benign
240//   as the calls come from jacket that wraps lock(), and not from deep within lock() itself.
241//
242//   It's unfortunate that native mutexes and thread state transitions were convolved.
243//   They're really separate concerns and should have remained that way.  Melding
244//   them together was facile -- a bit too facile.   The current implementation badly
245//   conflates the two concerns.
246//
247// * TODO-FIXME:
248//
249//   -- Add DTRACE probes for contended acquire, contended acquired, contended unlock
250//      We should also add DTRACE probes in the ParkEvent subsystem for
251//      Park-entry, Park-exit, and Unpark.
252//
253//   -- We have an excess of mutex-like constructs in the JVM, namely:
254//      1. objectMonitors for Java-level synchronization (synchronizer.cpp)
255//      2. low-level muxAcquire and muxRelease
256//      3. low-level spinAcquire and spinRelease
257//      4. native Mutex:: and Monitor::
258//      5. jvm_raw_lock() and _unlock()
259//      6. JVMTI raw monitors -- distinct from (5) despite having a confusingly
260//         similar name.
261//
262// o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o
263
264
265// CASPTR() uses the canonical argument order that dominates in the literature.
266// Our internal cmpxchg_ptr() uses a bastardized ordering to accommodate Sun .il templates.
267
268#define CASPTR(a,c,s) intptr_t(Atomic::cmpxchg_ptr ((void *)(s),(void *)(a),(void *)(c)))
269#define UNS(x) (uintptr_t(x))
270#define TRACE(m) { static volatile int ctr = 0 ; int x = ++ctr ; if ((x & (x-1))==0) { ::printf ("%d:%s\n", x, #m); ::fflush(stdout); }}
271
272// Simplistic low-quality Marsaglia SHIFT-XOR RNG.
273// Bijective except for the trailing mask operation.
274// Useful for spin loops as the compiler can't optimize it away.
275
276static inline jint MarsagliaXORV (jint x) {
277  if (x == 0) x = 1|os::random() ;
278  x ^= x << 6;
279  x ^= ((unsigned)x) >> 21;
280  x ^= x << 7 ;
281  return x & 0x7FFFFFFF ;
282}
283
284static int Stall (int its) {
285  static volatile jint rv = 1 ;
286  volatile int OnFrame = 0 ;
287  jint v = rv ^ UNS(OnFrame) ;
288  while (--its >= 0) {
289    v = MarsagliaXORV (v) ;
290  }
291  // Make this impossible for the compiler to optimize away,
292  // but (mostly) avoid W coherency sharing on MP systems.
293  if (v == 0x12345) rv = v ;
294  return v ;
295}
296
297int Monitor::TryLock () {
298  intptr_t v = _LockWord.FullWord ;
299  for (;;) {
300    if ((v & _LBIT) != 0) return 0 ;
301    const intptr_t u = CASPTR (&_LockWord, v, v|_LBIT) ;
302    if (v == u) return 1 ;
303    v = u ;
304  }
305}
306
307int Monitor::TryFast () {
308  // Optimistic fast-path form ...
309  // Fast-path attempt for the common uncontended case.
310  // Avoid RTS->RTO $ coherence upgrade on typical SMP systems.
311  intptr_t v = CASPTR (&_LockWord, 0, _LBIT) ;  // agro ...
312  if (v == 0) return 1 ;
313
314  for (;;) {
315    if ((v & _LBIT) != 0) return 0 ;
316    const intptr_t u = CASPTR (&_LockWord, v, v|_LBIT) ;
317    if (v == u) return 1 ;
318    v = u ;
319  }
320}
321
322int Monitor::ILocked () {
323  const intptr_t w = _LockWord.FullWord & 0xFF ;
324  assert (w == 0 || w == _LBIT, "invariant") ;
325  return w == _LBIT ;
326}
327
328// Polite TATAS spinlock with exponential backoff - bounded spin.
329// Ideally we'd use processor cycles, time or vtime to control
330// the loop, but we currently use iterations.
331// All the constants within were derived empirically but work over
332// over the spectrum of J2SE reference platforms.
333// On Niagara-class systems the back-off is unnecessary but
334// is relatively harmless.  (At worst it'll slightly retard
335// acquisition times).  The back-off is critical for older SMP systems
336// where constant fetching of the LockWord would otherwise impair
337// scalability.
338//
339// Clamp spinning at approximately 1/2 of a context-switch round-trip.
340// See synchronizer.cpp for details and rationale.
341
342int Monitor::TrySpin (Thread * const Self) {
343  if (TryLock())    return 1 ;
344  if (!os::is_MP()) return 0 ;
345
346  int Probes  = 0 ;
347  int Delay   = 0 ;
348  int Steps   = 0 ;
349  int SpinMax = NativeMonitorSpinLimit ;
350  int flgs    = NativeMonitorFlags ;
351  for (;;) {
352    intptr_t v = _LockWord.FullWord;
353    if ((v & _LBIT) == 0) {
354      if (CASPTR (&_LockWord, v, v|_LBIT) == v) {
355        return 1 ;
356      }
357      continue ;
358    }
359
360    if ((flgs & 8) == 0) {
361      SpinPause () ;
362    }
363
364    // Periodically increase Delay -- variable Delay form
365    // conceptually: delay *= 1 + 1/Exponent
366    ++ Probes;
367    if (Probes > SpinMax) return 0 ;
368
369    if ((Probes & 0x7) == 0) {
370      Delay = ((Delay << 1)|1) & 0x7FF ;
371      // CONSIDER: Delay += 1 + (Delay/4); Delay &= 0x7FF ;
372    }
373
374    if (flgs & 2) continue ;
375
376    // Consider checking _owner's schedctl state, if OFFPROC abort spin.
377    // If the owner is OFFPROC then it's unlike that the lock will be dropped
378    // in a timely fashion, which suggests that spinning would not be fruitful
379    // or profitable.
380
381    // Stall for "Delay" time units - iterations in the current implementation.
382    // Avoid generating coherency traffic while stalled.
383    // Possible ways to delay:
384    //   PAUSE, SLEEP, MEMBAR #sync, MEMBAR #halt,
385    //   wr %g0,%asi, gethrtime, rdstick, rdtick, rdtsc, etc. ...
386    // Note that on Niagara-class systems we want to minimize STs in the
387    // spin loop.  N1 and brethren write-around the L1$ over the xbar into the L2$.
388    // Furthermore, they don't have a W$ like traditional SPARC processors.
389    // We currently use a Marsaglia Shift-Xor RNG loop.
390    Steps += Delay ;
391    if (Self != NULL) {
392      jint rv = Self->rng[0] ;
393      for (int k = Delay ; --k >= 0; ) {
394        rv = MarsagliaXORV (rv) ;
395        if ((flgs & 4) == 0 && SafepointSynchronize::do_call_back()) return 0 ;
396      }
397      Self->rng[0] = rv ;
398    } else {
399      Stall (Delay) ;
400    }
401  }
402}
403
404static int ParkCommon (ParkEvent * ev, jlong timo) {
405  // Diagnostic support - periodically unwedge blocked threads
406  intx nmt = NativeMonitorTimeout ;
407  if (nmt > 0 && (nmt < timo || timo <= 0)) {
408     timo = nmt ;
409  }
410  int err = OS_OK ;
411  if (0 == timo) {
412    ev->park() ;
413  } else {
414    err = ev->park(timo) ;
415  }
416  return err ;
417}
418
419inline int Monitor::AcquireOrPush (ParkEvent * ESelf) {
420  intptr_t v = _LockWord.FullWord ;
421  for (;;) {
422    if ((v & _LBIT) == 0) {
423      const intptr_t u = CASPTR (&_LockWord, v, v|_LBIT) ;
424      if (u == v) return 1 ;        // indicate acquired
425      v = u ;
426    } else {
427      // Anticipate success ...
428      ESelf->ListNext = (ParkEvent *) (v & ~_LBIT) ;
429      const intptr_t u = CASPTR (&_LockWord, v, intptr_t(ESelf)|_LBIT) ;
430      if (u == v) return 0 ;        // indicate pushed onto cxq
431      v = u ;
432    }
433    // Interference - LockWord change - just retry
434  }
435}
436
437// ILock and IWait are the lowest level primitive internal blocking
438// synchronization functions.  The callers of IWait and ILock must have
439// performed any needed state transitions beforehand.
440// IWait and ILock may directly call park() without any concern for thread state.
441// Note that ILock and IWait do *not* access _owner.
442// _owner is a higher-level logical concept.
443
444void Monitor::ILock (Thread * Self) {
445  assert (_OnDeck != Self->_MutexEvent, "invariant") ;
446
447  if (TryFast()) {
448 Exeunt:
449    assert (ILocked(), "invariant") ;
450    return ;
451  }
452
453  ParkEvent * const ESelf = Self->_MutexEvent ;
454  assert (_OnDeck != ESelf, "invariant") ;
455
456  // As an optimization, spinners could conditionally try to set ONDECK to _LBIT
457  // Synchronizer.cpp uses a similar optimization.
458  if (TrySpin (Self)) goto Exeunt ;
459
460  // Slow-path - the lock is contended.
461  // Either Enqueue Self on cxq or acquire the outer lock.
462  // LockWord encoding = (cxq,LOCKBYTE)
463  ESelf->reset() ;
464  OrderAccess::fence() ;
465
466  // Optional optimization ... try barging on the inner lock
467  if ((NativeMonitorFlags & 32) && CASPTR (&_OnDeck, NULL, UNS(Self)) == 0) {
468    goto OnDeck_LOOP ;
469  }
470
471  if (AcquireOrPush (ESelf)) goto Exeunt ;
472
473  // At any given time there is at most one ondeck thread.
474  // ondeck implies not resident on cxq and not resident on EntryList
475  // Only the OnDeck thread can try to acquire -- contended for -- the lock.
476  // CONSIDER: use Self->OnDeck instead of m->OnDeck.
477  // Deschedule Self so that others may run.
478  while (_OnDeck != ESelf) {
479    ParkCommon (ESelf, 0) ;
480  }
481
482  // Self is now in the ONDECK position and will remain so until it
483  // manages to acquire the lock.
484 OnDeck_LOOP:
485  for (;;) {
486    assert (_OnDeck == ESelf, "invariant") ;
487    if (TrySpin (Self)) break ;
488    // CONSIDER: if ESelf->TryPark() && TryLock() break ...
489    // It's probably wise to spin only if we *actually* blocked
490    // CONSIDER: check the lockbyte, if it remains set then
491    // preemptively drain the cxq into the EntryList.
492    // The best place and time to perform queue operations -- lock metadata --
493    // is _before having acquired the outer lock, while waiting for the lock to drop.
494    ParkCommon (ESelf, 0) ;
495  }
496
497  assert (_OnDeck == ESelf, "invariant") ;
498  _OnDeck = NULL ;
499
500  // Note that we current drop the inner lock (clear OnDeck) in the slow-path
501  // epilogue immediately after having acquired the outer lock.
502  // But instead we could consider the following optimizations:
503  // A. Shift or defer dropping the inner lock until the subsequent IUnlock() operation.
504  //    This might avoid potential reacquisition of the inner lock in IUlock().
505  // B. While still holding the inner lock, attempt to opportunistically select
506  //    and unlink the next ONDECK thread from the EntryList.
507  //    If successful, set ONDECK to refer to that thread, otherwise clear ONDECK.
508  //    It's critical that the select-and-unlink operation run in constant-time as
509  //    it executes when holding the outer lock and may artificially increase the
510  //    effective length of the critical section.
511  // Note that (A) and (B) are tantamount to succession by direct handoff for
512  // the inner lock.
513  goto Exeunt ;
514}
515
516void Monitor::IUnlock (bool RelaxAssert) {
517  assert (ILocked(), "invariant") ;
518  // Conceptually we need a MEMBAR #storestore|#loadstore barrier or fence immediately
519  // before the store that releases the lock.  Crucially, all the stores and loads in the
520  // critical section must be globally visible before the store of 0 into the lock-word
521  // that releases the lock becomes globally visible.  That is, memory accesses in the
522  // critical section should not be allowed to bypass or overtake the following ST that
523  // releases the lock.  As such, to prevent accesses within the critical section
524  // from "leaking" out, we need a release fence between the critical section and the
525  // store that releases the lock.  In practice that release barrier is elided on
526  // platforms with strong memory models such as TSO.
527  //
528  // Note that the OrderAccess::storeload() fence that appears after unlock store
529  // provides for progress conditions and succession and is _not related to exclusion
530  // safety or lock release consistency.
531  OrderAccess::release_store(&_LockWord.Bytes[_LSBINDEX], 0); // drop outer lock
532
533  OrderAccess::storeload ();
534  ParkEvent * const w = _OnDeck ;
535  assert (RelaxAssert || w != Thread::current()->_MutexEvent, "invariant") ;
536  if (w != NULL) {
537    // Either we have a valid ondeck thread or ondeck is transiently "locked"
538    // by some exiting thread as it arranges for succession.  The LSBit of
539    // OnDeck allows us to discriminate two cases.  If the latter, the
540    // responsibility for progress and succession lies with that other thread.
541    // For good performance, we also depend on the fact that redundant unpark()
542    // operations are cheap.  That is, repeated Unpark()ing of the ONDECK thread
543    // is inexpensive.  This approach provides implicit futile wakeup throttling.
544    // Note that the referent "w" might be stale with respect to the lock.
545    // In that case the following unpark() is harmless and the worst that'll happen
546    // is a spurious return from a park() operation.  Critically, if "w" _is stale,
547    // then progress is known to have occurred as that means the thread associated
548    // with "w" acquired the lock.  In that case this thread need take no further
549    // action to guarantee progress.
550    if ((UNS(w) & _LBIT) == 0) w->unpark() ;
551    return ;
552  }
553
554  intptr_t cxq = _LockWord.FullWord ;
555  if (((cxq & ~_LBIT)|UNS(_EntryList)) == 0) {
556    return ;      // normal fast-path exit - cxq and EntryList both empty
557  }
558  if (cxq & _LBIT) {
559    // Optional optimization ...
560    // Some other thread acquired the lock in the window since this
561    // thread released it.  Succession is now that thread's responsibility.
562    return ;
563  }
564
565 Succession:
566  // Slow-path exit - this thread must ensure succession and progress.
567  // OnDeck serves as lock to protect cxq and EntryList.
568  // Only the holder of OnDeck can manipulate EntryList or detach the RATs from cxq.
569  // Avoid ABA - allow multiple concurrent producers (enqueue via push-CAS)
570  // but only one concurrent consumer (detacher of RATs).
571  // Consider protecting this critical section with schedctl on Solaris.
572  // Unlike a normal lock, however, the exiting thread "locks" OnDeck,
573  // picks a successor and marks that thread as OnDeck.  That successor
574  // thread will then clear OnDeck once it eventually acquires the outer lock.
575  if (CASPTR (&_OnDeck, NULL, _LBIT) != UNS(NULL)) {
576    return ;
577  }
578
579  ParkEvent * List = _EntryList ;
580  if (List != NULL) {
581    // Transfer the head of the EntryList to the OnDeck position.
582    // Once OnDeck, a thread stays OnDeck until it acquires the lock.
583    // For a given lock there is at most OnDeck thread at any one instant.
584   WakeOne:
585    assert (List == _EntryList, "invariant") ;
586    ParkEvent * const w = List ;
587    assert (RelaxAssert || w != Thread::current()->_MutexEvent, "invariant") ;
588    _EntryList = w->ListNext ;
589    // as a diagnostic measure consider setting w->_ListNext = BAD
590    assert (UNS(_OnDeck) == _LBIT, "invariant") ;
591    _OnDeck = w ;           // pass OnDeck to w.
592                            // w will clear OnDeck once it acquires the outer lock
593
594    // Another optional optimization ...
595    // For heavily contended locks it's not uncommon that some other
596    // thread acquired the lock while this thread was arranging succession.
597    // Try to defer the unpark() operation - Delegate the responsibility
598    // for unpark()ing the OnDeck thread to the current or subsequent owners
599    // That is, the new owner is responsible for unparking the OnDeck thread.
600    OrderAccess::storeload() ;
601    cxq = _LockWord.FullWord ;
602    if (cxq & _LBIT) return ;
603
604    w->unpark() ;
605    return ;
606  }
607
608  cxq = _LockWord.FullWord ;
609  if ((cxq & ~_LBIT) != 0) {
610    // The EntryList is empty but the cxq is populated.
611    // drain RATs from cxq into EntryList
612    // Detach RATs segment with CAS and then merge into EntryList
613    for (;;) {
614      // optional optimization - if locked, the owner is responsible for succession
615      if (cxq & _LBIT) goto Punt ;
616      const intptr_t vfy = CASPTR (&_LockWord, cxq, cxq & _LBIT) ;
617      if (vfy == cxq) break ;
618      cxq = vfy ;
619      // Interference - LockWord changed - Just retry
620      // We can see concurrent interference from contending threads
621      // pushing themselves onto the cxq or from lock-unlock operations.
622      // From the perspective of this thread, EntryList is stable and
623      // the cxq is prepend-only -- the head is volatile but the interior
624      // of the cxq is stable.  In theory if we encounter interference from threads
625      // pushing onto cxq we could simply break off the original cxq suffix and
626      // move that segment to the EntryList, avoiding a 2nd or multiple CAS attempts
627      // on the high-traffic LockWord variable.   For instance lets say the cxq is "ABCD"
628      // when we first fetch cxq above.  Between the fetch -- where we observed "A"
629      // -- and CAS -- where we attempt to CAS null over A -- "PQR" arrive,
630      // yielding cxq = "PQRABCD".  In this case we could simply set A.ListNext
631      // null, leaving cxq = "PQRA" and transfer the "BCD" segment to the EntryList.
632      // Note too, that it's safe for this thread to traverse the cxq
633      // without taking any special concurrency precautions.
634    }
635
636    // We don't currently reorder the cxq segment as we move it onto
637    // the EntryList, but it might make sense to reverse the order
638    // or perhaps sort by thread priority.  See the comments in
639    // synchronizer.cpp objectMonitor::exit().
640    assert (_EntryList == NULL, "invariant") ;
641    _EntryList = List = (ParkEvent *)(cxq & ~_LBIT) ;
642    assert (List != NULL, "invariant") ;
643    goto WakeOne ;
644  }
645
646  // cxq|EntryList is empty.
647  // w == NULL implies that cxq|EntryList == NULL in the past.
648  // Possible race - rare inopportune interleaving.
649  // A thread could have added itself to cxq since this thread previously checked.
650  // Detect and recover by refetching cxq.
651 Punt:
652  assert (UNS(_OnDeck) == _LBIT, "invariant") ;
653  _OnDeck = NULL ;            // Release inner lock.
654  OrderAccess::storeload();   // Dekker duality - pivot point
655
656  // Resample LockWord/cxq to recover from possible race.
657  // For instance, while this thread T1 held OnDeck, some other thread T2 might
658  // acquire the outer lock.  Another thread T3 might try to acquire the outer
659  // lock, but encounter contention and enqueue itself on cxq.  T2 then drops the
660  // outer lock, but skips succession as this thread T1 still holds OnDeck.
661  // T1 is and remains responsible for ensuring succession of T3.
662  //
663  // Note that we don't need to recheck EntryList, just cxq.
664  // If threads moved onto EntryList since we dropped OnDeck
665  // that implies some other thread forced succession.
666  cxq = _LockWord.FullWord ;
667  if ((cxq & ~_LBIT) != 0 && (cxq & _LBIT) == 0) {
668    goto Succession ;         // potential race -- re-run succession
669  }
670  return ;
671}
672
673bool Monitor::notify() {
674  assert (_owner == Thread::current(), "invariant") ;
675  assert (ILocked(), "invariant") ;
676  if (_WaitSet == NULL) return true ;
677  NotifyCount ++ ;
678
679  // Transfer one thread from the WaitSet to the EntryList or cxq.
680  // Currently we just unlink the head of the WaitSet and prepend to the cxq.
681  // And of course we could just unlink it and unpark it, too, but
682  // in that case it'd likely impale itself on the reentry.
683  Thread::muxAcquire (_WaitLock, "notify:WaitLock") ;
684  ParkEvent * nfy = _WaitSet ;
685  if (nfy != NULL) {                  // DCL idiom
686    _WaitSet = nfy->ListNext ;
687    assert (nfy->Notified == 0, "invariant") ;
688    // push nfy onto the cxq
689    for (;;) {
690      const intptr_t v = _LockWord.FullWord ;
691      assert ((v & 0xFF) == _LBIT, "invariant") ;
692      nfy->ListNext = (ParkEvent *)(v & ~_LBIT);
693      if (CASPTR (&_LockWord, v, UNS(nfy)|_LBIT) == v) break;
694      // interference - _LockWord changed -- just retry
695    }
696    // Note that setting Notified before pushing nfy onto the cxq is
697    // also legal and safe, but the safety properties are much more
698    // subtle, so for the sake of code stewardship ...
699    OrderAccess::fence() ;
700    nfy->Notified = 1;
701  }
702  Thread::muxRelease (_WaitLock) ;
703  if (nfy != NULL && (NativeMonitorFlags & 16)) {
704    // Experimental code ... light up the wakee in the hope that this thread (the owner)
705    // will drop the lock just about the time the wakee comes ONPROC.
706    nfy->unpark() ;
707  }
708  assert (ILocked(), "invariant") ;
709  return true ;
710}
711
712// Currently notifyAll() transfers the waiters one-at-a-time from the waitset
713// to the cxq.  This could be done more efficiently with a single bulk en-mass transfer,
714// but in practice notifyAll() for large #s of threads is rare and not time-critical.
715// Beware too, that we invert the order of the waiters.  Lets say that the
716// waitset is "ABCD" and the cxq is "XYZ".  After a notifyAll() the waitset
717// will be empty and the cxq will be "DCBAXYZ".  This is benign, of course.
718
719bool Monitor::notify_all() {
720  assert (_owner == Thread::current(), "invariant") ;
721  assert (ILocked(), "invariant") ;
722  while (_WaitSet != NULL) notify() ;
723  return true ;
724}
725
726int Monitor::IWait (Thread * Self, jlong timo) {
727  assert (ILocked(), "invariant") ;
728
729  // Phases:
730  // 1. Enqueue Self on WaitSet - currently prepend
731  // 2. unlock - drop the outer lock
732  // 3. wait for either notification or timeout
733  // 4. lock - reentry - reacquire the outer lock
734
735  ParkEvent * const ESelf = Self->_MutexEvent ;
736  ESelf->Notified = 0 ;
737  ESelf->reset() ;
738  OrderAccess::fence() ;
739
740  // Add Self to WaitSet
741  // Ideally only the holder of the outer lock would manipulate the WaitSet -
742  // That is, the outer lock would implicitly protect the WaitSet.
743  // But if a thread in wait() encounters a timeout it will need to dequeue itself
744  // from the WaitSet _before it becomes the owner of the lock.  We need to dequeue
745  // as the ParkEvent -- which serves as a proxy for the thread -- can't reside
746  // on both the WaitSet and the EntryList|cxq at the same time..  That is, a thread
747  // on the WaitSet can't be allowed to compete for the lock until it has managed to
748  // unlink its ParkEvent from WaitSet.  Thus the need for WaitLock.
749  // Contention on the WaitLock is minimal.
750  //
751  // Another viable approach would be add another ParkEvent, "WaitEvent" to the
752  // thread class.  The WaitSet would be composed of WaitEvents.  Only the
753  // owner of the outer lock would manipulate the WaitSet.  A thread in wait()
754  // could then compete for the outer lock, and then, if necessary, unlink itself
755  // from the WaitSet only after having acquired the outer lock.  More precisely,
756  // there would be no WaitLock.  A thread in in wait() would enqueue its WaitEvent
757  // on the WaitSet; release the outer lock; wait for either notification or timeout;
758  // reacquire the inner lock; and then, if needed, unlink itself from the WaitSet.
759  //
760  // Alternatively, a 2nd set of list link fields in the ParkEvent might suffice.
761  // One set would be for the WaitSet and one for the EntryList.
762  // We could also deconstruct the ParkEvent into a "pure" event and add a
763  // new immortal/TSM "ListElement" class that referred to ParkEvents.
764  // In that case we could have one ListElement on the WaitSet and another
765  // on the EntryList, with both referring to the same pure Event.
766
767  Thread::muxAcquire (_WaitLock, "wait:WaitLock:Add") ;
768  ESelf->ListNext = _WaitSet ;
769  _WaitSet = ESelf ;
770  Thread::muxRelease (_WaitLock) ;
771
772  // Release the outer lock
773  // We call IUnlock (RelaxAssert=true) as a thread T1 might
774  // enqueue itself on the WaitSet, call IUnlock(), drop the lock,
775  // and then stall before it can attempt to wake a successor.
776  // Some other thread T2 acquires the lock, and calls notify(), moving
777  // T1 from the WaitSet to the cxq.  T2 then drops the lock.  T1 resumes,
778  // and then finds *itself* on the cxq.  During the course of a normal
779  // IUnlock() call a thread should _never find itself on the EntryList
780  // or cxq, but in the case of wait() it's possible.
781  // See synchronizer.cpp objectMonitor::wait().
782  IUnlock (true) ;
783
784  // Wait for either notification or timeout
785  // Beware that in some circumstances we might propagate
786  // spurious wakeups back to the caller.
787
788  for (;;) {
789    if (ESelf->Notified) break ;
790    int err = ParkCommon (ESelf, timo) ;
791    if (err == OS_TIMEOUT || (NativeMonitorFlags & 1)) break ;
792  }
793
794  // Prepare for reentry - if necessary, remove ESelf from WaitSet
795  // ESelf can be:
796  // 1. Still on the WaitSet.  This can happen if we exited the loop by timeout.
797  // 2. On the cxq or EntryList
798  // 3. Not resident on cxq, EntryList or WaitSet, but in the OnDeck position.
799
800  OrderAccess::fence() ;
801  int WasOnWaitSet = 0 ;
802  if (ESelf->Notified == 0) {
803    Thread::muxAcquire (_WaitLock, "wait:WaitLock:remove") ;
804    if (ESelf->Notified == 0) {     // DCL idiom
805      assert (_OnDeck != ESelf, "invariant") ;   // can't be both OnDeck and on WaitSet
806      // ESelf is resident on the WaitSet -- unlink it.
807      // A doubly-linked list would be better here so we can unlink in constant-time.
808      // We have to unlink before we potentially recontend as ESelf might otherwise
809      // end up on the cxq|EntryList -- it can't be on two lists at once.
810      ParkEvent * p = _WaitSet ;
811      ParkEvent * q = NULL ;            // classic q chases p
812      while (p != NULL && p != ESelf) {
813        q = p ;
814        p = p->ListNext ;
815      }
816      assert (p == ESelf, "invariant") ;
817      if (p == _WaitSet) {      // found at head
818        assert (q == NULL, "invariant") ;
819        _WaitSet = p->ListNext ;
820      } else {                  // found in interior
821        assert (q->ListNext == p, "invariant") ;
822        q->ListNext = p->ListNext ;
823      }
824      WasOnWaitSet = 1 ;        // We were *not* notified but instead encountered timeout
825    }
826    Thread::muxRelease (_WaitLock) ;
827  }
828
829  // Reentry phase - reacquire the lock
830  if (WasOnWaitSet) {
831    // ESelf was previously on the WaitSet but we just unlinked it above
832    // because of a timeout.  ESelf is not resident on any list and is not OnDeck
833    assert (_OnDeck != ESelf, "invariant") ;
834    ILock (Self) ;
835  } else {
836    // A prior notify() operation moved ESelf from the WaitSet to the cxq.
837    // ESelf is now on the cxq, EntryList or at the OnDeck position.
838    // The following fragment is extracted from Monitor::ILock()
839    for (;;) {
840      if (_OnDeck == ESelf && TrySpin(Self)) break ;
841      ParkCommon (ESelf, 0) ;
842    }
843    assert (_OnDeck == ESelf, "invariant") ;
844    _OnDeck = NULL ;
845  }
846
847  assert (ILocked(), "invariant") ;
848  return WasOnWaitSet != 0 ;        // return true IFF timeout
849}
850
851
852// ON THE VMTHREAD SNEAKING PAST HELD LOCKS:
853// In particular, there are certain types of global lock that may be held
854// by a Java thread while it is blocked at a safepoint but before it has
855// written the _owner field. These locks may be sneakily acquired by the
856// VM thread during a safepoint to avoid deadlocks. Alternatively, one should
857// identify all such locks, and ensure that Java threads never block at
858// safepoints while holding them (_no_safepoint_check_flag). While it
859// seems as though this could increase the time to reach a safepoint
860// (or at least increase the mean, if not the variance), the latter
861// approach might make for a cleaner, more maintainable JVM design.
862//
863// Sneaking is vile and reprehensible and should be excised at the 1st
864// opportunity.  It's possible that the need for sneaking could be obviated
865// as follows.  Currently, a thread might (a) while TBIVM, call pthread_mutex_lock
866// or ILock() thus acquiring the "physical" lock underlying Monitor/Mutex.
867// (b) stall at the TBIVM exit point as a safepoint is in effect.  Critically,
868// it'll stall at the TBIVM reentry state transition after having acquired the
869// underlying lock, but before having set _owner and having entered the actual
870// critical section.  The lock-sneaking facility leverages that fact and allowed the
871// VM thread to logically acquire locks that had already be physically locked by mutators
872// but where mutators were known blocked by the reentry thread state transition.
873//
874// If we were to modify the Monitor-Mutex so that TBIVM state transitions tightly
875// wrapped calls to park(), then we could likely do away with sneaking.  We'd
876// decouple lock acquisition and parking.  The critical invariant  to eliminating
877// sneaking is to ensure that we never "physically" acquire the lock while TBIVM.
878// An easy way to accomplish this is to wrap the park calls in a narrow TBIVM jacket.
879// One difficulty with this approach is that the TBIVM wrapper could recurse and
880// call lock() deep from within a lock() call, while the MutexEvent was already enqueued.
881// Using a stack (N=2 at minimum) of ParkEvents would take care of that problem.
882//
883// But of course the proper ultimate approach is to avoid schemes that require explicit
884// sneaking or dependence on any any clever invariants or subtle implementation properties
885// of Mutex-Monitor and instead directly address the underlying design flaw.
886
887void Monitor::lock (Thread * Self) {
888#ifdef CHECK_UNHANDLED_OOPS
889  // Clear unhandled oops so we get a crash right away.  Only clear for non-vm
890  // or GC threads.
891  if (Self->is_Java_thread()) {
892    Self->clear_unhandled_oops();
893  }
894#endif // CHECK_UNHANDLED_OOPS
895
896  debug_only(check_prelock_state(Self));
897  assert (_owner != Self              , "invariant") ;
898  assert (_OnDeck != Self->_MutexEvent, "invariant") ;
899
900  if (TryFast()) {
901 Exeunt:
902    assert (ILocked(), "invariant") ;
903    assert (owner() == NULL, "invariant");
904    set_owner (Self);
905    return ;
906  }
907
908  // The lock is contended ...
909
910  bool can_sneak = Self->is_VM_thread() && SafepointSynchronize::is_at_safepoint();
911  if (can_sneak && _owner == NULL) {
912    // a java thread has locked the lock but has not entered the
913    // critical region -- let's just pretend we've locked the lock
914    // and go on.  we note this with _snuck so we can also
915    // pretend to unlock when the time comes.
916    _snuck = true;
917    goto Exeunt ;
918  }
919
920  // Try a brief spin to avoid passing thru thread state transition ...
921  if (TrySpin (Self)) goto Exeunt ;
922
923  check_block_state(Self);
924  if (Self->is_Java_thread()) {
925    // Horrible dictu - we suffer through a state transition
926    assert(rank() > Mutex::special, "Potential deadlock with special or lesser rank mutex");
927    ThreadBlockInVM tbivm ((JavaThread *) Self) ;
928    ILock (Self) ;
929  } else {
930    // Mirabile dictu
931    ILock (Self) ;
932  }
933  goto Exeunt ;
934}
935
936void Monitor::lock() {
937  this->lock(Thread::current());
938}
939
940// Lock without safepoint check - a degenerate variant of lock().
941// Should ONLY be used by safepoint code and other code
942// that is guaranteed not to block while running inside the VM. If this is called with
943// thread state set to be in VM, the safepoint synchronization code will deadlock!
944
945void Monitor::lock_without_safepoint_check (Thread * Self) {
946  assert (_owner != Self, "invariant") ;
947  ILock (Self) ;
948  assert (_owner == NULL, "invariant");
949  set_owner (Self);
950}
951
952void Monitor::lock_without_safepoint_check () {
953  lock_without_safepoint_check (Thread::current()) ;
954}
955
956
957// Returns true if thread succeeds in grabbing the lock, otherwise false.
958
959bool Monitor::try_lock() {
960  Thread * const Self = Thread::current();
961  debug_only(check_prelock_state(Self));
962  // assert(!thread->is_inside_signal_handler(), "don't lock inside signal handler");
963
964  // Special case, where all Java threads are stopped.
965  // The lock may have been acquired but _owner is not yet set.
966  // In that case the VM thread can safely grab the lock.
967  // It strikes me this should appear _after the TryLock() fails, below.
968  bool can_sneak = Self->is_VM_thread() && SafepointSynchronize::is_at_safepoint();
969  if (can_sneak && _owner == NULL) {
970    set_owner(Self); // Do not need to be atomic, since we are at a safepoint
971    _snuck = true;
972    return true;
973  }
974
975  if (TryLock()) {
976    // We got the lock
977    assert (_owner == NULL, "invariant");
978    set_owner (Self);
979    return true;
980  }
981  return false;
982}
983
984void Monitor::unlock() {
985  assert (_owner  == Thread::current(), "invariant") ;
986  assert (_OnDeck != Thread::current()->_MutexEvent , "invariant") ;
987  set_owner (NULL) ;
988  if (_snuck) {
989    assert(SafepointSynchronize::is_at_safepoint() && Thread::current()->is_VM_thread(), "sneak");
990    _snuck = false;
991    return ;
992  }
993  IUnlock (false) ;
994}
995
996// Yet another degenerate version of Monitor::lock() or lock_without_safepoint_check()
997// jvm_raw_lock() and _unlock() can be called by non-Java threads via JVM_RawMonitorEnter.
998//
999// There's no expectation that JVM_RawMonitors will interoperate properly with the native
1000// Mutex-Monitor constructs.  We happen to implement JVM_RawMonitors in terms of
1001// native Mutex-Monitors simply as a matter of convenience.  A simple abstraction layer
1002// over a pthread_mutex_t would work equally as well, but require more platform-specific
1003// code -- a "PlatformMutex".  Alternatively, a simply layer over muxAcquire-muxRelease
1004// would work too.
1005//
1006// Since the caller might be a foreign thread, we don't necessarily have a Thread.MutexEvent
1007// instance available.  Instead, we transiently allocate a ParkEvent on-demand if
1008// we encounter contention.  That ParkEvent remains associated with the thread
1009// until it manages to acquire the lock, at which time we return the ParkEvent
1010// to the global ParkEvent free list.  This is correct and suffices for our purposes.
1011//
1012// Beware that the original jvm_raw_unlock() had a "_snuck" test but that
1013// jvm_raw_lock() didn't have the corresponding test.  I suspect that's an
1014// oversight, but I've replicated the original suspect logic in the new code ...
1015
1016void Monitor::jvm_raw_lock() {
1017  assert(rank() == native, "invariant");
1018
1019  if (TryLock()) {
1020 Exeunt:
1021    assert (ILocked(), "invariant") ;
1022    assert (_owner == NULL, "invariant");
1023    // This can potentially be called by non-java Threads. Thus, the ThreadLocalStorage
1024    // might return NULL. Don't call set_owner since it will break on an NULL owner
1025    // Consider installing a non-null "ANON" distinguished value instead of just NULL.
1026    _owner = ThreadLocalStorage::thread();
1027    return ;
1028  }
1029
1030  if (TrySpin(NULL)) goto Exeunt ;
1031
1032  // slow-path - apparent contention
1033  // Allocate a ParkEvent for transient use.
1034  // The ParkEvent remains associated with this thread until
1035  // the time the thread manages to acquire the lock.
1036  ParkEvent * const ESelf = ParkEvent::Allocate(NULL) ;
1037  ESelf->reset() ;
1038  OrderAccess::storeload() ;
1039
1040  // Either Enqueue Self on cxq or acquire the outer lock.
1041  if (AcquireOrPush (ESelf)) {
1042    ParkEvent::Release (ESelf) ;      // surrender the ParkEvent
1043    goto Exeunt ;
1044  }
1045
1046  // At any given time there is at most one ondeck thread.
1047  // ondeck implies not resident on cxq and not resident on EntryList
1048  // Only the OnDeck thread can try to acquire -- contended for -- the lock.
1049  // CONSIDER: use Self->OnDeck instead of m->OnDeck.
1050  for (;;) {
1051    if (_OnDeck == ESelf && TrySpin(NULL)) break ;
1052    ParkCommon (ESelf, 0) ;
1053  }
1054
1055  assert (_OnDeck == ESelf, "invariant") ;
1056  _OnDeck = NULL ;
1057  ParkEvent::Release (ESelf) ;      // surrender the ParkEvent
1058  goto Exeunt ;
1059}
1060
1061void Monitor::jvm_raw_unlock() {
1062  // Nearly the same as Monitor::unlock() ...
1063  // directly set _owner instead of using set_owner(null)
1064  _owner = NULL ;
1065  if (_snuck) {         // ???
1066    assert(SafepointSynchronize::is_at_safepoint() && Thread::current()->is_VM_thread(), "sneak");
1067    _snuck = false;
1068    return ;
1069  }
1070  IUnlock(false) ;
1071}
1072
1073bool Monitor::wait(bool no_safepoint_check, long timeout, bool as_suspend_equivalent) {
1074  Thread * const Self = Thread::current() ;
1075  assert (_owner == Self, "invariant") ;
1076  assert (ILocked(), "invariant") ;
1077
1078  // as_suspend_equivalent logically implies !no_safepoint_check
1079  guarantee (!as_suspend_equivalent || !no_safepoint_check, "invariant") ;
1080  // !no_safepoint_check logically implies java_thread
1081  guarantee (no_safepoint_check || Self->is_Java_thread(), "invariant") ;
1082
1083  #ifdef ASSERT
1084    Monitor * least = get_least_ranked_lock_besides_this(Self->owned_locks());
1085    assert(least != this, "Specification of get_least_... call above");
1086    if (least != NULL && least->rank() <= special) {
1087      tty->print("Attempting to wait on monitor %s/%d while holding"
1088                 " lock %s/%d -- possible deadlock",
1089                 name(), rank(), least->name(), least->rank());
1090      assert(false, "Shouldn't block(wait) while holding a lock of rank special");
1091    }
1092  #endif // ASSERT
1093
1094  int wait_status ;
1095  // conceptually set the owner to NULL in anticipation of
1096  // abdicating the lock in wait
1097  set_owner(NULL);
1098  if (no_safepoint_check) {
1099    wait_status = IWait (Self, timeout) ;
1100  } else {
1101    assert (Self->is_Java_thread(), "invariant") ;
1102    JavaThread *jt = (JavaThread *)Self;
1103
1104    // Enter safepoint region - ornate and Rococo ...
1105    ThreadBlockInVM tbivm(jt);
1106    OSThreadWaitState osts(Self->osthread(), false /* not Object.wait() */);
1107
1108    if (as_suspend_equivalent) {
1109      jt->set_suspend_equivalent();
1110      // cleared by handle_special_suspend_equivalent_condition() or
1111      // java_suspend_self()
1112    }
1113
1114    wait_status = IWait (Self, timeout) ;
1115
1116    // were we externally suspended while we were waiting?
1117    if (as_suspend_equivalent && jt->handle_special_suspend_equivalent_condition()) {
1118      // Our event wait has finished and we own the lock, but
1119      // while we were waiting another thread suspended us. We don't
1120      // want to hold the lock while suspended because that
1121      // would surprise the thread that suspended us.
1122      assert (ILocked(), "invariant") ;
1123      IUnlock (true) ;
1124      jt->java_suspend_self();
1125      ILock (Self) ;
1126      assert (ILocked(), "invariant") ;
1127    }
1128  }
1129
1130  // Conceptually reestablish ownership of the lock.
1131  // The "real" lock -- the LockByte -- was reacquired by IWait().
1132  assert (ILocked(), "invariant") ;
1133  assert (_owner == NULL, "invariant") ;
1134  set_owner (Self) ;
1135  return wait_status != 0 ;          // return true IFF timeout
1136}
1137
1138Monitor::~Monitor() {
1139  assert ((UNS(_owner)|UNS(_LockWord.FullWord)|UNS(_EntryList)|UNS(_WaitSet)|UNS(_OnDeck)) == 0, "") ;
1140}
1141
1142void Monitor::ClearMonitor (Monitor * m, const char *name) {
1143  m->_owner             = NULL ;
1144  m->_snuck             = false ;
1145  if (name == NULL) {
1146    strcpy(m->_name, "UNKNOWN") ;
1147  } else {
1148    strncpy(m->_name, name, MONITOR_NAME_LEN - 1);
1149    m->_name[MONITOR_NAME_LEN - 1] = '\0';
1150  }
1151  m->_LockWord.FullWord = 0 ;
1152  m->_EntryList         = NULL ;
1153  m->_OnDeck            = NULL ;
1154  m->_WaitSet           = NULL ;
1155  m->_WaitLock[0]       = 0 ;
1156}
1157
1158Monitor::Monitor() { ClearMonitor(this); }
1159
1160Monitor::Monitor (int Rank, const char * name, bool allow_vm_block) {
1161  ClearMonitor (this, name) ;
1162#ifdef ASSERT
1163  _allow_vm_block  = allow_vm_block;
1164  _rank            = Rank ;
1165#endif
1166}
1167
1168Mutex::~Mutex() {
1169  assert ((UNS(_owner)|UNS(_LockWord.FullWord)|UNS(_EntryList)|UNS(_WaitSet)|UNS(_OnDeck)) == 0, "") ;
1170}
1171
1172Mutex::Mutex (int Rank, const char * name, bool allow_vm_block) {
1173  ClearMonitor ((Monitor *) this, name) ;
1174#ifdef ASSERT
1175 _allow_vm_block   = allow_vm_block;
1176 _rank             = Rank ;
1177#endif
1178}
1179
1180bool Monitor::owned_by_self() const {
1181  bool ret = _owner == Thread::current();
1182  assert (!ret || _LockWord.Bytes[_LSBINDEX] != 0, "invariant") ;
1183  return ret;
1184}
1185
1186void Monitor::print_on_error(outputStream* st) const {
1187  st->print("[" PTR_FORMAT, this);
1188  st->print("] %s", _name);
1189  st->print(" - owner thread: " PTR_FORMAT, _owner);
1190}
1191
1192
1193
1194
1195// ----------------------------------------------------------------------------------
1196// Non-product code
1197
1198#ifndef PRODUCT
1199void Monitor::print_on(outputStream* st) const {
1200  st->print_cr("Mutex: [0x%lx/0x%lx] %s - owner: 0x%lx", this, _LockWord.FullWord, _name, _owner);
1201}
1202#endif
1203
1204#ifndef PRODUCT
1205#ifdef ASSERT
1206Monitor * Monitor::get_least_ranked_lock(Monitor * locks) {
1207  Monitor *res, *tmp;
1208  for (res = tmp = locks; tmp != NULL; tmp = tmp->next()) {
1209    if (tmp->rank() < res->rank()) {
1210      res = tmp;
1211    }
1212  }
1213  if (!SafepointSynchronize::is_at_safepoint()) {
1214    // In this case, we expect the held locks to be
1215    // in increasing rank order (modulo any native ranks)
1216    for (tmp = locks; tmp != NULL; tmp = tmp->next()) {
1217      if (tmp->next() != NULL) {
1218        assert(tmp->rank() == Mutex::native ||
1219               tmp->rank() <= tmp->next()->rank(), "mutex rank anomaly?");
1220      }
1221    }
1222  }
1223  return res;
1224}
1225
1226Monitor* Monitor::get_least_ranked_lock_besides_this(Monitor* locks) {
1227  Monitor *res, *tmp;
1228  for (res = NULL, tmp = locks; tmp != NULL; tmp = tmp->next()) {
1229    if (tmp != this && (res == NULL || tmp->rank() < res->rank())) {
1230      res = tmp;
1231    }
1232  }
1233  if (!SafepointSynchronize::is_at_safepoint()) {
1234    // In this case, we expect the held locks to be
1235    // in increasing rank order (modulo any native ranks)
1236    for (tmp = locks; tmp != NULL; tmp = tmp->next()) {
1237      if (tmp->next() != NULL) {
1238        assert(tmp->rank() == Mutex::native ||
1239               tmp->rank() <= tmp->next()->rank(), "mutex rank anomaly?");
1240      }
1241    }
1242  }
1243  return res;
1244}
1245
1246
1247bool Monitor::contains(Monitor* locks, Monitor * lock) {
1248  for (; locks != NULL; locks = locks->next()) {
1249    if (locks == lock)
1250      return true;
1251  }
1252  return false;
1253}
1254#endif
1255
1256// Called immediately after lock acquisition or release as a diagnostic
1257// to track the lock-set of the thread and test for rank violations that
1258// might indicate exposure to deadlock.
1259// Rather like an EventListener for _owner (:>).
1260
1261void Monitor::set_owner_implementation(Thread *new_owner) {
1262  // This function is solely responsible for maintaining
1263  // and checking the invariant that threads and locks
1264  // are in a 1/N relation, with some some locks unowned.
1265  // It uses the Mutex::_owner, Mutex::_next, and
1266  // Thread::_owned_locks fields, and no other function
1267  // changes those fields.
1268  // It is illegal to set the mutex from one non-NULL
1269  // owner to another--it must be owned by NULL as an
1270  // intermediate state.
1271
1272  if (new_owner != NULL) {
1273    // the thread is acquiring this lock
1274
1275    assert(new_owner == Thread::current(), "Should I be doing this?");
1276    assert(_owner == NULL, "setting the owner thread of an already owned mutex");
1277    _owner = new_owner; // set the owner
1278
1279    // link "this" into the owned locks list
1280
1281    #ifdef ASSERT  // Thread::_owned_locks is under the same ifdef
1282      Monitor* locks = get_least_ranked_lock(new_owner->owned_locks());
1283                    // Mutex::set_owner_implementation is a friend of Thread
1284
1285      assert(this->rank() >= 0, "bad lock rank");
1286
1287      // Deadlock avoidance rules require us to acquire Mutexes only in
1288      // a global total order. For example m1 is the lowest ranked mutex
1289      // that the thread holds and m2 is the mutex the thread is trying
1290      // to acquire, then  deadlock avoidance rules require that the rank
1291      // of m2 be less  than the rank of m1.
1292      // The rank Mutex::native  is an exception in that it is not subject
1293      // to the verification rules.
1294      // Here are some further notes relating to mutex acquisition anomalies:
1295      // . under Solaris, the interrupt lock gets acquired when doing
1296      //   profiling, so any lock could be held.
1297      // . it is also ok to acquire Safepoint_lock at the very end while we
1298      //   already hold Terminator_lock - may happen because of periodic safepoints
1299      if (this->rank() != Mutex::native &&
1300          this->rank() != Mutex::suspend_resume &&
1301          locks != NULL && locks->rank() <= this->rank() &&
1302          !SafepointSynchronize::is_at_safepoint() &&
1303          this != Interrupt_lock && this != ProfileVM_lock &&
1304          !(this == Safepoint_lock && contains(locks, Terminator_lock) &&
1305            SafepointSynchronize::is_synchronizing())) {
1306        new_owner->print_owned_locks();
1307        fatal(err_msg("acquiring lock %s/%d out of order with lock %s/%d -- "
1308                      "possible deadlock", this->name(), this->rank(),
1309                      locks->name(), locks->rank()));
1310      }
1311
1312      this->_next = new_owner->_owned_locks;
1313      new_owner->_owned_locks = this;
1314    #endif
1315
1316  } else {
1317    // the thread is releasing this lock
1318
1319    Thread* old_owner = _owner;
1320    debug_only(_last_owner = old_owner);
1321
1322    assert(old_owner != NULL, "removing the owner thread of an unowned mutex");
1323    assert(old_owner == Thread::current(), "removing the owner thread of an unowned mutex");
1324
1325    _owner = NULL; // set the owner
1326
1327    #ifdef ASSERT
1328      Monitor *locks = old_owner->owned_locks();
1329
1330      // remove "this" from the owned locks list
1331
1332      Monitor *prev = NULL;
1333      bool found = false;
1334      for (; locks != NULL; prev = locks, locks = locks->next()) {
1335        if (locks == this) {
1336          found = true;
1337          break;
1338        }
1339      }
1340      assert(found, "Removing a lock not owned");
1341      if (prev == NULL) {
1342        old_owner->_owned_locks = _next;
1343      } else {
1344        prev->_next = _next;
1345      }
1346      _next = NULL;
1347    #endif
1348  }
1349}
1350
1351
1352// Factored out common sanity checks for locking mutex'es. Used by lock() and try_lock()
1353void Monitor::check_prelock_state(Thread *thread) {
1354  assert((!thread->is_Java_thread() || ((JavaThread *)thread)->thread_state() == _thread_in_vm)
1355         || rank() == Mutex::special, "wrong thread state for using locks");
1356  if (StrictSafepointChecks) {
1357    if (thread->is_VM_thread() && !allow_vm_block()) {
1358      fatal(err_msg("VM thread using lock %s (not allowed to block on)",
1359                    name()));
1360    }
1361    debug_only(if (rank() != Mutex::special) \
1362      thread->check_for_valid_safepoint_state(false);)
1363  }
1364  if (thread->is_Watcher_thread()) {
1365    assert(!WatcherThread::watcher_thread()->has_crash_protection(),
1366        "locking not allowed when crash protection is set");
1367  }
1368}
1369
1370void Monitor::check_block_state(Thread *thread) {
1371  if (!_allow_vm_block && thread->is_VM_thread()) {
1372    warning("VM thread blocked on lock");
1373    print();
1374    BREAKPOINT;
1375  }
1376  assert(_owner != thread, "deadlock: blocking on monitor owned by current thread");
1377}
1378
1379#endif // PRODUCT
1380