duke@435: /* xdono@1014: * Copyright 1998-2009 Sun Microsystems, Inc. All Rights Reserved. duke@435: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. duke@435: * duke@435: * This code is free software; you can redistribute it and/or modify it duke@435: * under the terms of the GNU General Public License version 2 only, as duke@435: * published by the Free Software Foundation. duke@435: * duke@435: * This code is distributed in the hope that it will be useful, but WITHOUT duke@435: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or duke@435: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License duke@435: * version 2 for more details (a copy is included in the LICENSE file that duke@435: * accompanied this code). duke@435: * duke@435: * You should have received a copy of the GNU General Public License version duke@435: * 2 along with this work; if not, write to the Free Software Foundation, duke@435: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. duke@435: * duke@435: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, duke@435: * CA 95054 USA or visit www.sun.com if you need additional information or duke@435: * have any questions. duke@435: * duke@435: */ duke@435: duke@435: # include "incls/_precompiled.incl" duke@435: # include "incls/_synchronizer.cpp.incl" duke@435: duke@435: #if defined(__GNUC__) && !defined(IA64) duke@435: // Need to inhibit inlining for older versions of GCC to avoid build-time failures duke@435: #define ATTR __attribute__((noinline)) duke@435: #else duke@435: #define ATTR duke@435: #endif duke@435: duke@435: // Native markword accessors for synchronization and hashCode(). duke@435: // duke@435: // The "core" versions of monitor enter and exit reside in this file. duke@435: // The interpreter and compilers contain specialized transliterated duke@435: // variants of the enter-exit fast-path operations. See i486.ad fast_lock(), duke@435: // for instance. If you make changes here, make sure to modify the duke@435: // interpreter, and both C1 and C2 fast-path inline locking code emission. duke@435: // duke@435: // TODO: merge the objectMonitor and synchronizer classes. duke@435: // duke@435: // ----------------------------------------------------------------------------- duke@435: duke@435: #ifdef DTRACE_ENABLED duke@435: duke@435: // Only bother with this argument setup if dtrace is available duke@435: // TODO-FIXME: probes should not fire when caller is _blocked. assert() accordingly. duke@435: duke@435: HS_DTRACE_PROBE_DECL5(hotspot, monitor__wait, duke@435: jlong, uintptr_t, char*, int, long); duke@435: HS_DTRACE_PROBE_DECL4(hotspot, monitor__waited, duke@435: jlong, uintptr_t, char*, int); duke@435: HS_DTRACE_PROBE_DECL4(hotspot, monitor__notify, duke@435: jlong, uintptr_t, char*, int); duke@435: HS_DTRACE_PROBE_DECL4(hotspot, monitor__notifyAll, duke@435: jlong, uintptr_t, char*, int); duke@435: HS_DTRACE_PROBE_DECL4(hotspot, monitor__contended__enter, duke@435: jlong, uintptr_t, char*, int); duke@435: HS_DTRACE_PROBE_DECL4(hotspot, monitor__contended__entered, duke@435: jlong, uintptr_t, char*, int); duke@435: HS_DTRACE_PROBE_DECL4(hotspot, monitor__contended__exit, duke@435: jlong, uintptr_t, char*, int); duke@435: duke@435: #define DTRACE_MONITOR_PROBE_COMMON(klassOop, thread) \ duke@435: char* bytes = NULL; \ duke@435: int len = 0; \ duke@435: jlong jtid = SharedRuntime::get_java_tid(thread); \ duke@435: symbolOop klassname = ((oop)(klassOop))->klass()->klass_part()->name(); \ duke@435: if (klassname != NULL) { \ duke@435: bytes = (char*)klassname->bytes(); \ duke@435: len = klassname->utf8_length(); \ duke@435: } duke@435: duke@435: #define DTRACE_MONITOR_WAIT_PROBE(monitor, klassOop, thread, millis) \ duke@435: { \ duke@435: if (DTraceMonitorProbes) { \ duke@435: DTRACE_MONITOR_PROBE_COMMON(klassOop, thread); \ duke@435: HS_DTRACE_PROBE5(hotspot, monitor__wait, jtid, \ duke@435: (monitor), bytes, len, (millis)); \ duke@435: } \ duke@435: } duke@435: duke@435: #define DTRACE_MONITOR_PROBE(probe, monitor, klassOop, thread) \ duke@435: { \ duke@435: if (DTraceMonitorProbes) { \ duke@435: DTRACE_MONITOR_PROBE_COMMON(klassOop, thread); \ duke@435: HS_DTRACE_PROBE4(hotspot, monitor__##probe, jtid, \ duke@435: (uintptr_t)(monitor), bytes, len); \ duke@435: } \ duke@435: } duke@435: duke@435: #else // ndef DTRACE_ENABLED duke@435: duke@435: #define DTRACE_MONITOR_WAIT_PROBE(klassOop, thread, millis, mon) {;} duke@435: #define DTRACE_MONITOR_PROBE(probe, klassOop, thread, mon) {;} duke@435: duke@435: #endif // ndef DTRACE_ENABLED duke@435: duke@435: // ObjectWaiter serves as a "proxy" or surrogate thread. duke@435: // TODO-FIXME: Eliminate ObjectWaiter and use the thread-specific duke@435: // ParkEvent instead. Beware, however, that the JVMTI code duke@435: // knows about ObjectWaiters, so we'll have to reconcile that code. duke@435: // See next_waiter(), first_waiter(), etc. duke@435: duke@435: class ObjectWaiter : public StackObj { duke@435: public: duke@435: enum TStates { TS_UNDEF, TS_READY, TS_RUN, TS_WAIT, TS_ENTER, TS_CXQ } ; duke@435: enum Sorted { PREPEND, APPEND, SORTED } ; duke@435: ObjectWaiter * volatile _next; duke@435: ObjectWaiter * volatile _prev; duke@435: Thread* _thread; duke@435: ParkEvent * _event; duke@435: volatile int _notified ; duke@435: volatile TStates TState ; duke@435: Sorted _Sorted ; // List placement disposition duke@435: bool _active ; // Contention monitoring is enabled duke@435: public: duke@435: ObjectWaiter(Thread* thread) { duke@435: _next = NULL; duke@435: _prev = NULL; duke@435: _notified = 0; duke@435: TState = TS_RUN ; duke@435: _thread = thread; duke@435: _event = thread->_ParkEvent ; duke@435: _active = false; duke@435: assert (_event != NULL, "invariant") ; duke@435: } duke@435: duke@435: void wait_reenter_begin(ObjectMonitor *mon) { duke@435: JavaThread *jt = (JavaThread *)this->_thread; duke@435: _active = JavaThreadBlockedOnMonitorEnterState::wait_reenter_begin(jt, mon); duke@435: } duke@435: duke@435: void wait_reenter_end(ObjectMonitor *mon) { duke@435: JavaThread *jt = (JavaThread *)this->_thread; duke@435: JavaThreadBlockedOnMonitorEnterState::wait_reenter_end(jt, _active); duke@435: } duke@435: }; duke@435: duke@435: enum ManifestConstants { duke@435: ClearResponsibleAtSTW = 0, duke@435: MaximumRecheckInterval = 1000 duke@435: } ; duke@435: duke@435: duke@435: #undef TEVENT duke@435: #define TEVENT(nom) {if (SyncVerbose) FEVENT(nom); } duke@435: duke@435: #define FEVENT(nom) { static volatile int ctr = 0 ; int v = ++ctr ; if ((v & (v-1)) == 0) { ::printf (#nom " : %d \n", v); ::fflush(stdout); }} duke@435: duke@435: #undef TEVENT duke@435: #define TEVENT(nom) {;} duke@435: duke@435: // Performance concern: duke@435: // OrderAccess::storestore() calls release() which STs 0 into the global volatile duke@435: // OrderAccess::Dummy variable. This store is unnecessary for correctness. duke@435: // Many threads STing into a common location causes considerable cache migration duke@435: // or "sloshing" on large SMP system. As such, I avoid using OrderAccess::storestore() duke@435: // until it's repaired. In some cases OrderAccess::fence() -- which incurs local duke@435: // latency on the executing processor -- is a better choice as it scales on SMP duke@435: // systems. See http://blogs.sun.com/dave/entry/biased_locking_in_hotspot for a duke@435: // discussion of coherency costs. Note that all our current reference platforms duke@435: // provide strong ST-ST order, so the issue is moot on IA32, x64, and SPARC. duke@435: // duke@435: // As a general policy we use "volatile" to control compiler-based reordering duke@435: // and explicit fences (barriers) to control for architectural reordering performed duke@435: // by the CPU(s) or platform. duke@435: duke@435: static int MBFence (int x) { OrderAccess::fence(); return x; } duke@435: duke@435: struct SharedGlobals { duke@435: // These are highly shared mostly-read variables. duke@435: // To avoid false-sharing they need to be the sole occupants of a $ line. duke@435: double padPrefix [8]; duke@435: volatile int stwRandom ; duke@435: volatile int stwCycle ; duke@435: duke@435: // Hot RW variables -- Sequester to avoid false-sharing duke@435: double padSuffix [16]; duke@435: volatile int hcSequence ; duke@435: double padFinal [8] ; duke@435: } ; duke@435: duke@435: static SharedGlobals GVars ; duke@435: duke@435: duke@435: // Tunables ... duke@435: // The knob* variables are effectively final. Once set they should duke@435: // never be modified hence. Consider using __read_mostly with GCC. duke@435: duke@435: static int Knob_LogSpins = 0 ; // enable jvmstat tally for spins duke@435: static int Knob_HandOff = 0 ; duke@435: static int Knob_Verbose = 0 ; duke@435: static int Knob_ReportSettings = 0 ; duke@435: duke@435: static int Knob_SpinLimit = 5000 ; // derived by an external tool - duke@435: static int Knob_SpinBase = 0 ; // Floor AKA SpinMin duke@435: static int Knob_SpinBackOff = 0 ; // spin-loop backoff duke@435: static int Knob_CASPenalty = -1 ; // Penalty for failed CAS duke@435: static int Knob_OXPenalty = -1 ; // Penalty for observed _owner change duke@435: static int Knob_SpinSetSucc = 1 ; // spinners set the _succ field duke@435: static int Knob_SpinEarly = 1 ; duke@435: static int Knob_SuccEnabled = 1 ; // futile wake throttling duke@435: static int Knob_SuccRestrict = 0 ; // Limit successors + spinners to at-most-one duke@435: static int Knob_MaxSpinners = -1 ; // Should be a function of # CPUs duke@435: static int Knob_Bonus = 100 ; // spin success bonus duke@435: static int Knob_BonusB = 100 ; // spin success bonus duke@435: static int Knob_Penalty = 200 ; // spin failure penalty duke@435: static int Knob_Poverty = 1000 ; duke@435: static int Knob_SpinAfterFutile = 1 ; // Spin after returning from park() duke@435: static int Knob_FixedSpin = 0 ; duke@435: static int Knob_OState = 3 ; // Spinner checks thread state of _owner duke@435: static int Knob_UsePause = 1 ; duke@435: static int Knob_ExitPolicy = 0 ; duke@435: static int Knob_PreSpin = 10 ; // 20-100 likely better duke@435: static int Knob_ResetEvent = 0 ; duke@435: static int BackOffMask = 0 ; duke@435: duke@435: static int Knob_FastHSSEC = 0 ; duke@435: static int Knob_MoveNotifyee = 2 ; // notify() - disposition of notifyee duke@435: static int Knob_QMode = 0 ; // EntryList-cxq policy - queue discipline duke@435: static volatile int InitDone = 0 ; duke@435: duke@435: duke@435: // hashCode() generation : duke@435: // duke@435: // Possibilities: duke@435: // * MD5Digest of {obj,stwRandom} duke@435: // * CRC32 of {obj,stwRandom} or any linear-feedback shift register function. duke@435: // * A DES- or AES-style SBox[] mechanism duke@435: // * One of the Phi-based schemes, such as: duke@435: // 2654435761 = 2^32 * Phi (golden ratio) duke@435: // HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stwRandom ; duke@435: // * A variation of Marsaglia's shift-xor RNG scheme. duke@435: // * (obj ^ stwRandom) is appealing, but can result duke@435: // in undesirable regularity in the hashCode values of adjacent objects duke@435: // (objects allocated back-to-back, in particular). This could potentially duke@435: // result in hashtable collisions and reduced hashtable efficiency. duke@435: // There are simple ways to "diffuse" the middle address bits over the duke@435: // generated hashCode values: duke@435: // duke@435: duke@435: static inline intptr_t get_next_hash(Thread * Self, oop obj) { duke@435: intptr_t value = 0 ; duke@435: if (hashCode == 0) { duke@435: // This form uses an unguarded global Park-Miller RNG, duke@435: // so it's possible for two threads to race and generate the same RNG. duke@435: // On MP system we'll have lots of RW access to a global, so the duke@435: // mechanism induces lots of coherency traffic. duke@435: value = os::random() ; duke@435: } else duke@435: if (hashCode == 1) { duke@435: // This variation has the property of being stable (idempotent) duke@435: // between STW operations. This can be useful in some of the 1-0 duke@435: // synchronization schemes. duke@435: intptr_t addrBits = intptr_t(obj) >> 3 ; duke@435: value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom ; duke@435: } else duke@435: if (hashCode == 2) { duke@435: value = 1 ; // for sensitivity testing duke@435: } else duke@435: if (hashCode == 3) { duke@435: value = ++GVars.hcSequence ; duke@435: } else duke@435: if (hashCode == 4) { duke@435: value = intptr_t(obj) ; duke@435: } else { duke@435: // Marsaglia's xor-shift scheme with thread-specific state duke@435: // This is probably the best overall implementation -- we'll duke@435: // likely make this the default in future releases. duke@435: unsigned t = Self->_hashStateX ; duke@435: t ^= (t << 11) ; duke@435: Self->_hashStateX = Self->_hashStateY ; duke@435: Self->_hashStateY = Self->_hashStateZ ; duke@435: Self->_hashStateZ = Self->_hashStateW ; duke@435: unsigned v = Self->_hashStateW ; duke@435: v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)) ; duke@435: Self->_hashStateW = v ; duke@435: value = v ; duke@435: } duke@435: duke@435: value &= markOopDesc::hash_mask; duke@435: if (value == 0) value = 0xBAD ; duke@435: assert (value != markOopDesc::no_hash, "invariant") ; duke@435: TEVENT (hashCode: GENERATE) ; duke@435: return value; duke@435: } duke@435: duke@435: void BasicLock::print_on(outputStream* st) const { duke@435: st->print("monitor"); duke@435: } duke@435: duke@435: void BasicLock::move_to(oop obj, BasicLock* dest) { duke@435: // Check to see if we need to inflate the lock. This is only needed duke@435: // if an object is locked using "this" lightweight monitor. In that duke@435: // case, the displaced_header() is unlocked, because the duke@435: // displaced_header() contains the header for the originally unlocked duke@435: // object. However the object could have already been inflated. But it duke@435: // does not matter, the inflation will just a no-op. For other cases, duke@435: // the displaced header will be either 0x0 or 0x3, which are location duke@435: // independent, therefore the BasicLock is free to move. duke@435: // duke@435: // During OSR we may need to relocate a BasicLock (which contains a duke@435: // displaced word) from a location in an interpreter frame to a duke@435: // new location in a compiled frame. "this" refers to the source duke@435: // basiclock in the interpreter frame. "dest" refers to the destination duke@435: // basiclock in the new compiled frame. We *always* inflate in move_to(). duke@435: // The always-Inflate policy works properly, but in 1.5.0 it can sometimes duke@435: // cause performance problems in code that makes heavy use of a small # of duke@435: // uncontended locks. (We'd inflate during OSR, and then sync performance duke@435: // would subsequently plummet because the thread would be forced thru the slow-path). duke@435: // This problem has been made largely moot on IA32 by inlining the inflated fast-path duke@435: // operations in Fast_Lock and Fast_Unlock in i486.ad. duke@435: // duke@435: // Note that there is a way to safely swing the object's markword from duke@435: // one stack location to another. This avoids inflation. Obviously, duke@435: // we need to ensure that both locations refer to the current thread's stack. duke@435: // There are some subtle concurrency issues, however, and since the benefit is duke@435: // is small (given the support for inflated fast-path locking in the fast_lock, etc) duke@435: // we'll leave that optimization for another time. duke@435: duke@435: if (displaced_header()->is_neutral()) { duke@435: ObjectSynchronizer::inflate_helper(obj); duke@435: // WARNING: We can not put check here, because the inflation duke@435: // will not update the displaced header. Once BasicLock is inflated, duke@435: // no one should ever look at its content. duke@435: } else { duke@435: // Typically the displaced header will be 0 (recursive stack lock) or duke@435: // unused_mark. Naively we'd like to assert that the displaced mark duke@435: // value is either 0, neutral, or 3. But with the advent of the duke@435: // store-before-CAS avoidance in fast_lock/compiler_lock_object duke@435: // we can find any flavor mark in the displaced mark. duke@435: } duke@435: // [RGV] The next line appears to do nothing! duke@435: intptr_t dh = (intptr_t) displaced_header(); duke@435: dest->set_displaced_header(displaced_header()); duke@435: } duke@435: duke@435: // ----------------------------------------------------------------------------- duke@435: duke@435: // standard constructor, allows locking failures duke@435: ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool doLock) { duke@435: _dolock = doLock; duke@435: _thread = thread; duke@435: debug_only(if (StrictSafepointChecks) _thread->check_for_valid_safepoint_state(false);) duke@435: _obj = obj; duke@435: duke@435: if (_dolock) { duke@435: TEVENT (ObjectLocker) ; duke@435: duke@435: ObjectSynchronizer::fast_enter(_obj, &_lock, false, _thread); duke@435: } duke@435: } duke@435: duke@435: ObjectLocker::~ObjectLocker() { duke@435: if (_dolock) { duke@435: ObjectSynchronizer::fast_exit(_obj(), &_lock, _thread); duke@435: } duke@435: } duke@435: duke@435: // ----------------------------------------------------------------------------- duke@435: duke@435: duke@435: PerfCounter * ObjectSynchronizer::_sync_Inflations = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_Deflations = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_ContendedLockAttempts = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_FutileWakeups = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_Parks = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_EmptyNotifications = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_Notifications = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_PrivateA = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_PrivateB = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_SlowExit = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_SlowEnter = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_SlowNotify = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_SlowNotifyAll = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_FailedSpins = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_SuccessfulSpins = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_MonInCirculation = NULL ; duke@435: PerfCounter * ObjectSynchronizer::_sync_MonScavenged = NULL ; duke@435: PerfLongVariable * ObjectSynchronizer::_sync_MonExtant = NULL ; duke@435: duke@435: // One-shot global initialization for the sync subsystem. duke@435: // We could also defer initialization and initialize on-demand duke@435: // the first time we call inflate(). Initialization would duke@435: // be protected - like so many things - by the MonitorCache_lock. duke@435: duke@435: void ObjectSynchronizer::Initialize () { duke@435: static int InitializationCompleted = 0 ; duke@435: assert (InitializationCompleted == 0, "invariant") ; duke@435: InitializationCompleted = 1 ; duke@435: if (UsePerfData) { duke@435: EXCEPTION_MARK ; duke@435: #define NEWPERFCOUNTER(n) {n = PerfDataManager::create_counter(SUN_RT, #n, PerfData::U_Events,CHECK); } duke@435: #define NEWPERFVARIABLE(n) {n = PerfDataManager::create_variable(SUN_RT, #n, PerfData::U_Events,CHECK); } duke@435: NEWPERFCOUNTER(_sync_Inflations) ; duke@435: NEWPERFCOUNTER(_sync_Deflations) ; duke@435: NEWPERFCOUNTER(_sync_ContendedLockAttempts) ; duke@435: NEWPERFCOUNTER(_sync_FutileWakeups) ; duke@435: NEWPERFCOUNTER(_sync_Parks) ; duke@435: NEWPERFCOUNTER(_sync_EmptyNotifications) ; duke@435: NEWPERFCOUNTER(_sync_Notifications) ; duke@435: NEWPERFCOUNTER(_sync_SlowEnter) ; duke@435: NEWPERFCOUNTER(_sync_SlowExit) ; duke@435: NEWPERFCOUNTER(_sync_SlowNotify) ; duke@435: NEWPERFCOUNTER(_sync_SlowNotifyAll) ; duke@435: NEWPERFCOUNTER(_sync_FailedSpins) ; duke@435: NEWPERFCOUNTER(_sync_SuccessfulSpins) ; duke@435: NEWPERFCOUNTER(_sync_PrivateA) ; duke@435: NEWPERFCOUNTER(_sync_PrivateB) ; duke@435: NEWPERFCOUNTER(_sync_MonInCirculation) ; duke@435: NEWPERFCOUNTER(_sync_MonScavenged) ; duke@435: NEWPERFVARIABLE(_sync_MonExtant) ; duke@435: #undef NEWPERFCOUNTER duke@435: } duke@435: } duke@435: duke@435: // Compile-time asserts duke@435: // When possible, it's better to catch errors deterministically at duke@435: // compile-time than at runtime. The down-side to using compile-time duke@435: // asserts is that error message -- often something about negative array duke@435: // indices -- is opaque. duke@435: xlu@948: #define CTASSERT(x) { int tag[1-(2*!(x))]; printf ("Tag @" INTPTR_FORMAT "\n", (intptr_t)tag); } duke@435: duke@435: void ObjectMonitor::ctAsserts() { duke@435: CTASSERT(offset_of (ObjectMonitor, _header) == 0); duke@435: } duke@435: duke@435: static int Adjust (volatile int * adr, int dx) { duke@435: int v ; duke@435: for (v = *adr ; Atomic::cmpxchg (v + dx, adr, v) != v; v = *adr) ; duke@435: return v ; duke@435: } duke@435: duke@435: // Ad-hoc mutual exclusion primitives: SpinLock and Mux duke@435: // duke@435: // We employ SpinLocks _only for low-contention, fixed-length duke@435: // short-duration critical sections where we're concerned duke@435: // about native mutex_t or HotSpot Mutex:: latency. duke@435: // The mux construct provides a spin-then-block mutual exclusion duke@435: // mechanism. duke@435: // duke@435: // Testing has shown that contention on the ListLock guarding gFreeList duke@435: // is common. If we implement ListLock as a simple SpinLock it's common duke@435: // for the JVM to devolve to yielding with little progress. This is true duke@435: // despite the fact that the critical sections protected by ListLock are duke@435: // extremely short. duke@435: // duke@435: // TODO-FIXME: ListLock should be of type SpinLock. duke@435: // We should make this a 1st-class type, integrated into the lock duke@435: // hierarchy as leaf-locks. Critically, the SpinLock structure duke@435: // should have sufficient padding to avoid false-sharing and excessive duke@435: // cache-coherency traffic. duke@435: duke@435: duke@435: typedef volatile int SpinLockT ; duke@435: duke@435: void Thread::SpinAcquire (volatile int * adr, const char * LockName) { duke@435: if (Atomic::cmpxchg (1, adr, 0) == 0) { duke@435: return ; // normal fast-path return duke@435: } duke@435: duke@435: // Slow-path : We've encountered contention -- Spin/Yield/Block strategy. duke@435: TEVENT (SpinAcquire - ctx) ; duke@435: int ctr = 0 ; duke@435: int Yields = 0 ; duke@435: for (;;) { duke@435: while (*adr != 0) { duke@435: ++ctr ; duke@435: if ((ctr & 0xFFF) == 0 || !os::is_MP()) { duke@435: if (Yields > 5) { duke@435: // Consider using a simple NakedSleep() instead. duke@435: // Then SpinAcquire could be called by non-JVM threads duke@435: Thread::current()->_ParkEvent->park(1) ; duke@435: } else { duke@435: os::NakedYield() ; duke@435: ++Yields ; duke@435: } duke@435: } else { duke@435: SpinPause() ; duke@435: } duke@435: } duke@435: if (Atomic::cmpxchg (1, adr, 0) == 0) return ; duke@435: } duke@435: } duke@435: duke@435: void Thread::SpinRelease (volatile int * adr) { duke@435: assert (*adr != 0, "invariant") ; duke@435: OrderAccess::fence() ; // guarantee at least release consistency. duke@435: // Roach-motel semantics. duke@435: // It's safe if subsequent LDs and STs float "up" into the critical section, duke@435: // but prior LDs and STs within the critical section can't be allowed duke@435: // to reorder or float past the ST that releases the lock. duke@435: *adr = 0 ; duke@435: } duke@435: duke@435: // muxAcquire and muxRelease: duke@435: // duke@435: // * muxAcquire and muxRelease support a single-word lock-word construct. duke@435: // The LSB of the word is set IFF the lock is held. duke@435: // The remainder of the word points to the head of a singly-linked list duke@435: // of threads blocked on the lock. duke@435: // duke@435: // * The current implementation of muxAcquire-muxRelease uses its own duke@435: // dedicated Thread._MuxEvent instance. If we're interested in duke@435: // minimizing the peak number of extant ParkEvent instances then duke@435: // we could eliminate _MuxEvent and "borrow" _ParkEvent as long duke@435: // as certain invariants were satisfied. Specifically, care would need duke@435: // to be taken with regards to consuming unpark() "permits". duke@435: // A safe rule of thumb is that a thread would never call muxAcquire() duke@435: // if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently duke@435: // park(). Otherwise the _ParkEvent park() operation in muxAcquire() could duke@435: // consume an unpark() permit intended for monitorenter, for instance. duke@435: // One way around this would be to widen the restricted-range semaphore duke@435: // implemented in park(). Another alternative would be to provide duke@435: // multiple instances of the PlatformEvent() for each thread. One duke@435: // instance would be dedicated to muxAcquire-muxRelease, for instance. duke@435: // duke@435: // * Usage: duke@435: // -- Only as leaf locks duke@435: // -- for short-term locking only as muxAcquire does not perform duke@435: // thread state transitions. duke@435: // duke@435: // Alternatives: duke@435: // * We could implement muxAcquire and muxRelease with MCS or CLH locks duke@435: // but with parking or spin-then-park instead of pure spinning. duke@435: // * Use Taura-Oyama-Yonenzawa locks. duke@435: // * It's possible to construct a 1-0 lock if we encode the lockword as duke@435: // (List,LockByte). Acquire will CAS the full lockword while Release duke@435: // will STB 0 into the LockByte. The 1-0 scheme admits stranding, so duke@435: // acquiring threads use timers (ParkTimed) to detect and recover from duke@435: // the stranding window. Thread/Node structures must be aligned on 256-byte duke@435: // boundaries by using placement-new. duke@435: // * Augment MCS with advisory back-link fields maintained with CAS(). duke@435: // Pictorially: LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner. duke@435: // The validity of the backlinks must be ratified before we trust the value. duke@435: // If the backlinks are invalid the exiting thread must back-track through the duke@435: // the forward links, which are always trustworthy. duke@435: // * Add a successor indication. The LockWord is currently encoded as duke@435: // (List, LOCKBIT:1). We could also add a SUCCBIT or an explicit _succ variable duke@435: // to provide the usual futile-wakeup optimization. duke@435: // See RTStt for details. duke@435: // * Consider schedctl.sc_nopreempt to cover the critical section. duke@435: // duke@435: duke@435: duke@435: typedef volatile intptr_t MutexT ; // Mux Lock-word duke@435: enum MuxBits { LOCKBIT = 1 } ; duke@435: duke@435: void Thread::muxAcquire (volatile intptr_t * Lock, const char * LockName) { duke@435: intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ; duke@435: if (w == 0) return ; duke@435: if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { duke@435: return ; duke@435: } duke@435: duke@435: TEVENT (muxAcquire - Contention) ; duke@435: ParkEvent * const Self = Thread::current()->_MuxEvent ; duke@435: assert ((intptr_t(Self) & LOCKBIT) == 0, "invariant") ; duke@435: for (;;) { duke@435: int its = (os::is_MP() ? 100 : 0) + 1 ; duke@435: duke@435: // Optional spin phase: spin-then-park strategy duke@435: while (--its >= 0) { duke@435: w = *Lock ; duke@435: if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { duke@435: return ; duke@435: } duke@435: } duke@435: duke@435: Self->reset() ; duke@435: Self->OnList = intptr_t(Lock) ; duke@435: // The following fence() isn't _strictly necessary as the subsequent duke@435: // CAS() both serializes execution and ratifies the fetched *Lock value. duke@435: OrderAccess::fence(); duke@435: for (;;) { duke@435: w = *Lock ; duke@435: if ((w & LOCKBIT) == 0) { duke@435: if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { duke@435: Self->OnList = 0 ; // hygiene - allows stronger asserts duke@435: return ; duke@435: } duke@435: continue ; // Interference -- *Lock changed -- Just retry duke@435: } duke@435: assert (w & LOCKBIT, "invariant") ; duke@435: Self->ListNext = (ParkEvent *) (w & ~LOCKBIT ); duke@435: if (Atomic::cmpxchg_ptr (intptr_t(Self)|LOCKBIT, Lock, w) == w) break ; duke@435: } duke@435: duke@435: while (Self->OnList != 0) { duke@435: Self->park() ; duke@435: } duke@435: } duke@435: } duke@435: duke@435: void Thread::muxAcquireW (volatile intptr_t * Lock, ParkEvent * ev) { duke@435: intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ; duke@435: if (w == 0) return ; duke@435: if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { duke@435: return ; duke@435: } duke@435: duke@435: TEVENT (muxAcquire - Contention) ; duke@435: ParkEvent * ReleaseAfter = NULL ; duke@435: if (ev == NULL) { duke@435: ev = ReleaseAfter = ParkEvent::Allocate (NULL) ; duke@435: } duke@435: assert ((intptr_t(ev) & LOCKBIT) == 0, "invariant") ; duke@435: for (;;) { duke@435: guarantee (ev->OnList == 0, "invariant") ; duke@435: int its = (os::is_MP() ? 100 : 0) + 1 ; duke@435: duke@435: // Optional spin phase: spin-then-park strategy duke@435: while (--its >= 0) { duke@435: w = *Lock ; duke@435: if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { duke@435: if (ReleaseAfter != NULL) { duke@435: ParkEvent::Release (ReleaseAfter) ; duke@435: } duke@435: return ; duke@435: } duke@435: } duke@435: duke@435: ev->reset() ; duke@435: ev->OnList = intptr_t(Lock) ; duke@435: // The following fence() isn't _strictly necessary as the subsequent duke@435: // CAS() both serializes execution and ratifies the fetched *Lock value. duke@435: OrderAccess::fence(); duke@435: for (;;) { duke@435: w = *Lock ; duke@435: if ((w & LOCKBIT) == 0) { duke@435: if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) { duke@435: ev->OnList = 0 ; duke@435: // We call ::Release while holding the outer lock, thus duke@435: // artificially lengthening the critical section. duke@435: // Consider deferring the ::Release() until the subsequent unlock(), duke@435: // after we've dropped the outer lock. duke@435: if (ReleaseAfter != NULL) { duke@435: ParkEvent::Release (ReleaseAfter) ; duke@435: } duke@435: return ; duke@435: } duke@435: continue ; // Interference -- *Lock changed -- Just retry duke@435: } duke@435: assert (w & LOCKBIT, "invariant") ; duke@435: ev->ListNext = (ParkEvent *) (w & ~LOCKBIT ); duke@435: if (Atomic::cmpxchg_ptr (intptr_t(ev)|LOCKBIT, Lock, w) == w) break ; duke@435: } duke@435: duke@435: while (ev->OnList != 0) { duke@435: ev->park() ; duke@435: } duke@435: } duke@435: } duke@435: duke@435: // Release() must extract a successor from the list and then wake that thread. duke@435: // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme duke@435: // similar to that used by ParkEvent::Allocate() and ::Release(). DMR-based duke@435: // Release() would : duke@435: // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list. duke@435: // (B) Extract a successor from the private list "in-hand" duke@435: // (C) attempt to CAS() the residual back into *Lock over null. duke@435: // If there were any newly arrived threads and the CAS() would fail. duke@435: // In that case Release() would detach the RATs, re-merge the list in-hand duke@435: // with the RATs and repeat as needed. Alternately, Release() might duke@435: // detach and extract a successor, but then pass the residual list to the wakee. duke@435: // The wakee would be responsible for reattaching and remerging before it duke@435: // competed for the lock. duke@435: // duke@435: // Both "pop" and DMR are immune from ABA corruption -- there can be duke@435: // multiple concurrent pushers, but only one popper or detacher. duke@435: // This implementation pops from the head of the list. This is unfair, duke@435: // but tends to provide excellent throughput as hot threads remain hot. duke@435: // (We wake recently run threads first). duke@435: duke@435: void Thread::muxRelease (volatile intptr_t * Lock) { duke@435: for (;;) { duke@435: const intptr_t w = Atomic::cmpxchg_ptr (0, Lock, LOCKBIT) ; duke@435: assert (w & LOCKBIT, "invariant") ; duke@435: if (w == LOCKBIT) return ; duke@435: ParkEvent * List = (ParkEvent *) (w & ~LOCKBIT) ; duke@435: assert (List != NULL, "invariant") ; duke@435: assert (List->OnList == intptr_t(Lock), "invariant") ; duke@435: ParkEvent * nxt = List->ListNext ; duke@435: duke@435: // The following CAS() releases the lock and pops the head element. duke@435: if (Atomic::cmpxchg_ptr (intptr_t(nxt), Lock, w) != w) { duke@435: continue ; duke@435: } duke@435: List->OnList = 0 ; duke@435: OrderAccess::fence() ; duke@435: List->unpark () ; duke@435: return ; duke@435: } duke@435: } duke@435: duke@435: // ObjectMonitor Lifecycle duke@435: // ----------------------- duke@435: // Inflation unlinks monitors from the global gFreeList and duke@435: // associates them with objects. Deflation -- which occurs at duke@435: // STW-time -- disassociates idle monitors from objects. Such duke@435: // scavenged monitors are returned to the gFreeList. duke@435: // duke@435: // The global list is protected by ListLock. All the critical sections duke@435: // are short and operate in constant-time. duke@435: // duke@435: // ObjectMonitors reside in type-stable memory (TSM) and are immortal. duke@435: // duke@435: // Lifecycle: duke@435: // -- unassigned and on the global free list duke@435: // -- unassigned and on a thread's private omFreeList duke@435: // -- assigned to an object. The object is inflated and the mark refers duke@435: // to the objectmonitor. duke@435: // duke@435: // TODO-FIXME: duke@435: // duke@435: // * We currently protect the gFreeList with a simple lock. duke@435: // An alternate lock-free scheme would be to pop elements from the gFreeList duke@435: // with CAS. This would be safe from ABA corruption as long we only duke@435: // recycled previously appearing elements onto the list in deflate_idle_monitors() duke@435: // at STW-time. Completely new elements could always be pushed onto the gFreeList duke@435: // with CAS. Elements that appeared previously on the list could only duke@435: // be installed at STW-time. duke@435: // duke@435: // * For efficiency and to help reduce the store-before-CAS penalty duke@435: // the objectmonitors on gFreeList or local free lists should be ready to install duke@435: // with the exception of _header and _object. _object can be set after inflation. duke@435: // In particular, keep all objectMonitors on a thread's private list in ready-to-install duke@435: // state with m.Owner set properly. duke@435: // duke@435: // * We could all diffuse contention by using multiple global (FreeList, Lock) duke@435: // pairs -- threads could use trylock() and a cyclic-scan strategy to search for duke@435: // an unlocked free list. duke@435: // duke@435: // * Add lifecycle tags and assert()s. duke@435: // duke@435: // * Be more consistent about when we clear an objectmonitor's fields: duke@435: // A. After extracting the objectmonitor from a free list. duke@435: // B. After adding an objectmonitor to a free list. duke@435: // duke@435: duke@435: ObjectMonitor * ObjectSynchronizer::gBlockList = NULL ; duke@435: ObjectMonitor * volatile ObjectSynchronizer::gFreeList = NULL ; duke@435: static volatile intptr_t ListLock = 0 ; // protects global monitor free-list cache duke@435: #define CHAINMARKER ((oop)-1) duke@435: duke@435: ObjectMonitor * ATTR ObjectSynchronizer::omAlloc (Thread * Self) { duke@435: // A large MAXPRIVATE value reduces both list lock contention duke@435: // and list coherency traffic, but also tends to increase the duke@435: // number of objectMonitors in circulation as well as the STW duke@435: // scavenge costs. As usual, we lean toward time in space-time duke@435: // tradeoffs. duke@435: const int MAXPRIVATE = 1024 ; duke@435: for (;;) { duke@435: ObjectMonitor * m ; duke@435: duke@435: // 1: try to allocate from the thread's local omFreeList. duke@435: // Threads will attempt to allocate first from their local list, then duke@435: // from the global list, and only after those attempts fail will the thread duke@435: // attempt to instantiate new monitors. Thread-local free lists take duke@435: // heat off the ListLock and improve allocation latency, as well as reducing duke@435: // coherency traffic on the shared global list. duke@435: m = Self->omFreeList ; duke@435: if (m != NULL) { duke@435: Self->omFreeList = m->FreeNext ; duke@435: Self->omFreeCount -- ; duke@435: // CONSIDER: set m->FreeNext = BAD -- diagnostic hygiene duke@435: guarantee (m->object() == NULL, "invariant") ; duke@435: return m ; duke@435: } duke@435: duke@435: // 2: try to allocate from the global gFreeList duke@435: // CONSIDER: use muxTry() instead of muxAcquire(). duke@435: // If the muxTry() fails then drop immediately into case 3. duke@435: // If we're using thread-local free lists then try duke@435: // to reprovision the caller's free list. duke@435: if (gFreeList != NULL) { duke@435: // Reprovision the thread's omFreeList. duke@435: // Use bulk transfers to reduce the allocation rate and heat duke@435: // on various locks. duke@435: Thread::muxAcquire (&ListLock, "omAlloc") ; duke@435: for (int i = Self->omFreeProvision; --i >= 0 && gFreeList != NULL; ) { duke@435: ObjectMonitor * take = gFreeList ; duke@435: gFreeList = take->FreeNext ; duke@435: guarantee (take->object() == NULL, "invariant") ; duke@435: guarantee (!take->is_busy(), "invariant") ; duke@435: take->Recycle() ; duke@435: omRelease (Self, take) ; duke@435: } duke@435: Thread::muxRelease (&ListLock) ; duke@435: Self->omFreeProvision += 1 + (Self->omFreeProvision/2) ; duke@435: if (Self->omFreeProvision > MAXPRIVATE ) Self->omFreeProvision = MAXPRIVATE ; duke@435: TEVENT (omFirst - reprovision) ; duke@435: continue ; duke@435: } duke@435: duke@435: // 3: allocate a block of new ObjectMonitors duke@435: // Both the local and global free lists are empty -- resort to malloc(). duke@435: // In the current implementation objectMonitors are TSM - immortal. duke@435: assert (_BLOCKSIZE > 1, "invariant") ; duke@435: ObjectMonitor * temp = new ObjectMonitor[_BLOCKSIZE]; duke@435: duke@435: // NOTE: (almost) no way to recover if allocation failed. duke@435: // We might be able to induce a STW safepoint and scavenge enough duke@435: // objectMonitors to permit progress. duke@435: if (temp == NULL) { duke@435: vm_exit_out_of_memory (sizeof (ObjectMonitor[_BLOCKSIZE]), "Allocate ObjectMonitors") ; duke@435: } duke@435: duke@435: // Format the block. duke@435: // initialize the linked list, each monitor points to its next duke@435: // forming the single linked free list, the very first monitor duke@435: // will points to next block, which forms the block list. duke@435: // The trick of using the 1st element in the block as gBlockList duke@435: // linkage should be reconsidered. A better implementation would duke@435: // look like: class Block { Block * next; int N; ObjectMonitor Body [N] ; } duke@435: duke@435: for (int i = 1; i < _BLOCKSIZE ; i++) { duke@435: temp[i].FreeNext = &temp[i+1]; duke@435: } duke@435: duke@435: // terminate the last monitor as the end of list duke@435: temp[_BLOCKSIZE - 1].FreeNext = NULL ; duke@435: duke@435: // Element [0] is reserved for global list linkage duke@435: temp[0].set_object(CHAINMARKER); duke@435: duke@435: // Consider carving out this thread's current request from the duke@435: // block in hand. This avoids some lock traffic and redundant duke@435: // list activity. duke@435: duke@435: // Acquire the ListLock to manipulate BlockList and FreeList. duke@435: // An Oyama-Taura-Yonezawa scheme might be more efficient. duke@435: Thread::muxAcquire (&ListLock, "omAlloc [2]") ; duke@435: duke@435: // Add the new block to the list of extant blocks (gBlockList). duke@435: // The very first objectMonitor in a block is reserved and dedicated. duke@435: // It serves as blocklist "next" linkage. duke@435: temp[0].FreeNext = gBlockList; duke@435: gBlockList = temp; duke@435: duke@435: // Add the new string of objectMonitors to the global free list duke@435: temp[_BLOCKSIZE - 1].FreeNext = gFreeList ; duke@435: gFreeList = temp + 1; duke@435: Thread::muxRelease (&ListLock) ; duke@435: TEVENT (Allocate block of monitors) ; duke@435: } duke@435: } duke@435: duke@435: // Place "m" on the caller's private per-thread omFreeList. duke@435: // In practice there's no need to clamp or limit the number of duke@435: // monitors on a thread's omFreeList as the only time we'll call duke@435: // omRelease is to return a monitor to the free list after a CAS duke@435: // attempt failed. This doesn't allow unbounded #s of monitors to duke@435: // accumulate on a thread's free list. duke@435: // duke@435: // In the future the usage of omRelease() might change and monitors duke@435: // could migrate between free lists. In that case to avoid excessive duke@435: // accumulation we could limit omCount to (omProvision*2), otherwise return duke@435: // the objectMonitor to the global list. We should drain (return) in reasonable chunks. duke@435: // That is, *not* one-at-a-time. duke@435: duke@435: duke@435: void ObjectSynchronizer::omRelease (Thread * Self, ObjectMonitor * m) { duke@435: guarantee (m->object() == NULL, "invariant") ; duke@435: m->FreeNext = Self->omFreeList ; duke@435: Self->omFreeList = m ; duke@435: Self->omFreeCount ++ ; duke@435: } duke@435: duke@435: // Return the monitors of a moribund thread's local free list to duke@435: // the global free list. Typically a thread calls omFlush() when duke@435: // it's dying. We could also consider having the VM thread steal duke@435: // monitors from threads that have not run java code over a few duke@435: // consecutive STW safepoints. Relatedly, we might decay duke@435: // omFreeProvision at STW safepoints. duke@435: // duke@435: // We currently call omFlush() from the Thread:: dtor _after the thread duke@435: // has been excised from the thread list and is no longer a mutator. duke@435: // That means that omFlush() can run concurrently with a safepoint and duke@435: // the scavenge operator. Calling omFlush() from JavaThread::exit() might duke@435: // be a better choice as we could safely reason that that the JVM is duke@435: // not at a safepoint at the time of the call, and thus there could duke@435: // be not inopportune interleavings between omFlush() and the scavenge duke@435: // operator. duke@435: duke@435: void ObjectSynchronizer::omFlush (Thread * Self) { duke@435: ObjectMonitor * List = Self->omFreeList ; // Null-terminated SLL duke@435: Self->omFreeList = NULL ; duke@435: if (List == NULL) return ; duke@435: ObjectMonitor * Tail = NULL ; duke@435: ObjectMonitor * s ; duke@435: for (s = List ; s != NULL ; s = s->FreeNext) { duke@435: Tail = s ; duke@435: guarantee (s->object() == NULL, "invariant") ; duke@435: guarantee (!s->is_busy(), "invariant") ; duke@435: s->set_owner (NULL) ; // redundant but good hygiene duke@435: TEVENT (omFlush - Move one) ; duke@435: } duke@435: duke@435: guarantee (Tail != NULL && List != NULL, "invariant") ; duke@435: Thread::muxAcquire (&ListLock, "omFlush") ; duke@435: Tail->FreeNext = gFreeList ; duke@435: gFreeList = List ; duke@435: Thread::muxRelease (&ListLock) ; duke@435: TEVENT (omFlush) ; duke@435: } duke@435: duke@435: duke@435: // Get the next block in the block list. duke@435: static inline ObjectMonitor* next(ObjectMonitor* block) { duke@435: assert(block->object() == CHAINMARKER, "must be a block header"); duke@435: block = block->FreeNext ; duke@435: assert(block == NULL || block->object() == CHAINMARKER, "must be a block header"); duke@435: return block; duke@435: } duke@435: duke@435: // Fast path code shared by multiple functions duke@435: ObjectMonitor* ObjectSynchronizer::inflate_helper(oop obj) { duke@435: markOop mark = obj->mark(); duke@435: if (mark->has_monitor()) { duke@435: assert(ObjectSynchronizer::verify_objmon_isinpool(mark->monitor()), "monitor is invalid"); duke@435: assert(mark->monitor()->header()->is_neutral(), "monitor must record a good object header"); duke@435: return mark->monitor(); duke@435: } duke@435: return ObjectSynchronizer::inflate(Thread::current(), obj); duke@435: } duke@435: duke@435: // Note that we could encounter some performance loss through false-sharing as duke@435: // multiple locks occupy the same $ line. Padding might be appropriate. duke@435: duke@435: #define NINFLATIONLOCKS 256 duke@435: static volatile intptr_t InflationLocks [NINFLATIONLOCKS] ; duke@435: duke@435: static markOop ReadStableMark (oop obj) { duke@435: markOop mark = obj->mark() ; duke@435: if (!mark->is_being_inflated()) { duke@435: return mark ; // normal fast-path return duke@435: } duke@435: duke@435: int its = 0 ; duke@435: for (;;) { duke@435: markOop mark = obj->mark() ; duke@435: if (!mark->is_being_inflated()) { duke@435: return mark ; // normal fast-path return duke@435: } duke@435: duke@435: // The object is being inflated by some other thread. duke@435: // The caller of ReadStableMark() must wait for inflation to complete. duke@435: // Avoid live-lock duke@435: // TODO: consider calling SafepointSynchronize::do_call_back() while duke@435: // spinning to see if there's a safepoint pending. If so, immediately duke@435: // yielding or blocking would be appropriate. Avoid spinning while duke@435: // there is a safepoint pending. duke@435: // TODO: add inflation contention performance counters. duke@435: // TODO: restrict the aggregate number of spinners. duke@435: duke@435: ++its ; duke@435: if (its > 10000 || !os::is_MP()) { duke@435: if (its & 1) { duke@435: os::NakedYield() ; duke@435: TEVENT (Inflate: INFLATING - yield) ; duke@435: } else { duke@435: // Note that the following code attenuates the livelock problem but is not duke@435: // a complete remedy. A more complete solution would require that the inflating duke@435: // thread hold the associated inflation lock. The following code simply restricts duke@435: // the number of spinners to at most one. We'll have N-2 threads blocked duke@435: // on the inflationlock, 1 thread holding the inflation lock and using duke@435: // a yield/park strategy, and 1 thread in the midst of inflation. duke@435: // A more refined approach would be to change the encoding of INFLATING duke@435: // to allow encapsulation of a native thread pointer. Threads waiting for duke@435: // inflation to complete would use CAS to push themselves onto a singly linked duke@435: // list rooted at the markword. Once enqueued, they'd loop, checking a per-thread flag duke@435: // and calling park(). When inflation was complete the thread that accomplished inflation duke@435: // would detach the list and set the markword to inflated with a single CAS and duke@435: // then for each thread on the list, set the flag and unpark() the thread. duke@435: // This is conceptually similar to muxAcquire-muxRelease, except that muxRelease duke@435: // wakes at most one thread whereas we need to wake the entire list. duke@435: int ix = (intptr_t(obj) >> 5) & (NINFLATIONLOCKS-1) ; duke@435: int YieldThenBlock = 0 ; duke@435: assert (ix >= 0 && ix < NINFLATIONLOCKS, "invariant") ; duke@435: assert ((NINFLATIONLOCKS & (NINFLATIONLOCKS-1)) == 0, "invariant") ; duke@435: Thread::muxAcquire (InflationLocks + ix, "InflationLock") ; duke@435: while (obj->mark() == markOopDesc::INFLATING()) { duke@435: // Beware: NakedYield() is advisory and has almost no effect on some platforms duke@435: // so we periodically call Self->_ParkEvent->park(1). duke@435: // We use a mixed spin/yield/block mechanism. duke@435: if ((YieldThenBlock++) >= 16) { duke@435: Thread::current()->_ParkEvent->park(1) ; duke@435: } else { duke@435: os::NakedYield() ; duke@435: } duke@435: } duke@435: Thread::muxRelease (InflationLocks + ix ) ; duke@435: TEVENT (Inflate: INFLATING - yield/park) ; duke@435: } duke@435: } else { duke@435: SpinPause() ; // SMP-polite spinning duke@435: } duke@435: } duke@435: } duke@435: duke@435: ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) { duke@435: // Inflate mutates the heap ... duke@435: // Relaxing assertion for bug 6320749. duke@435: assert (Universe::verify_in_progress() || duke@435: !SafepointSynchronize::is_at_safepoint(), "invariant") ; duke@435: duke@435: for (;;) { duke@435: const markOop mark = object->mark() ; duke@435: assert (!mark->has_bias_pattern(), "invariant") ; duke@435: duke@435: // The mark can be in one of the following states: duke@435: // * Inflated - just return duke@435: // * Stack-locked - coerce it to inflated duke@435: // * INFLATING - busy wait for conversion to complete duke@435: // * Neutral - aggressively inflate the object. duke@435: // * BIASED - Illegal. We should never see this duke@435: duke@435: // CASE: inflated duke@435: if (mark->has_monitor()) { duke@435: ObjectMonitor * inf = mark->monitor() ; duke@435: assert (inf->header()->is_neutral(), "invariant"); duke@435: assert (inf->object() == object, "invariant") ; duke@435: assert (ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid"); duke@435: return inf ; duke@435: } duke@435: duke@435: // CASE: inflation in progress - inflating over a stack-lock. duke@435: // Some other thread is converting from stack-locked to inflated. duke@435: // Only that thread can complete inflation -- other threads must wait. duke@435: // The INFLATING value is transient. duke@435: // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish. duke@435: // We could always eliminate polling by parking the thread on some auxiliary list. duke@435: if (mark == markOopDesc::INFLATING()) { duke@435: TEVENT (Inflate: spin while INFLATING) ; duke@435: ReadStableMark(object) ; duke@435: continue ; duke@435: } duke@435: duke@435: // CASE: stack-locked duke@435: // Could be stack-locked either by this thread or by some other thread. duke@435: // duke@435: // Note that we allocate the objectmonitor speculatively, _before_ attempting duke@435: // to install INFLATING into the mark word. We originally installed INFLATING, duke@435: // allocated the objectmonitor, and then finally STed the address of the duke@435: // objectmonitor into the mark. This was correct, but artificially lengthened duke@435: // the interval in which INFLATED appeared in the mark, thus increasing duke@435: // the odds of inflation contention. duke@435: // duke@435: // We now use per-thread private objectmonitor free lists. duke@435: // These list are reprovisioned from the global free list outside the duke@435: // critical INFLATING...ST interval. A thread can transfer duke@435: // multiple objectmonitors en-mass from the global free list to its local free list. duke@435: // This reduces coherency traffic and lock contention on the global free list. duke@435: // Using such local free lists, it doesn't matter if the omAlloc() call appears duke@435: // before or after the CAS(INFLATING) operation. duke@435: // See the comments in omAlloc(). duke@435: duke@435: if (mark->has_locker()) { duke@435: ObjectMonitor * m = omAlloc (Self) ; duke@435: // Optimistically prepare the objectmonitor - anticipate successful CAS duke@435: // We do this before the CAS in order to minimize the length of time duke@435: // in which INFLATING appears in the mark. duke@435: m->Recycle(); duke@435: m->FreeNext = NULL ; duke@435: m->_Responsible = NULL ; duke@435: m->OwnerIsThread = 0 ; duke@435: m->_recursions = 0 ; duke@435: m->_SpinDuration = Knob_SpinLimit ; // Consider: maintain by type/class duke@435: duke@435: markOop cmp = (markOop) Atomic::cmpxchg_ptr (markOopDesc::INFLATING(), object->mark_addr(), mark) ; duke@435: if (cmp != mark) { duke@435: omRelease (Self, m) ; duke@435: continue ; // Interference -- just retry duke@435: } duke@435: duke@435: // We've successfully installed INFLATING (0) into the mark-word. duke@435: // This is the only case where 0 will appear in a mark-work. duke@435: // Only the singular thread that successfully swings the mark-word duke@435: // to 0 can perform (or more precisely, complete) inflation. duke@435: // duke@435: // Why do we CAS a 0 into the mark-word instead of just CASing the duke@435: // mark-word from the stack-locked value directly to the new inflated state? duke@435: // Consider what happens when a thread unlocks a stack-locked object. duke@435: // It attempts to use CAS to swing the displaced header value from the duke@435: // on-stack basiclock back into the object header. Recall also that the duke@435: // header value (hashcode, etc) can reside in (a) the object header, or duke@435: // (b) a displaced header associated with the stack-lock, or (c) a displaced duke@435: // header in an objectMonitor. The inflate() routine must copy the header duke@435: // value from the basiclock on the owner's stack to the objectMonitor, all duke@435: // the while preserving the hashCode stability invariants. If the owner duke@435: // decides to release the lock while the value is 0, the unlock will fail duke@435: // and control will eventually pass from slow_exit() to inflate. The owner duke@435: // will then spin, waiting for the 0 value to disappear. Put another way, duke@435: // the 0 causes the owner to stall if the owner happens to try to duke@435: // drop the lock (restoring the header from the basiclock to the object) duke@435: // while inflation is in-progress. This protocol avoids races that might duke@435: // would otherwise permit hashCode values to change or "flicker" for an object. duke@435: // Critically, while object->mark is 0 mark->displaced_mark_helper() is stable. duke@435: // 0 serves as a "BUSY" inflate-in-progress indicator. duke@435: duke@435: duke@435: // fetch the displaced mark from the owner's stack. duke@435: // The owner can't die or unwind past the lock while our INFLATING duke@435: // object is in the mark. Furthermore the owner can't complete duke@435: // an unlock on the object, either. duke@435: markOop dmw = mark->displaced_mark_helper() ; duke@435: assert (dmw->is_neutral(), "invariant") ; duke@435: duke@435: // Setup monitor fields to proper values -- prepare the monitor duke@435: m->set_header(dmw) ; duke@435: duke@435: // Optimization: if the mark->locker stack address is associated duke@435: // with this thread we could simply set m->_owner = Self and duke@435: // m->OwnerIsThread = 1. Note that a thread can inflate an object duke@435: // that it has stack-locked -- as might happen in wait() -- directly duke@435: // with CAS. That is, we can avoid the xchg-NULL .... ST idiom. duke@435: m->set_owner (mark->locker()); duke@435: m->set_object(object); duke@435: // TODO-FIXME: assert BasicLock->dhw != 0. duke@435: duke@435: // Must preserve store ordering. The monitor state must duke@435: // be stable at the time of publishing the monitor address. duke@435: guarantee (object->mark() == markOopDesc::INFLATING(), "invariant") ; duke@435: object->release_set_mark(markOopDesc::encode(m)); duke@435: duke@435: // Hopefully the performance counters are allocated on distinct cache lines duke@435: // to avoid false sharing on MP systems ... duke@435: if (_sync_Inflations != NULL) _sync_Inflations->inc() ; duke@435: TEVENT(Inflate: overwrite stacklock) ; duke@435: if (TraceMonitorInflation) { duke@435: if (object->is_instance()) { duke@435: ResourceMark rm; duke@435: tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s", duke@435: (intptr_t) object, (intptr_t) object->mark(), duke@435: Klass::cast(object->klass())->external_name()); duke@435: } duke@435: } duke@435: return m ; duke@435: } duke@435: duke@435: // CASE: neutral duke@435: // TODO-FIXME: for entry we currently inflate and then try to CAS _owner. duke@435: // If we know we're inflating for entry it's better to inflate by swinging a duke@435: // pre-locked objectMonitor pointer into the object header. A successful duke@435: // CAS inflates the object *and* confers ownership to the inflating thread. duke@435: // In the current implementation we use a 2-step mechanism where we CAS() duke@435: // to inflate and then CAS() again to try to swing _owner from NULL to Self. duke@435: // An inflateTry() method that we could call from fast_enter() and slow_enter() duke@435: // would be useful. duke@435: duke@435: assert (mark->is_neutral(), "invariant"); duke@435: ObjectMonitor * m = omAlloc (Self) ; duke@435: // prepare m for installation - set monitor to initial state duke@435: m->Recycle(); duke@435: m->set_header(mark); duke@435: m->set_owner(NULL); duke@435: m->set_object(object); duke@435: m->OwnerIsThread = 1 ; duke@435: m->_recursions = 0 ; duke@435: m->FreeNext = NULL ; duke@435: m->_Responsible = NULL ; duke@435: m->_SpinDuration = Knob_SpinLimit ; // consider: keep metastats by type/class duke@435: duke@435: if (Atomic::cmpxchg_ptr (markOopDesc::encode(m), object->mark_addr(), mark) != mark) { duke@435: m->set_object (NULL) ; duke@435: m->set_owner (NULL) ; duke@435: m->OwnerIsThread = 0 ; duke@435: m->Recycle() ; duke@435: omRelease (Self, m) ; duke@435: m = NULL ; duke@435: continue ; duke@435: // interference - the markword changed - just retry. duke@435: // The state-transitions are one-way, so there's no chance of duke@435: // live-lock -- "Inflated" is an absorbing state. duke@435: } duke@435: duke@435: // Hopefully the performance counters are allocated on distinct duke@435: // cache lines to avoid false sharing on MP systems ... duke@435: if (_sync_Inflations != NULL) _sync_Inflations->inc() ; duke@435: TEVENT(Inflate: overwrite neutral) ; duke@435: if (TraceMonitorInflation) { duke@435: if (object->is_instance()) { duke@435: ResourceMark rm; duke@435: tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s", duke@435: (intptr_t) object, (intptr_t) object->mark(), duke@435: Klass::cast(object->klass())->external_name()); duke@435: } duke@435: } duke@435: return m ; duke@435: } duke@435: } duke@435: duke@435: duke@435: // This the fast monitor enter. The interpreter and compiler use duke@435: // some assembly copies of this code. Make sure update those code duke@435: // if the following function is changed. The implementation is duke@435: // extremely sensitive to race condition. Be careful. duke@435: duke@435: void ObjectSynchronizer::fast_enter(Handle obj, BasicLock* lock, bool attempt_rebias, TRAPS) { duke@435: if (UseBiasedLocking) { duke@435: if (!SafepointSynchronize::is_at_safepoint()) { duke@435: BiasedLocking::Condition cond = BiasedLocking::revoke_and_rebias(obj, attempt_rebias, THREAD); duke@435: if (cond == BiasedLocking::BIAS_REVOKED_AND_REBIASED) { duke@435: return; duke@435: } duke@435: } else { duke@435: assert(!attempt_rebias, "can not rebias toward VM thread"); duke@435: BiasedLocking::revoke_at_safepoint(obj); duke@435: } duke@435: assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); duke@435: } duke@435: duke@435: THREAD->update_highest_lock((address)lock); duke@435: slow_enter (obj, lock, THREAD) ; duke@435: } duke@435: duke@435: void ObjectSynchronizer::fast_exit(oop object, BasicLock* lock, TRAPS) { duke@435: assert(!object->mark()->has_bias_pattern(), "should not see bias pattern here"); duke@435: // if displaced header is null, the previous enter is recursive enter, no-op duke@435: markOop dhw = lock->displaced_header(); duke@435: markOop mark ; duke@435: if (dhw == NULL) { duke@435: // Recursive stack-lock. duke@435: // Diagnostics -- Could be: stack-locked, inflating, inflated. duke@435: mark = object->mark() ; duke@435: assert (!mark->is_neutral(), "invariant") ; duke@435: if (mark->has_locker() && mark != markOopDesc::INFLATING()) { duke@435: assert(THREAD->is_lock_owned((address)mark->locker()), "invariant") ; duke@435: } duke@435: if (mark->has_monitor()) { duke@435: ObjectMonitor * m = mark->monitor() ; duke@435: assert(((oop)(m->object()))->mark() == mark, "invariant") ; duke@435: assert(m->is_entered(THREAD), "invariant") ; duke@435: } duke@435: return ; duke@435: } duke@435: duke@435: mark = object->mark() ; duke@435: duke@435: // If the object is stack-locked by the current thread, try to duke@435: // swing the displaced header from the box back to the mark. duke@435: if (mark == (markOop) lock) { duke@435: assert (dhw->is_neutral(), "invariant") ; duke@435: if ((markOop) Atomic::cmpxchg_ptr (dhw, object->mark_addr(), mark) == mark) { duke@435: TEVENT (fast_exit: release stacklock) ; duke@435: return; duke@435: } duke@435: } duke@435: duke@435: ObjectSynchronizer::inflate(THREAD, object)->exit (THREAD) ; duke@435: } duke@435: duke@435: // This routine is used to handle interpreter/compiler slow case duke@435: // We don't need to use fast path here, because it must have been duke@435: // failed in the interpreter/compiler code. duke@435: void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) { duke@435: markOop mark = obj->mark(); duke@435: assert(!mark->has_bias_pattern(), "should not see bias pattern here"); duke@435: duke@435: if (mark->is_neutral()) { duke@435: // Anticipate successful CAS -- the ST of the displaced mark must duke@435: // be visible <= the ST performed by the CAS. duke@435: lock->set_displaced_header(mark); duke@435: if (mark == (markOop) Atomic::cmpxchg_ptr(lock, obj()->mark_addr(), mark)) { duke@435: TEVENT (slow_enter: release stacklock) ; duke@435: return ; duke@435: } duke@435: // Fall through to inflate() ... duke@435: } else duke@435: if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) { duke@435: assert(lock != mark->locker(), "must not re-lock the same lock"); duke@435: assert(lock != (BasicLock*)obj->mark(), "don't relock with same BasicLock"); duke@435: lock->set_displaced_header(NULL); duke@435: return; duke@435: } duke@435: duke@435: #if 0 duke@435: // The following optimization isn't particularly useful. duke@435: if (mark->has_monitor() && mark->monitor()->is_entered(THREAD)) { duke@435: lock->set_displaced_header (NULL) ; duke@435: return ; duke@435: } duke@435: #endif duke@435: duke@435: // The object header will never be displaced to this lock, duke@435: // so it does not matter what the value is, except that it duke@435: // must be non-zero to avoid looking like a re-entrant lock, duke@435: // and must not look locked either. duke@435: lock->set_displaced_header(markOopDesc::unused_mark()); duke@435: ObjectSynchronizer::inflate(THREAD, obj())->enter(THREAD); duke@435: } duke@435: duke@435: // This routine is used to handle interpreter/compiler slow case duke@435: // We don't need to use fast path here, because it must have duke@435: // failed in the interpreter/compiler code. Simply use the heavy duke@435: // weight monitor should be ok, unless someone find otherwise. duke@435: void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) { duke@435: fast_exit (object, lock, THREAD) ; duke@435: } duke@435: duke@435: // NOTE: must use heavy weight monitor to handle jni monitor enter duke@435: void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) { // possible entry from jni enter duke@435: // the current locking is from JNI instead of Java code duke@435: TEVENT (jni_enter) ; duke@435: if (UseBiasedLocking) { duke@435: BiasedLocking::revoke_and_rebias(obj, false, THREAD); duke@435: assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); duke@435: } duke@435: THREAD->set_current_pending_monitor_is_from_java(false); duke@435: ObjectSynchronizer::inflate(THREAD, obj())->enter(THREAD); duke@435: THREAD->set_current_pending_monitor_is_from_java(true); duke@435: } duke@435: duke@435: // NOTE: must use heavy weight monitor to handle jni monitor enter duke@435: bool ObjectSynchronizer::jni_try_enter(Handle obj, Thread* THREAD) { duke@435: if (UseBiasedLocking) { duke@435: BiasedLocking::revoke_and_rebias(obj, false, THREAD); duke@435: assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); duke@435: } duke@435: duke@435: ObjectMonitor* monitor = ObjectSynchronizer::inflate_helper(obj()); duke@435: return monitor->try_enter(THREAD); duke@435: } duke@435: duke@435: duke@435: // NOTE: must use heavy weight monitor to handle jni monitor exit duke@435: void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) { duke@435: TEVENT (jni_exit) ; duke@435: if (UseBiasedLocking) { duke@435: BiasedLocking::revoke_and_rebias(obj, false, THREAD); duke@435: } duke@435: assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); duke@435: duke@435: ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj); duke@435: // If this thread has locked the object, exit the monitor. Note: can't use duke@435: // monitor->check(CHECK); must exit even if an exception is pending. duke@435: if (monitor->check(THREAD)) { duke@435: monitor->exit(THREAD); duke@435: } duke@435: } duke@435: duke@435: // complete_exit()/reenter() are used to wait on a nested lock duke@435: // i.e. to give up an outer lock completely and then re-enter duke@435: // Used when holding nested locks - lock acquisition order: lock1 then lock2 duke@435: // 1) complete_exit lock1 - saving recursion count duke@435: // 2) wait on lock2 duke@435: // 3) when notified on lock2, unlock lock2 duke@435: // 4) reenter lock1 with original recursion count duke@435: // 5) lock lock2 duke@435: // NOTE: must use heavy weight monitor to handle complete_exit/reenter() duke@435: intptr_t ObjectSynchronizer::complete_exit(Handle obj, TRAPS) { duke@435: TEVENT (complete_exit) ; duke@435: if (UseBiasedLocking) { duke@435: BiasedLocking::revoke_and_rebias(obj, false, THREAD); duke@435: assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); duke@435: } duke@435: duke@435: ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj()); duke@435: duke@435: return monitor->complete_exit(THREAD); duke@435: } duke@435: duke@435: // NOTE: must use heavy weight monitor to handle complete_exit/reenter() duke@435: void ObjectSynchronizer::reenter(Handle obj, intptr_t recursion, TRAPS) { duke@435: TEVENT (reenter) ; duke@435: if (UseBiasedLocking) { duke@435: BiasedLocking::revoke_and_rebias(obj, false, THREAD); duke@435: assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); duke@435: } duke@435: duke@435: ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj()); duke@435: duke@435: monitor->reenter(recursion, THREAD); duke@435: } duke@435: duke@435: // This exists only as a workaround of dtrace bug 6254741 duke@435: int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) { duke@435: DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr); duke@435: return 0; duke@435: } duke@435: duke@435: // NOTE: must use heavy weight monitor to handle wait() duke@435: void ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) { duke@435: if (UseBiasedLocking) { duke@435: BiasedLocking::revoke_and_rebias(obj, false, THREAD); duke@435: assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); duke@435: } duke@435: if (millis < 0) { duke@435: TEVENT (wait - throw IAX) ; duke@435: THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative"); duke@435: } duke@435: ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj()); duke@435: DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis); duke@435: monitor->wait(millis, true, THREAD); duke@435: duke@435: /* This dummy call is in place to get around dtrace bug 6254741. Once duke@435: that's fixed we can uncomment the following line and remove the call */ duke@435: // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD); duke@435: dtrace_waited_probe(monitor, obj, THREAD); duke@435: } duke@435: duke@435: void ObjectSynchronizer::waitUninterruptibly (Handle obj, jlong millis, TRAPS) { duke@435: if (UseBiasedLocking) { duke@435: BiasedLocking::revoke_and_rebias(obj, false, THREAD); duke@435: assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); duke@435: } duke@435: if (millis < 0) { duke@435: TEVENT (wait - throw IAX) ; duke@435: THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative"); duke@435: } duke@435: ObjectSynchronizer::inflate(THREAD, obj()) -> wait(millis, false, THREAD) ; duke@435: } duke@435: duke@435: void ObjectSynchronizer::notify(Handle obj, TRAPS) { duke@435: if (UseBiasedLocking) { duke@435: BiasedLocking::revoke_and_rebias(obj, false, THREAD); duke@435: assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); duke@435: } duke@435: duke@435: markOop mark = obj->mark(); duke@435: if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) { duke@435: return; duke@435: } duke@435: ObjectSynchronizer::inflate(THREAD, obj())->notify(THREAD); duke@435: } duke@435: duke@435: // NOTE: see comment of notify() duke@435: void ObjectSynchronizer::notifyall(Handle obj, TRAPS) { duke@435: if (UseBiasedLocking) { duke@435: BiasedLocking::revoke_and_rebias(obj, false, THREAD); duke@435: assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); duke@435: } duke@435: duke@435: markOop mark = obj->mark(); duke@435: if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) { duke@435: return; duke@435: } duke@435: ObjectSynchronizer::inflate(THREAD, obj())->notifyAll(THREAD); duke@435: } duke@435: duke@435: intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) { duke@435: if (UseBiasedLocking) { duke@435: // NOTE: many places throughout the JVM do not expect a safepoint duke@435: // to be taken here, in particular most operations on perm gen duke@435: // objects. However, we only ever bias Java instances and all of duke@435: // the call sites of identity_hash that might revoke biases have duke@435: // been checked to make sure they can handle a safepoint. The duke@435: // added check of the bias pattern is to avoid useless calls to duke@435: // thread-local storage. duke@435: if (obj->mark()->has_bias_pattern()) { duke@435: // Box and unbox the raw reference just in case we cause a STW safepoint. duke@435: Handle hobj (Self, obj) ; duke@435: // Relaxing assertion for bug 6320749. duke@435: assert (Universe::verify_in_progress() || duke@435: !SafepointSynchronize::is_at_safepoint(), duke@435: "biases should not be seen by VM thread here"); duke@435: BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current()); duke@435: obj = hobj() ; duke@435: assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); duke@435: } duke@435: } duke@435: duke@435: // hashCode() is a heap mutator ... duke@435: // Relaxing assertion for bug 6320749. duke@435: assert (Universe::verify_in_progress() || duke@435: !SafepointSynchronize::is_at_safepoint(), "invariant") ; duke@435: assert (Universe::verify_in_progress() || duke@435: Self->is_Java_thread() , "invariant") ; duke@435: assert (Universe::verify_in_progress() || duke@435: ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant") ; duke@435: duke@435: ObjectMonitor* monitor = NULL; duke@435: markOop temp, test; duke@435: intptr_t hash; duke@435: markOop mark = ReadStableMark (obj); duke@435: duke@435: // object should remain ineligible for biased locking duke@435: assert (!mark->has_bias_pattern(), "invariant") ; duke@435: duke@435: if (mark->is_neutral()) { duke@435: hash = mark->hash(); // this is a normal header duke@435: if (hash) { // if it has hash, just return it duke@435: return hash; duke@435: } duke@435: hash = get_next_hash(Self, obj); // allocate a new hash code duke@435: temp = mark->copy_set_hash(hash); // merge the hash code into header duke@435: // use (machine word version) atomic operation to install the hash duke@435: test = (markOop) Atomic::cmpxchg_ptr(temp, obj->mark_addr(), mark); duke@435: if (test == mark) { duke@435: return hash; duke@435: } duke@435: // If atomic operation failed, we must inflate the header duke@435: // into heavy weight monitor. We could add more code here duke@435: // for fast path, but it does not worth the complexity. duke@435: } else if (mark->has_monitor()) { duke@435: monitor = mark->monitor(); duke@435: temp = monitor->header(); duke@435: assert (temp->is_neutral(), "invariant") ; duke@435: hash = temp->hash(); duke@435: if (hash) { duke@435: return hash; duke@435: } duke@435: // Skip to the following code to reduce code size duke@435: } else if (Self->is_lock_owned((address)mark->locker())) { duke@435: temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned duke@435: assert (temp->is_neutral(), "invariant") ; duke@435: hash = temp->hash(); // by current thread, check if the displaced duke@435: if (hash) { // header contains hash code duke@435: return hash; duke@435: } duke@435: // WARNING: duke@435: // The displaced header is strictly immutable. duke@435: // It can NOT be changed in ANY cases. So we have duke@435: // to inflate the header into heavyweight monitor duke@435: // even the current thread owns the lock. The reason duke@435: // is the BasicLock (stack slot) will be asynchronously duke@435: // read by other threads during the inflate() function. duke@435: // Any change to stack may not propagate to other threads duke@435: // correctly. duke@435: } duke@435: duke@435: // Inflate the monitor to set hash code duke@435: monitor = ObjectSynchronizer::inflate(Self, obj); duke@435: // Load displaced header and check it has hash code duke@435: mark = monitor->header(); duke@435: assert (mark->is_neutral(), "invariant") ; duke@435: hash = mark->hash(); duke@435: if (hash == 0) { duke@435: hash = get_next_hash(Self, obj); duke@435: temp = mark->copy_set_hash(hash); // merge hash code into header duke@435: assert (temp->is_neutral(), "invariant") ; duke@435: test = (markOop) Atomic::cmpxchg_ptr(temp, monitor, mark); duke@435: if (test != mark) { duke@435: // The only update to the header in the monitor (outside GC) duke@435: // is install the hash code. If someone add new usage of duke@435: // displaced header, please update this code duke@435: hash = test->hash(); duke@435: assert (test->is_neutral(), "invariant") ; duke@435: assert (hash != 0, "Trivial unexpected object/monitor header usage."); duke@435: } duke@435: } duke@435: // We finally get the hash duke@435: return hash; duke@435: } duke@435: duke@435: // Deprecated -- use FastHashCode() instead. duke@435: duke@435: intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) { duke@435: return FastHashCode (Thread::current(), obj()) ; duke@435: } duke@435: duke@435: bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread, duke@435: Handle h_obj) { duke@435: if (UseBiasedLocking) { duke@435: BiasedLocking::revoke_and_rebias(h_obj, false, thread); duke@435: assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now"); duke@435: } duke@435: duke@435: assert(thread == JavaThread::current(), "Can only be called on current thread"); duke@435: oop obj = h_obj(); duke@435: duke@435: markOop mark = ReadStableMark (obj) ; duke@435: duke@435: // Uncontended case, header points to stack duke@435: if (mark->has_locker()) { duke@435: return thread->is_lock_owned((address)mark->locker()); duke@435: } duke@435: // Contended case, header points to ObjectMonitor (tagged pointer) duke@435: if (mark->has_monitor()) { duke@435: ObjectMonitor* monitor = mark->monitor(); duke@435: return monitor->is_entered(thread) != 0 ; duke@435: } duke@435: // Unlocked case, header in place duke@435: assert(mark->is_neutral(), "sanity check"); duke@435: return false; duke@435: } duke@435: duke@435: // Be aware of this method could revoke bias of the lock object. duke@435: // This method querys the ownership of the lock handle specified by 'h_obj'. duke@435: // If the current thread owns the lock, it returns owner_self. If no duke@435: // thread owns the lock, it returns owner_none. Otherwise, it will return duke@435: // ower_other. duke@435: ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership duke@435: (JavaThread *self, Handle h_obj) { duke@435: // The caller must beware this method can revoke bias, and duke@435: // revocation can result in a safepoint. duke@435: assert (!SafepointSynchronize::is_at_safepoint(), "invariant") ; duke@435: assert (self->thread_state() != _thread_blocked , "invariant") ; duke@435: duke@435: // Possible mark states: neutral, biased, stack-locked, inflated duke@435: duke@435: if (UseBiasedLocking && h_obj()->mark()->has_bias_pattern()) { duke@435: // CASE: biased duke@435: BiasedLocking::revoke_and_rebias(h_obj, false, self); duke@435: assert(!h_obj->mark()->has_bias_pattern(), duke@435: "biases should be revoked by now"); duke@435: } duke@435: duke@435: assert(self == JavaThread::current(), "Can only be called on current thread"); duke@435: oop obj = h_obj(); duke@435: markOop mark = ReadStableMark (obj) ; duke@435: duke@435: // CASE: stack-locked. Mark points to a BasicLock on the owner's stack. duke@435: if (mark->has_locker()) { duke@435: return self->is_lock_owned((address)mark->locker()) ? duke@435: owner_self : owner_other; duke@435: } duke@435: duke@435: // CASE: inflated. Mark (tagged pointer) points to an objectMonitor. duke@435: // The Object:ObjectMonitor relationship is stable as long as we're duke@435: // not at a safepoint. duke@435: if (mark->has_monitor()) { duke@435: void * owner = mark->monitor()->_owner ; duke@435: if (owner == NULL) return owner_none ; duke@435: return (owner == self || duke@435: self->is_lock_owned((address)owner)) ? owner_self : owner_other; duke@435: } duke@435: duke@435: // CASE: neutral duke@435: assert(mark->is_neutral(), "sanity check"); duke@435: return owner_none ; // it's unlocked duke@435: } duke@435: duke@435: // FIXME: jvmti should call this duke@435: JavaThread* ObjectSynchronizer::get_lock_owner(Handle h_obj, bool doLock) { duke@435: if (UseBiasedLocking) { duke@435: if (SafepointSynchronize::is_at_safepoint()) { duke@435: BiasedLocking::revoke_at_safepoint(h_obj); duke@435: } else { duke@435: BiasedLocking::revoke_and_rebias(h_obj, false, JavaThread::current()); duke@435: } duke@435: assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now"); duke@435: } duke@435: duke@435: oop obj = h_obj(); duke@435: address owner = NULL; duke@435: duke@435: markOop mark = ReadStableMark (obj) ; duke@435: duke@435: // Uncontended case, header points to stack duke@435: if (mark->has_locker()) { duke@435: owner = (address) mark->locker(); duke@435: } duke@435: duke@435: // Contended case, header points to ObjectMonitor (tagged pointer) duke@435: if (mark->has_monitor()) { duke@435: ObjectMonitor* monitor = mark->monitor(); duke@435: assert(monitor != NULL, "monitor should be non-null"); duke@435: owner = (address) monitor->owner(); duke@435: } duke@435: duke@435: if (owner != NULL) { duke@435: return Threads::owning_thread_from_monitor_owner(owner, doLock); duke@435: } duke@435: duke@435: // Unlocked case, header in place duke@435: // Cannot have assertion since this object may have been duke@435: // locked by another thread when reaching here. duke@435: // assert(mark->is_neutral(), "sanity check"); duke@435: duke@435: return NULL; duke@435: } duke@435: duke@435: // Iterate through monitor cache and attempt to release thread's monitors duke@435: // Gives up on a particular monitor if an exception occurs, but continues duke@435: // the overall iteration, swallowing the exception. duke@435: class ReleaseJavaMonitorsClosure: public MonitorClosure { duke@435: private: duke@435: TRAPS; duke@435: duke@435: public: duke@435: ReleaseJavaMonitorsClosure(Thread* thread) : THREAD(thread) {} duke@435: void do_monitor(ObjectMonitor* mid) { duke@435: if (mid->owner() == THREAD) { duke@435: (void)mid->complete_exit(CHECK); duke@435: } duke@435: } duke@435: }; duke@435: duke@435: // Release all inflated monitors owned by THREAD. Lightweight monitors are duke@435: // ignored. This is meant to be called during JNI thread detach which assumes duke@435: // all remaining monitors are heavyweight. All exceptions are swallowed. duke@435: // Scanning the extant monitor list can be time consuming. duke@435: // A simple optimization is to add a per-thread flag that indicates a thread duke@435: // called jni_monitorenter() during its lifetime. duke@435: // duke@435: // Instead of No_Savepoint_Verifier it might be cheaper to duke@435: // use an idiom of the form: duke@435: // auto int tmp = SafepointSynchronize::_safepoint_counter ; duke@435: // duke@435: // guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ; duke@435: // Since the tests are extremely cheap we could leave them enabled duke@435: // for normal product builds. duke@435: duke@435: void ObjectSynchronizer::release_monitors_owned_by_thread(TRAPS) { duke@435: assert(THREAD == JavaThread::current(), "must be current Java thread"); duke@435: No_Safepoint_Verifier nsv ; duke@435: ReleaseJavaMonitorsClosure rjmc(THREAD); duke@435: Thread::muxAcquire(&ListLock, "release_monitors_owned_by_thread"); duke@435: ObjectSynchronizer::monitors_iterate(&rjmc); duke@435: Thread::muxRelease(&ListLock); duke@435: THREAD->clear_pending_exception(); duke@435: } duke@435: duke@435: // Visitors ... duke@435: duke@435: void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure) { duke@435: ObjectMonitor* block = gBlockList; duke@435: ObjectMonitor* mid; duke@435: while (block) { duke@435: assert(block->object() == CHAINMARKER, "must be a block header"); duke@435: for (int i = _BLOCKSIZE - 1; i > 0; i--) { duke@435: mid = block + i; duke@435: oop object = (oop) mid->object(); duke@435: if (object != NULL) { duke@435: closure->do_monitor(mid); duke@435: } duke@435: } duke@435: block = (ObjectMonitor*) block->FreeNext; duke@435: } duke@435: } duke@435: duke@435: void ObjectSynchronizer::oops_do(OopClosure* f) { duke@435: assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); duke@435: for (ObjectMonitor* block = gBlockList; block != NULL; block = next(block)) { duke@435: assert(block->object() == CHAINMARKER, "must be a block header"); duke@435: for (int i = 1; i < _BLOCKSIZE; i++) { duke@435: ObjectMonitor* mid = &block[i]; duke@435: if (mid->object() != NULL) { duke@435: f->do_oop((oop*)mid->object_addr()); duke@435: } duke@435: } duke@435: } duke@435: } duke@435: duke@435: // Deflate_idle_monitors() is called at all safepoints, immediately duke@435: // after all mutators are stopped, but before any objects have moved. duke@435: // It traverses the list of known monitors, deflating where possible. duke@435: // The scavenged monitor are returned to the monitor free list. duke@435: // duke@435: // Beware that we scavenge at *every* stop-the-world point. duke@435: // Having a large number of monitors in-circulation negatively duke@435: // impacts the performance of some applications (e.g., PointBase). duke@435: // Broadly, we want to minimize the # of monitors in circulation. duke@435: // Alternately, we could partition the active monitors into sub-lists duke@435: // of those that need scanning and those that do not. duke@435: // Specifically, we would add a new sub-list of objectmonitors duke@435: // that are in-circulation and potentially active. deflate_idle_monitors() duke@435: // would scan only that list. Other monitors could reside on a quiescent duke@435: // list. Such sequestered monitors wouldn't need to be scanned by duke@435: // deflate_idle_monitors(). omAlloc() would first check the global free list, duke@435: // then the quiescent list, and, failing those, would allocate a new block. duke@435: // Deflate_idle_monitors() would scavenge and move monitors to the duke@435: // quiescent list. duke@435: // duke@435: // Perversely, the heap size -- and thus the STW safepoint rate -- duke@435: // typically drives the scavenge rate. Large heaps can mean infrequent GC, duke@435: // which in turn can mean large(r) numbers of objectmonitors in circulation. duke@435: // This is an unfortunate aspect of this design. duke@435: // duke@435: // Another refinement would be to refrain from calling deflate_idle_monitors() duke@435: // except at stop-the-world points associated with garbage collections. duke@435: // duke@435: // An even better solution would be to deflate on-the-fly, aggressively, duke@435: // at monitorexit-time as is done in EVM's metalock or Relaxed Locks. duke@435: duke@435: void ObjectSynchronizer::deflate_idle_monitors() { duke@435: assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); duke@435: int nInuse = 0 ; // currently associated with objects duke@435: int nInCirculation = 0 ; // extant duke@435: int nScavenged = 0 ; // reclaimed duke@435: duke@435: ObjectMonitor * FreeHead = NULL ; // Local SLL of scavenged monitors duke@435: ObjectMonitor * FreeTail = NULL ; duke@435: duke@435: // Iterate over all extant monitors - Scavenge all idle monitors. duke@435: TEVENT (deflate_idle_monitors) ; duke@435: for (ObjectMonitor* block = gBlockList; block != NULL; block = next(block)) { duke@435: assert(block->object() == CHAINMARKER, "must be a block header"); duke@435: nInCirculation += _BLOCKSIZE ; duke@435: for (int i = 1 ; i < _BLOCKSIZE; i++) { duke@435: ObjectMonitor* mid = &block[i]; duke@435: oop obj = (oop) mid->object(); duke@435: duke@435: if (obj == NULL) { duke@435: // The monitor is not associated with an object. duke@435: // The monitor should either be a thread-specific private duke@435: // free list or the global free list. duke@435: // obj == NULL IMPLIES mid->is_busy() == 0 duke@435: guarantee (!mid->is_busy(), "invariant") ; duke@435: continue ; duke@435: } duke@435: duke@435: // Normal case ... The monitor is associated with obj. duke@435: guarantee (obj->mark() == markOopDesc::encode(mid), "invariant") ; duke@435: guarantee (mid == obj->mark()->monitor(), "invariant"); duke@435: guarantee (mid->header()->is_neutral(), "invariant"); duke@435: duke@435: if (mid->is_busy()) { duke@435: if (ClearResponsibleAtSTW) mid->_Responsible = NULL ; duke@435: nInuse ++ ; duke@435: } else { duke@435: // Deflate the monitor if it is no longer being used duke@435: // It's idle - scavenge and return to the global free list duke@435: // plain old deflation ... duke@435: TEVENT (deflate_idle_monitors - scavenge1) ; duke@435: if (TraceMonitorInflation) { duke@435: if (obj->is_instance()) { duke@435: ResourceMark rm; duke@435: tty->print_cr("Deflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s", duke@435: (intptr_t) obj, (intptr_t) obj->mark(), Klass::cast(obj->klass())->external_name()); duke@435: } duke@435: } duke@435: duke@435: // Restore the header back to obj duke@435: obj->release_set_mark(mid->header()); duke@435: mid->clear(); duke@435: duke@435: assert (mid->object() == NULL, "invariant") ; duke@435: duke@435: // Move the object to the working free list defined by FreeHead,FreeTail. duke@435: mid->FreeNext = NULL ; duke@435: if (FreeHead == NULL) FreeHead = mid ; duke@435: if (FreeTail != NULL) FreeTail->FreeNext = mid ; duke@435: FreeTail = mid ; duke@435: nScavenged ++ ; duke@435: } duke@435: } duke@435: } duke@435: duke@435: // Move the scavenged monitors back to the global free list. duke@435: // In theory we don't need the freelist lock as we're at a STW safepoint. duke@435: // omAlloc() and omFree() can only be called while a thread is _not in safepoint state. duke@435: // But it's remotely possible that omFlush() or release_monitors_owned_by_thread() duke@435: // might be called while not at a global STW safepoint. In the interest of duke@435: // safety we protect the following access with ListLock. duke@435: // An even more conservative and prudent approach would be to guard duke@435: // the main loop in scavenge_idle_monitors() with ListLock. duke@435: if (FreeHead != NULL) { duke@435: guarantee (FreeTail != NULL && nScavenged > 0, "invariant") ; duke@435: assert (FreeTail->FreeNext == NULL, "invariant") ; duke@435: // constant-time list splice - prepend scavenged segment to gFreeList duke@435: Thread::muxAcquire (&ListLock, "scavenge - return") ; duke@435: FreeTail->FreeNext = gFreeList ; duke@435: gFreeList = FreeHead ; duke@435: Thread::muxRelease (&ListLock) ; duke@435: } duke@435: duke@435: if (_sync_Deflations != NULL) _sync_Deflations->inc(nScavenged) ; duke@435: if (_sync_MonExtant != NULL) _sync_MonExtant ->set_value(nInCirculation); duke@435: duke@435: // TODO: Add objectMonitor leak detection. duke@435: // Audit/inventory the objectMonitors -- make sure they're all accounted for. duke@435: GVars.stwRandom = os::random() ; duke@435: GVars.stwCycle ++ ; duke@435: } duke@435: duke@435: // A macro is used below because there may already be a pending duke@435: // exception which should not abort the execution of the routines duke@435: // which use this (which is why we don't put this into check_slow and duke@435: // call it with a CHECK argument). duke@435: duke@435: #define CHECK_OWNER() \ duke@435: do { \ duke@435: if (THREAD != _owner) { \ duke@435: if (THREAD->is_lock_owned((address) _owner)) { \ duke@435: _owner = THREAD ; /* Convert from basiclock addr to Thread addr */ \ duke@435: _recursions = 0; \ duke@435: OwnerIsThread = 1 ; \ duke@435: } else { \ duke@435: TEVENT (Throw IMSX) ; \ duke@435: THROW(vmSymbols::java_lang_IllegalMonitorStateException()); \ duke@435: } \ duke@435: } \ duke@435: } while (false) duke@435: duke@435: // TODO-FIXME: eliminate ObjectWaiters. Replace this visitor/enumerator duke@435: // interface with a simple FirstWaitingThread(), NextWaitingThread() interface. duke@435: duke@435: ObjectWaiter* ObjectMonitor::first_waiter() { duke@435: return _WaitSet; duke@435: } duke@435: duke@435: ObjectWaiter* ObjectMonitor::next_waiter(ObjectWaiter* o) { duke@435: return o->_next; duke@435: } duke@435: duke@435: Thread* ObjectMonitor::thread_of_waiter(ObjectWaiter* o) { duke@435: return o->_thread; duke@435: } duke@435: duke@435: // initialize the monitor, exception the semaphore, all other fields duke@435: // are simple integers or pointers duke@435: ObjectMonitor::ObjectMonitor() { duke@435: _header = NULL; duke@435: _count = 0; duke@435: _waiters = 0, duke@435: _recursions = 0; duke@435: _object = NULL; duke@435: _owner = NULL; duke@435: _WaitSet = NULL; duke@435: _WaitSetLock = 0 ; duke@435: _Responsible = NULL ; duke@435: _succ = NULL ; duke@435: _cxq = NULL ; duke@435: FreeNext = NULL ; duke@435: _EntryList = NULL ; duke@435: _SpinFreq = 0 ; duke@435: _SpinClock = 0 ; duke@435: OwnerIsThread = 0 ; duke@435: } duke@435: duke@435: ObjectMonitor::~ObjectMonitor() { duke@435: // TODO: Add asserts ... duke@435: // _cxq == 0 _succ == NULL _owner == NULL _waiters == 0 duke@435: // _count == 0 _EntryList == NULL etc duke@435: } duke@435: duke@435: intptr_t ObjectMonitor::is_busy() const { duke@435: // TODO-FIXME: merge _count and _waiters. duke@435: // TODO-FIXME: assert _owner == null implies _recursions = 0 duke@435: // TODO-FIXME: assert _WaitSet != null implies _count > 0 duke@435: return _count|_waiters|intptr_t(_owner)|intptr_t(_cxq)|intptr_t(_EntryList ) ; duke@435: } duke@435: duke@435: void ObjectMonitor::Recycle () { duke@435: // TODO: add stronger asserts ... duke@435: // _cxq == 0 _succ == NULL _owner == NULL _waiters == 0 duke@435: // _count == 0 EntryList == NULL duke@435: // _recursions == 0 _WaitSet == NULL duke@435: // TODO: assert (is_busy()|_recursions) == 0 duke@435: _succ = NULL ; duke@435: _EntryList = NULL ; duke@435: _cxq = NULL ; duke@435: _WaitSet = NULL ; duke@435: _recursions = 0 ; duke@435: _SpinFreq = 0 ; duke@435: _SpinClock = 0 ; duke@435: OwnerIsThread = 0 ; duke@435: } duke@435: duke@435: // WaitSet management ... duke@435: duke@435: inline void ObjectMonitor::AddWaiter(ObjectWaiter* node) { duke@435: assert(node != NULL, "should not dequeue NULL node"); duke@435: assert(node->_prev == NULL, "node already in list"); duke@435: assert(node->_next == NULL, "node already in list"); duke@435: // put node at end of queue (circular doubly linked list) duke@435: if (_WaitSet == NULL) { duke@435: _WaitSet = node; duke@435: node->_prev = node; duke@435: node->_next = node; duke@435: } else { duke@435: ObjectWaiter* head = _WaitSet ; duke@435: ObjectWaiter* tail = head->_prev; duke@435: assert(tail->_next == head, "invariant check"); duke@435: tail->_next = node; duke@435: head->_prev = node; duke@435: node->_next = head; duke@435: node->_prev = tail; duke@435: } duke@435: } duke@435: duke@435: inline ObjectWaiter* ObjectMonitor::DequeueWaiter() { duke@435: // dequeue the very first waiter duke@435: ObjectWaiter* waiter = _WaitSet; duke@435: if (waiter) { duke@435: DequeueSpecificWaiter(waiter); duke@435: } duke@435: return waiter; duke@435: } duke@435: duke@435: inline void ObjectMonitor::DequeueSpecificWaiter(ObjectWaiter* node) { duke@435: assert(node != NULL, "should not dequeue NULL node"); duke@435: assert(node->_prev != NULL, "node already removed from list"); duke@435: assert(node->_next != NULL, "node already removed from list"); duke@435: // when the waiter has woken up because of interrupt, duke@435: // timeout or other spurious wake-up, dequeue the duke@435: // waiter from waiting list duke@435: ObjectWaiter* next = node->_next; duke@435: if (next == node) { duke@435: assert(node->_prev == node, "invariant check"); duke@435: _WaitSet = NULL; duke@435: } else { duke@435: ObjectWaiter* prev = node->_prev; duke@435: assert(prev->_next == node, "invariant check"); duke@435: assert(next->_prev == node, "invariant check"); duke@435: next->_prev = prev; duke@435: prev->_next = next; duke@435: if (_WaitSet == node) { duke@435: _WaitSet = next; duke@435: } duke@435: } duke@435: node->_next = NULL; duke@435: node->_prev = NULL; duke@435: } duke@435: duke@435: static char * kvGet (char * kvList, const char * Key) { duke@435: if (kvList == NULL) return NULL ; duke@435: size_t n = strlen (Key) ; duke@435: char * Search ; duke@435: for (Search = kvList ; *Search ; Search += strlen(Search) + 1) { duke@435: if (strncmp (Search, Key, n) == 0) { duke@435: if (Search[n] == '=') return Search + n + 1 ; duke@435: if (Search[n] == 0) return (char *) "1" ; duke@435: } duke@435: } duke@435: return NULL ; duke@435: } duke@435: duke@435: static int kvGetInt (char * kvList, const char * Key, int Default) { duke@435: char * v = kvGet (kvList, Key) ; duke@435: int rslt = v ? ::strtol (v, NULL, 0) : Default ; duke@435: if (Knob_ReportSettings && v != NULL) { duke@435: ::printf (" SyncKnob: %s %d(%d)\n", Key, rslt, Default) ; duke@435: ::fflush (stdout) ; duke@435: } duke@435: return rslt ; duke@435: } duke@435: duke@435: // By convention we unlink a contending thread from EntryList|cxq immediately duke@435: // after the thread acquires the lock in ::enter(). Equally, we could defer duke@435: // unlinking the thread until ::exit()-time. duke@435: duke@435: void ObjectMonitor::UnlinkAfterAcquire (Thread * Self, ObjectWaiter * SelfNode) duke@435: { duke@435: assert (_owner == Self, "invariant") ; duke@435: assert (SelfNode->_thread == Self, "invariant") ; duke@435: duke@435: if (SelfNode->TState == ObjectWaiter::TS_ENTER) { duke@435: // Normal case: remove Self from the DLL EntryList . duke@435: // This is a constant-time operation. duke@435: ObjectWaiter * nxt = SelfNode->_next ; duke@435: ObjectWaiter * prv = SelfNode->_prev ; duke@435: if (nxt != NULL) nxt->_prev = prv ; duke@435: if (prv != NULL) prv->_next = nxt ; duke@435: if (SelfNode == _EntryList ) _EntryList = nxt ; duke@435: assert (nxt == NULL || nxt->TState == ObjectWaiter::TS_ENTER, "invariant") ; duke@435: assert (prv == NULL || prv->TState == ObjectWaiter::TS_ENTER, "invariant") ; duke@435: TEVENT (Unlink from EntryList) ; duke@435: } else { duke@435: guarantee (SelfNode->TState == ObjectWaiter::TS_CXQ, "invariant") ; duke@435: // Inopportune interleaving -- Self is still on the cxq. duke@435: // This usually means the enqueue of self raced an exiting thread. duke@435: // Normally we'll find Self near the front of the cxq, so duke@435: // dequeueing is typically fast. If needbe we can accelerate duke@435: // this with some MCS/CHL-like bidirectional list hints and advisory duke@435: // back-links so dequeueing from the interior will normally operate duke@435: // in constant-time. duke@435: // Dequeue Self from either the head (with CAS) or from the interior duke@435: // with a linear-time scan and normal non-atomic memory operations. duke@435: // CONSIDER: if Self is on the cxq then simply drain cxq into EntryList duke@435: // and then unlink Self from EntryList. We have to drain eventually, duke@435: // so it might as well be now. duke@435: duke@435: ObjectWaiter * v = _cxq ; duke@435: assert (v != NULL, "invariant") ; duke@435: if (v != SelfNode || Atomic::cmpxchg_ptr (SelfNode->_next, &_cxq, v) != v) { duke@435: // The CAS above can fail from interference IFF a "RAT" arrived. duke@435: // In that case Self must be in the interior and can no longer be duke@435: // at the head of cxq. duke@435: if (v == SelfNode) { duke@435: assert (_cxq != v, "invariant") ; duke@435: v = _cxq ; // CAS above failed - start scan at head of list duke@435: } duke@435: ObjectWaiter * p ; duke@435: ObjectWaiter * q = NULL ; duke@435: for (p = v ; p != NULL && p != SelfNode; p = p->_next) { duke@435: q = p ; duke@435: assert (p->TState == ObjectWaiter::TS_CXQ, "invariant") ; duke@435: } duke@435: assert (v != SelfNode, "invariant") ; duke@435: assert (p == SelfNode, "Node not found on cxq") ; duke@435: assert (p != _cxq, "invariant") ; duke@435: assert (q != NULL, "invariant") ; duke@435: assert (q->_next == p, "invariant") ; duke@435: q->_next = p->_next ; duke@435: } duke@435: TEVENT (Unlink from cxq) ; duke@435: } duke@435: duke@435: // Diagnostic hygiene ... duke@435: SelfNode->_prev = (ObjectWaiter *) 0xBAD ; duke@435: SelfNode->_next = (ObjectWaiter *) 0xBAD ; duke@435: SelfNode->TState = ObjectWaiter::TS_RUN ; duke@435: } duke@435: duke@435: // Caveat: TryLock() is not necessarily serializing if it returns failure. duke@435: // Callers must compensate as needed. duke@435: duke@435: int ObjectMonitor::TryLock (Thread * Self) { duke@435: for (;;) { duke@435: void * own = _owner ; duke@435: if (own != NULL) return 0 ; duke@435: if (Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) { duke@435: // Either guarantee _recursions == 0 or set _recursions = 0. duke@435: assert (_recursions == 0, "invariant") ; duke@435: assert (_owner == Self, "invariant") ; duke@435: // CONSIDER: set or assert that OwnerIsThread == 1 duke@435: return 1 ; duke@435: } duke@435: // The lock had been free momentarily, but we lost the race to the lock. duke@435: // Interference -- the CAS failed. duke@435: // We can either return -1 or retry. duke@435: // Retry doesn't make as much sense because the lock was just acquired. duke@435: if (true) return -1 ; duke@435: } duke@435: } duke@435: duke@435: // NotRunnable() -- informed spinning duke@435: // duke@435: // Don't bother spinning if the owner is not eligible to drop the lock. duke@435: // Peek at the owner's schedctl.sc_state and Thread._thread_values and duke@435: // spin only if the owner thread is _thread_in_Java or _thread_in_vm. duke@435: // The thread must be runnable in order to drop the lock in timely fashion. duke@435: // If the _owner is not runnable then spinning will not likely be duke@435: // successful (profitable). duke@435: // duke@435: // Beware -- the thread referenced by _owner could have died duke@435: // so a simply fetch from _owner->_thread_state might trap. duke@435: // Instead, we use SafeFetchXX() to safely LD _owner->_thread_state. duke@435: // Because of the lifecycle issues the schedctl and _thread_state values duke@435: // observed by NotRunnable() might be garbage. NotRunnable must duke@435: // tolerate this and consider the observed _thread_state value duke@435: // as advisory. duke@435: // duke@435: // Beware too, that _owner is sometimes a BasicLock address and sometimes duke@435: // a thread pointer. We differentiate the two cases with OwnerIsThread. duke@435: // Alternately, we might tag the type (thread pointer vs basiclock pointer) duke@435: // with the LSB of _owner. Another option would be to probablistically probe duke@435: // the putative _owner->TypeTag value. duke@435: // duke@435: // Checking _thread_state isn't perfect. Even if the thread is duke@435: // in_java it might be blocked on a page-fault or have been preempted duke@435: // and sitting on a ready/dispatch queue. _thread state in conjunction duke@435: // with schedctl.sc_state gives us a good picture of what the duke@435: // thread is doing, however. duke@435: // duke@435: // TODO: check schedctl.sc_state. duke@435: // We'll need to use SafeFetch32() to read from the schedctl block. duke@435: // See RFE #5004247 and http://sac.sfbay.sun.com/Archives/CaseLog/arc/PSARC/2005/351/ duke@435: // duke@435: // The return value from NotRunnable() is *advisory* -- the duke@435: // result is based on sampling and is not necessarily coherent. duke@435: // The caller must tolerate false-negative and false-positive errors. duke@435: // Spinning, in general, is probabilistic anyway. duke@435: duke@435: duke@435: int ObjectMonitor::NotRunnable (Thread * Self, Thread * ox) { duke@435: // Check either OwnerIsThread or ox->TypeTag == 2BAD. duke@435: if (!OwnerIsThread) return 0 ; duke@435: duke@435: if (ox == NULL) return 0 ; duke@435: duke@435: // Avoid transitive spinning ... duke@435: // Say T1 spins or blocks trying to acquire L. T1._Stalled is set to L. duke@435: // Immediately after T1 acquires L it's possible that T2, also duke@435: // spinning on L, will see L.Owner=T1 and T1._Stalled=L. duke@435: // This occurs transiently after T1 acquired L but before duke@435: // T1 managed to clear T1.Stalled. T2 does not need to abort duke@435: // its spin in this circumstance. duke@435: intptr_t BlockedOn = SafeFetchN ((intptr_t *) &ox->_Stalled, intptr_t(1)) ; duke@435: duke@435: if (BlockedOn == 1) return 1 ; duke@435: if (BlockedOn != 0) { duke@435: return BlockedOn != intptr_t(this) && _owner == ox ; duke@435: } duke@435: duke@435: assert (sizeof(((JavaThread *)ox)->_thread_state == sizeof(int)), "invariant") ; duke@435: int jst = SafeFetch32 ((int *) &((JavaThread *) ox)->_thread_state, -1) ; ; duke@435: // consider also: jst != _thread_in_Java -- but that's overspecific. duke@435: return jst == _thread_blocked || jst == _thread_in_native ; duke@435: } duke@435: duke@435: duke@435: // Adaptive spin-then-block - rational spinning duke@435: // duke@435: // Note that we spin "globally" on _owner with a classic SMP-polite TATAS duke@435: // algorithm. On high order SMP systems it would be better to start with duke@435: // a brief global spin and then revert to spinning locally. In the spirit of MCS/CLH, duke@435: // a contending thread could enqueue itself on the cxq and then spin locally duke@435: // on a thread-specific variable such as its ParkEvent._Event flag. duke@435: // That's left as an exercise for the reader. Note that global spinning is duke@435: // not problematic on Niagara, as the L2$ serves the interconnect and has both duke@435: // low latency and massive bandwidth. duke@435: // duke@435: // Broadly, we can fix the spin frequency -- that is, the % of contended lock duke@435: // acquisition attempts where we opt to spin -- at 100% and vary the spin count duke@435: // (duration) or we can fix the count at approximately the duration of duke@435: // a context switch and vary the frequency. Of course we could also duke@435: // vary both satisfying K == Frequency * Duration, where K is adaptive by monitor. duke@435: // See http://j2se.east/~dice/PERSIST/040824-AdaptiveSpinning.html. duke@435: // duke@435: // This implementation varies the duration "D", where D varies with duke@435: // the success rate of recent spin attempts. (D is capped at approximately duke@435: // length of a round-trip context switch). The success rate for recent duke@435: // spin attempts is a good predictor of the success rate of future spin duke@435: // attempts. The mechanism adapts automatically to varying critical duke@435: // section length (lock modality), system load and degree of parallelism. duke@435: // D is maintained per-monitor in _SpinDuration and is initialized duke@435: // optimistically. Spin frequency is fixed at 100%. duke@435: // duke@435: // Note that _SpinDuration is volatile, but we update it without locks duke@435: // or atomics. The code is designed so that _SpinDuration stays within duke@435: // a reasonable range even in the presence of races. The arithmetic duke@435: // operations on _SpinDuration are closed over the domain of legal values, duke@435: // so at worst a race will install and older but still legal value. duke@435: // At the very worst this introduces some apparent non-determinism. duke@435: // We might spin when we shouldn't or vice-versa, but since the spin duke@435: // count are relatively short, even in the worst case, the effect is harmless. duke@435: // duke@435: // Care must be taken that a low "D" value does not become an duke@435: // an absorbing state. Transient spinning failures -- when spinning duke@435: // is overall profitable -- should not cause the system to converge duke@435: // on low "D" values. We want spinning to be stable and predictable duke@435: // and fairly responsive to change and at the same time we don't want duke@435: // it to oscillate, become metastable, be "too" non-deterministic, duke@435: // or converge on or enter undesirable stable absorbing states. duke@435: // duke@435: // We implement a feedback-based control system -- using past behavior duke@435: // to predict future behavior. We face two issues: (a) if the duke@435: // input signal is random then the spin predictor won't provide optimal duke@435: // results, and (b) if the signal frequency is too high then the control duke@435: // system, which has some natural response lag, will "chase" the signal. duke@435: // (b) can arise from multimodal lock hold times. Transient preemption duke@435: // can also result in apparent bimodal lock hold times. duke@435: // Although sub-optimal, neither condition is particularly harmful, as duke@435: // in the worst-case we'll spin when we shouldn't or vice-versa. duke@435: // The maximum spin duration is rather short so the failure modes aren't bad. duke@435: // To be conservative, I've tuned the gain in system to bias toward duke@435: // _not spinning. Relatedly, the system can sometimes enter a mode where it duke@435: // "rings" or oscillates between spinning and not spinning. This happens duke@435: // when spinning is just on the cusp of profitability, however, so the duke@435: // situation is not dire. The state is benign -- there's no need to add duke@435: // hysteresis control to damp the transition rate between spinning and duke@435: // not spinning. duke@435: // duke@435: // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - duke@435: // duke@435: // Spin-then-block strategies ... duke@435: // duke@435: // Thoughts on ways to improve spinning : duke@435: // duke@435: // * Periodically call {psr_}getloadavg() while spinning, and duke@435: // permit unbounded spinning if the load average is < duke@435: // the number of processors. Beware, however, that getloadavg() duke@435: // is exceptionally fast on solaris (about 1/10 the cost of a full duke@435: // spin cycle, but quite expensive on linux. Beware also, that duke@435: // multiple JVMs could "ring" or oscillate in a feedback loop. duke@435: // Sufficient damping would solve that problem. duke@435: // duke@435: // * We currently use spin loops with iteration counters to approximate duke@435: // spinning for some interval. Given the availability of high-precision duke@435: // time sources such as gethrtime(), %TICK, %STICK, RDTSC, etc., we should duke@435: // someday reimplement the spin loops to duration-based instead of iteration-based. duke@435: // duke@435: // * Don't spin if there are more than N = (CPUs/2) threads duke@435: // currently spinning on the monitor (or globally). duke@435: // That is, limit the number of concurrent spinners. duke@435: // We might also limit the # of spinners in the JVM, globally. duke@435: // duke@435: // * If a spinning thread observes _owner change hands it should duke@435: // abort the spin (and park immediately) or at least debit duke@435: // the spin counter by a large "penalty". duke@435: // duke@435: // * Classically, the spin count is either K*(CPUs-1) or is a duke@435: // simple constant that approximates the length of a context switch. duke@435: // We currently use a value -- computed by a special utility -- that duke@435: // approximates round-trip context switch times. duke@435: // duke@435: // * Normally schedctl_start()/_stop() is used to advise the kernel duke@435: // to avoid preempting threads that are running in short, bounded duke@435: // critical sections. We could use the schedctl hooks in an inverted duke@435: // sense -- spinners would set the nopreempt flag, but poll the preempt duke@435: // pending flag. If a spinner observed a pending preemption it'd immediately duke@435: // abort the spin and park. As such, the schedctl service acts as duke@435: // a preemption warning mechanism. duke@435: // duke@435: // * In lieu of spinning, if the system is running below saturation duke@435: // (that is, loadavg() << #cpus), we can instead suppress futile duke@435: // wakeup throttling, or even wake more than one successor at exit-time. duke@435: // The net effect is largely equivalent to spinning. In both cases, duke@435: // contending threads go ONPROC and opportunistically attempt to acquire duke@435: // the lock, decreasing lock handover latency at the expense of wasted duke@435: // cycles and context switching. duke@435: // duke@435: // * We might to spin less after we've parked as the thread will duke@435: // have less $ and TLB affinity with the processor. duke@435: // Likewise, we might spin less if we come ONPROC on a different duke@435: // processor or after a long period (>> rechose_interval). duke@435: // duke@435: // * A table-driven state machine similar to Solaris' dispadmin scheduling duke@435: // tables might be a better design. Instead of encoding information in duke@435: // _SpinDuration, _SpinFreq and _SpinClock we'd just use explicit, duke@435: // discrete states. Success or failure during a spin would drive duke@435: // state transitions, and each state node would contain a spin count. duke@435: // duke@435: // * If the processor is operating in a mode intended to conserve power duke@435: // (such as Intel's SpeedStep) or to reduce thermal output (thermal duke@435: // step-down mode) then the Java synchronization subsystem should duke@435: // forgo spinning. duke@435: // duke@435: // * The minimum spin duration should be approximately the worst-case duke@435: // store propagation latency on the platform. That is, the time duke@435: // it takes a store on CPU A to become visible on CPU B, where A and duke@435: // B are "distant". duke@435: // duke@435: // * We might want to factor a thread's priority in the spin policy. duke@435: // Threads with a higher priority might spin for slightly longer. duke@435: // Similarly, if we use back-off in the TATAS loop, lower priority duke@435: // threads might back-off longer. We don't currently use a duke@435: // thread's priority when placing it on the entry queue. We may duke@435: // want to consider doing so in future releases. duke@435: // duke@435: // * We might transiently drop a thread's scheduling priority while it spins. duke@435: // SCHED_BATCH on linux and FX scheduling class at priority=0 on Solaris duke@435: // would suffice. We could even consider letting the thread spin indefinitely at duke@435: // a depressed or "idle" priority. This brings up fairness issues, however -- duke@435: // in a saturated system a thread would with a reduced priority could languish duke@435: // for extended periods on the ready queue. duke@435: // duke@435: // * While spinning try to use the otherwise wasted time to help the VM make duke@435: // progress: duke@435: // duke@435: // -- YieldTo() the owner, if the owner is OFFPROC but ready duke@435: // Done our remaining quantum directly to the ready thread. duke@435: // This helps "push" the lock owner through the critical section. duke@435: // It also tends to improve affinity/locality as the lock duke@435: // "migrates" less frequently between CPUs. duke@435: // -- Walk our own stack in anticipation of blocking. Memoize the roots. duke@435: // -- Perform strand checking for other thread. Unpark potential strandees. duke@435: // -- Help GC: trace or mark -- this would need to be a bounded unit of work. duke@435: // Unfortunately this will pollute our $ and TLBs. Recall that we duke@435: // spin to avoid context switching -- context switching has an duke@435: // immediate cost in latency, a disruptive cost to other strands on a CMT duke@435: // processor, and an amortized cost because of the D$ and TLB cache duke@435: // reload transient when the thread comes back ONPROC and repopulates duke@435: // $s and TLBs. duke@435: // -- call getloadavg() to see if the system is saturated. It'd probably duke@435: // make sense to call getloadavg() half way through the spin. duke@435: // If the system isn't at full capacity the we'd simply reset duke@435: // the spin counter to and extend the spin attempt. duke@435: // -- Doug points out that we should use the same "helping" policy duke@435: // in thread.yield(). duke@435: // duke@435: // * Try MONITOR-MWAIT on systems that support those instructions. duke@435: // duke@435: // * The spin statistics that drive spin decisions & frequency are duke@435: // maintained in the objectmonitor structure so if we deflate and reinflate duke@435: // we lose spin state. In practice this is not usually a concern duke@435: // as the default spin state after inflation is aggressive (optimistic) duke@435: // and tends toward spinning. So in the worst case for a lock where duke@435: // spinning is not profitable we may spin unnecessarily for a brief duke@435: // period. But then again, if a lock is contended it'll tend not to deflate duke@435: // in the first place. duke@435: duke@435: duke@435: intptr_t ObjectMonitor::SpinCallbackArgument = 0 ; duke@435: int (*ObjectMonitor::SpinCallbackFunction)(intptr_t, int) = NULL ; duke@435: duke@435: // Spinning: Fixed frequency (100%), vary duration duke@435: duke@435: int ObjectMonitor::TrySpin_VaryDuration (Thread * Self) { duke@435: duke@435: // Dumb, brutal spin. Good for comparative measurements against adaptive spinning. duke@435: int ctr = Knob_FixedSpin ; duke@435: if (ctr != 0) { duke@435: while (--ctr >= 0) { duke@435: if (TryLock (Self) > 0) return 1 ; duke@435: SpinPause () ; duke@435: } duke@435: return 0 ; duke@435: } duke@435: duke@435: for (ctr = Knob_PreSpin + 1; --ctr >= 0 ; ) { duke@435: if (TryLock(Self) > 0) { duke@435: // Increase _SpinDuration ... duke@435: // Note that we don't clamp SpinDuration precisely at SpinLimit. duke@435: // Raising _SpurDuration to the poverty line is key. duke@435: int x = _SpinDuration ; duke@435: if (x < Knob_SpinLimit) { duke@435: if (x < Knob_Poverty) x = Knob_Poverty ; duke@435: _SpinDuration = x + Knob_BonusB ; duke@435: } duke@435: return 1 ; duke@435: } duke@435: SpinPause () ; duke@435: } duke@435: duke@435: // Admission control - verify preconditions for spinning duke@435: // duke@435: // We always spin a little bit, just to prevent _SpinDuration == 0 from duke@435: // becoming an absorbing state. Put another way, we spin briefly to duke@435: // sample, just in case the system load, parallelism, contention, or lock duke@435: // modality changed. duke@435: // duke@435: // Consider the following alternative: duke@435: // Periodically set _SpinDuration = _SpinLimit and try a long/full duke@435: // spin attempt. "Periodically" might mean after a tally of duke@435: // the # of failed spin attempts (or iterations) reaches some threshold. duke@435: // This takes us into the realm of 1-out-of-N spinning, where we duke@435: // hold the duration constant but vary the frequency. duke@435: duke@435: ctr = _SpinDuration ; duke@435: if (ctr < Knob_SpinBase) ctr = Knob_SpinBase ; duke@435: if (ctr <= 0) return 0 ; duke@435: duke@435: if (Knob_SuccRestrict && _succ != NULL) return 0 ; duke@435: if (Knob_OState && NotRunnable (Self, (Thread *) _owner)) { duke@435: TEVENT (Spin abort - notrunnable [TOP]); duke@435: return 0 ; duke@435: } duke@435: duke@435: int MaxSpin = Knob_MaxSpinners ; duke@435: if (MaxSpin >= 0) { duke@435: if (_Spinner > MaxSpin) { duke@435: TEVENT (Spin abort -- too many spinners) ; duke@435: return 0 ; duke@435: } duke@435: // Slighty racy, but benign ... duke@435: Adjust (&_Spinner, 1) ; duke@435: } duke@435: duke@435: // We're good to spin ... spin ingress. duke@435: // CONSIDER: use Prefetch::write() to avoid RTS->RTO upgrades duke@435: // when preparing to LD...CAS _owner, etc and the CAS is likely duke@435: // to succeed. duke@435: int hits = 0 ; duke@435: int msk = 0 ; duke@435: int caspty = Knob_CASPenalty ; duke@435: int oxpty = Knob_OXPenalty ; duke@435: int sss = Knob_SpinSetSucc ; duke@435: if (sss && _succ == NULL ) _succ = Self ; duke@435: Thread * prv = NULL ; duke@435: duke@435: // There are three ways to exit the following loop: duke@435: // 1. A successful spin where this thread has acquired the lock. duke@435: // 2. Spin failure with prejudice duke@435: // 3. Spin failure without prejudice duke@435: duke@435: while (--ctr >= 0) { duke@435: duke@435: // Periodic polling -- Check for pending GC duke@435: // Threads may spin while they're unsafe. duke@435: // We don't want spinning threads to delay the JVM from reaching duke@435: // a stop-the-world safepoint or to steal cycles from GC. duke@435: // If we detect a pending safepoint we abort in order that duke@435: // (a) this thread, if unsafe, doesn't delay the safepoint, and (b) duke@435: // this thread, if safe, doesn't steal cycles from GC. duke@435: // This is in keeping with the "no loitering in runtime" rule. duke@435: // We periodically check to see if there's a safepoint pending. duke@435: if ((ctr & 0xFF) == 0) { duke@435: if (SafepointSynchronize::do_call_back()) { duke@435: TEVENT (Spin: safepoint) ; duke@435: goto Abort ; // abrupt spin egress duke@435: } duke@435: if (Knob_UsePause & 1) SpinPause () ; duke@435: duke@435: int (*scb)(intptr_t,int) = SpinCallbackFunction ; duke@435: if (hits > 50 && scb != NULL) { duke@435: int abend = (*scb)(SpinCallbackArgument, 0) ; duke@435: } duke@435: } duke@435: duke@435: if (Knob_UsePause & 2) SpinPause() ; duke@435: duke@435: // Exponential back-off ... Stay off the bus to reduce coherency traffic. duke@435: // This is useful on classic SMP systems, but is of less utility on duke@435: // N1-style CMT platforms. duke@435: // duke@435: // Trade-off: lock acquisition latency vs coherency bandwidth. duke@435: // Lock hold times are typically short. A histogram duke@435: // of successful spin attempts shows that we usually acquire duke@435: // the lock early in the spin. That suggests we want to duke@435: // sample _owner frequently in the early phase of the spin, duke@435: // but then back-off and sample less frequently as the spin duke@435: // progresses. The back-off makes a good citizen on SMP big duke@435: // SMP systems. Oversampling _owner can consume excessive duke@435: // coherency bandwidth. Relatedly, if we _oversample _owner we duke@435: // can inadvertently interfere with the the ST m->owner=null. duke@435: // executed by the lock owner. duke@435: if (ctr & msk) continue ; duke@435: ++hits ; duke@435: if ((hits & 0xF) == 0) { duke@435: // The 0xF, above, corresponds to the exponent. duke@435: // Consider: (msk+1)|msk duke@435: msk = ((msk << 2)|3) & BackOffMask ; duke@435: } duke@435: duke@435: // Probe _owner with TATAS duke@435: // If this thread observes the monitor transition or flicker duke@435: // from locked to unlocked to locked, then the odds that this duke@435: // thread will acquire the lock in this spin attempt go down duke@435: // considerably. The same argument applies if the CAS fails duke@435: // or if we observe _owner change from one non-null value to duke@435: // another non-null value. In such cases we might abort duke@435: // the spin without prejudice or apply a "penalty" to the duke@435: // spin count-down variable "ctr", reducing it by 100, say. duke@435: duke@435: Thread * ox = (Thread *) _owner ; duke@435: if (ox == NULL) { duke@435: ox = (Thread *) Atomic::cmpxchg_ptr (Self, &_owner, NULL) ; duke@435: if (ox == NULL) { duke@435: // The CAS succeeded -- this thread acquired ownership duke@435: // Take care of some bookkeeping to exit spin state. duke@435: if (sss && _succ == Self) { duke@435: _succ = NULL ; duke@435: } duke@435: if (MaxSpin > 0) Adjust (&_Spinner, -1) ; duke@435: duke@435: // Increase _SpinDuration : duke@435: // The spin was successful (profitable) so we tend toward duke@435: // longer spin attempts in the future. duke@435: // CONSIDER: factor "ctr" into the _SpinDuration adjustment. duke@435: // If we acquired the lock early in the spin cycle it duke@435: // makes sense to increase _SpinDuration proportionally. duke@435: // Note that we don't clamp SpinDuration precisely at SpinLimit. duke@435: int x = _SpinDuration ; duke@435: if (x < Knob_SpinLimit) { duke@435: if (x < Knob_Poverty) x = Knob_Poverty ; duke@435: _SpinDuration = x + Knob_Bonus ; duke@435: } duke@435: return 1 ; duke@435: } duke@435: duke@435: // The CAS failed ... we can take any of the following actions: duke@435: // * penalize: ctr -= Knob_CASPenalty duke@435: // * exit spin with prejudice -- goto Abort; duke@435: // * exit spin without prejudice. duke@435: // * Since CAS is high-latency, retry again immediately. duke@435: prv = ox ; duke@435: TEVENT (Spin: cas failed) ; duke@435: if (caspty == -2) break ; duke@435: if (caspty == -1) goto Abort ; duke@435: ctr -= caspty ; duke@435: continue ; duke@435: } duke@435: duke@435: // Did lock ownership change hands ? duke@435: if (ox != prv && prv != NULL ) { duke@435: TEVENT (spin: Owner changed) duke@435: if (oxpty == -2) break ; duke@435: if (oxpty == -1) goto Abort ; duke@435: ctr -= oxpty ; duke@435: } duke@435: prv = ox ; duke@435: duke@435: // Abort the spin if the owner is not executing. duke@435: // The owner must be executing in order to drop the lock. duke@435: // Spinning while the owner is OFFPROC is idiocy. duke@435: // Consider: ctr -= RunnablePenalty ; duke@435: if (Knob_OState && NotRunnable (Self, ox)) { duke@435: TEVENT (Spin abort - notrunnable); duke@435: goto Abort ; duke@435: } duke@435: if (sss && _succ == NULL ) _succ = Self ; duke@435: } duke@435: duke@435: // Spin failed with prejudice -- reduce _SpinDuration. duke@435: // TODO: Use an AIMD-like policy to adjust _SpinDuration. duke@435: // AIMD is globally stable. duke@435: TEVENT (Spin failure) ; duke@435: { duke@435: int x = _SpinDuration ; duke@435: if (x > 0) { duke@435: // Consider an AIMD scheme like: x -= (x >> 3) + 100 duke@435: // This is globally sample and tends to damp the response. duke@435: x -= Knob_Penalty ; duke@435: if (x < 0) x = 0 ; duke@435: _SpinDuration = x ; duke@435: } duke@435: } duke@435: duke@435: Abort: duke@435: if (MaxSpin >= 0) Adjust (&_Spinner, -1) ; duke@435: if (sss && _succ == Self) { duke@435: _succ = NULL ; duke@435: // Invariant: after setting succ=null a contending thread duke@435: // must recheck-retry _owner before parking. This usually happens duke@435: // in the normal usage of TrySpin(), but it's safest duke@435: // to make TrySpin() as foolproof as possible. duke@435: OrderAccess::fence() ; duke@435: if (TryLock(Self) > 0) return 1 ; duke@435: } duke@435: return 0 ; duke@435: } duke@435: duke@435: #define TrySpin TrySpin_VaryDuration duke@435: duke@435: static void DeferredInitialize () { duke@435: if (InitDone > 0) return ; duke@435: if (Atomic::cmpxchg (-1, &InitDone, 0) != 0) { duke@435: while (InitDone != 1) ; duke@435: return ; duke@435: } duke@435: duke@435: // One-shot global initialization ... duke@435: // The initialization is idempotent, so we don't need locks. duke@435: // In the future consider doing this via os::init_2(). duke@435: // SyncKnobs consist of = pairs in the style duke@435: // of environment variables. Start by converting ':' to NUL. duke@435: duke@435: if (SyncKnobs == NULL) SyncKnobs = "" ; duke@435: duke@435: size_t sz = strlen (SyncKnobs) ; duke@435: char * knobs = (char *) malloc (sz + 2) ; duke@435: if (knobs == NULL) { duke@435: vm_exit_out_of_memory (sz + 2, "Parse SyncKnobs") ; duke@435: guarantee (0, "invariant") ; duke@435: } duke@435: strcpy (knobs, SyncKnobs) ; duke@435: knobs[sz+1] = 0 ; duke@435: for (char * p = knobs ; *p ; p++) { duke@435: if (*p == ':') *p = 0 ; duke@435: } duke@435: duke@435: #define SETKNOB(x) { Knob_##x = kvGetInt (knobs, #x, Knob_##x); } duke@435: SETKNOB(ReportSettings) ; duke@435: SETKNOB(Verbose) ; duke@435: SETKNOB(FixedSpin) ; duke@435: SETKNOB(SpinLimit) ; duke@435: SETKNOB(SpinBase) ; duke@435: SETKNOB(SpinBackOff); duke@435: SETKNOB(CASPenalty) ; duke@435: SETKNOB(OXPenalty) ; duke@435: SETKNOB(LogSpins) ; duke@435: SETKNOB(SpinSetSucc) ; duke@435: SETKNOB(SuccEnabled) ; duke@435: SETKNOB(SuccRestrict) ; duke@435: SETKNOB(Penalty) ; duke@435: SETKNOB(Bonus) ; duke@435: SETKNOB(BonusB) ; duke@435: SETKNOB(Poverty) ; duke@435: SETKNOB(SpinAfterFutile) ; duke@435: SETKNOB(UsePause) ; duke@435: SETKNOB(SpinEarly) ; duke@435: SETKNOB(OState) ; duke@435: SETKNOB(MaxSpinners) ; duke@435: SETKNOB(PreSpin) ; duke@435: SETKNOB(ExitPolicy) ; duke@435: SETKNOB(QMode); duke@435: SETKNOB(ResetEvent) ; duke@435: SETKNOB(MoveNotifyee) ; duke@435: SETKNOB(FastHSSEC) ; duke@435: #undef SETKNOB duke@435: duke@435: if (os::is_MP()) { duke@435: BackOffMask = (1 << Knob_SpinBackOff) - 1 ; duke@435: if (Knob_ReportSettings) ::printf ("BackOffMask=%X\n", BackOffMask) ; duke@435: // CONSIDER: BackOffMask = ROUNDUP_NEXT_POWER2 (ncpus-1) duke@435: } else { duke@435: Knob_SpinLimit = 0 ; duke@435: Knob_SpinBase = 0 ; duke@435: Knob_PreSpin = 0 ; duke@435: Knob_FixedSpin = -1 ; duke@435: } duke@435: duke@435: if (Knob_LogSpins == 0) { duke@435: ObjectSynchronizer::_sync_FailedSpins = NULL ; duke@435: } duke@435: duke@435: free (knobs) ; duke@435: OrderAccess::fence() ; duke@435: InitDone = 1 ; duke@435: } duke@435: duke@435: // Theory of operations -- Monitors lists, thread residency, etc: duke@435: // duke@435: // * A thread acquires ownership of a monitor by successfully duke@435: // CAS()ing the _owner field from null to non-null. duke@435: // duke@435: // * Invariant: A thread appears on at most one monitor list -- duke@435: // cxq, EntryList or WaitSet -- at any one time. duke@435: // duke@435: // * Contending threads "push" themselves onto the cxq with CAS duke@435: // and then spin/park. duke@435: // duke@435: // * After a contending thread eventually acquires the lock it must duke@435: // dequeue itself from either the EntryList or the cxq. duke@435: // duke@435: // * The exiting thread identifies and unparks an "heir presumptive" duke@435: // tentative successor thread on the EntryList. Critically, the duke@435: // exiting thread doesn't unlink the successor thread from the EntryList. duke@435: // After having been unparked, the wakee will recontend for ownership of duke@435: // the monitor. The successor (wakee) will either acquire the lock or duke@435: // re-park itself. duke@435: // duke@435: // Succession is provided for by a policy of competitive handoff. duke@435: // The exiting thread does _not_ grant or pass ownership to the duke@435: // successor thread. (This is also referred to as "handoff" succession"). duke@435: // Instead the exiting thread releases ownership and possibly wakes duke@435: // a successor, so the successor can (re)compete for ownership of the lock. duke@435: // If the EntryList is empty but the cxq is populated the exiting duke@435: // thread will drain the cxq into the EntryList. It does so by duke@435: // by detaching the cxq (installing null with CAS) and folding duke@435: // the threads from the cxq into the EntryList. The EntryList is duke@435: // doubly linked, while the cxq is singly linked because of the duke@435: // CAS-based "push" used to enqueue recently arrived threads (RATs). duke@435: // duke@435: // * Concurrency invariants: duke@435: // duke@435: // -- only the monitor owner may access or mutate the EntryList. duke@435: // The mutex property of the monitor itself protects the EntryList duke@435: // from concurrent interference. duke@435: // -- Only the monitor owner may detach the cxq. duke@435: // duke@435: // * The monitor entry list operations avoid locks, but strictly speaking duke@435: // they're not lock-free. Enter is lock-free, exit is not. duke@435: // See http://j2se.east/~dice/PERSIST/040825-LockFreeQueues.html duke@435: // duke@435: // * The cxq can have multiple concurrent "pushers" but only one concurrent duke@435: // detaching thread. This mechanism is immune from the ABA corruption. duke@435: // More precisely, the CAS-based "push" onto cxq is ABA-oblivious. duke@435: // duke@435: // * Taken together, the cxq and the EntryList constitute or form a duke@435: // single logical queue of threads stalled trying to acquire the lock. duke@435: // We use two distinct lists to improve the odds of a constant-time duke@435: // dequeue operation after acquisition (in the ::enter() epilog) and duke@435: // to reduce heat on the list ends. (c.f. Michael Scott's "2Q" algorithm). duke@435: // A key desideratum is to minimize queue & monitor metadata manipulation duke@435: // that occurs while holding the monitor lock -- that is, we want to duke@435: // minimize monitor lock holds times. Note that even a small amount of duke@435: // fixed spinning will greatly reduce the # of enqueue-dequeue operations duke@435: // on EntryList|cxq. That is, spinning relieves contention on the "inner" duke@435: // locks and monitor metadata. duke@435: // duke@435: // Cxq points to the the set of Recently Arrived Threads attempting entry. duke@435: // Because we push threads onto _cxq with CAS, the RATs must take the form of duke@435: // a singly-linked LIFO. We drain _cxq into EntryList at unlock-time when duke@435: // the unlocking thread notices that EntryList is null but _cxq is != null. duke@435: // duke@435: // The EntryList is ordered by the prevailing queue discipline and duke@435: // can be organized in any convenient fashion, such as a doubly-linked list or duke@435: // a circular doubly-linked list. Critically, we want insert and delete operations duke@435: // to operate in constant-time. If we need a priority queue then something akin duke@435: // to Solaris' sleepq would work nicely. Viz., duke@435: // http://agg.eng/ws/on10_nightly/source/usr/src/uts/common/os/sleepq.c. duke@435: // Queue discipline is enforced at ::exit() time, when the unlocking thread duke@435: // drains the cxq into the EntryList, and orders or reorders the threads on the duke@435: // EntryList accordingly. duke@435: // duke@435: // Barring "lock barging", this mechanism provides fair cyclic ordering, duke@435: // somewhat similar to an elevator-scan. duke@435: // duke@435: // * The monitor synchronization subsystem avoids the use of native duke@435: // synchronization primitives except for the narrow platform-specific duke@435: // park-unpark abstraction. See the comments in os_solaris.cpp regarding duke@435: // the semantics of park-unpark. Put another way, this monitor implementation duke@435: // depends only on atomic operations and park-unpark. The monitor subsystem duke@435: // manages all RUNNING->BLOCKED and BLOCKED->READY transitions while the duke@435: // underlying OS manages the READY<->RUN transitions. duke@435: // duke@435: // * Waiting threads reside on the WaitSet list -- wait() puts duke@435: // the caller onto the WaitSet. duke@435: // duke@435: // * notify() or notifyAll() simply transfers threads from the WaitSet to duke@435: // either the EntryList or cxq. Subsequent exit() operations will duke@435: // unpark the notifyee. Unparking a notifee in notify() is inefficient - duke@435: // it's likely the notifyee would simply impale itself on the lock held duke@435: // by the notifier. duke@435: // duke@435: // * An interesting alternative is to encode cxq as (List,LockByte) where duke@435: // the LockByte is 0 iff the monitor is owned. _owner is simply an auxiliary duke@435: // variable, like _recursions, in the scheme. The threads or Events that form duke@435: // the list would have to be aligned in 256-byte addresses. A thread would duke@435: // try to acquire the lock or enqueue itself with CAS, but exiting threads duke@435: // could use a 1-0 protocol and simply STB to set the LockByte to 0. duke@435: // Note that is is *not* word-tearing, but it does presume that full-word duke@435: // CAS operations are coherent with intermix with STB operations. That's true duke@435: // on most common processors. duke@435: // duke@435: // * See also http://blogs.sun.com/dave duke@435: duke@435: duke@435: void ATTR ObjectMonitor::EnterI (TRAPS) { duke@435: Thread * Self = THREAD ; duke@435: assert (Self->is_Java_thread(), "invariant") ; duke@435: assert (((JavaThread *) Self)->thread_state() == _thread_blocked , "invariant") ; duke@435: duke@435: // Try the lock - TATAS duke@435: if (TryLock (Self) > 0) { duke@435: assert (_succ != Self , "invariant") ; duke@435: assert (_owner == Self , "invariant") ; duke@435: assert (_Responsible != Self , "invariant") ; duke@435: return ; duke@435: } duke@435: duke@435: DeferredInitialize () ; duke@435: duke@435: // We try one round of spinning *before* enqueueing Self. duke@435: // duke@435: // If the _owner is ready but OFFPROC we could use a YieldTo() duke@435: // operation to donate the remainder of this thread's quantum duke@435: // to the owner. This has subtle but beneficial affinity duke@435: // effects. duke@435: duke@435: if (TrySpin (Self) > 0) { duke@435: assert (_owner == Self , "invariant") ; duke@435: assert (_succ != Self , "invariant") ; duke@435: assert (_Responsible != Self , "invariant") ; duke@435: return ; duke@435: } duke@435: duke@435: // The Spin failed -- Enqueue and park the thread ... duke@435: assert (_succ != Self , "invariant") ; duke@435: assert (_owner != Self , "invariant") ; duke@435: assert (_Responsible != Self , "invariant") ; duke@435: duke@435: // Enqueue "Self" on ObjectMonitor's _cxq. duke@435: // duke@435: // Node acts as a proxy for Self. duke@435: // As an aside, if were to ever rewrite the synchronization code mostly duke@435: // in Java, WaitNodes, ObjectMonitors, and Events would become 1st-class duke@435: // Java objects. This would avoid awkward lifecycle and liveness issues, duke@435: // as well as eliminate a subset of ABA issues. duke@435: // TODO: eliminate ObjectWaiter and enqueue either Threads or Events. duke@435: // duke@435: duke@435: ObjectWaiter node(Self) ; duke@435: Self->_ParkEvent->reset() ; duke@435: node._prev = (ObjectWaiter *) 0xBAD ; duke@435: node.TState = ObjectWaiter::TS_CXQ ; duke@435: duke@435: // Push "Self" onto the front of the _cxq. duke@435: // Once on cxq/EntryList, Self stays on-queue until it acquires the lock. duke@435: // Note that spinning tends to reduce the rate at which threads duke@435: // enqueue and dequeue on EntryList|cxq. duke@435: ObjectWaiter * nxt ; duke@435: for (;;) { duke@435: node._next = nxt = _cxq ; duke@435: if (Atomic::cmpxchg_ptr (&node, &_cxq, nxt) == nxt) break ; duke@435: duke@435: // Interference - the CAS failed because _cxq changed. Just retry. duke@435: // As an optional optimization we retry the lock. duke@435: if (TryLock (Self) > 0) { duke@435: assert (_succ != Self , "invariant") ; duke@435: assert (_owner == Self , "invariant") ; duke@435: assert (_Responsible != Self , "invariant") ; duke@435: return ; duke@435: } duke@435: } duke@435: duke@435: // Check for cxq|EntryList edge transition to non-null. This indicates duke@435: // the onset of contention. While contention persists exiting threads duke@435: // will use a ST:MEMBAR:LD 1-1 exit protocol. When contention abates exit duke@435: // operations revert to the faster 1-0 mode. This enter operation may interleave duke@435: // (race) a concurrent 1-0 exit operation, resulting in stranding, so we duke@435: // arrange for one of the contending thread to use a timed park() operations duke@435: // to detect and recover from the race. (Stranding is form of progress failure duke@435: // where the monitor is unlocked but all the contending threads remain parked). duke@435: // That is, at least one of the contended threads will periodically poll _owner. duke@435: // One of the contending threads will become the designated "Responsible" thread. duke@435: // The Responsible thread uses a timed park instead of a normal indefinite park duke@435: // operation -- it periodically wakes and checks for and recovers from potential duke@435: // strandings admitted by 1-0 exit operations. We need at most one Responsible duke@435: // thread per-monitor at any given moment. Only threads on cxq|EntryList may duke@435: // be responsible for a monitor. duke@435: // duke@435: // Currently, one of the contended threads takes on the added role of "Responsible". duke@435: // A viable alternative would be to use a dedicated "stranding checker" thread duke@435: // that periodically iterated over all the threads (or active monitors) and unparked duke@435: // successors where there was risk of stranding. This would help eliminate the duke@435: // timer scalability issues we see on some platforms as we'd only have one thread duke@435: // -- the checker -- parked on a timer. duke@435: duke@435: if ((SyncFlags & 16) == 0 && nxt == NULL && _EntryList == NULL) { duke@435: // Try to assume the role of responsible thread for the monitor. duke@435: // CONSIDER: ST vs CAS vs { if (Responsible==null) Responsible=Self } duke@435: Atomic::cmpxchg_ptr (Self, &_Responsible, NULL) ; duke@435: } duke@435: duke@435: // The lock have been released while this thread was occupied queueing duke@435: // itself onto _cxq. To close the race and avoid "stranding" and duke@435: // progress-liveness failure we must resample-retry _owner before parking. duke@435: // Note the Dekker/Lamport duality: ST cxq; MEMBAR; LD Owner. duke@435: // In this case the ST-MEMBAR is accomplished with CAS(). duke@435: // duke@435: // TODO: Defer all thread state transitions until park-time. duke@435: // Since state transitions are heavy and inefficient we'd like duke@435: // to defer the state transitions until absolutely necessary, duke@435: // and in doing so avoid some transitions ... duke@435: duke@435: TEVENT (Inflated enter - Contention) ; duke@435: int nWakeups = 0 ; duke@435: int RecheckInterval = 1 ; duke@435: duke@435: for (;;) { duke@435: duke@435: if (TryLock (Self) > 0) break ; duke@435: assert (_owner != Self, "invariant") ; duke@435: duke@435: if ((SyncFlags & 2) && _Responsible == NULL) { duke@435: Atomic::cmpxchg_ptr (Self, &_Responsible, NULL) ; duke@435: } duke@435: duke@435: // park self duke@435: if (_Responsible == Self || (SyncFlags & 1)) { duke@435: TEVENT (Inflated enter - park TIMED) ; duke@435: Self->_ParkEvent->park ((jlong) RecheckInterval) ; duke@435: // Increase the RecheckInterval, but clamp the value. duke@435: RecheckInterval *= 8 ; duke@435: if (RecheckInterval > 1000) RecheckInterval = 1000 ; duke@435: } else { duke@435: TEVENT (Inflated enter - park UNTIMED) ; duke@435: Self->_ParkEvent->park() ; duke@435: } duke@435: duke@435: if (TryLock(Self) > 0) break ; duke@435: duke@435: // The lock is still contested. duke@435: // Keep a tally of the # of futile wakeups. duke@435: // Note that the counter is not protected by a lock or updated by atomics. duke@435: // That is by design - we trade "lossy" counters which are exposed to duke@435: // races during updates for a lower probe effect. duke@435: TEVENT (Inflated enter - Futile wakeup) ; duke@435: if (ObjectSynchronizer::_sync_FutileWakeups != NULL) { duke@435: ObjectSynchronizer::_sync_FutileWakeups->inc() ; duke@435: } duke@435: ++ nWakeups ; duke@435: duke@435: // Assuming this is not a spurious wakeup we'll normally find _succ == Self. duke@435: // We can defer clearing _succ until after the spin completes duke@435: // TrySpin() must tolerate being called with _succ == Self. duke@435: // Try yet another round of adaptive spinning. duke@435: if ((Knob_SpinAfterFutile & 1) && TrySpin (Self) > 0) break ; duke@435: duke@435: // We can find that we were unpark()ed and redesignated _succ while duke@435: // we were spinning. That's harmless. If we iterate and call park(), duke@435: // park() will consume the event and return immediately and we'll duke@435: // just spin again. This pattern can repeat, leaving _succ to simply duke@435: // spin on a CPU. Enable Knob_ResetEvent to clear pending unparks(). duke@435: // Alternately, we can sample fired() here, and if set, forgo spinning duke@435: // in the next iteration. duke@435: duke@435: if ((Knob_ResetEvent & 1) && Self->_ParkEvent->fired()) { duke@435: Self->_ParkEvent->reset() ; duke@435: OrderAccess::fence() ; duke@435: } duke@435: if (_succ == Self) _succ = NULL ; duke@435: duke@435: // Invariant: after clearing _succ a thread *must* retry _owner before parking. duke@435: OrderAccess::fence() ; duke@435: } duke@435: duke@435: // Egress : duke@435: // Self has acquired the lock -- Unlink Self from the cxq or EntryList. duke@435: // Normally we'll find Self on the EntryList . duke@435: // From the perspective of the lock owner (this thread), the duke@435: // EntryList is stable and cxq is prepend-only. duke@435: // The head of cxq is volatile but the interior is stable. duke@435: // In addition, Self.TState is stable. duke@435: duke@435: assert (_owner == Self , "invariant") ; duke@435: assert (object() != NULL , "invariant") ; duke@435: // I'd like to write: duke@435: // guarantee (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; duke@435: // but as we're at a safepoint that's not safe. duke@435: duke@435: UnlinkAfterAcquire (Self, &node) ; duke@435: if (_succ == Self) _succ = NULL ; duke@435: duke@435: assert (_succ != Self, "invariant") ; duke@435: if (_Responsible == Self) { duke@435: _Responsible = NULL ; duke@435: // Dekker pivot-point. duke@435: // Consider OrderAccess::storeload() here duke@435: duke@435: // We may leave threads on cxq|EntryList without a designated duke@435: // "Responsible" thread. This is benign. When this thread subsequently duke@435: // exits the monitor it can "see" such preexisting "old" threads -- duke@435: // threads that arrived on the cxq|EntryList before the fence, above -- duke@435: // by LDing cxq|EntryList. Newly arrived threads -- that is, threads duke@435: // that arrive on cxq after the ST:MEMBAR, above -- will set Responsible duke@435: // non-null and elect a new "Responsible" timer thread. duke@435: // duke@435: // This thread executes: duke@435: // ST Responsible=null; MEMBAR (in enter epilog - here) duke@435: // LD cxq|EntryList (in subsequent exit) duke@435: // duke@435: // Entering threads in the slow/contended path execute: duke@435: // ST cxq=nonnull; MEMBAR; LD Responsible (in enter prolog) duke@435: // The (ST cxq; MEMBAR) is accomplished with CAS(). duke@435: // duke@435: // The MEMBAR, above, prevents the LD of cxq|EntryList in the subsequent duke@435: // exit operation from floating above the ST Responsible=null. duke@435: // duke@435: // In *practice* however, EnterI() is always followed by some atomic duke@435: // operation such as the decrement of _count in ::enter(). Those atomics duke@435: // obviate the need for the explicit MEMBAR, above. duke@435: } duke@435: duke@435: // We've acquired ownership with CAS(). duke@435: // CAS is serializing -- it has MEMBAR/FENCE-equivalent semantics. duke@435: // But since the CAS() this thread may have also stored into _succ, duke@435: // EntryList, cxq or Responsible. These meta-data updates must be duke@435: // visible __before this thread subsequently drops the lock. duke@435: // Consider what could occur if we didn't enforce this constraint -- duke@435: // STs to monitor meta-data and user-data could reorder with (become duke@435: // visible after) the ST in exit that drops ownership of the lock. duke@435: // Some other thread could then acquire the lock, but observe inconsistent duke@435: // or old monitor meta-data and heap data. That violates the JMM. duke@435: // To that end, the 1-0 exit() operation must have at least STST|LDST duke@435: // "release" barrier semantics. Specifically, there must be at least a duke@435: // STST|LDST barrier in exit() before the ST of null into _owner that drops duke@435: // the lock. The barrier ensures that changes to monitor meta-data and data duke@435: // protected by the lock will be visible before we release the lock, and duke@435: // therefore before some other thread (CPU) has a chance to acquire the lock. duke@435: // See also: http://gee.cs.oswego.edu/dl/jmm/cookbook.html. duke@435: // duke@435: // Critically, any prior STs to _succ or EntryList must be visible before duke@435: // the ST of null into _owner in the *subsequent* (following) corresponding duke@435: // monitorexit. Recall too, that in 1-0 mode monitorexit does not necessarily duke@435: // execute a serializing instruction. duke@435: duke@435: if (SyncFlags & 8) { duke@435: OrderAccess::fence() ; duke@435: } duke@435: return ; duke@435: } duke@435: duke@435: // ExitSuspendEquivalent: duke@435: // A faster alternate to handle_special_suspend_equivalent_condition() duke@435: // duke@435: // handle_special_suspend_equivalent_condition() unconditionally duke@435: // acquires the SR_lock. On some platforms uncontended MutexLocker() duke@435: // operations have high latency. Note that in ::enter() we call HSSEC duke@435: // while holding the monitor, so we effectively lengthen the critical sections. duke@435: // duke@435: // There are a number of possible solutions: duke@435: // duke@435: // A. To ameliorate the problem we might also defer state transitions duke@435: // to as late as possible -- just prior to parking. duke@435: // Given that, we'd call HSSEC after having returned from park(), duke@435: // but before attempting to acquire the monitor. This is only a duke@435: // partial solution. It avoids calling HSSEC while holding the duke@435: // monitor (good), but it still increases successor reacquisition latency -- duke@435: // the interval between unparking a successor and the time the successor duke@435: // resumes and retries the lock. See ReenterI(), which defers state transitions. duke@435: // If we use this technique we can also avoid EnterI()-exit() loop duke@435: // in ::enter() where we iteratively drop the lock and then attempt duke@435: // to reacquire it after suspending. duke@435: // duke@435: // B. In the future we might fold all the suspend bits into a duke@435: // composite per-thread suspend flag and then update it with CAS(). duke@435: // Alternately, a Dekker-like mechanism with multiple variables duke@435: // would suffice: duke@435: // ST Self->_suspend_equivalent = false duke@435: // MEMBAR duke@435: // LD Self_>_suspend_flags duke@435: // duke@435: duke@435: duke@435: bool ObjectMonitor::ExitSuspendEquivalent (JavaThread * jSelf) { duke@435: int Mode = Knob_FastHSSEC ; duke@435: if (Mode && !jSelf->is_external_suspend()) { duke@435: assert (jSelf->is_suspend_equivalent(), "invariant") ; duke@435: jSelf->clear_suspend_equivalent() ; duke@435: if (2 == Mode) OrderAccess::storeload() ; duke@435: if (!jSelf->is_external_suspend()) return false ; duke@435: // We raced a suspension -- fall thru into the slow path duke@435: TEVENT (ExitSuspendEquivalent - raced) ; duke@435: jSelf->set_suspend_equivalent() ; duke@435: } duke@435: return jSelf->handle_special_suspend_equivalent_condition() ; duke@435: } duke@435: duke@435: duke@435: // ReenterI() is a specialized inline form of the latter half of the duke@435: // contended slow-path from EnterI(). We use ReenterI() only for duke@435: // monitor reentry in wait(). duke@435: // duke@435: // In the future we should reconcile EnterI() and ReenterI(), adding duke@435: // Knob_Reset and Knob_SpinAfterFutile support and restructuring the duke@435: // loop accordingly. duke@435: duke@435: void ATTR ObjectMonitor::ReenterI (Thread * Self, ObjectWaiter * SelfNode) { duke@435: assert (Self != NULL , "invariant") ; duke@435: assert (SelfNode != NULL , "invariant") ; duke@435: assert (SelfNode->_thread == Self , "invariant") ; duke@435: assert (_waiters > 0 , "invariant") ; duke@435: assert (((oop)(object()))->mark() == markOopDesc::encode(this) , "invariant") ; duke@435: assert (((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant") ; duke@435: JavaThread * jt = (JavaThread *) Self ; duke@435: duke@435: int nWakeups = 0 ; duke@435: for (;;) { duke@435: ObjectWaiter::TStates v = SelfNode->TState ; duke@435: guarantee (v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant") ; duke@435: assert (_owner != Self, "invariant") ; duke@435: duke@435: if (TryLock (Self) > 0) break ; duke@435: if (TrySpin (Self) > 0) break ; duke@435: duke@435: TEVENT (Wait Reentry - parking) ; duke@435: duke@435: // State transition wrappers around park() ... duke@435: // ReenterI() wisely defers state transitions until duke@435: // it's clear we must park the thread. duke@435: { duke@435: OSThreadContendState osts(Self->osthread()); duke@435: ThreadBlockInVM tbivm(jt); duke@435: duke@435: // cleared by handle_special_suspend_equivalent_condition() duke@435: // or java_suspend_self() duke@435: jt->set_suspend_equivalent(); duke@435: if (SyncFlags & 1) { duke@435: Self->_ParkEvent->park ((jlong)1000) ; duke@435: } else { duke@435: Self->_ParkEvent->park () ; duke@435: } duke@435: duke@435: // were we externally suspended while we were waiting? duke@435: for (;;) { duke@435: if (!ExitSuspendEquivalent (jt)) break ; duke@435: if (_succ == Self) { _succ = NULL; OrderAccess::fence(); } duke@435: jt->java_suspend_self(); duke@435: jt->set_suspend_equivalent(); duke@435: } duke@435: } duke@435: duke@435: // Try again, but just so we distinguish between futile wakeups and duke@435: // successful wakeups. The following test isn't algorithmically duke@435: // necessary, but it helps us maintain sensible statistics. duke@435: if (TryLock(Self) > 0) break ; duke@435: duke@435: // The lock is still contested. duke@435: // Keep a tally of the # of futile wakeups. duke@435: // Note that the counter is not protected by a lock or updated by atomics. duke@435: // That is by design - we trade "lossy" counters which are exposed to duke@435: // races during updates for a lower probe effect. duke@435: TEVENT (Wait Reentry - futile wakeup) ; duke@435: ++ nWakeups ; duke@435: duke@435: // Assuming this is not a spurious wakeup we'll normally duke@435: // find that _succ == Self. duke@435: if (_succ == Self) _succ = NULL ; duke@435: duke@435: // Invariant: after clearing _succ a contending thread duke@435: // *must* retry _owner before parking. duke@435: OrderAccess::fence() ; duke@435: duke@435: if (ObjectSynchronizer::_sync_FutileWakeups != NULL) { duke@435: ObjectSynchronizer::_sync_FutileWakeups->inc() ; duke@435: } duke@435: } duke@435: duke@435: // Self has acquired the lock -- Unlink Self from the cxq or EntryList . duke@435: // Normally we'll find Self on the EntryList. duke@435: // Unlinking from the EntryList is constant-time and atomic-free. duke@435: // From the perspective of the lock owner (this thread), the duke@435: // EntryList is stable and cxq is prepend-only. duke@435: // The head of cxq is volatile but the interior is stable. duke@435: // In addition, Self.TState is stable. duke@435: duke@435: assert (_owner == Self, "invariant") ; duke@435: assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; duke@435: UnlinkAfterAcquire (Self, SelfNode) ; duke@435: if (_succ == Self) _succ = NULL ; duke@435: assert (_succ != Self, "invariant") ; duke@435: SelfNode->TState = ObjectWaiter::TS_RUN ; duke@435: OrderAccess::fence() ; // see comments at the end of EnterI() duke@435: } duke@435: duke@435: bool ObjectMonitor::try_enter(Thread* THREAD) { duke@435: if (THREAD != _owner) { duke@435: if (THREAD->is_lock_owned ((address)_owner)) { duke@435: assert(_recursions == 0, "internal state error"); duke@435: _owner = THREAD ; duke@435: _recursions = 1 ; duke@435: OwnerIsThread = 1 ; duke@435: return true; duke@435: } duke@435: if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) { duke@435: return false; duke@435: } duke@435: return true; duke@435: } else { duke@435: _recursions++; duke@435: return true; duke@435: } duke@435: } duke@435: duke@435: void ATTR ObjectMonitor::enter(TRAPS) { duke@435: // The following code is ordered to check the most common cases first duke@435: // and to reduce RTS->RTO cache line upgrades on SPARC and IA32 processors. duke@435: Thread * const Self = THREAD ; duke@435: void * cur ; duke@435: duke@435: cur = Atomic::cmpxchg_ptr (Self, &_owner, NULL) ; duke@435: if (cur == NULL) { duke@435: // Either ASSERT _recursions == 0 or explicitly set _recursions = 0. duke@435: assert (_recursions == 0 , "invariant") ; duke@435: assert (_owner == Self, "invariant") ; duke@435: // CONSIDER: set or assert OwnerIsThread == 1 duke@435: return ; duke@435: } duke@435: duke@435: if (cur == Self) { duke@435: // TODO-FIXME: check for integer overflow! BUGID 6557169. duke@435: _recursions ++ ; duke@435: return ; duke@435: } duke@435: duke@435: if (Self->is_lock_owned ((address)cur)) { duke@435: assert (_recursions == 0, "internal state error"); duke@435: _recursions = 1 ; duke@435: // Commute owner from a thread-specific on-stack BasicLockObject address to duke@435: // a full-fledged "Thread *". duke@435: _owner = Self ; duke@435: OwnerIsThread = 1 ; duke@435: return ; duke@435: } duke@435: duke@435: // We've encountered genuine contention. duke@435: assert (Self->_Stalled == 0, "invariant") ; duke@435: Self->_Stalled = intptr_t(this) ; duke@435: duke@435: // Try one round of spinning *before* enqueueing Self duke@435: // and before going through the awkward and expensive state duke@435: // transitions. The following spin is strictly optional ... duke@435: // Note that if we acquire the monitor from an initial spin duke@435: // we forgo posting JVMTI events and firing DTRACE probes. duke@435: if (Knob_SpinEarly && TrySpin (Self) > 0) { duke@435: assert (_owner == Self , "invariant") ; duke@435: assert (_recursions == 0 , "invariant") ; duke@435: assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; duke@435: Self->_Stalled = 0 ; duke@435: return ; duke@435: } duke@435: duke@435: assert (_owner != Self , "invariant") ; duke@435: assert (_succ != Self , "invariant") ; duke@435: assert (Self->is_Java_thread() , "invariant") ; duke@435: JavaThread * jt = (JavaThread *) Self ; duke@435: assert (!SafepointSynchronize::is_at_safepoint(), "invariant") ; duke@435: assert (jt->thread_state() != _thread_blocked , "invariant") ; duke@435: assert (this->object() != NULL , "invariant") ; duke@435: assert (_count >= 0, "invariant") ; duke@435: duke@435: // Prevent deflation at STW-time. See deflate_idle_monitors() and is_busy(). duke@435: // Ensure the object-monitor relationship remains stable while there's contention. duke@435: Atomic::inc_ptr(&_count); duke@435: duke@435: { // Change java thread status to indicate blocked on monitor enter. duke@435: JavaThreadBlockedOnMonitorEnterState jtbmes(jt, this); duke@435: duke@435: DTRACE_MONITOR_PROBE(contended__enter, this, object(), jt); duke@435: if (JvmtiExport::should_post_monitor_contended_enter()) { duke@435: JvmtiExport::post_monitor_contended_enter(jt, this); duke@435: } duke@435: duke@435: OSThreadContendState osts(Self->osthread()); duke@435: ThreadBlockInVM tbivm(jt); duke@435: duke@435: Self->set_current_pending_monitor(this); duke@435: duke@435: // TODO-FIXME: change the following for(;;) loop to straight-line code. duke@435: for (;;) { duke@435: jt->set_suspend_equivalent(); duke@435: // cleared by handle_special_suspend_equivalent_condition() duke@435: // or java_suspend_self() duke@435: duke@435: EnterI (THREAD) ; duke@435: duke@435: if (!ExitSuspendEquivalent(jt)) break ; duke@435: duke@435: // duke@435: // We have acquired the contended monitor, but while we were duke@435: // waiting another thread suspended us. We don't want to enter duke@435: // the monitor while suspended because that would surprise the duke@435: // thread that suspended us. duke@435: // duke@435: _recursions = 0 ; duke@435: _succ = NULL ; duke@435: exit (Self) ; duke@435: duke@435: jt->java_suspend_self(); duke@435: } duke@435: Self->set_current_pending_monitor(NULL); duke@435: } duke@435: duke@435: Atomic::dec_ptr(&_count); duke@435: assert (_count >= 0, "invariant") ; duke@435: Self->_Stalled = 0 ; duke@435: duke@435: // Must either set _recursions = 0 or ASSERT _recursions == 0. duke@435: assert (_recursions == 0 , "invariant") ; duke@435: assert (_owner == Self , "invariant") ; duke@435: assert (_succ != Self , "invariant") ; duke@435: assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; duke@435: duke@435: // The thread -- now the owner -- is back in vm mode. duke@435: // Report the glorious news via TI,DTrace and jvmstat. duke@435: // The probe effect is non-trivial. All the reportage occurs duke@435: // while we hold the monitor, increasing the length of the critical duke@435: // section. Amdahl's parallel speedup law comes vividly into play. duke@435: // duke@435: // Another option might be to aggregate the events (thread local or duke@435: // per-monitor aggregation) and defer reporting until a more opportune duke@435: // time -- such as next time some thread encounters contention but has duke@435: // yet to acquire the lock. While spinning that thread could duke@435: // spinning we could increment JVMStat counters, etc. duke@435: duke@435: DTRACE_MONITOR_PROBE(contended__entered, this, object(), jt); duke@435: if (JvmtiExport::should_post_monitor_contended_entered()) { duke@435: JvmtiExport::post_monitor_contended_entered(jt, this); duke@435: } duke@435: if (ObjectSynchronizer::_sync_ContendedLockAttempts != NULL) { duke@435: ObjectSynchronizer::_sync_ContendedLockAttempts->inc() ; duke@435: } duke@435: } duke@435: duke@435: void ObjectMonitor::ExitEpilog (Thread * Self, ObjectWaiter * Wakee) { duke@435: assert (_owner == Self, "invariant") ; duke@435: duke@435: // Exit protocol: duke@435: // 1. ST _succ = wakee duke@435: // 2. membar #loadstore|#storestore; duke@435: // 2. ST _owner = NULL duke@435: // 3. unpark(wakee) duke@435: duke@435: _succ = Knob_SuccEnabled ? Wakee->_thread : NULL ; duke@435: ParkEvent * Trigger = Wakee->_event ; duke@435: duke@435: // Hygiene -- once we've set _owner = NULL we can't safely dereference Wakee again. duke@435: // The thread associated with Wakee may have grabbed the lock and "Wakee" may be duke@435: // out-of-scope (non-extant). duke@435: Wakee = NULL ; duke@435: duke@435: // Drop the lock duke@435: OrderAccess::release_store_ptr (&_owner, NULL) ; duke@435: OrderAccess::fence() ; // ST _owner vs LD in unpark() duke@435: duke@435: // TODO-FIXME: duke@435: // If there's a safepoint pending the best policy would be to duke@435: // get _this thread to a safepoint and only wake the successor duke@435: // after the safepoint completed. monitorexit uses a "leaf" duke@435: // state transition, however, so this thread can't become duke@435: // safe at this point in time. (Its stack isn't walkable). duke@435: // The next best thing is to defer waking the successor by duke@435: // adding to a list of thread to be unparked after at the duke@435: // end of the forthcoming STW). duke@435: if (SafepointSynchronize::do_call_back()) { duke@435: TEVENT (unpark before SAFEPOINT) ; duke@435: } duke@435: duke@435: // Possible optimizations ... duke@435: // duke@435: // * Consider: set Wakee->UnparkTime = timeNow() duke@435: // When the thread wakes up it'll compute (timeNow() - Self->UnparkTime()). duke@435: // By measuring recent ONPROC latency we can approximate the duke@435: // system load. In turn, we can feed that information back duke@435: // into the spinning & succession policies. duke@435: // (ONPROC latency correlates strongly with load). duke@435: // duke@435: // * Pull affinity: duke@435: // If the wakee is cold then transiently setting it's affinity duke@435: // to the current CPU is a good idea. duke@435: // See http://j2se.east/~dice/PERSIST/050624-PullAffinity.txt blacklion@913: DTRACE_MONITOR_PROBE(contended__exit, this, object(), Self); duke@435: Trigger->unpark() ; duke@435: duke@435: // Maintain stats and report events to JVMTI duke@435: if (ObjectSynchronizer::_sync_Parks != NULL) { duke@435: ObjectSynchronizer::_sync_Parks->inc() ; duke@435: } duke@435: } duke@435: duke@435: duke@435: // exit() duke@435: // ~~~~~~ duke@435: // Note that the collector can't reclaim the objectMonitor or deflate duke@435: // the object out from underneath the thread calling ::exit() as the duke@435: // thread calling ::exit() never transitions to a stable state. duke@435: // This inhibits GC, which in turn inhibits asynchronous (and duke@435: // inopportune) reclamation of "this". duke@435: // duke@435: // We'd like to assert that: (THREAD->thread_state() != _thread_blocked) ; duke@435: // There's one exception to the claim above, however. EnterI() can call duke@435: // exit() to drop a lock if the acquirer has been externally suspended. duke@435: // In that case exit() is called with _thread_state as _thread_blocked, duke@435: // but the monitor's _count field is > 0, which inhibits reclamation. duke@435: // duke@435: // 1-0 exit duke@435: // ~~~~~~~~ duke@435: // ::exit() uses a canonical 1-1 idiom with a MEMBAR although some of duke@435: // the fast-path operators have been optimized so the common ::exit() duke@435: // operation is 1-0. See i486.ad fast_unlock(), for instance. duke@435: // The code emitted by fast_unlock() elides the usual MEMBAR. This duke@435: // greatly improves latency -- MEMBAR and CAS having considerable local duke@435: // latency on modern processors -- but at the cost of "stranding". Absent the duke@435: // MEMBAR, a thread in fast_unlock() can race a thread in the slow duke@435: // ::enter() path, resulting in the entering thread being stranding duke@435: // and a progress-liveness failure. Stranding is extremely rare. duke@435: // We use timers (timed park operations) & periodic polling to detect duke@435: // and recover from stranding. Potentially stranded threads periodically duke@435: // wake up and poll the lock. See the usage of the _Responsible variable. duke@435: // duke@435: // The CAS() in enter provides for safety and exclusion, while the CAS or duke@435: // MEMBAR in exit provides for progress and avoids stranding. 1-0 locking duke@435: // eliminates the CAS/MEMBAR from the exist path, but it admits stranding. duke@435: // We detect and recover from stranding with timers. duke@435: // duke@435: // If a thread transiently strands it'll park until (a) another duke@435: // thread acquires the lock and then drops the lock, at which time the duke@435: // exiting thread will notice and unpark the stranded thread, or, (b) duke@435: // the timer expires. If the lock is high traffic then the stranding latency duke@435: // will be low due to (a). If the lock is low traffic then the odds of duke@435: // stranding are lower, although the worst-case stranding latency duke@435: // is longer. Critically, we don't want to put excessive load in the duke@435: // platform's timer subsystem. We want to minimize both the timer injection duke@435: // rate (timers created/sec) as well as the number of timers active at duke@435: // any one time. (more precisely, we want to minimize timer-seconds, which is duke@435: // the integral of the # of active timers at any instant over time). duke@435: // Both impinge on OS scalability. Given that, at most one thread parked on duke@435: // a monitor will use a timer. duke@435: duke@435: void ATTR ObjectMonitor::exit(TRAPS) { duke@435: Thread * Self = THREAD ; duke@435: if (THREAD != _owner) { duke@435: if (THREAD->is_lock_owned((address) _owner)) { duke@435: // Transmute _owner from a BasicLock pointer to a Thread address. duke@435: // We don't need to hold _mutex for this transition. duke@435: // Non-null to Non-null is safe as long as all readers can duke@435: // tolerate either flavor. duke@435: assert (_recursions == 0, "invariant") ; duke@435: _owner = THREAD ; duke@435: _recursions = 0 ; duke@435: OwnerIsThread = 1 ; duke@435: } else { duke@435: // NOTE: we need to handle unbalanced monitor enter/exit duke@435: // in native code by throwing an exception. duke@435: // TODO: Throw an IllegalMonitorStateException ? duke@435: TEVENT (Exit - Throw IMSX) ; duke@435: assert(false, "Non-balanced monitor enter/exit!"); duke@435: if (false) { duke@435: THROW(vmSymbols::java_lang_IllegalMonitorStateException()); duke@435: } duke@435: return; duke@435: } duke@435: } duke@435: duke@435: if (_recursions != 0) { duke@435: _recursions--; // this is simple recursive enter duke@435: TEVENT (Inflated exit - recursive) ; duke@435: return ; duke@435: } duke@435: duke@435: // Invariant: after setting Responsible=null an thread must execute duke@435: // a MEMBAR or other serializing instruction before fetching EntryList|cxq. duke@435: if ((SyncFlags & 4) == 0) { duke@435: _Responsible = NULL ; duke@435: } duke@435: duke@435: for (;;) { duke@435: assert (THREAD == _owner, "invariant") ; duke@435: duke@435: // Fast-path monitor exit: duke@435: // duke@435: // Observe the Dekker/Lamport duality: duke@435: // A thread in ::exit() executes: duke@435: // ST Owner=null; MEMBAR; LD EntryList|cxq. duke@435: // A thread in the contended ::enter() path executes the complementary: duke@435: // ST EntryList|cxq = nonnull; MEMBAR; LD Owner. duke@435: // duke@435: // Note that there's a benign race in the exit path. We can drop the duke@435: // lock, another thread can reacquire the lock immediately, and we can duke@435: // then wake a thread unnecessarily (yet another flavor of futile wakeup). duke@435: // This is benign, and we've structured the code so the windows are short duke@435: // and the frequency of such futile wakeups is low. duke@435: // duke@435: // We could eliminate the race by encoding both the "LOCKED" state and duke@435: // the queue head in a single word. Exit would then use either CAS to duke@435: // clear the LOCKED bit/byte. This precludes the desirable 1-0 optimization, duke@435: // however. duke@435: // duke@435: // Possible fast-path ::exit() optimization: duke@435: // The current fast-path exit implementation fetches both cxq and EntryList. duke@435: // See also i486.ad fast_unlock(). Testing has shown that two LDs duke@435: // isn't measurably slower than a single LD on any platforms. duke@435: // Still, we could reduce the 2 LDs to one or zero by one of the following: duke@435: // duke@435: // - Use _count instead of cxq|EntryList duke@435: // We intend to eliminate _count, however, when we switch duke@435: // to on-the-fly deflation in ::exit() as is used in duke@435: // Metalocks and RelaxedLocks. duke@435: // duke@435: // - Establish the invariant that cxq == null implies EntryList == null. duke@435: // set cxq == EMPTY (1) to encode the state where cxq is empty duke@435: // by EntryList != null. EMPTY is a distinguished value. duke@435: // The fast-path exit() would fetch cxq but not EntryList. duke@435: // duke@435: // - Encode succ as follows: duke@435: // succ = t : Thread t is the successor -- t is ready or is spinning. duke@435: // Exiting thread does not need to wake a successor. duke@435: // succ = 0 : No successor required -> (EntryList|cxq) == null duke@435: // Exiting thread does not need to wake a successor duke@435: // succ = 1 : Successor required -> (EntryList|cxq) != null and duke@435: // logically succ == null. duke@435: // Exiting thread must wake a successor. duke@435: // duke@435: // The 1-1 fast-exit path would appear as : duke@435: // _owner = null ; membar ; duke@435: // if (_succ == 1 && CAS (&_owner, null, Self) == null) goto SlowPath duke@435: // goto FastPathDone ; duke@435: // duke@435: // and the 1-0 fast-exit path would appear as: duke@435: // if (_succ == 1) goto SlowPath duke@435: // Owner = null ; duke@435: // goto FastPathDone duke@435: // duke@435: // - Encode the LSB of _owner as 1 to indicate that exit() duke@435: // must use the slow-path and make a successor ready. duke@435: // (_owner & 1) == 0 IFF succ != null || (EntryList|cxq) == null duke@435: // (_owner & 1) == 0 IFF succ == null && (EntryList|cxq) != null (obviously) duke@435: // The 1-0 fast exit path would read: duke@435: // if (_owner != Self) goto SlowPath duke@435: // _owner = null duke@435: // goto FastPathDone duke@435: duke@435: if (Knob_ExitPolicy == 0) { duke@435: // release semantics: prior loads and stores from within the critical section duke@435: // must not float (reorder) past the following store that drops the lock. duke@435: // On SPARC that requires MEMBAR #loadstore|#storestore. duke@435: // But of course in TSO #loadstore|#storestore is not required. duke@435: // I'd like to write one of the following: duke@435: // A. OrderAccess::release() ; _owner = NULL duke@435: // B. OrderAccess::loadstore(); OrderAccess::storestore(); _owner = NULL; duke@435: // Unfortunately OrderAccess::release() and OrderAccess::loadstore() both duke@435: // store into a _dummy variable. That store is not needed, but can result duke@435: // in massive wasteful coherency traffic on classic SMP systems. duke@435: // Instead, I use release_store(), which is implemented as just a simple duke@435: // ST on x64, x86 and SPARC. duke@435: OrderAccess::release_store_ptr (&_owner, NULL) ; // drop the lock duke@435: OrderAccess::storeload() ; // See if we need to wake a successor duke@435: if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != NULL) { duke@435: TEVENT (Inflated exit - simple egress) ; duke@435: return ; duke@435: } duke@435: TEVENT (Inflated exit - complex egress) ; duke@435: duke@435: // Normally the exiting thread is responsible for ensuring succession, duke@435: // but if other successors are ready or other entering threads are spinning duke@435: // then this thread can simply store NULL into _owner and exit without duke@435: // waking a successor. The existence of spinners or ready successors duke@435: // guarantees proper succession (liveness). Responsibility passes to the duke@435: // ready or running successors. The exiting thread delegates the duty. duke@435: // More precisely, if a successor already exists this thread is absolved duke@435: // of the responsibility of waking (unparking) one. duke@435: // duke@435: // The _succ variable is critical to reducing futile wakeup frequency. duke@435: // _succ identifies the "heir presumptive" thread that has been made duke@435: // ready (unparked) but that has not yet run. We need only one such duke@435: // successor thread to guarantee progress. duke@435: // See http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf duke@435: // section 3.3 "Futile Wakeup Throttling" for details. duke@435: // duke@435: // Note that spinners in Enter() also set _succ non-null. duke@435: // In the current implementation spinners opportunistically set duke@435: // _succ so that exiting threads might avoid waking a successor. duke@435: // Another less appealing alternative would be for the exiting thread duke@435: // to drop the lock and then spin briefly to see if a spinner managed duke@435: // to acquire the lock. If so, the exiting thread could exit duke@435: // immediately without waking a successor, otherwise the exiting duke@435: // thread would need to dequeue and wake a successor. duke@435: // (Note that we'd need to make the post-drop spin short, but no duke@435: // shorter than the worst-case round-trip cache-line migration time. duke@435: // The dropped lock needs to become visible to the spinner, and then duke@435: // the acquisition of the lock by the spinner must become visible to duke@435: // the exiting thread). duke@435: // duke@435: duke@435: // It appears that an heir-presumptive (successor) must be made ready. duke@435: // Only the current lock owner can manipulate the EntryList or duke@435: // drain _cxq, so we need to reacquire the lock. If we fail duke@435: // to reacquire the lock the responsibility for ensuring succession duke@435: // falls to the new owner. duke@435: // duke@435: if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) { duke@435: return ; duke@435: } duke@435: TEVENT (Exit - Reacquired) ; duke@435: } else { duke@435: if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != NULL) { duke@435: OrderAccess::release_store_ptr (&_owner, NULL) ; // drop the lock duke@435: OrderAccess::storeload() ; duke@435: // Ratify the previously observed values. duke@435: if (_cxq == NULL || _succ != NULL) { duke@435: TEVENT (Inflated exit - simple egress) ; duke@435: return ; duke@435: } duke@435: duke@435: // inopportune interleaving -- the exiting thread (this thread) duke@435: // in the fast-exit path raced an entering thread in the slow-enter duke@435: // path. duke@435: // We have two choices: duke@435: // A. Try to reacquire the lock. duke@435: // If the CAS() fails return immediately, otherwise duke@435: // we either restart/rerun the exit operation, or simply duke@435: // fall-through into the code below which wakes a successor. duke@435: // B. If the elements forming the EntryList|cxq are TSM duke@435: // we could simply unpark() the lead thread and return duke@435: // without having set _succ. duke@435: if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) { duke@435: TEVENT (Inflated exit - reacquired succeeded) ; duke@435: return ; duke@435: } duke@435: TEVENT (Inflated exit - reacquired failed) ; duke@435: } else { duke@435: TEVENT (Inflated exit - complex egress) ; duke@435: } duke@435: } duke@435: duke@435: guarantee (_owner == THREAD, "invariant") ; duke@435: duke@435: // Select an appropriate successor ("heir presumptive") from the EntryList duke@435: // and make it ready. Generally we just wake the head of EntryList . duke@435: // There's no algorithmic constraint that we use the head - it's just duke@435: // a policy decision. Note that the thread at head of the EntryList duke@435: // remains at the head until it acquires the lock. This means we'll duke@435: // repeatedly wake the same thread until it manages to grab the lock. duke@435: // This is generally a good policy - if we're seeing lots of futile wakeups duke@435: // at least we're waking/rewaking a thread that's like to be hot or warm duke@435: // (have residual D$ and TLB affinity). duke@435: // duke@435: // "Wakeup locality" optimization: duke@435: // http://j2se.east/~dice/PERSIST/040825-WakeLocality.txt duke@435: // In the future we'll try to bias the selection mechanism duke@435: // to preferentially pick a thread that recently ran on duke@435: // a processor element that shares cache with the CPU on which duke@435: // the exiting thread is running. We need access to Solaris' duke@435: // schedctl.sc_cpu to make that work. duke@435: // duke@435: ObjectWaiter * w = NULL ; duke@435: int QMode = Knob_QMode ; duke@435: duke@435: if (QMode == 2 && _cxq != NULL) { duke@435: // QMode == 2 : cxq has precedence over EntryList. duke@435: // Try to directly wake a successor from the cxq. duke@435: // If successful, the successor will need to unlink itself from cxq. duke@435: w = _cxq ; duke@435: assert (w != NULL, "invariant") ; duke@435: assert (w->TState == ObjectWaiter::TS_CXQ, "Invariant") ; duke@435: ExitEpilog (Self, w) ; duke@435: return ; duke@435: } duke@435: duke@435: if (QMode == 3 && _cxq != NULL) { duke@435: // Aggressively drain cxq into EntryList at the first opportunity. duke@435: // This policy ensure that recently-run threads live at the head of EntryList. duke@435: // Drain _cxq into EntryList - bulk transfer. duke@435: // First, detach _cxq. duke@435: // The following loop is tantamount to: w = swap (&cxq, NULL) duke@435: w = _cxq ; duke@435: for (;;) { duke@435: assert (w != NULL, "Invariant") ; duke@435: ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ; duke@435: if (u == w) break ; duke@435: w = u ; duke@435: } duke@435: assert (w != NULL , "invariant") ; duke@435: duke@435: ObjectWaiter * q = NULL ; duke@435: ObjectWaiter * p ; duke@435: for (p = w ; p != NULL ; p = p->_next) { duke@435: guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ; duke@435: p->TState = ObjectWaiter::TS_ENTER ; duke@435: p->_prev = q ; duke@435: q = p ; duke@435: } duke@435: duke@435: // Append the RATs to the EntryList duke@435: // TODO: organize EntryList as a CDLL so we can locate the tail in constant-time. duke@435: ObjectWaiter * Tail ; duke@435: for (Tail = _EntryList ; Tail != NULL && Tail->_next != NULL ; Tail = Tail->_next) ; duke@435: if (Tail == NULL) { duke@435: _EntryList = w ; duke@435: } else { duke@435: Tail->_next = w ; duke@435: w->_prev = Tail ; duke@435: } duke@435: duke@435: // Fall thru into code that tries to wake a successor from EntryList duke@435: } duke@435: duke@435: if (QMode == 4 && _cxq != NULL) { duke@435: // Aggressively drain cxq into EntryList at the first opportunity. duke@435: // This policy ensure that recently-run threads live at the head of EntryList. duke@435: duke@435: // Drain _cxq into EntryList - bulk transfer. duke@435: // First, detach _cxq. duke@435: // The following loop is tantamount to: w = swap (&cxq, NULL) duke@435: w = _cxq ; duke@435: for (;;) { duke@435: assert (w != NULL, "Invariant") ; duke@435: ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ; duke@435: if (u == w) break ; duke@435: w = u ; duke@435: } duke@435: assert (w != NULL , "invariant") ; duke@435: duke@435: ObjectWaiter * q = NULL ; duke@435: ObjectWaiter * p ; duke@435: for (p = w ; p != NULL ; p = p->_next) { duke@435: guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ; duke@435: p->TState = ObjectWaiter::TS_ENTER ; duke@435: p->_prev = q ; duke@435: q = p ; duke@435: } duke@435: duke@435: // Prepend the RATs to the EntryList duke@435: if (_EntryList != NULL) { duke@435: q->_next = _EntryList ; duke@435: _EntryList->_prev = q ; duke@435: } duke@435: _EntryList = w ; duke@435: duke@435: // Fall thru into code that tries to wake a successor from EntryList duke@435: } duke@435: duke@435: w = _EntryList ; duke@435: if (w != NULL) { duke@435: // I'd like to write: guarantee (w->_thread != Self). duke@435: // But in practice an exiting thread may find itself on the EntryList. duke@435: // Lets say thread T1 calls O.wait(). Wait() enqueues T1 on O's waitset and duke@435: // then calls exit(). Exit release the lock by setting O._owner to NULL. duke@435: // Lets say T1 then stalls. T2 acquires O and calls O.notify(). The duke@435: // notify() operation moves T1 from O's waitset to O's EntryList. T2 then duke@435: // release the lock "O". T2 resumes immediately after the ST of null into duke@435: // _owner, above. T2 notices that the EntryList is populated, so it duke@435: // reacquires the lock and then finds itself on the EntryList. duke@435: // Given all that, we have to tolerate the circumstance where "w" is duke@435: // associated with Self. duke@435: assert (w->TState == ObjectWaiter::TS_ENTER, "invariant") ; duke@435: ExitEpilog (Self, w) ; duke@435: return ; duke@435: } duke@435: duke@435: // If we find that both _cxq and EntryList are null then just duke@435: // re-run the exit protocol from the top. duke@435: w = _cxq ; duke@435: if (w == NULL) continue ; duke@435: duke@435: // Drain _cxq into EntryList - bulk transfer. duke@435: // First, detach _cxq. duke@435: // The following loop is tantamount to: w = swap (&cxq, NULL) duke@435: for (;;) { duke@435: assert (w != NULL, "Invariant") ; duke@435: ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ; duke@435: if (u == w) break ; duke@435: w = u ; duke@435: } duke@435: TEVENT (Inflated exit - drain cxq into EntryList) ; duke@435: duke@435: assert (w != NULL , "invariant") ; duke@435: assert (_EntryList == NULL , "invariant") ; duke@435: duke@435: // Convert the LIFO SLL anchored by _cxq into a DLL. duke@435: // The list reorganization step operates in O(LENGTH(w)) time. duke@435: // It's critical that this step operate quickly as duke@435: // "Self" still holds the outer-lock, restricting parallelism duke@435: // and effectively lengthening the critical section. duke@435: // Invariant: s chases t chases u. duke@435: // TODO-FIXME: consider changing EntryList from a DLL to a CDLL so duke@435: // we have faster access to the tail. duke@435: duke@435: if (QMode == 1) { duke@435: // QMode == 1 : drain cxq to EntryList, reversing order duke@435: // We also reverse the order of the list. duke@435: ObjectWaiter * s = NULL ; duke@435: ObjectWaiter * t = w ; duke@435: ObjectWaiter * u = NULL ; duke@435: while (t != NULL) { duke@435: guarantee (t->TState == ObjectWaiter::TS_CXQ, "invariant") ; duke@435: t->TState = ObjectWaiter::TS_ENTER ; duke@435: u = t->_next ; duke@435: t->_prev = u ; duke@435: t->_next = s ; duke@435: s = t; duke@435: t = u ; duke@435: } duke@435: _EntryList = s ; duke@435: assert (s != NULL, "invariant") ; duke@435: } else { duke@435: // QMode == 0 or QMode == 2 duke@435: _EntryList = w ; duke@435: ObjectWaiter * q = NULL ; duke@435: ObjectWaiter * p ; duke@435: for (p = w ; p != NULL ; p = p->_next) { duke@435: guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ; duke@435: p->TState = ObjectWaiter::TS_ENTER ; duke@435: p->_prev = q ; duke@435: q = p ; duke@435: } duke@435: } duke@435: duke@435: // In 1-0 mode we need: ST EntryList; MEMBAR #storestore; ST _owner = NULL duke@435: // The MEMBAR is satisfied by the release_store() operation in ExitEpilog(). duke@435: duke@435: // See if we can abdicate to a spinner instead of waking a thread. duke@435: // A primary goal of the implementation is to reduce the duke@435: // context-switch rate. duke@435: if (_succ != NULL) continue; duke@435: duke@435: w = _EntryList ; duke@435: if (w != NULL) { duke@435: guarantee (w->TState == ObjectWaiter::TS_ENTER, "invariant") ; duke@435: ExitEpilog (Self, w) ; duke@435: return ; duke@435: } duke@435: } duke@435: } duke@435: // complete_exit exits a lock returning recursion count duke@435: // complete_exit/reenter operate as a wait without waiting duke@435: // complete_exit requires an inflated monitor duke@435: // The _owner field is not always the Thread addr even with an duke@435: // inflated monitor, e.g. the monitor can be inflated by a non-owning duke@435: // thread due to contention. duke@435: intptr_t ObjectMonitor::complete_exit(TRAPS) { duke@435: Thread * const Self = THREAD; duke@435: assert(Self->is_Java_thread(), "Must be Java thread!"); duke@435: JavaThread *jt = (JavaThread *)THREAD; duke@435: duke@435: DeferredInitialize(); duke@435: duke@435: if (THREAD != _owner) { duke@435: if (THREAD->is_lock_owned ((address)_owner)) { duke@435: assert(_recursions == 0, "internal state error"); duke@435: _owner = THREAD ; /* Convert from basiclock addr to Thread addr */ duke@435: _recursions = 0 ; duke@435: OwnerIsThread = 1 ; duke@435: } duke@435: } duke@435: duke@435: guarantee(Self == _owner, "complete_exit not owner"); duke@435: intptr_t save = _recursions; // record the old recursion count duke@435: _recursions = 0; // set the recursion level to be 0 duke@435: exit (Self) ; // exit the monitor duke@435: guarantee (_owner != Self, "invariant"); duke@435: return save; duke@435: } duke@435: duke@435: // reenter() enters a lock and sets recursion count duke@435: // complete_exit/reenter operate as a wait without waiting duke@435: void ObjectMonitor::reenter(intptr_t recursions, TRAPS) { duke@435: Thread * const Self = THREAD; duke@435: assert(Self->is_Java_thread(), "Must be Java thread!"); duke@435: JavaThread *jt = (JavaThread *)THREAD; duke@435: duke@435: guarantee(_owner != Self, "reenter already owner"); duke@435: enter (THREAD); // enter the monitor duke@435: guarantee (_recursions == 0, "reenter recursion"); duke@435: _recursions = recursions; duke@435: return; duke@435: } duke@435: duke@435: // Note: a subset of changes to ObjectMonitor::wait() duke@435: // will need to be replicated in complete_exit above duke@435: void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) { duke@435: Thread * const Self = THREAD ; duke@435: assert(Self->is_Java_thread(), "Must be Java thread!"); duke@435: JavaThread *jt = (JavaThread *)THREAD; duke@435: duke@435: DeferredInitialize () ; duke@435: duke@435: // Throw IMSX or IEX. duke@435: CHECK_OWNER(); duke@435: duke@435: // check for a pending interrupt duke@435: if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) { duke@435: // post monitor waited event. Note that this is past-tense, we are done waiting. duke@435: if (JvmtiExport::should_post_monitor_waited()) { duke@435: // Note: 'false' parameter is passed here because the duke@435: // wait was not timed out due to thread interrupt. duke@435: JvmtiExport::post_monitor_waited(jt, this, false); duke@435: } duke@435: TEVENT (Wait - Throw IEX) ; duke@435: THROW(vmSymbols::java_lang_InterruptedException()); duke@435: return ; duke@435: } duke@435: TEVENT (Wait) ; duke@435: duke@435: assert (Self->_Stalled == 0, "invariant") ; duke@435: Self->_Stalled = intptr_t(this) ; duke@435: jt->set_current_waiting_monitor(this); duke@435: duke@435: // create a node to be put into the queue duke@435: // Critically, after we reset() the event but prior to park(), we must check duke@435: // for a pending interrupt. duke@435: ObjectWaiter node(Self); duke@435: node.TState = ObjectWaiter::TS_WAIT ; duke@435: Self->_ParkEvent->reset() ; duke@435: OrderAccess::fence(); // ST into Event; membar ; LD interrupted-flag duke@435: duke@435: // Enter the waiting queue, which is a circular doubly linked list in this case duke@435: // but it could be a priority queue or any data structure. duke@435: // _WaitSetLock protects the wait queue. Normally the wait queue is accessed only duke@435: // by the the owner of the monitor *except* in the case where park() duke@435: // returns because of a timeout of interrupt. Contention is exceptionally rare duke@435: // so we use a simple spin-lock instead of a heavier-weight blocking lock. duke@435: duke@435: Thread::SpinAcquire (&_WaitSetLock, "WaitSet - add") ; duke@435: AddWaiter (&node) ; duke@435: Thread::SpinRelease (&_WaitSetLock) ; duke@435: duke@435: if ((SyncFlags & 4) == 0) { duke@435: _Responsible = NULL ; duke@435: } duke@435: intptr_t save = _recursions; // record the old recursion count duke@435: _waiters++; // increment the number of waiters duke@435: _recursions = 0; // set the recursion level to be 1 duke@435: exit (Self) ; // exit the monitor duke@435: guarantee (_owner != Self, "invariant") ; duke@435: duke@435: // As soon as the ObjectMonitor's ownership is dropped in the exit() duke@435: // call above, another thread can enter() the ObjectMonitor, do the duke@435: // notify(), and exit() the ObjectMonitor. If the other thread's duke@435: // exit() call chooses this thread as the successor and the unpark() duke@435: // call happens to occur while this thread is posting a duke@435: // MONITOR_CONTENDED_EXIT event, then we run the risk of the event duke@435: // handler using RawMonitors and consuming the unpark(). duke@435: // duke@435: // To avoid the problem, we re-post the event. This does no harm duke@435: // even if the original unpark() was not consumed because we are the duke@435: // chosen successor for this monitor. duke@435: if (node._notified != 0 && _succ == Self) { duke@435: node._event->unpark(); duke@435: } duke@435: duke@435: // The thread is on the WaitSet list - now park() it. duke@435: // On MP systems it's conceivable that a brief spin before we park duke@435: // could be profitable. duke@435: // duke@435: // TODO-FIXME: change the following logic to a loop of the form duke@435: // while (!timeout && !interrupted && _notified == 0) park() duke@435: duke@435: int ret = OS_OK ; duke@435: int WasNotified = 0 ; duke@435: { // State transition wrappers duke@435: OSThread* osthread = Self->osthread(); duke@435: OSThreadWaitState osts(osthread, true); duke@435: { duke@435: ThreadBlockInVM tbivm(jt); duke@435: // Thread is in thread_blocked state and oop access is unsafe. duke@435: jt->set_suspend_equivalent(); duke@435: duke@435: if (interruptible && (Thread::is_interrupted(THREAD, false) || HAS_PENDING_EXCEPTION)) { duke@435: // Intentionally empty duke@435: } else duke@435: if (node._notified == 0) { duke@435: if (millis <= 0) { duke@435: Self->_ParkEvent->park () ; duke@435: } else { duke@435: ret = Self->_ParkEvent->park (millis) ; duke@435: } duke@435: } duke@435: duke@435: // were we externally suspended while we were waiting? duke@435: if (ExitSuspendEquivalent (jt)) { duke@435: // TODO-FIXME: add -- if succ == Self then succ = null. duke@435: jt->java_suspend_self(); duke@435: } duke@435: duke@435: } // Exit thread safepoint: transition _thread_blocked -> _thread_in_vm duke@435: duke@435: duke@435: // Node may be on the WaitSet, the EntryList (or cxq), or in transition duke@435: // from the WaitSet to the EntryList. duke@435: // See if we need to remove Node from the WaitSet. duke@435: // We use double-checked locking to avoid grabbing _WaitSetLock duke@435: // if the thread is not on the wait queue. duke@435: // duke@435: // Note that we don't need a fence before the fetch of TState. duke@435: // In the worst case we'll fetch a old-stale value of TS_WAIT previously duke@435: // written by the is thread. (perhaps the fetch might even be satisfied duke@435: // by a look-aside into the processor's own store buffer, although given duke@435: // the length of the code path between the prior ST and this load that's duke@435: // highly unlikely). If the following LD fetches a stale TS_WAIT value duke@435: // then we'll acquire the lock and then re-fetch a fresh TState value. duke@435: // That is, we fail toward safety. duke@435: duke@435: if (node.TState == ObjectWaiter::TS_WAIT) { duke@435: Thread::SpinAcquire (&_WaitSetLock, "WaitSet - unlink") ; duke@435: if (node.TState == ObjectWaiter::TS_WAIT) { duke@435: DequeueSpecificWaiter (&node) ; // unlink from WaitSet duke@435: assert(node._notified == 0, "invariant"); duke@435: node.TState = ObjectWaiter::TS_RUN ; duke@435: } duke@435: Thread::SpinRelease (&_WaitSetLock) ; duke@435: } duke@435: duke@435: // The thread is now either on off-list (TS_RUN), duke@435: // on the EntryList (TS_ENTER), or on the cxq (TS_CXQ). duke@435: // The Node's TState variable is stable from the perspective of this thread. duke@435: // No other threads will asynchronously modify TState. duke@435: guarantee (node.TState != ObjectWaiter::TS_WAIT, "invariant") ; duke@435: OrderAccess::loadload() ; duke@435: if (_succ == Self) _succ = NULL ; duke@435: WasNotified = node._notified ; duke@435: duke@435: // Reentry phase -- reacquire the monitor. duke@435: // re-enter contended monitor after object.wait(). duke@435: // retain OBJECT_WAIT state until re-enter successfully completes duke@435: // Thread state is thread_in_vm and oop access is again safe, duke@435: // although the raw address of the object may have changed. duke@435: // (Don't cache naked oops over safepoints, of course). duke@435: duke@435: // post monitor waited event. Note that this is past-tense, we are done waiting. duke@435: if (JvmtiExport::should_post_monitor_waited()) { duke@435: JvmtiExport::post_monitor_waited(jt, this, ret == OS_TIMEOUT); duke@435: } duke@435: OrderAccess::fence() ; duke@435: duke@435: assert (Self->_Stalled != 0, "invariant") ; duke@435: Self->_Stalled = 0 ; duke@435: duke@435: assert (_owner != Self, "invariant") ; duke@435: ObjectWaiter::TStates v = node.TState ; duke@435: if (v == ObjectWaiter::TS_RUN) { duke@435: enter (Self) ; duke@435: } else { duke@435: guarantee (v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant") ; duke@435: ReenterI (Self, &node) ; duke@435: node.wait_reenter_end(this); duke@435: } duke@435: duke@435: // Self has reacquired the lock. duke@435: // Lifecycle - the node representing Self must not appear on any queues. duke@435: // Node is about to go out-of-scope, but even if it were immortal we wouldn't duke@435: // want residual elements associated with this thread left on any lists. duke@435: guarantee (node.TState == ObjectWaiter::TS_RUN, "invariant") ; duke@435: assert (_owner == Self, "invariant") ; duke@435: assert (_succ != Self , "invariant") ; duke@435: } // OSThreadWaitState() duke@435: duke@435: jt->set_current_waiting_monitor(NULL); duke@435: duke@435: guarantee (_recursions == 0, "invariant") ; duke@435: _recursions = save; // restore the old recursion count duke@435: _waiters--; // decrement the number of waiters duke@435: duke@435: // Verify a few postconditions duke@435: assert (_owner == Self , "invariant") ; duke@435: assert (_succ != Self , "invariant") ; duke@435: assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ; duke@435: duke@435: if (SyncFlags & 32) { duke@435: OrderAccess::fence() ; duke@435: } duke@435: duke@435: // check if the notification happened duke@435: if (!WasNotified) { duke@435: // no, it could be timeout or Thread.interrupt() or both duke@435: // check for interrupt event, otherwise it is timeout duke@435: if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) { duke@435: TEVENT (Wait - throw IEX from epilog) ; duke@435: THROW(vmSymbols::java_lang_InterruptedException()); duke@435: } duke@435: } duke@435: duke@435: // NOTE: Spurious wake up will be consider as timeout. duke@435: // Monitor notify has precedence over thread interrupt. duke@435: } duke@435: duke@435: duke@435: // Consider: duke@435: // If the lock is cool (cxq == null && succ == null) and we're on an MP system duke@435: // then instead of transferring a thread from the WaitSet to the EntryList duke@435: // we might just dequeue a thread from the WaitSet and directly unpark() it. duke@435: duke@435: void ObjectMonitor::notify(TRAPS) { duke@435: CHECK_OWNER(); duke@435: if (_WaitSet == NULL) { duke@435: TEVENT (Empty-Notify) ; duke@435: return ; duke@435: } duke@435: DTRACE_MONITOR_PROBE(notify, this, object(), THREAD); duke@435: duke@435: int Policy = Knob_MoveNotifyee ; duke@435: duke@435: Thread::SpinAcquire (&_WaitSetLock, "WaitSet - notify") ; duke@435: ObjectWaiter * iterator = DequeueWaiter() ; duke@435: if (iterator != NULL) { duke@435: TEVENT (Notify1 - Transfer) ; duke@435: guarantee (iterator->TState == ObjectWaiter::TS_WAIT, "invariant") ; duke@435: guarantee (iterator->_notified == 0, "invariant") ; duke@435: // Disposition - what might we do with iterator ? duke@435: // a. add it directly to the EntryList - either tail or head. duke@435: // b. push it onto the front of the _cxq. duke@435: // For now we use (a). duke@435: if (Policy != 4) { duke@435: iterator->TState = ObjectWaiter::TS_ENTER ; duke@435: } duke@435: iterator->_notified = 1 ; duke@435: duke@435: ObjectWaiter * List = _EntryList ; duke@435: if (List != NULL) { duke@435: assert (List->_prev == NULL, "invariant") ; duke@435: assert (List->TState == ObjectWaiter::TS_ENTER, "invariant") ; duke@435: assert (List != iterator, "invariant") ; duke@435: } duke@435: duke@435: if (Policy == 0) { // prepend to EntryList duke@435: if (List == NULL) { duke@435: iterator->_next = iterator->_prev = NULL ; duke@435: _EntryList = iterator ; duke@435: } else { duke@435: List->_prev = iterator ; duke@435: iterator->_next = List ; duke@435: iterator->_prev = NULL ; duke@435: _EntryList = iterator ; duke@435: } duke@435: } else duke@435: if (Policy == 1) { // append to EntryList duke@435: if (List == NULL) { duke@435: iterator->_next = iterator->_prev = NULL ; duke@435: _EntryList = iterator ; duke@435: } else { duke@435: // CONSIDER: finding the tail currently requires a linear-time walk of duke@435: // the EntryList. We can make tail access constant-time by converting to duke@435: // a CDLL instead of using our current DLL. duke@435: ObjectWaiter * Tail ; duke@435: for (Tail = List ; Tail->_next != NULL ; Tail = Tail->_next) ; duke@435: assert (Tail != NULL && Tail->_next == NULL, "invariant") ; duke@435: Tail->_next = iterator ; duke@435: iterator->_prev = Tail ; duke@435: iterator->_next = NULL ; duke@435: } duke@435: } else duke@435: if (Policy == 2) { // prepend to cxq duke@435: // prepend to cxq duke@435: if (List == NULL) { duke@435: iterator->_next = iterator->_prev = NULL ; duke@435: _EntryList = iterator ; duke@435: } else { duke@435: iterator->TState = ObjectWaiter::TS_CXQ ; duke@435: for (;;) { duke@435: ObjectWaiter * Front = _cxq ; duke@435: iterator->_next = Front ; duke@435: if (Atomic::cmpxchg_ptr (iterator, &_cxq, Front) == Front) { duke@435: break ; duke@435: } duke@435: } duke@435: } duke@435: } else duke@435: if (Policy == 3) { // append to cxq duke@435: iterator->TState = ObjectWaiter::TS_CXQ ; duke@435: for (;;) { duke@435: ObjectWaiter * Tail ; duke@435: Tail = _cxq ; duke@435: if (Tail == NULL) { duke@435: iterator->_next = NULL ; duke@435: if (Atomic::cmpxchg_ptr (iterator, &_cxq, NULL) == NULL) { duke@435: break ; duke@435: } duke@435: } else { duke@435: while (Tail->_next != NULL) Tail = Tail->_next ; duke@435: Tail->_next = iterator ; duke@435: iterator->_prev = Tail ; duke@435: iterator->_next = NULL ; duke@435: break ; duke@435: } duke@435: } duke@435: } else { duke@435: ParkEvent * ev = iterator->_event ; duke@435: iterator->TState = ObjectWaiter::TS_RUN ; duke@435: OrderAccess::fence() ; duke@435: ev->unpark() ; duke@435: } duke@435: duke@435: if (Policy < 4) { duke@435: iterator->wait_reenter_begin(this); duke@435: } duke@435: duke@435: // _WaitSetLock protects the wait queue, not the EntryList. We could duke@435: // move the add-to-EntryList operation, above, outside the critical section duke@435: // protected by _WaitSetLock. In practice that's not useful. With the duke@435: // exception of wait() timeouts and interrupts the monitor owner duke@435: // is the only thread that grabs _WaitSetLock. There's almost no contention duke@435: // on _WaitSetLock so it's not profitable to reduce the length of the duke@435: // critical section. duke@435: } duke@435: duke@435: Thread::SpinRelease (&_WaitSetLock) ; duke@435: duke@435: if (iterator != NULL && ObjectSynchronizer::_sync_Notifications != NULL) { duke@435: ObjectSynchronizer::_sync_Notifications->inc() ; duke@435: } duke@435: } duke@435: duke@435: duke@435: void ObjectMonitor::notifyAll(TRAPS) { duke@435: CHECK_OWNER(); duke@435: ObjectWaiter* iterator; duke@435: if (_WaitSet == NULL) { duke@435: TEVENT (Empty-NotifyAll) ; duke@435: return ; duke@435: } duke@435: DTRACE_MONITOR_PROBE(notifyAll, this, object(), THREAD); duke@435: duke@435: int Policy = Knob_MoveNotifyee ; duke@435: int Tally = 0 ; duke@435: Thread::SpinAcquire (&_WaitSetLock, "WaitSet - notifyall") ; duke@435: duke@435: for (;;) { duke@435: iterator = DequeueWaiter () ; duke@435: if (iterator == NULL) break ; duke@435: TEVENT (NotifyAll - Transfer1) ; duke@435: ++Tally ; duke@435: duke@435: // Disposition - what might we do with iterator ? duke@435: // a. add it directly to the EntryList - either tail or head. duke@435: // b. push it onto the front of the _cxq. duke@435: // For now we use (a). duke@435: // duke@435: // TODO-FIXME: currently notifyAll() transfers the waiters one-at-a-time from the waitset duke@435: // to the EntryList. This could be done more efficiently with a single bulk transfer, duke@435: // but in practice it's not time-critical. Beware too, that in prepend-mode we invert the duke@435: // order of the waiters. Lets say that the waitset is "ABCD" and the EntryList is "XYZ". duke@435: // After a notifyAll() in prepend mode the waitset will be empty and the EntryList will duke@435: // be "DCBAXYZ". duke@435: duke@435: guarantee (iterator->TState == ObjectWaiter::TS_WAIT, "invariant") ; duke@435: guarantee (iterator->_notified == 0, "invariant") ; duke@435: iterator->_notified = 1 ; duke@435: if (Policy != 4) { duke@435: iterator->TState = ObjectWaiter::TS_ENTER ; duke@435: } duke@435: duke@435: ObjectWaiter * List = _EntryList ; duke@435: if (List != NULL) { duke@435: assert (List->_prev == NULL, "invariant") ; duke@435: assert (List->TState == ObjectWaiter::TS_ENTER, "invariant") ; duke@435: assert (List != iterator, "invariant") ; duke@435: } duke@435: duke@435: if (Policy == 0) { // prepend to EntryList duke@435: if (List == NULL) { duke@435: iterator->_next = iterator->_prev = NULL ; duke@435: _EntryList = iterator ; duke@435: } else { duke@435: List->_prev = iterator ; duke@435: iterator->_next = List ; duke@435: iterator->_prev = NULL ; duke@435: _EntryList = iterator ; duke@435: } duke@435: } else duke@435: if (Policy == 1) { // append to EntryList duke@435: if (List == NULL) { duke@435: iterator->_next = iterator->_prev = NULL ; duke@435: _EntryList = iterator ; duke@435: } else { duke@435: // CONSIDER: finding the tail currently requires a linear-time walk of duke@435: // the EntryList. We can make tail access constant-time by converting to duke@435: // a CDLL instead of using our current DLL. duke@435: ObjectWaiter * Tail ; duke@435: for (Tail = List ; Tail->_next != NULL ; Tail = Tail->_next) ; duke@435: assert (Tail != NULL && Tail->_next == NULL, "invariant") ; duke@435: Tail->_next = iterator ; duke@435: iterator->_prev = Tail ; duke@435: iterator->_next = NULL ; duke@435: } duke@435: } else duke@435: if (Policy == 2) { // prepend to cxq duke@435: // prepend to cxq duke@435: iterator->TState = ObjectWaiter::TS_CXQ ; duke@435: for (;;) { duke@435: ObjectWaiter * Front = _cxq ; duke@435: iterator->_next = Front ; duke@435: if (Atomic::cmpxchg_ptr (iterator, &_cxq, Front) == Front) { duke@435: break ; duke@435: } duke@435: } duke@435: } else duke@435: if (Policy == 3) { // append to cxq duke@435: iterator->TState = ObjectWaiter::TS_CXQ ; duke@435: for (;;) { duke@435: ObjectWaiter * Tail ; duke@435: Tail = _cxq ; duke@435: if (Tail == NULL) { duke@435: iterator->_next = NULL ; duke@435: if (Atomic::cmpxchg_ptr (iterator, &_cxq, NULL) == NULL) { duke@435: break ; duke@435: } duke@435: } else { duke@435: while (Tail->_next != NULL) Tail = Tail->_next ; duke@435: Tail->_next = iterator ; duke@435: iterator->_prev = Tail ; duke@435: iterator->_next = NULL ; duke@435: break ; duke@435: } duke@435: } duke@435: } else { duke@435: ParkEvent * ev = iterator->_event ; duke@435: iterator->TState = ObjectWaiter::TS_RUN ; duke@435: OrderAccess::fence() ; duke@435: ev->unpark() ; duke@435: } duke@435: duke@435: if (Policy < 4) { duke@435: iterator->wait_reenter_begin(this); duke@435: } duke@435: duke@435: // _WaitSetLock protects the wait queue, not the EntryList. We could duke@435: // move the add-to-EntryList operation, above, outside the critical section duke@435: // protected by _WaitSetLock. In practice that's not useful. With the duke@435: // exception of wait() timeouts and interrupts the monitor owner duke@435: // is the only thread that grabs _WaitSetLock. There's almost no contention duke@435: // on _WaitSetLock so it's not profitable to reduce the length of the duke@435: // critical section. duke@435: } duke@435: duke@435: Thread::SpinRelease (&_WaitSetLock) ; duke@435: duke@435: if (Tally != 0 && ObjectSynchronizer::_sync_Notifications != NULL) { duke@435: ObjectSynchronizer::_sync_Notifications->inc(Tally) ; duke@435: } duke@435: } duke@435: duke@435: // check_slow() is a misnomer. It's called to simply to throw an IMSX exception. duke@435: // TODO-FIXME: remove check_slow() -- it's likely dead. duke@435: duke@435: void ObjectMonitor::check_slow(TRAPS) { duke@435: TEVENT (check_slow - throw IMSX) ; duke@435: assert(THREAD != _owner && !THREAD->is_lock_owned((address) _owner), "must not be owner"); duke@435: THROW_MSG(vmSymbols::java_lang_IllegalMonitorStateException(), "current thread not owner"); duke@435: } duke@435: duke@435: duke@435: // ------------------------------------------------------------------------- duke@435: // The raw monitor subsystem is entirely distinct from normal duke@435: // java-synchronization or jni-synchronization. raw monitors are not duke@435: // associated with objects. They can be implemented in any manner duke@435: // that makes sense. The original implementors decided to piggy-back duke@435: // the raw-monitor implementation on the existing Java objectMonitor mechanism. duke@435: // This flaw needs to fixed. We should reimplement raw monitors as sui-generis. duke@435: // Specifically, we should not implement raw monitors via java monitors. duke@435: // Time permitting, we should disentangle and deconvolve the two implementations duke@435: // and move the resulting raw monitor implementation over to the JVMTI directories. duke@435: // Ideally, the raw monitor implementation would be built on top of duke@435: // park-unpark and nothing else. duke@435: // duke@435: // raw monitors are used mainly by JVMTI duke@435: // The raw monitor implementation borrows the ObjectMonitor structure, duke@435: // but the operators are degenerate and extremely simple. duke@435: // duke@435: // Mixed use of a single objectMonitor instance -- as both a raw monitor duke@435: // and a normal java monitor -- is not permissible. duke@435: // duke@435: // Note that we use the single RawMonitor_lock to protect queue operations for duke@435: // _all_ raw monitors. This is a scalability impediment, but since raw monitor usage duke@435: // is deprecated and rare, this is not of concern. The RawMonitor_lock can not duke@435: // be held indefinitely. The critical sections must be short and bounded. duke@435: // duke@435: // ------------------------------------------------------------------------- duke@435: duke@435: int ObjectMonitor::SimpleEnter (Thread * Self) { duke@435: for (;;) { duke@435: if (Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) { duke@435: return OS_OK ; duke@435: } duke@435: duke@435: ObjectWaiter Node (Self) ; duke@435: Self->_ParkEvent->reset() ; // strictly optional duke@435: Node.TState = ObjectWaiter::TS_ENTER ; duke@435: duke@435: RawMonitor_lock->lock_without_safepoint_check() ; duke@435: Node._next = _EntryList ; duke@435: _EntryList = &Node ; duke@435: OrderAccess::fence() ; duke@435: if (_owner == NULL && Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) { duke@435: _EntryList = Node._next ; duke@435: RawMonitor_lock->unlock() ; duke@435: return OS_OK ; duke@435: } duke@435: RawMonitor_lock->unlock() ; duke@435: while (Node.TState == ObjectWaiter::TS_ENTER) { duke@435: Self->_ParkEvent->park() ; duke@435: } duke@435: } duke@435: } duke@435: duke@435: int ObjectMonitor::SimpleExit (Thread * Self) { duke@435: guarantee (_owner == Self, "invariant") ; duke@435: OrderAccess::release_store_ptr (&_owner, NULL) ; duke@435: OrderAccess::fence() ; duke@435: if (_EntryList == NULL) return OS_OK ; duke@435: ObjectWaiter * w ; duke@435: duke@435: RawMonitor_lock->lock_without_safepoint_check() ; duke@435: w = _EntryList ; duke@435: if (w != NULL) { duke@435: _EntryList = w->_next ; duke@435: } duke@435: RawMonitor_lock->unlock() ; duke@435: if (w != NULL) { duke@435: guarantee (w ->TState == ObjectWaiter::TS_ENTER, "invariant") ; duke@435: ParkEvent * ev = w->_event ; duke@435: w->TState = ObjectWaiter::TS_RUN ; duke@435: OrderAccess::fence() ; duke@435: ev->unpark() ; duke@435: } duke@435: return OS_OK ; duke@435: } duke@435: duke@435: int ObjectMonitor::SimpleWait (Thread * Self, jlong millis) { duke@435: guarantee (_owner == Self , "invariant") ; duke@435: guarantee (_recursions == 0, "invariant") ; duke@435: duke@435: ObjectWaiter Node (Self) ; duke@435: Node._notified = 0 ; duke@435: Node.TState = ObjectWaiter::TS_WAIT ; duke@435: duke@435: RawMonitor_lock->lock_without_safepoint_check() ; duke@435: Node._next = _WaitSet ; duke@435: _WaitSet = &Node ; duke@435: RawMonitor_lock->unlock() ; duke@435: duke@435: SimpleExit (Self) ; duke@435: guarantee (_owner != Self, "invariant") ; duke@435: duke@435: int ret = OS_OK ; duke@435: if (millis <= 0) { duke@435: Self->_ParkEvent->park(); duke@435: } else { duke@435: ret = Self->_ParkEvent->park(millis); duke@435: } duke@435: duke@435: // If thread still resides on the waitset then unlink it. duke@435: // Double-checked locking -- the usage is safe in this context duke@435: // as we TState is volatile and the lock-unlock operators are duke@435: // serializing (barrier-equivalent). duke@435: duke@435: if (Node.TState == ObjectWaiter::TS_WAIT) { duke@435: RawMonitor_lock->lock_without_safepoint_check() ; duke@435: if (Node.TState == ObjectWaiter::TS_WAIT) { duke@435: // Simple O(n) unlink, but performance isn't critical here. duke@435: ObjectWaiter * p ; duke@435: ObjectWaiter * q = NULL ; duke@435: for (p = _WaitSet ; p != &Node; p = p->_next) { duke@435: q = p ; duke@435: } duke@435: guarantee (p == &Node, "invariant") ; duke@435: if (q == NULL) { duke@435: guarantee (p == _WaitSet, "invariant") ; duke@435: _WaitSet = p->_next ; duke@435: } else { duke@435: guarantee (p == q->_next, "invariant") ; duke@435: q->_next = p->_next ; duke@435: } duke@435: Node.TState = ObjectWaiter::TS_RUN ; duke@435: } duke@435: RawMonitor_lock->unlock() ; duke@435: } duke@435: duke@435: guarantee (Node.TState == ObjectWaiter::TS_RUN, "invariant") ; duke@435: SimpleEnter (Self) ; duke@435: duke@435: guarantee (_owner == Self, "invariant") ; duke@435: guarantee (_recursions == 0, "invariant") ; duke@435: return ret ; duke@435: } duke@435: duke@435: int ObjectMonitor::SimpleNotify (Thread * Self, bool All) { duke@435: guarantee (_owner == Self, "invariant") ; duke@435: if (_WaitSet == NULL) return OS_OK ; duke@435: duke@435: // We have two options: duke@435: // A. Transfer the threads from the WaitSet to the EntryList duke@435: // B. Remove the thread from the WaitSet and unpark() it. duke@435: // duke@435: // We use (B), which is crude and results in lots of futile duke@435: // context switching. In particular (B) induces lots of contention. duke@435: duke@435: ParkEvent * ev = NULL ; // consider using a small auto array ... duke@435: RawMonitor_lock->lock_without_safepoint_check() ; duke@435: for (;;) { duke@435: ObjectWaiter * w = _WaitSet ; duke@435: if (w == NULL) break ; duke@435: _WaitSet = w->_next ; duke@435: if (ev != NULL) { ev->unpark(); ev = NULL; } duke@435: ev = w->_event ; duke@435: OrderAccess::loadstore() ; duke@435: w->TState = ObjectWaiter::TS_RUN ; duke@435: OrderAccess::storeload(); duke@435: if (!All) break ; duke@435: } duke@435: RawMonitor_lock->unlock() ; duke@435: if (ev != NULL) ev->unpark(); duke@435: return OS_OK ; duke@435: } duke@435: duke@435: // Any JavaThread will enter here with state _thread_blocked duke@435: int ObjectMonitor::raw_enter(TRAPS) { duke@435: TEVENT (raw_enter) ; duke@435: void * Contended ; duke@435: duke@435: // don't enter raw monitor if thread is being externally suspended, it will duke@435: // surprise the suspender if a "suspended" thread can still enter monitor duke@435: JavaThread * jt = (JavaThread *)THREAD; duke@435: if (THREAD->is_Java_thread()) { duke@435: jt->SR_lock()->lock_without_safepoint_check(); duke@435: while (jt->is_external_suspend()) { duke@435: jt->SR_lock()->unlock(); duke@435: jt->java_suspend_self(); duke@435: jt->SR_lock()->lock_without_safepoint_check(); duke@435: } duke@435: // guarded by SR_lock to avoid racing with new external suspend requests. duke@435: Contended = Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) ; duke@435: jt->SR_lock()->unlock(); duke@435: } else { duke@435: Contended = Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) ; duke@435: } duke@435: duke@435: if (Contended == THREAD) { duke@435: _recursions ++ ; duke@435: return OM_OK ; duke@435: } duke@435: duke@435: if (Contended == NULL) { duke@435: guarantee (_owner == THREAD, "invariant") ; duke@435: guarantee (_recursions == 0, "invariant") ; duke@435: return OM_OK ; duke@435: } duke@435: duke@435: THREAD->set_current_pending_monitor(this); duke@435: duke@435: if (!THREAD->is_Java_thread()) { duke@435: // No other non-Java threads besides VM thread would acquire duke@435: // a raw monitor. duke@435: assert(THREAD->is_VM_thread(), "must be VM thread"); duke@435: SimpleEnter (THREAD) ; duke@435: } else { duke@435: guarantee (jt->thread_state() == _thread_blocked, "invariant") ; duke@435: for (;;) { duke@435: jt->set_suspend_equivalent(); duke@435: // cleared by handle_special_suspend_equivalent_condition() or duke@435: // java_suspend_self() duke@435: SimpleEnter (THREAD) ; duke@435: duke@435: // were we externally suspended while we were waiting? duke@435: if (!jt->handle_special_suspend_equivalent_condition()) break ; duke@435: duke@435: // This thread was externally suspended duke@435: // duke@435: // This logic isn't needed for JVMTI raw monitors, duke@435: // but doesn't hurt just in case the suspend rules change. This duke@435: // logic is needed for the ObjectMonitor.wait() reentry phase. duke@435: // We have reentered the contended monitor, but while we were duke@435: // waiting another thread suspended us. We don't want to reenter duke@435: // the monitor while suspended because that would surprise the duke@435: // thread that suspended us. duke@435: // duke@435: // Drop the lock - duke@435: SimpleExit (THREAD) ; duke@435: duke@435: jt->java_suspend_self(); duke@435: } duke@435: duke@435: assert(_owner == THREAD, "Fatal error with monitor owner!"); duke@435: assert(_recursions == 0, "Fatal error with monitor recursions!"); duke@435: } duke@435: duke@435: THREAD->set_current_pending_monitor(NULL); duke@435: guarantee (_recursions == 0, "invariant") ; duke@435: return OM_OK; duke@435: } duke@435: duke@435: // Used mainly for JVMTI raw monitor implementation duke@435: // Also used for ObjectMonitor::wait(). duke@435: int ObjectMonitor::raw_exit(TRAPS) { duke@435: TEVENT (raw_exit) ; duke@435: if (THREAD != _owner) { duke@435: return OM_ILLEGAL_MONITOR_STATE; duke@435: } duke@435: if (_recursions > 0) { duke@435: --_recursions ; duke@435: return OM_OK ; duke@435: } duke@435: duke@435: void * List = _EntryList ; duke@435: SimpleExit (THREAD) ; duke@435: duke@435: return OM_OK; duke@435: } duke@435: duke@435: // Used for JVMTI raw monitor implementation. duke@435: // All JavaThreads will enter here with state _thread_blocked duke@435: duke@435: int ObjectMonitor::raw_wait(jlong millis, bool interruptible, TRAPS) { duke@435: TEVENT (raw_wait) ; duke@435: if (THREAD != _owner) { duke@435: return OM_ILLEGAL_MONITOR_STATE; duke@435: } duke@435: duke@435: // To avoid spurious wakeups we reset the parkevent -- This is strictly optional. duke@435: // The caller must be able to tolerate spurious returns from raw_wait(). duke@435: THREAD->_ParkEvent->reset() ; duke@435: OrderAccess::fence() ; duke@435: duke@435: // check interrupt event duke@435: if (interruptible && Thread::is_interrupted(THREAD, true)) { duke@435: return OM_INTERRUPTED; duke@435: } duke@435: duke@435: intptr_t save = _recursions ; duke@435: _recursions = 0 ; duke@435: _waiters ++ ; duke@435: if (THREAD->is_Java_thread()) { duke@435: guarantee (((JavaThread *) THREAD)->thread_state() == _thread_blocked, "invariant") ; duke@435: ((JavaThread *)THREAD)->set_suspend_equivalent(); duke@435: } duke@435: int rv = SimpleWait (THREAD, millis) ; duke@435: _recursions = save ; duke@435: _waiters -- ; duke@435: duke@435: guarantee (THREAD == _owner, "invariant") ; duke@435: if (THREAD->is_Java_thread()) { duke@435: JavaThread * jSelf = (JavaThread *) THREAD ; duke@435: for (;;) { duke@435: if (!jSelf->handle_special_suspend_equivalent_condition()) break ; duke@435: SimpleExit (THREAD) ; duke@435: jSelf->java_suspend_self(); duke@435: SimpleEnter (THREAD) ; duke@435: jSelf->set_suspend_equivalent() ; duke@435: } duke@435: } duke@435: guarantee (THREAD == _owner, "invariant") ; duke@435: duke@435: if (interruptible && Thread::is_interrupted(THREAD, true)) { duke@435: return OM_INTERRUPTED; duke@435: } duke@435: return OM_OK ; duke@435: } duke@435: duke@435: int ObjectMonitor::raw_notify(TRAPS) { duke@435: TEVENT (raw_notify) ; duke@435: if (THREAD != _owner) { duke@435: return OM_ILLEGAL_MONITOR_STATE; duke@435: } duke@435: SimpleNotify (THREAD, false) ; duke@435: return OM_OK; duke@435: } duke@435: duke@435: int ObjectMonitor::raw_notifyAll(TRAPS) { duke@435: TEVENT (raw_notifyAll) ; duke@435: if (THREAD != _owner) { duke@435: return OM_ILLEGAL_MONITOR_STATE; duke@435: } duke@435: SimpleNotify (THREAD, true) ; duke@435: return OM_OK; duke@435: } duke@435: duke@435: #ifndef PRODUCT duke@435: void ObjectMonitor::verify() { duke@435: } duke@435: duke@435: void ObjectMonitor::print() { duke@435: } duke@435: #endif duke@435: duke@435: //------------------------------------------------------------------------------ duke@435: // Non-product code duke@435: duke@435: #ifndef PRODUCT duke@435: duke@435: void ObjectSynchronizer::trace_locking(Handle locking_obj, bool is_compiled, duke@435: bool is_method, bool is_locking) { duke@435: // Don't know what to do here duke@435: } duke@435: duke@435: // Verify all monitors in the monitor cache, the verification is weak. duke@435: void ObjectSynchronizer::verify() { duke@435: ObjectMonitor* block = gBlockList; duke@435: ObjectMonitor* mid; duke@435: while (block) { duke@435: assert(block->object() == CHAINMARKER, "must be a block header"); duke@435: for (int i = 1; i < _BLOCKSIZE; i++) { duke@435: mid = block + i; duke@435: oop object = (oop) mid->object(); duke@435: if (object != NULL) { duke@435: mid->verify(); duke@435: } duke@435: } duke@435: block = (ObjectMonitor*) block->FreeNext; duke@435: } duke@435: } duke@435: duke@435: // Check if monitor belongs to the monitor cache duke@435: // The list is grow-only so it's *relatively* safe to traverse duke@435: // the list of extant blocks without taking a lock. duke@435: duke@435: int ObjectSynchronizer::verify_objmon_isinpool(ObjectMonitor *monitor) { duke@435: ObjectMonitor* block = gBlockList; duke@435: duke@435: while (block) { duke@435: assert(block->object() == CHAINMARKER, "must be a block header"); duke@435: if (monitor > &block[0] && monitor < &block[_BLOCKSIZE]) { duke@435: address mon = (address) monitor; duke@435: address blk = (address) block; duke@435: size_t diff = mon - blk; duke@435: assert((diff % sizeof(ObjectMonitor)) == 0, "check"); duke@435: return 1; duke@435: } duke@435: block = (ObjectMonitor*) block->FreeNext; duke@435: } duke@435: return 0; duke@435: } duke@435: duke@435: #endif