src/share/vm/runtime/mutex.cpp

Fri, 24 Jun 2016 17:12:13 +0800

author
aoqi<aoqi@loongson.cn>
date
Fri, 24 Jun 2016 17:12:13 +0800
changeset 25
873fd82b133d
parent 0
f90c822e73f8
child 6876
710a3c8b516e
permissions
-rw-r--r--

[Code Reorganization] Removed GC related modifications made by Loongson, for example, UseOldNUMA.

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

mercurial