src/share/vm/runtime/synchronizer.cpp

Fri, 04 Jun 2010 17:44:51 -0400

author
coleenp
date
Fri, 04 Jun 2010 17:44:51 -0400
changeset 1944
3a9de63b2209
parent 1942
b96a3e44582f
parent 1907
c18cbe5936b8
child 1995
bfc89697cccb
permissions
-rw-r--r--

Merge

duke@435 1 /*
trims@1907 2 * Copyright (c) 1998, 2009, Oracle and/or its affiliates. All rights reserved.
duke@435 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
duke@435 4 *
duke@435 5 * This code is free software; you can redistribute it and/or modify it
duke@435 6 * under the terms of the GNU General Public License version 2 only, as
duke@435 7 * published by the Free Software Foundation.
duke@435 8 *
duke@435 9 * This code is distributed in the hope that it will be useful, but WITHOUT
duke@435 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
duke@435 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
duke@435 12 * version 2 for more details (a copy is included in the LICENSE file that
duke@435 13 * accompanied this code).
duke@435 14 *
duke@435 15 * You should have received a copy of the GNU General Public License version
duke@435 16 * 2 along with this work; if not, write to the Free Software Foundation,
duke@435 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
duke@435 18 *
trims@1907 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
trims@1907 20 * or visit www.oracle.com if you need additional information or have any
trims@1907 21 * questions.
duke@435 22 *
duke@435 23 */
duke@435 24
duke@435 25 # include "incls/_precompiled.incl"
duke@435 26 # include "incls/_synchronizer.cpp.incl"
duke@435 27
duke@435 28 #if defined(__GNUC__) && !defined(IA64)
duke@435 29 // Need to inhibit inlining for older versions of GCC to avoid build-time failures
duke@435 30 #define ATTR __attribute__((noinline))
duke@435 31 #else
duke@435 32 #define ATTR
duke@435 33 #endif
duke@435 34
duke@435 35 // Native markword accessors for synchronization and hashCode().
duke@435 36 //
duke@435 37 // The "core" versions of monitor enter and exit reside in this file.
duke@435 38 // The interpreter and compilers contain specialized transliterated
duke@435 39 // variants of the enter-exit fast-path operations. See i486.ad fast_lock(),
duke@435 40 // for instance. If you make changes here, make sure to modify the
duke@435 41 // interpreter, and both C1 and C2 fast-path inline locking code emission.
duke@435 42 //
duke@435 43 // TODO: merge the objectMonitor and synchronizer classes.
duke@435 44 //
duke@435 45 // -----------------------------------------------------------------------------
duke@435 46
duke@435 47 #ifdef DTRACE_ENABLED
duke@435 48
duke@435 49 // Only bother with this argument setup if dtrace is available
duke@435 50 // TODO-FIXME: probes should not fire when caller is _blocked. assert() accordingly.
duke@435 51
duke@435 52 HS_DTRACE_PROBE_DECL5(hotspot, monitor__wait,
duke@435 53 jlong, uintptr_t, char*, int, long);
duke@435 54 HS_DTRACE_PROBE_DECL4(hotspot, monitor__waited,
duke@435 55 jlong, uintptr_t, char*, int);
duke@435 56 HS_DTRACE_PROBE_DECL4(hotspot, monitor__notify,
duke@435 57 jlong, uintptr_t, char*, int);
duke@435 58 HS_DTRACE_PROBE_DECL4(hotspot, monitor__notifyAll,
duke@435 59 jlong, uintptr_t, char*, int);
duke@435 60 HS_DTRACE_PROBE_DECL4(hotspot, monitor__contended__enter,
duke@435 61 jlong, uintptr_t, char*, int);
duke@435 62 HS_DTRACE_PROBE_DECL4(hotspot, monitor__contended__entered,
duke@435 63 jlong, uintptr_t, char*, int);
duke@435 64 HS_DTRACE_PROBE_DECL4(hotspot, monitor__contended__exit,
duke@435 65 jlong, uintptr_t, char*, int);
duke@435 66
duke@435 67 #define DTRACE_MONITOR_PROBE_COMMON(klassOop, thread) \
duke@435 68 char* bytes = NULL; \
duke@435 69 int len = 0; \
duke@435 70 jlong jtid = SharedRuntime::get_java_tid(thread); \
duke@435 71 symbolOop klassname = ((oop)(klassOop))->klass()->klass_part()->name(); \
duke@435 72 if (klassname != NULL) { \
duke@435 73 bytes = (char*)klassname->bytes(); \
duke@435 74 len = klassname->utf8_length(); \
duke@435 75 }
duke@435 76
duke@435 77 #define DTRACE_MONITOR_WAIT_PROBE(monitor, klassOop, thread, millis) \
duke@435 78 { \
duke@435 79 if (DTraceMonitorProbes) { \
duke@435 80 DTRACE_MONITOR_PROBE_COMMON(klassOop, thread); \
duke@435 81 HS_DTRACE_PROBE5(hotspot, monitor__wait, jtid, \
duke@435 82 (monitor), bytes, len, (millis)); \
duke@435 83 } \
duke@435 84 }
duke@435 85
duke@435 86 #define DTRACE_MONITOR_PROBE(probe, monitor, klassOop, thread) \
duke@435 87 { \
duke@435 88 if (DTraceMonitorProbes) { \
duke@435 89 DTRACE_MONITOR_PROBE_COMMON(klassOop, thread); \
duke@435 90 HS_DTRACE_PROBE4(hotspot, monitor__##probe, jtid, \
duke@435 91 (uintptr_t)(monitor), bytes, len); \
duke@435 92 } \
duke@435 93 }
duke@435 94
duke@435 95 #else // ndef DTRACE_ENABLED
duke@435 96
duke@435 97 #define DTRACE_MONITOR_WAIT_PROBE(klassOop, thread, millis, mon) {;}
duke@435 98 #define DTRACE_MONITOR_PROBE(probe, klassOop, thread, mon) {;}
duke@435 99
duke@435 100 #endif // ndef DTRACE_ENABLED
duke@435 101
duke@435 102 // ObjectWaiter serves as a "proxy" or surrogate thread.
duke@435 103 // TODO-FIXME: Eliminate ObjectWaiter and use the thread-specific
duke@435 104 // ParkEvent instead. Beware, however, that the JVMTI code
duke@435 105 // knows about ObjectWaiters, so we'll have to reconcile that code.
duke@435 106 // See next_waiter(), first_waiter(), etc.
duke@435 107
duke@435 108 class ObjectWaiter : public StackObj {
duke@435 109 public:
duke@435 110 enum TStates { TS_UNDEF, TS_READY, TS_RUN, TS_WAIT, TS_ENTER, TS_CXQ } ;
duke@435 111 enum Sorted { PREPEND, APPEND, SORTED } ;
duke@435 112 ObjectWaiter * volatile _next;
duke@435 113 ObjectWaiter * volatile _prev;
duke@435 114 Thread* _thread;
duke@435 115 ParkEvent * _event;
duke@435 116 volatile int _notified ;
duke@435 117 volatile TStates TState ;
duke@435 118 Sorted _Sorted ; // List placement disposition
duke@435 119 bool _active ; // Contention monitoring is enabled
duke@435 120 public:
duke@435 121 ObjectWaiter(Thread* thread) {
duke@435 122 _next = NULL;
duke@435 123 _prev = NULL;
duke@435 124 _notified = 0;
duke@435 125 TState = TS_RUN ;
duke@435 126 _thread = thread;
duke@435 127 _event = thread->_ParkEvent ;
duke@435 128 _active = false;
duke@435 129 assert (_event != NULL, "invariant") ;
duke@435 130 }
duke@435 131
duke@435 132 void wait_reenter_begin(ObjectMonitor *mon) {
duke@435 133 JavaThread *jt = (JavaThread *)this->_thread;
duke@435 134 _active = JavaThreadBlockedOnMonitorEnterState::wait_reenter_begin(jt, mon);
duke@435 135 }
duke@435 136
duke@435 137 void wait_reenter_end(ObjectMonitor *mon) {
duke@435 138 JavaThread *jt = (JavaThread *)this->_thread;
duke@435 139 JavaThreadBlockedOnMonitorEnterState::wait_reenter_end(jt, _active);
duke@435 140 }
duke@435 141 };
duke@435 142
duke@435 143 enum ManifestConstants {
duke@435 144 ClearResponsibleAtSTW = 0,
duke@435 145 MaximumRecheckInterval = 1000
duke@435 146 } ;
duke@435 147
duke@435 148
duke@435 149 #undef TEVENT
duke@435 150 #define TEVENT(nom) {if (SyncVerbose) FEVENT(nom); }
duke@435 151
duke@435 152 #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 153
duke@435 154 #undef TEVENT
duke@435 155 #define TEVENT(nom) {;}
duke@435 156
duke@435 157 // Performance concern:
duke@435 158 // OrderAccess::storestore() calls release() which STs 0 into the global volatile
duke@435 159 // OrderAccess::Dummy variable. This store is unnecessary for correctness.
duke@435 160 // Many threads STing into a common location causes considerable cache migration
duke@435 161 // or "sloshing" on large SMP system. As such, I avoid using OrderAccess::storestore()
duke@435 162 // until it's repaired. In some cases OrderAccess::fence() -- which incurs local
duke@435 163 // latency on the executing processor -- is a better choice as it scales on SMP
duke@435 164 // systems. See http://blogs.sun.com/dave/entry/biased_locking_in_hotspot for a
duke@435 165 // discussion of coherency costs. Note that all our current reference platforms
duke@435 166 // provide strong ST-ST order, so the issue is moot on IA32, x64, and SPARC.
duke@435 167 //
duke@435 168 // As a general policy we use "volatile" to control compiler-based reordering
duke@435 169 // and explicit fences (barriers) to control for architectural reordering performed
duke@435 170 // by the CPU(s) or platform.
duke@435 171
duke@435 172 static int MBFence (int x) { OrderAccess::fence(); return x; }
duke@435 173
duke@435 174 struct SharedGlobals {
duke@435 175 // These are highly shared mostly-read variables.
duke@435 176 // To avoid false-sharing they need to be the sole occupants of a $ line.
duke@435 177 double padPrefix [8];
duke@435 178 volatile int stwRandom ;
duke@435 179 volatile int stwCycle ;
duke@435 180
duke@435 181 // Hot RW variables -- Sequester to avoid false-sharing
duke@435 182 double padSuffix [16];
duke@435 183 volatile int hcSequence ;
duke@435 184 double padFinal [8] ;
duke@435 185 } ;
duke@435 186
duke@435 187 static SharedGlobals GVars ;
acorn@1942 188 static int MonitorScavengeThreshold = 1000000 ;
acorn@1942 189 static volatile int ForceMonitorScavenge = 0 ; // Scavenge required and pending
duke@435 190
duke@435 191
duke@435 192 // Tunables ...
duke@435 193 // The knob* variables are effectively final. Once set they should
duke@435 194 // never be modified hence. Consider using __read_mostly with GCC.
duke@435 195
duke@435 196 static int Knob_LogSpins = 0 ; // enable jvmstat tally for spins
duke@435 197 static int Knob_HandOff = 0 ;
duke@435 198 static int Knob_Verbose = 0 ;
duke@435 199 static int Knob_ReportSettings = 0 ;
duke@435 200
duke@435 201 static int Knob_SpinLimit = 5000 ; // derived by an external tool -
duke@435 202 static int Knob_SpinBase = 0 ; // Floor AKA SpinMin
duke@435 203 static int Knob_SpinBackOff = 0 ; // spin-loop backoff
duke@435 204 static int Knob_CASPenalty = -1 ; // Penalty for failed CAS
duke@435 205 static int Knob_OXPenalty = -1 ; // Penalty for observed _owner change
duke@435 206 static int Knob_SpinSetSucc = 1 ; // spinners set the _succ field
duke@435 207 static int Knob_SpinEarly = 1 ;
duke@435 208 static int Knob_SuccEnabled = 1 ; // futile wake throttling
duke@435 209 static int Knob_SuccRestrict = 0 ; // Limit successors + spinners to at-most-one
duke@435 210 static int Knob_MaxSpinners = -1 ; // Should be a function of # CPUs
duke@435 211 static int Knob_Bonus = 100 ; // spin success bonus
duke@435 212 static int Knob_BonusB = 100 ; // spin success bonus
duke@435 213 static int Knob_Penalty = 200 ; // spin failure penalty
duke@435 214 static int Knob_Poverty = 1000 ;
duke@435 215 static int Knob_SpinAfterFutile = 1 ; // Spin after returning from park()
duke@435 216 static int Knob_FixedSpin = 0 ;
duke@435 217 static int Knob_OState = 3 ; // Spinner checks thread state of _owner
duke@435 218 static int Knob_UsePause = 1 ;
duke@435 219 static int Knob_ExitPolicy = 0 ;
duke@435 220 static int Knob_PreSpin = 10 ; // 20-100 likely better
duke@435 221 static int Knob_ResetEvent = 0 ;
duke@435 222 static int BackOffMask = 0 ;
duke@435 223
duke@435 224 static int Knob_FastHSSEC = 0 ;
duke@435 225 static int Knob_MoveNotifyee = 2 ; // notify() - disposition of notifyee
duke@435 226 static int Knob_QMode = 0 ; // EntryList-cxq policy - queue discipline
duke@435 227 static volatile int InitDone = 0 ;
duke@435 228
duke@435 229
duke@435 230 // hashCode() generation :
duke@435 231 //
duke@435 232 // Possibilities:
duke@435 233 // * MD5Digest of {obj,stwRandom}
duke@435 234 // * CRC32 of {obj,stwRandom} or any linear-feedback shift register function.
duke@435 235 // * A DES- or AES-style SBox[] mechanism
duke@435 236 // * One of the Phi-based schemes, such as:
duke@435 237 // 2654435761 = 2^32 * Phi (golden ratio)
duke@435 238 // HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stwRandom ;
duke@435 239 // * A variation of Marsaglia's shift-xor RNG scheme.
duke@435 240 // * (obj ^ stwRandom) is appealing, but can result
duke@435 241 // in undesirable regularity in the hashCode values of adjacent objects
duke@435 242 // (objects allocated back-to-back, in particular). This could potentially
duke@435 243 // result in hashtable collisions and reduced hashtable efficiency.
duke@435 244 // There are simple ways to "diffuse" the middle address bits over the
duke@435 245 // generated hashCode values:
duke@435 246 //
duke@435 247
duke@435 248 static inline intptr_t get_next_hash(Thread * Self, oop obj) {
duke@435 249 intptr_t value = 0 ;
duke@435 250 if (hashCode == 0) {
duke@435 251 // This form uses an unguarded global Park-Miller RNG,
duke@435 252 // so it's possible for two threads to race and generate the same RNG.
duke@435 253 // On MP system we'll have lots of RW access to a global, so the
duke@435 254 // mechanism induces lots of coherency traffic.
duke@435 255 value = os::random() ;
duke@435 256 } else
duke@435 257 if (hashCode == 1) {
duke@435 258 // This variation has the property of being stable (idempotent)
duke@435 259 // between STW operations. This can be useful in some of the 1-0
duke@435 260 // synchronization schemes.
duke@435 261 intptr_t addrBits = intptr_t(obj) >> 3 ;
duke@435 262 value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom ;
duke@435 263 } else
duke@435 264 if (hashCode == 2) {
duke@435 265 value = 1 ; // for sensitivity testing
duke@435 266 } else
duke@435 267 if (hashCode == 3) {
duke@435 268 value = ++GVars.hcSequence ;
duke@435 269 } else
duke@435 270 if (hashCode == 4) {
duke@435 271 value = intptr_t(obj) ;
duke@435 272 } else {
duke@435 273 // Marsaglia's xor-shift scheme with thread-specific state
duke@435 274 // This is probably the best overall implementation -- we'll
duke@435 275 // likely make this the default in future releases.
duke@435 276 unsigned t = Self->_hashStateX ;
duke@435 277 t ^= (t << 11) ;
duke@435 278 Self->_hashStateX = Self->_hashStateY ;
duke@435 279 Self->_hashStateY = Self->_hashStateZ ;
duke@435 280 Self->_hashStateZ = Self->_hashStateW ;
duke@435 281 unsigned v = Self->_hashStateW ;
duke@435 282 v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)) ;
duke@435 283 Self->_hashStateW = v ;
duke@435 284 value = v ;
duke@435 285 }
duke@435 286
duke@435 287 value &= markOopDesc::hash_mask;
duke@435 288 if (value == 0) value = 0xBAD ;
duke@435 289 assert (value != markOopDesc::no_hash, "invariant") ;
duke@435 290 TEVENT (hashCode: GENERATE) ;
duke@435 291 return value;
duke@435 292 }
duke@435 293
duke@435 294 void BasicLock::print_on(outputStream* st) const {
duke@435 295 st->print("monitor");
duke@435 296 }
duke@435 297
duke@435 298 void BasicLock::move_to(oop obj, BasicLock* dest) {
duke@435 299 // Check to see if we need to inflate the lock. This is only needed
duke@435 300 // if an object is locked using "this" lightweight monitor. In that
duke@435 301 // case, the displaced_header() is unlocked, because the
duke@435 302 // displaced_header() contains the header for the originally unlocked
duke@435 303 // object. However the object could have already been inflated. But it
duke@435 304 // does not matter, the inflation will just a no-op. For other cases,
duke@435 305 // the displaced header will be either 0x0 or 0x3, which are location
duke@435 306 // independent, therefore the BasicLock is free to move.
duke@435 307 //
duke@435 308 // During OSR we may need to relocate a BasicLock (which contains a
duke@435 309 // displaced word) from a location in an interpreter frame to a
duke@435 310 // new location in a compiled frame. "this" refers to the source
duke@435 311 // basiclock in the interpreter frame. "dest" refers to the destination
duke@435 312 // basiclock in the new compiled frame. We *always* inflate in move_to().
duke@435 313 // The always-Inflate policy works properly, but in 1.5.0 it can sometimes
duke@435 314 // cause performance problems in code that makes heavy use of a small # of
duke@435 315 // uncontended locks. (We'd inflate during OSR, and then sync performance
duke@435 316 // would subsequently plummet because the thread would be forced thru the slow-path).
duke@435 317 // This problem has been made largely moot on IA32 by inlining the inflated fast-path
duke@435 318 // operations in Fast_Lock and Fast_Unlock in i486.ad.
duke@435 319 //
duke@435 320 // Note that there is a way to safely swing the object's markword from
duke@435 321 // one stack location to another. This avoids inflation. Obviously,
duke@435 322 // we need to ensure that both locations refer to the current thread's stack.
duke@435 323 // There are some subtle concurrency issues, however, and since the benefit is
duke@435 324 // is small (given the support for inflated fast-path locking in the fast_lock, etc)
duke@435 325 // we'll leave that optimization for another time.
duke@435 326
duke@435 327 if (displaced_header()->is_neutral()) {
duke@435 328 ObjectSynchronizer::inflate_helper(obj);
duke@435 329 // WARNING: We can not put check here, because the inflation
duke@435 330 // will not update the displaced header. Once BasicLock is inflated,
duke@435 331 // no one should ever look at its content.
duke@435 332 } else {
duke@435 333 // Typically the displaced header will be 0 (recursive stack lock) or
duke@435 334 // unused_mark. Naively we'd like to assert that the displaced mark
duke@435 335 // value is either 0, neutral, or 3. But with the advent of the
duke@435 336 // store-before-CAS avoidance in fast_lock/compiler_lock_object
duke@435 337 // we can find any flavor mark in the displaced mark.
duke@435 338 }
duke@435 339 // [RGV] The next line appears to do nothing!
duke@435 340 intptr_t dh = (intptr_t) displaced_header();
duke@435 341 dest->set_displaced_header(displaced_header());
duke@435 342 }
duke@435 343
duke@435 344 // -----------------------------------------------------------------------------
duke@435 345
duke@435 346 // standard constructor, allows locking failures
duke@435 347 ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool doLock) {
duke@435 348 _dolock = doLock;
duke@435 349 _thread = thread;
duke@435 350 debug_only(if (StrictSafepointChecks) _thread->check_for_valid_safepoint_state(false);)
duke@435 351 _obj = obj;
duke@435 352
duke@435 353 if (_dolock) {
duke@435 354 TEVENT (ObjectLocker) ;
duke@435 355
duke@435 356 ObjectSynchronizer::fast_enter(_obj, &_lock, false, _thread);
duke@435 357 }
duke@435 358 }
duke@435 359
duke@435 360 ObjectLocker::~ObjectLocker() {
duke@435 361 if (_dolock) {
duke@435 362 ObjectSynchronizer::fast_exit(_obj(), &_lock, _thread);
duke@435 363 }
duke@435 364 }
duke@435 365
duke@435 366 // -----------------------------------------------------------------------------
duke@435 367
duke@435 368
duke@435 369 PerfCounter * ObjectSynchronizer::_sync_Inflations = NULL ;
duke@435 370 PerfCounter * ObjectSynchronizer::_sync_Deflations = NULL ;
duke@435 371 PerfCounter * ObjectSynchronizer::_sync_ContendedLockAttempts = NULL ;
duke@435 372 PerfCounter * ObjectSynchronizer::_sync_FutileWakeups = NULL ;
duke@435 373 PerfCounter * ObjectSynchronizer::_sync_Parks = NULL ;
duke@435 374 PerfCounter * ObjectSynchronizer::_sync_EmptyNotifications = NULL ;
duke@435 375 PerfCounter * ObjectSynchronizer::_sync_Notifications = NULL ;
duke@435 376 PerfCounter * ObjectSynchronizer::_sync_PrivateA = NULL ;
duke@435 377 PerfCounter * ObjectSynchronizer::_sync_PrivateB = NULL ;
duke@435 378 PerfCounter * ObjectSynchronizer::_sync_SlowExit = NULL ;
duke@435 379 PerfCounter * ObjectSynchronizer::_sync_SlowEnter = NULL ;
duke@435 380 PerfCounter * ObjectSynchronizer::_sync_SlowNotify = NULL ;
duke@435 381 PerfCounter * ObjectSynchronizer::_sync_SlowNotifyAll = NULL ;
duke@435 382 PerfCounter * ObjectSynchronizer::_sync_FailedSpins = NULL ;
duke@435 383 PerfCounter * ObjectSynchronizer::_sync_SuccessfulSpins = NULL ;
duke@435 384 PerfCounter * ObjectSynchronizer::_sync_MonInCirculation = NULL ;
duke@435 385 PerfCounter * ObjectSynchronizer::_sync_MonScavenged = NULL ;
duke@435 386 PerfLongVariable * ObjectSynchronizer::_sync_MonExtant = NULL ;
duke@435 387
duke@435 388 // One-shot global initialization for the sync subsystem.
duke@435 389 // We could also defer initialization and initialize on-demand
duke@435 390 // the first time we call inflate(). Initialization would
duke@435 391 // be protected - like so many things - by the MonitorCache_lock.
duke@435 392
duke@435 393 void ObjectSynchronizer::Initialize () {
duke@435 394 static int InitializationCompleted = 0 ;
duke@435 395 assert (InitializationCompleted == 0, "invariant") ;
duke@435 396 InitializationCompleted = 1 ;
duke@435 397 if (UsePerfData) {
duke@435 398 EXCEPTION_MARK ;
duke@435 399 #define NEWPERFCOUNTER(n) {n = PerfDataManager::create_counter(SUN_RT, #n, PerfData::U_Events,CHECK); }
duke@435 400 #define NEWPERFVARIABLE(n) {n = PerfDataManager::create_variable(SUN_RT, #n, PerfData::U_Events,CHECK); }
duke@435 401 NEWPERFCOUNTER(_sync_Inflations) ;
duke@435 402 NEWPERFCOUNTER(_sync_Deflations) ;
duke@435 403 NEWPERFCOUNTER(_sync_ContendedLockAttempts) ;
duke@435 404 NEWPERFCOUNTER(_sync_FutileWakeups) ;
duke@435 405 NEWPERFCOUNTER(_sync_Parks) ;
duke@435 406 NEWPERFCOUNTER(_sync_EmptyNotifications) ;
duke@435 407 NEWPERFCOUNTER(_sync_Notifications) ;
duke@435 408 NEWPERFCOUNTER(_sync_SlowEnter) ;
duke@435 409 NEWPERFCOUNTER(_sync_SlowExit) ;
duke@435 410 NEWPERFCOUNTER(_sync_SlowNotify) ;
duke@435 411 NEWPERFCOUNTER(_sync_SlowNotifyAll) ;
duke@435 412 NEWPERFCOUNTER(_sync_FailedSpins) ;
duke@435 413 NEWPERFCOUNTER(_sync_SuccessfulSpins) ;
duke@435 414 NEWPERFCOUNTER(_sync_PrivateA) ;
duke@435 415 NEWPERFCOUNTER(_sync_PrivateB) ;
duke@435 416 NEWPERFCOUNTER(_sync_MonInCirculation) ;
duke@435 417 NEWPERFCOUNTER(_sync_MonScavenged) ;
duke@435 418 NEWPERFVARIABLE(_sync_MonExtant) ;
duke@435 419 #undef NEWPERFCOUNTER
duke@435 420 }
duke@435 421 }
duke@435 422
duke@435 423 // Compile-time asserts
duke@435 424 // When possible, it's better to catch errors deterministically at
duke@435 425 // compile-time than at runtime. The down-side to using compile-time
duke@435 426 // asserts is that error message -- often something about negative array
duke@435 427 // indices -- is opaque.
duke@435 428
xlu@948 429 #define CTASSERT(x) { int tag[1-(2*!(x))]; printf ("Tag @" INTPTR_FORMAT "\n", (intptr_t)tag); }
duke@435 430
duke@435 431 void ObjectMonitor::ctAsserts() {
duke@435 432 CTASSERT(offset_of (ObjectMonitor, _header) == 0);
duke@435 433 }
duke@435 434
duke@435 435 static int Adjust (volatile int * adr, int dx) {
duke@435 436 int v ;
duke@435 437 for (v = *adr ; Atomic::cmpxchg (v + dx, adr, v) != v; v = *adr) ;
duke@435 438 return v ;
duke@435 439 }
duke@435 440
duke@435 441 // Ad-hoc mutual exclusion primitives: SpinLock and Mux
duke@435 442 //
duke@435 443 // We employ SpinLocks _only for low-contention, fixed-length
duke@435 444 // short-duration critical sections where we're concerned
duke@435 445 // about native mutex_t or HotSpot Mutex:: latency.
duke@435 446 // The mux construct provides a spin-then-block mutual exclusion
duke@435 447 // mechanism.
duke@435 448 //
duke@435 449 // Testing has shown that contention on the ListLock guarding gFreeList
duke@435 450 // is common. If we implement ListLock as a simple SpinLock it's common
duke@435 451 // for the JVM to devolve to yielding with little progress. This is true
duke@435 452 // despite the fact that the critical sections protected by ListLock are
duke@435 453 // extremely short.
duke@435 454 //
duke@435 455 // TODO-FIXME: ListLock should be of type SpinLock.
duke@435 456 // We should make this a 1st-class type, integrated into the lock
duke@435 457 // hierarchy as leaf-locks. Critically, the SpinLock structure
duke@435 458 // should have sufficient padding to avoid false-sharing and excessive
duke@435 459 // cache-coherency traffic.
duke@435 460
duke@435 461
duke@435 462 typedef volatile int SpinLockT ;
duke@435 463
duke@435 464 void Thread::SpinAcquire (volatile int * adr, const char * LockName) {
duke@435 465 if (Atomic::cmpxchg (1, adr, 0) == 0) {
duke@435 466 return ; // normal fast-path return
duke@435 467 }
duke@435 468
duke@435 469 // Slow-path : We've encountered contention -- Spin/Yield/Block strategy.
duke@435 470 TEVENT (SpinAcquire - ctx) ;
duke@435 471 int ctr = 0 ;
duke@435 472 int Yields = 0 ;
duke@435 473 for (;;) {
duke@435 474 while (*adr != 0) {
duke@435 475 ++ctr ;
duke@435 476 if ((ctr & 0xFFF) == 0 || !os::is_MP()) {
duke@435 477 if (Yields > 5) {
duke@435 478 // Consider using a simple NakedSleep() instead.
duke@435 479 // Then SpinAcquire could be called by non-JVM threads
duke@435 480 Thread::current()->_ParkEvent->park(1) ;
duke@435 481 } else {
duke@435 482 os::NakedYield() ;
duke@435 483 ++Yields ;
duke@435 484 }
duke@435 485 } else {
duke@435 486 SpinPause() ;
duke@435 487 }
duke@435 488 }
duke@435 489 if (Atomic::cmpxchg (1, adr, 0) == 0) return ;
duke@435 490 }
duke@435 491 }
duke@435 492
duke@435 493 void Thread::SpinRelease (volatile int * adr) {
duke@435 494 assert (*adr != 0, "invariant") ;
duke@435 495 OrderAccess::fence() ; // guarantee at least release consistency.
duke@435 496 // Roach-motel semantics.
duke@435 497 // It's safe if subsequent LDs and STs float "up" into the critical section,
duke@435 498 // but prior LDs and STs within the critical section can't be allowed
duke@435 499 // to reorder or float past the ST that releases the lock.
duke@435 500 *adr = 0 ;
duke@435 501 }
duke@435 502
duke@435 503 // muxAcquire and muxRelease:
duke@435 504 //
duke@435 505 // * muxAcquire and muxRelease support a single-word lock-word construct.
duke@435 506 // The LSB of the word is set IFF the lock is held.
duke@435 507 // The remainder of the word points to the head of a singly-linked list
duke@435 508 // of threads blocked on the lock.
duke@435 509 //
duke@435 510 // * The current implementation of muxAcquire-muxRelease uses its own
duke@435 511 // dedicated Thread._MuxEvent instance. If we're interested in
duke@435 512 // minimizing the peak number of extant ParkEvent instances then
duke@435 513 // we could eliminate _MuxEvent and "borrow" _ParkEvent as long
duke@435 514 // as certain invariants were satisfied. Specifically, care would need
duke@435 515 // to be taken with regards to consuming unpark() "permits".
duke@435 516 // A safe rule of thumb is that a thread would never call muxAcquire()
duke@435 517 // if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently
duke@435 518 // park(). Otherwise the _ParkEvent park() operation in muxAcquire() could
duke@435 519 // consume an unpark() permit intended for monitorenter, for instance.
duke@435 520 // One way around this would be to widen the restricted-range semaphore
duke@435 521 // implemented in park(). Another alternative would be to provide
duke@435 522 // multiple instances of the PlatformEvent() for each thread. One
duke@435 523 // instance would be dedicated to muxAcquire-muxRelease, for instance.
duke@435 524 //
duke@435 525 // * Usage:
duke@435 526 // -- Only as leaf locks
duke@435 527 // -- for short-term locking only as muxAcquire does not perform
duke@435 528 // thread state transitions.
duke@435 529 //
duke@435 530 // Alternatives:
duke@435 531 // * We could implement muxAcquire and muxRelease with MCS or CLH locks
duke@435 532 // but with parking or spin-then-park instead of pure spinning.
duke@435 533 // * Use Taura-Oyama-Yonenzawa locks.
duke@435 534 // * It's possible to construct a 1-0 lock if we encode the lockword as
duke@435 535 // (List,LockByte). Acquire will CAS the full lockword while Release
duke@435 536 // will STB 0 into the LockByte. The 1-0 scheme admits stranding, so
duke@435 537 // acquiring threads use timers (ParkTimed) to detect and recover from
duke@435 538 // the stranding window. Thread/Node structures must be aligned on 256-byte
duke@435 539 // boundaries by using placement-new.
duke@435 540 // * Augment MCS with advisory back-link fields maintained with CAS().
duke@435 541 // Pictorially: LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner.
duke@435 542 // The validity of the backlinks must be ratified before we trust the value.
duke@435 543 // If the backlinks are invalid the exiting thread must back-track through the
duke@435 544 // the forward links, which are always trustworthy.
duke@435 545 // * Add a successor indication. The LockWord is currently encoded as
duke@435 546 // (List, LOCKBIT:1). We could also add a SUCCBIT or an explicit _succ variable
duke@435 547 // to provide the usual futile-wakeup optimization.
duke@435 548 // See RTStt for details.
duke@435 549 // * Consider schedctl.sc_nopreempt to cover the critical section.
duke@435 550 //
duke@435 551
duke@435 552
duke@435 553 typedef volatile intptr_t MutexT ; // Mux Lock-word
duke@435 554 enum MuxBits { LOCKBIT = 1 } ;
duke@435 555
duke@435 556 void Thread::muxAcquire (volatile intptr_t * Lock, const char * LockName) {
duke@435 557 intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ;
duke@435 558 if (w == 0) return ;
duke@435 559 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
duke@435 560 return ;
duke@435 561 }
duke@435 562
duke@435 563 TEVENT (muxAcquire - Contention) ;
duke@435 564 ParkEvent * const Self = Thread::current()->_MuxEvent ;
duke@435 565 assert ((intptr_t(Self) & LOCKBIT) == 0, "invariant") ;
duke@435 566 for (;;) {
duke@435 567 int its = (os::is_MP() ? 100 : 0) + 1 ;
duke@435 568
duke@435 569 // Optional spin phase: spin-then-park strategy
duke@435 570 while (--its >= 0) {
duke@435 571 w = *Lock ;
duke@435 572 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
duke@435 573 return ;
duke@435 574 }
duke@435 575 }
duke@435 576
duke@435 577 Self->reset() ;
duke@435 578 Self->OnList = intptr_t(Lock) ;
duke@435 579 // The following fence() isn't _strictly necessary as the subsequent
duke@435 580 // CAS() both serializes execution and ratifies the fetched *Lock value.
duke@435 581 OrderAccess::fence();
duke@435 582 for (;;) {
duke@435 583 w = *Lock ;
duke@435 584 if ((w & LOCKBIT) == 0) {
duke@435 585 if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
duke@435 586 Self->OnList = 0 ; // hygiene - allows stronger asserts
duke@435 587 return ;
duke@435 588 }
duke@435 589 continue ; // Interference -- *Lock changed -- Just retry
duke@435 590 }
duke@435 591 assert (w & LOCKBIT, "invariant") ;
duke@435 592 Self->ListNext = (ParkEvent *) (w & ~LOCKBIT );
duke@435 593 if (Atomic::cmpxchg_ptr (intptr_t(Self)|LOCKBIT, Lock, w) == w) break ;
duke@435 594 }
duke@435 595
duke@435 596 while (Self->OnList != 0) {
duke@435 597 Self->park() ;
duke@435 598 }
duke@435 599 }
duke@435 600 }
duke@435 601
duke@435 602 void Thread::muxAcquireW (volatile intptr_t * Lock, ParkEvent * ev) {
duke@435 603 intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ;
duke@435 604 if (w == 0) return ;
duke@435 605 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
duke@435 606 return ;
duke@435 607 }
duke@435 608
duke@435 609 TEVENT (muxAcquire - Contention) ;
duke@435 610 ParkEvent * ReleaseAfter = NULL ;
duke@435 611 if (ev == NULL) {
duke@435 612 ev = ReleaseAfter = ParkEvent::Allocate (NULL) ;
duke@435 613 }
duke@435 614 assert ((intptr_t(ev) & LOCKBIT) == 0, "invariant") ;
duke@435 615 for (;;) {
duke@435 616 guarantee (ev->OnList == 0, "invariant") ;
duke@435 617 int its = (os::is_MP() ? 100 : 0) + 1 ;
duke@435 618
duke@435 619 // Optional spin phase: spin-then-park strategy
duke@435 620 while (--its >= 0) {
duke@435 621 w = *Lock ;
duke@435 622 if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
duke@435 623 if (ReleaseAfter != NULL) {
duke@435 624 ParkEvent::Release (ReleaseAfter) ;
duke@435 625 }
duke@435 626 return ;
duke@435 627 }
duke@435 628 }
duke@435 629
duke@435 630 ev->reset() ;
duke@435 631 ev->OnList = intptr_t(Lock) ;
duke@435 632 // The following fence() isn't _strictly necessary as the subsequent
duke@435 633 // CAS() both serializes execution and ratifies the fetched *Lock value.
duke@435 634 OrderAccess::fence();
duke@435 635 for (;;) {
duke@435 636 w = *Lock ;
duke@435 637 if ((w & LOCKBIT) == 0) {
duke@435 638 if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
duke@435 639 ev->OnList = 0 ;
duke@435 640 // We call ::Release while holding the outer lock, thus
duke@435 641 // artificially lengthening the critical section.
duke@435 642 // Consider deferring the ::Release() until the subsequent unlock(),
duke@435 643 // after we've dropped the outer lock.
duke@435 644 if (ReleaseAfter != NULL) {
duke@435 645 ParkEvent::Release (ReleaseAfter) ;
duke@435 646 }
duke@435 647 return ;
duke@435 648 }
duke@435 649 continue ; // Interference -- *Lock changed -- Just retry
duke@435 650 }
duke@435 651 assert (w & LOCKBIT, "invariant") ;
duke@435 652 ev->ListNext = (ParkEvent *) (w & ~LOCKBIT );
duke@435 653 if (Atomic::cmpxchg_ptr (intptr_t(ev)|LOCKBIT, Lock, w) == w) break ;
duke@435 654 }
duke@435 655
duke@435 656 while (ev->OnList != 0) {
duke@435 657 ev->park() ;
duke@435 658 }
duke@435 659 }
duke@435 660 }
duke@435 661
duke@435 662 // Release() must extract a successor from the list and then wake that thread.
duke@435 663 // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme
duke@435 664 // similar to that used by ParkEvent::Allocate() and ::Release(). DMR-based
duke@435 665 // Release() would :
duke@435 666 // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list.
duke@435 667 // (B) Extract a successor from the private list "in-hand"
duke@435 668 // (C) attempt to CAS() the residual back into *Lock over null.
duke@435 669 // If there were any newly arrived threads and the CAS() would fail.
duke@435 670 // In that case Release() would detach the RATs, re-merge the list in-hand
duke@435 671 // with the RATs and repeat as needed. Alternately, Release() might
duke@435 672 // detach and extract a successor, but then pass the residual list to the wakee.
duke@435 673 // The wakee would be responsible for reattaching and remerging before it
duke@435 674 // competed for the lock.
duke@435 675 //
duke@435 676 // Both "pop" and DMR are immune from ABA corruption -- there can be
duke@435 677 // multiple concurrent pushers, but only one popper or detacher.
duke@435 678 // This implementation pops from the head of the list. This is unfair,
duke@435 679 // but tends to provide excellent throughput as hot threads remain hot.
duke@435 680 // (We wake recently run threads first).
duke@435 681
duke@435 682 void Thread::muxRelease (volatile intptr_t * Lock) {
duke@435 683 for (;;) {
duke@435 684 const intptr_t w = Atomic::cmpxchg_ptr (0, Lock, LOCKBIT) ;
duke@435 685 assert (w & LOCKBIT, "invariant") ;
duke@435 686 if (w == LOCKBIT) return ;
duke@435 687 ParkEvent * List = (ParkEvent *) (w & ~LOCKBIT) ;
duke@435 688 assert (List != NULL, "invariant") ;
duke@435 689 assert (List->OnList == intptr_t(Lock), "invariant") ;
duke@435 690 ParkEvent * nxt = List->ListNext ;
duke@435 691
duke@435 692 // The following CAS() releases the lock and pops the head element.
duke@435 693 if (Atomic::cmpxchg_ptr (intptr_t(nxt), Lock, w) != w) {
duke@435 694 continue ;
duke@435 695 }
duke@435 696 List->OnList = 0 ;
duke@435 697 OrderAccess::fence() ;
duke@435 698 List->unpark () ;
duke@435 699 return ;
duke@435 700 }
duke@435 701 }
duke@435 702
duke@435 703 // ObjectMonitor Lifecycle
duke@435 704 // -----------------------
duke@435 705 // Inflation unlinks monitors from the global gFreeList and
duke@435 706 // associates them with objects. Deflation -- which occurs at
duke@435 707 // STW-time -- disassociates idle monitors from objects. Such
duke@435 708 // scavenged monitors are returned to the gFreeList.
duke@435 709 //
duke@435 710 // The global list is protected by ListLock. All the critical sections
duke@435 711 // are short and operate in constant-time.
duke@435 712 //
duke@435 713 // ObjectMonitors reside in type-stable memory (TSM) and are immortal.
duke@435 714 //
duke@435 715 // Lifecycle:
duke@435 716 // -- unassigned and on the global free list
duke@435 717 // -- unassigned and on a thread's private omFreeList
duke@435 718 // -- assigned to an object. The object is inflated and the mark refers
duke@435 719 // to the objectmonitor.
duke@435 720 //
duke@435 721 // TODO-FIXME:
duke@435 722 //
duke@435 723 // * We currently protect the gFreeList with a simple lock.
duke@435 724 // An alternate lock-free scheme would be to pop elements from the gFreeList
duke@435 725 // with CAS. This would be safe from ABA corruption as long we only
duke@435 726 // recycled previously appearing elements onto the list in deflate_idle_monitors()
duke@435 727 // at STW-time. Completely new elements could always be pushed onto the gFreeList
duke@435 728 // with CAS. Elements that appeared previously on the list could only
duke@435 729 // be installed at STW-time.
duke@435 730 //
duke@435 731 // * For efficiency and to help reduce the store-before-CAS penalty
duke@435 732 // the objectmonitors on gFreeList or local free lists should be ready to install
duke@435 733 // with the exception of _header and _object. _object can be set after inflation.
duke@435 734 // In particular, keep all objectMonitors on a thread's private list in ready-to-install
duke@435 735 // state with m.Owner set properly.
duke@435 736 //
duke@435 737 // * We could all diffuse contention by using multiple global (FreeList, Lock)
duke@435 738 // pairs -- threads could use trylock() and a cyclic-scan strategy to search for
duke@435 739 // an unlocked free list.
duke@435 740 //
duke@435 741 // * Add lifecycle tags and assert()s.
duke@435 742 //
duke@435 743 // * Be more consistent about when we clear an objectmonitor's fields:
duke@435 744 // A. After extracting the objectmonitor from a free list.
duke@435 745 // B. After adding an objectmonitor to a free list.
duke@435 746 //
duke@435 747
duke@435 748 ObjectMonitor * ObjectSynchronizer::gBlockList = NULL ;
duke@435 749 ObjectMonitor * volatile ObjectSynchronizer::gFreeList = NULL ;
duke@435 750 static volatile intptr_t ListLock = 0 ; // protects global monitor free-list cache
acorn@1942 751 static volatile int MonitorFreeCount = 0 ; // # on gFreeList
acorn@1942 752 static volatile int MonitorPopulation = 0 ; // # Extant -- in circulation
duke@435 753 #define CHAINMARKER ((oop)-1)
duke@435 754
acorn@1942 755 // Constraining monitor pool growth via MonitorBound ...
acorn@1942 756 //
acorn@1942 757 // The monitor pool is grow-only. We scavenge at STW safepoint-time, but the
acorn@1942 758 // the rate of scavenging is driven primarily by GC. As such, we can find
acorn@1942 759 // an inordinate number of monitors in circulation.
acorn@1942 760 // To avoid that scenario we can artificially induce a STW safepoint
acorn@1942 761 // if the pool appears to be growing past some reasonable bound.
acorn@1942 762 // Generally we favor time in space-time tradeoffs, but as there's no
acorn@1942 763 // natural back-pressure on the # of extant monitors we need to impose some
acorn@1942 764 // type of limit. Beware that if MonitorBound is set to too low a value
acorn@1942 765 // we could just loop. In addition, if MonitorBound is set to a low value
acorn@1942 766 // we'll incur more safepoints, which are harmful to performance.
acorn@1942 767 // See also: GuaranteedSafepointInterval
acorn@1942 768 //
acorn@1942 769 // As noted elsewhere, the correct long-term solution is to deflate at
acorn@1942 770 // monitorexit-time, in which case the number of inflated objects is bounded
acorn@1942 771 // by the number of threads. That policy obviates the need for scavenging at
acorn@1942 772 // STW safepoint time. As an aside, scavenging can be time-consuming when the
acorn@1942 773 // # of extant monitors is large. Unfortunately there's a day-1 assumption baked
acorn@1942 774 // into much HotSpot code that the object::monitor relationship, once established
acorn@1942 775 // or observed, will remain stable except over potential safepoints.
acorn@1942 776 //
acorn@1942 777 // We can use either a blocking synchronous VM operation or an async VM operation.
acorn@1942 778 // -- If we use a blocking VM operation :
acorn@1942 779 // Calls to ScavengeCheck() should be inserted only into 'safe' locations in paths
acorn@1942 780 // that lead to ::inflate() or ::omAlloc().
acorn@1942 781 // Even though the safepoint will not directly induce GC, a GC might
acorn@1942 782 // piggyback on the safepoint operation, so the caller should hold no naked oops.
acorn@1942 783 // Furthermore, monitor::object relationships are NOT necessarily stable over this call
acorn@1942 784 // unless the caller has made provisions to "pin" the object to the monitor, say
acorn@1942 785 // by incrementing the monitor's _count field.
acorn@1942 786 // -- If we use a non-blocking asynchronous VM operation :
acorn@1942 787 // the constraints above don't apply. The safepoint will fire in the future
acorn@1942 788 // at a more convenient time. On the other hand the latency between posting and
acorn@1942 789 // running the safepoint introduces or admits "slop" or laxity during which the
acorn@1942 790 // monitor population can climb further above the threshold. The monitor population,
acorn@1942 791 // however, tends to converge asymptotically over time to a count that's slightly
acorn@1942 792 // above the target value specified by MonitorBound. That is, we avoid unbounded
acorn@1942 793 // growth, albeit with some imprecision.
acorn@1942 794 //
acorn@1942 795 // The current implementation uses asynchronous VM operations.
acorn@1942 796 //
acorn@1942 797 // Ideally we'd check if (MonitorPopulation > MonitorBound) in omAlloc()
acorn@1942 798 // immediately before trying to grow the global list via allocation.
acorn@1942 799 // If the predicate was true then we'd induce a synchronous safepoint, wait
acorn@1942 800 // for the safepoint to complete, and then again to allocate from the global
acorn@1942 801 // free list. This approach is much simpler and precise, admitting no "slop".
acorn@1942 802 // Unfortunately we can't safely safepoint in the midst of omAlloc(), so
acorn@1942 803 // instead we use asynchronous safepoints.
acorn@1942 804
acorn@1942 805 static void InduceScavenge (Thread * Self, const char * Whence) {
acorn@1942 806 // Induce STW safepoint to trim monitors
acorn@1942 807 // Ultimately, this results in a call to deflate_idle_monitors() in the near future.
acorn@1942 808 // More precisely, trigger an asynchronous STW safepoint as the number
acorn@1942 809 // of active monitors passes the specified threshold.
acorn@1942 810 // TODO: assert thread state is reasonable
acorn@1942 811
acorn@1942 812 if (ForceMonitorScavenge == 0 && Atomic::xchg (1, &ForceMonitorScavenge) == 0) {
acorn@1942 813 if (Knob_Verbose) {
acorn@1942 814 ::printf ("Monitor scavenge - Induced STW @%s (%d)\n", Whence, ForceMonitorScavenge) ;
acorn@1942 815 ::fflush(stdout) ;
acorn@1942 816 }
acorn@1942 817 // Induce a 'null' safepoint to scavenge monitors
acorn@1942 818 // Must VM_Operation instance be heap allocated as the op will be enqueue and posted
acorn@1942 819 // to the VMthread and have a lifespan longer than that of this activation record.
acorn@1942 820 // The VMThread will delete the op when completed.
acorn@1942 821 VMThread::execute (new VM_ForceAsyncSafepoint()) ;
acorn@1942 822
acorn@1942 823 if (Knob_Verbose) {
acorn@1942 824 ::printf ("Monitor scavenge - STW posted @%s (%d)\n", Whence, ForceMonitorScavenge) ;
acorn@1942 825 ::fflush(stdout) ;
acorn@1942 826 }
acorn@1942 827 }
acorn@1942 828 }
acorn@1942 829
duke@435 830 ObjectMonitor * ATTR ObjectSynchronizer::omAlloc (Thread * Self) {
duke@435 831 // A large MAXPRIVATE value reduces both list lock contention
duke@435 832 // and list coherency traffic, but also tends to increase the
duke@435 833 // number of objectMonitors in circulation as well as the STW
duke@435 834 // scavenge costs. As usual, we lean toward time in space-time
duke@435 835 // tradeoffs.
duke@435 836 const int MAXPRIVATE = 1024 ;
duke@435 837 for (;;) {
duke@435 838 ObjectMonitor * m ;
duke@435 839
duke@435 840 // 1: try to allocate from the thread's local omFreeList.
duke@435 841 // Threads will attempt to allocate first from their local list, then
duke@435 842 // from the global list, and only after those attempts fail will the thread
duke@435 843 // attempt to instantiate new monitors. Thread-local free lists take
duke@435 844 // heat off the ListLock and improve allocation latency, as well as reducing
duke@435 845 // coherency traffic on the shared global list.
duke@435 846 m = Self->omFreeList ;
duke@435 847 if (m != NULL) {
duke@435 848 Self->omFreeList = m->FreeNext ;
duke@435 849 Self->omFreeCount -- ;
duke@435 850 // CONSIDER: set m->FreeNext = BAD -- diagnostic hygiene
duke@435 851 guarantee (m->object() == NULL, "invariant") ;
acorn@1942 852 if (MonitorInUseLists) {
acorn@1942 853 m->FreeNext = Self->omInUseList;
acorn@1942 854 Self->omInUseList = m;
acorn@1942 855 Self->omInUseCount ++;
acorn@1942 856 }
duke@435 857 return m ;
duke@435 858 }
duke@435 859
duke@435 860 // 2: try to allocate from the global gFreeList
duke@435 861 // CONSIDER: use muxTry() instead of muxAcquire().
duke@435 862 // If the muxTry() fails then drop immediately into case 3.
duke@435 863 // If we're using thread-local free lists then try
duke@435 864 // to reprovision the caller's free list.
duke@435 865 if (gFreeList != NULL) {
duke@435 866 // Reprovision the thread's omFreeList.
duke@435 867 // Use bulk transfers to reduce the allocation rate and heat
duke@435 868 // on various locks.
duke@435 869 Thread::muxAcquire (&ListLock, "omAlloc") ;
duke@435 870 for (int i = Self->omFreeProvision; --i >= 0 && gFreeList != NULL; ) {
acorn@1942 871 MonitorFreeCount --;
duke@435 872 ObjectMonitor * take = gFreeList ;
duke@435 873 gFreeList = take->FreeNext ;
duke@435 874 guarantee (take->object() == NULL, "invariant") ;
duke@435 875 guarantee (!take->is_busy(), "invariant") ;
duke@435 876 take->Recycle() ;
duke@435 877 omRelease (Self, take) ;
duke@435 878 }
duke@435 879 Thread::muxRelease (&ListLock) ;
duke@435 880 Self->omFreeProvision += 1 + (Self->omFreeProvision/2) ;
duke@435 881 if (Self->omFreeProvision > MAXPRIVATE ) Self->omFreeProvision = MAXPRIVATE ;
duke@435 882 TEVENT (omFirst - reprovision) ;
duke@435 883 continue ;
acorn@1942 884
acorn@1942 885 const int mx = MonitorBound ;
acorn@1942 886 if (mx > 0 && (MonitorPopulation-MonitorFreeCount) > mx) {
acorn@1942 887 // We can't safely induce a STW safepoint from omAlloc() as our thread
acorn@1942 888 // state may not be appropriate for such activities and callers may hold
acorn@1942 889 // naked oops, so instead we defer the action.
acorn@1942 890 InduceScavenge (Self, "omAlloc") ;
acorn@1942 891 }
acorn@1942 892 continue;
duke@435 893 }
duke@435 894
duke@435 895 // 3: allocate a block of new ObjectMonitors
duke@435 896 // Both the local and global free lists are empty -- resort to malloc().
duke@435 897 // In the current implementation objectMonitors are TSM - immortal.
duke@435 898 assert (_BLOCKSIZE > 1, "invariant") ;
duke@435 899 ObjectMonitor * temp = new ObjectMonitor[_BLOCKSIZE];
duke@435 900
duke@435 901 // NOTE: (almost) no way to recover if allocation failed.
duke@435 902 // We might be able to induce a STW safepoint and scavenge enough
duke@435 903 // objectMonitors to permit progress.
duke@435 904 if (temp == NULL) {
duke@435 905 vm_exit_out_of_memory (sizeof (ObjectMonitor[_BLOCKSIZE]), "Allocate ObjectMonitors") ;
duke@435 906 }
duke@435 907
duke@435 908 // Format the block.
duke@435 909 // initialize the linked list, each monitor points to its next
duke@435 910 // forming the single linked free list, the very first monitor
duke@435 911 // will points to next block, which forms the block list.
duke@435 912 // The trick of using the 1st element in the block as gBlockList
duke@435 913 // linkage should be reconsidered. A better implementation would
duke@435 914 // look like: class Block { Block * next; int N; ObjectMonitor Body [N] ; }
duke@435 915
duke@435 916 for (int i = 1; i < _BLOCKSIZE ; i++) {
duke@435 917 temp[i].FreeNext = &temp[i+1];
duke@435 918 }
duke@435 919
duke@435 920 // terminate the last monitor as the end of list
duke@435 921 temp[_BLOCKSIZE - 1].FreeNext = NULL ;
duke@435 922
duke@435 923 // Element [0] is reserved for global list linkage
duke@435 924 temp[0].set_object(CHAINMARKER);
duke@435 925
duke@435 926 // Consider carving out this thread's current request from the
duke@435 927 // block in hand. This avoids some lock traffic and redundant
duke@435 928 // list activity.
duke@435 929
duke@435 930 // Acquire the ListLock to manipulate BlockList and FreeList.
duke@435 931 // An Oyama-Taura-Yonezawa scheme might be more efficient.
duke@435 932 Thread::muxAcquire (&ListLock, "omAlloc [2]") ;
acorn@1942 933 MonitorPopulation += _BLOCKSIZE-1;
acorn@1942 934 MonitorFreeCount += _BLOCKSIZE-1;
duke@435 935
duke@435 936 // Add the new block to the list of extant blocks (gBlockList).
duke@435 937 // The very first objectMonitor in a block is reserved and dedicated.
duke@435 938 // It serves as blocklist "next" linkage.
duke@435 939 temp[0].FreeNext = gBlockList;
duke@435 940 gBlockList = temp;
duke@435 941
duke@435 942 // Add the new string of objectMonitors to the global free list
duke@435 943 temp[_BLOCKSIZE - 1].FreeNext = gFreeList ;
duke@435 944 gFreeList = temp + 1;
duke@435 945 Thread::muxRelease (&ListLock) ;
duke@435 946 TEVENT (Allocate block of monitors) ;
duke@435 947 }
duke@435 948 }
duke@435 949
duke@435 950 // Place "m" on the caller's private per-thread omFreeList.
duke@435 951 // In practice there's no need to clamp or limit the number of
duke@435 952 // monitors on a thread's omFreeList as the only time we'll call
duke@435 953 // omRelease is to return a monitor to the free list after a CAS
duke@435 954 // attempt failed. This doesn't allow unbounded #s of monitors to
duke@435 955 // accumulate on a thread's free list.
duke@435 956 //
duke@435 957 // In the future the usage of omRelease() might change and monitors
duke@435 958 // could migrate between free lists. In that case to avoid excessive
duke@435 959 // accumulation we could limit omCount to (omProvision*2), otherwise return
duke@435 960 // the objectMonitor to the global list. We should drain (return) in reasonable chunks.
duke@435 961 // That is, *not* one-at-a-time.
duke@435 962
duke@435 963
duke@435 964 void ObjectSynchronizer::omRelease (Thread * Self, ObjectMonitor * m) {
duke@435 965 guarantee (m->object() == NULL, "invariant") ;
duke@435 966 m->FreeNext = Self->omFreeList ;
duke@435 967 Self->omFreeList = m ;
duke@435 968 Self->omFreeCount ++ ;
duke@435 969 }
duke@435 970
duke@435 971 // Return the monitors of a moribund thread's local free list to
duke@435 972 // the global free list. Typically a thread calls omFlush() when
duke@435 973 // it's dying. We could also consider having the VM thread steal
duke@435 974 // monitors from threads that have not run java code over a few
duke@435 975 // consecutive STW safepoints. Relatedly, we might decay
duke@435 976 // omFreeProvision at STW safepoints.
duke@435 977 //
duke@435 978 // We currently call omFlush() from the Thread:: dtor _after the thread
duke@435 979 // has been excised from the thread list and is no longer a mutator.
duke@435 980 // That means that omFlush() can run concurrently with a safepoint and
duke@435 981 // the scavenge operator. Calling omFlush() from JavaThread::exit() might
duke@435 982 // be a better choice as we could safely reason that that the JVM is
duke@435 983 // not at a safepoint at the time of the call, and thus there could
duke@435 984 // be not inopportune interleavings between omFlush() and the scavenge
duke@435 985 // operator.
duke@435 986
duke@435 987 void ObjectSynchronizer::omFlush (Thread * Self) {
duke@435 988 ObjectMonitor * List = Self->omFreeList ; // Null-terminated SLL
duke@435 989 Self->omFreeList = NULL ;
duke@435 990 if (List == NULL) return ;
duke@435 991 ObjectMonitor * Tail = NULL ;
duke@435 992 ObjectMonitor * s ;
acorn@1942 993 int Tally = 0;
duke@435 994 for (s = List ; s != NULL ; s = s->FreeNext) {
acorn@1942 995 Tally ++ ;
duke@435 996 Tail = s ;
duke@435 997 guarantee (s->object() == NULL, "invariant") ;
duke@435 998 guarantee (!s->is_busy(), "invariant") ;
duke@435 999 s->set_owner (NULL) ; // redundant but good hygiene
duke@435 1000 TEVENT (omFlush - Move one) ;
duke@435 1001 }
duke@435 1002
duke@435 1003 guarantee (Tail != NULL && List != NULL, "invariant") ;
duke@435 1004 Thread::muxAcquire (&ListLock, "omFlush") ;
duke@435 1005 Tail->FreeNext = gFreeList ;
duke@435 1006 gFreeList = List ;
acorn@1942 1007 MonitorFreeCount += Tally;
duke@435 1008 Thread::muxRelease (&ListLock) ;
duke@435 1009 TEVENT (omFlush) ;
duke@435 1010 }
duke@435 1011
duke@435 1012
duke@435 1013 // Get the next block in the block list.
duke@435 1014 static inline ObjectMonitor* next(ObjectMonitor* block) {
duke@435 1015 assert(block->object() == CHAINMARKER, "must be a block header");
duke@435 1016 block = block->FreeNext ;
duke@435 1017 assert(block == NULL || block->object() == CHAINMARKER, "must be a block header");
duke@435 1018 return block;
duke@435 1019 }
duke@435 1020
duke@435 1021 // Fast path code shared by multiple functions
duke@435 1022 ObjectMonitor* ObjectSynchronizer::inflate_helper(oop obj) {
duke@435 1023 markOop mark = obj->mark();
duke@435 1024 if (mark->has_monitor()) {
duke@435 1025 assert(ObjectSynchronizer::verify_objmon_isinpool(mark->monitor()), "monitor is invalid");
duke@435 1026 assert(mark->monitor()->header()->is_neutral(), "monitor must record a good object header");
duke@435 1027 return mark->monitor();
duke@435 1028 }
duke@435 1029 return ObjectSynchronizer::inflate(Thread::current(), obj);
duke@435 1030 }
duke@435 1031
duke@435 1032 // Note that we could encounter some performance loss through false-sharing as
duke@435 1033 // multiple locks occupy the same $ line. Padding might be appropriate.
duke@435 1034
duke@435 1035 #define NINFLATIONLOCKS 256
duke@435 1036 static volatile intptr_t InflationLocks [NINFLATIONLOCKS] ;
duke@435 1037
duke@435 1038 static markOop ReadStableMark (oop obj) {
duke@435 1039 markOop mark = obj->mark() ;
duke@435 1040 if (!mark->is_being_inflated()) {
duke@435 1041 return mark ; // normal fast-path return
duke@435 1042 }
duke@435 1043
duke@435 1044 int its = 0 ;
duke@435 1045 for (;;) {
duke@435 1046 markOop mark = obj->mark() ;
duke@435 1047 if (!mark->is_being_inflated()) {
duke@435 1048 return mark ; // normal fast-path return
duke@435 1049 }
duke@435 1050
duke@435 1051 // The object is being inflated by some other thread.
duke@435 1052 // The caller of ReadStableMark() must wait for inflation to complete.
duke@435 1053 // Avoid live-lock
duke@435 1054 // TODO: consider calling SafepointSynchronize::do_call_back() while
duke@435 1055 // spinning to see if there's a safepoint pending. If so, immediately
duke@435 1056 // yielding or blocking would be appropriate. Avoid spinning while
duke@435 1057 // there is a safepoint pending.
duke@435 1058 // TODO: add inflation contention performance counters.
duke@435 1059 // TODO: restrict the aggregate number of spinners.
duke@435 1060
duke@435 1061 ++its ;
duke@435 1062 if (its > 10000 || !os::is_MP()) {
duke@435 1063 if (its & 1) {
duke@435 1064 os::NakedYield() ;
duke@435 1065 TEVENT (Inflate: INFLATING - yield) ;
duke@435 1066 } else {
duke@435 1067 // Note that the following code attenuates the livelock problem but is not
duke@435 1068 // a complete remedy. A more complete solution would require that the inflating
duke@435 1069 // thread hold the associated inflation lock. The following code simply restricts
duke@435 1070 // the number of spinners to at most one. We'll have N-2 threads blocked
duke@435 1071 // on the inflationlock, 1 thread holding the inflation lock and using
duke@435 1072 // a yield/park strategy, and 1 thread in the midst of inflation.
duke@435 1073 // A more refined approach would be to change the encoding of INFLATING
duke@435 1074 // to allow encapsulation of a native thread pointer. Threads waiting for
duke@435 1075 // inflation to complete would use CAS to push themselves onto a singly linked
duke@435 1076 // list rooted at the markword. Once enqueued, they'd loop, checking a per-thread flag
duke@435 1077 // and calling park(). When inflation was complete the thread that accomplished inflation
duke@435 1078 // would detach the list and set the markword to inflated with a single CAS and
duke@435 1079 // then for each thread on the list, set the flag and unpark() the thread.
duke@435 1080 // This is conceptually similar to muxAcquire-muxRelease, except that muxRelease
duke@435 1081 // wakes at most one thread whereas we need to wake the entire list.
duke@435 1082 int ix = (intptr_t(obj) >> 5) & (NINFLATIONLOCKS-1) ;
duke@435 1083 int YieldThenBlock = 0 ;
duke@435 1084 assert (ix >= 0 && ix < NINFLATIONLOCKS, "invariant") ;
duke@435 1085 assert ((NINFLATIONLOCKS & (NINFLATIONLOCKS-1)) == 0, "invariant") ;
duke@435 1086 Thread::muxAcquire (InflationLocks + ix, "InflationLock") ;
duke@435 1087 while (obj->mark() == markOopDesc::INFLATING()) {
duke@435 1088 // Beware: NakedYield() is advisory and has almost no effect on some platforms
duke@435 1089 // so we periodically call Self->_ParkEvent->park(1).
duke@435 1090 // We use a mixed spin/yield/block mechanism.
duke@435 1091 if ((YieldThenBlock++) >= 16) {
duke@435 1092 Thread::current()->_ParkEvent->park(1) ;
duke@435 1093 } else {
duke@435 1094 os::NakedYield() ;
duke@435 1095 }
duke@435 1096 }
duke@435 1097 Thread::muxRelease (InflationLocks + ix ) ;
duke@435 1098 TEVENT (Inflate: INFLATING - yield/park) ;
duke@435 1099 }
duke@435 1100 } else {
duke@435 1101 SpinPause() ; // SMP-polite spinning
duke@435 1102 }
duke@435 1103 }
duke@435 1104 }
duke@435 1105
duke@435 1106 ObjectMonitor * ATTR ObjectSynchronizer::inflate (Thread * Self, oop object) {
duke@435 1107 // Inflate mutates the heap ...
duke@435 1108 // Relaxing assertion for bug 6320749.
duke@435 1109 assert (Universe::verify_in_progress() ||
duke@435 1110 !SafepointSynchronize::is_at_safepoint(), "invariant") ;
duke@435 1111
duke@435 1112 for (;;) {
duke@435 1113 const markOop mark = object->mark() ;
duke@435 1114 assert (!mark->has_bias_pattern(), "invariant") ;
duke@435 1115
duke@435 1116 // The mark can be in one of the following states:
duke@435 1117 // * Inflated - just return
duke@435 1118 // * Stack-locked - coerce it to inflated
duke@435 1119 // * INFLATING - busy wait for conversion to complete
duke@435 1120 // * Neutral - aggressively inflate the object.
duke@435 1121 // * BIASED - Illegal. We should never see this
duke@435 1122
duke@435 1123 // CASE: inflated
duke@435 1124 if (mark->has_monitor()) {
duke@435 1125 ObjectMonitor * inf = mark->monitor() ;
duke@435 1126 assert (inf->header()->is_neutral(), "invariant");
duke@435 1127 assert (inf->object() == object, "invariant") ;
duke@435 1128 assert (ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid");
duke@435 1129 return inf ;
duke@435 1130 }
duke@435 1131
duke@435 1132 // CASE: inflation in progress - inflating over a stack-lock.
duke@435 1133 // Some other thread is converting from stack-locked to inflated.
duke@435 1134 // Only that thread can complete inflation -- other threads must wait.
duke@435 1135 // The INFLATING value is transient.
duke@435 1136 // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish.
duke@435 1137 // We could always eliminate polling by parking the thread on some auxiliary list.
duke@435 1138 if (mark == markOopDesc::INFLATING()) {
duke@435 1139 TEVENT (Inflate: spin while INFLATING) ;
duke@435 1140 ReadStableMark(object) ;
duke@435 1141 continue ;
duke@435 1142 }
duke@435 1143
duke@435 1144 // CASE: stack-locked
duke@435 1145 // Could be stack-locked either by this thread or by some other thread.
duke@435 1146 //
duke@435 1147 // Note that we allocate the objectmonitor speculatively, _before_ attempting
duke@435 1148 // to install INFLATING into the mark word. We originally installed INFLATING,
duke@435 1149 // allocated the objectmonitor, and then finally STed the address of the
duke@435 1150 // objectmonitor into the mark. This was correct, but artificially lengthened
duke@435 1151 // the interval in which INFLATED appeared in the mark, thus increasing
duke@435 1152 // the odds of inflation contention.
duke@435 1153 //
duke@435 1154 // We now use per-thread private objectmonitor free lists.
duke@435 1155 // These list are reprovisioned from the global free list outside the
duke@435 1156 // critical INFLATING...ST interval. A thread can transfer
duke@435 1157 // multiple objectmonitors en-mass from the global free list to its local free list.
duke@435 1158 // This reduces coherency traffic and lock contention on the global free list.
duke@435 1159 // Using such local free lists, it doesn't matter if the omAlloc() call appears
duke@435 1160 // before or after the CAS(INFLATING) operation.
duke@435 1161 // See the comments in omAlloc().
duke@435 1162
duke@435 1163 if (mark->has_locker()) {
duke@435 1164 ObjectMonitor * m = omAlloc (Self) ;
duke@435 1165 // Optimistically prepare the objectmonitor - anticipate successful CAS
duke@435 1166 // We do this before the CAS in order to minimize the length of time
duke@435 1167 // in which INFLATING appears in the mark.
duke@435 1168 m->Recycle();
duke@435 1169 m->FreeNext = NULL ;
duke@435 1170 m->_Responsible = NULL ;
duke@435 1171 m->OwnerIsThread = 0 ;
duke@435 1172 m->_recursions = 0 ;
duke@435 1173 m->_SpinDuration = Knob_SpinLimit ; // Consider: maintain by type/class
duke@435 1174
duke@435 1175 markOop cmp = (markOop) Atomic::cmpxchg_ptr (markOopDesc::INFLATING(), object->mark_addr(), mark) ;
duke@435 1176 if (cmp != mark) {
duke@435 1177 omRelease (Self, m) ;
duke@435 1178 continue ; // Interference -- just retry
duke@435 1179 }
duke@435 1180
duke@435 1181 // We've successfully installed INFLATING (0) into the mark-word.
duke@435 1182 // This is the only case where 0 will appear in a mark-work.
duke@435 1183 // Only the singular thread that successfully swings the mark-word
duke@435 1184 // to 0 can perform (or more precisely, complete) inflation.
duke@435 1185 //
duke@435 1186 // Why do we CAS a 0 into the mark-word instead of just CASing the
duke@435 1187 // mark-word from the stack-locked value directly to the new inflated state?
duke@435 1188 // Consider what happens when a thread unlocks a stack-locked object.
duke@435 1189 // It attempts to use CAS to swing the displaced header value from the
duke@435 1190 // on-stack basiclock back into the object header. Recall also that the
duke@435 1191 // header value (hashcode, etc) can reside in (a) the object header, or
duke@435 1192 // (b) a displaced header associated with the stack-lock, or (c) a displaced
duke@435 1193 // header in an objectMonitor. The inflate() routine must copy the header
duke@435 1194 // value from the basiclock on the owner's stack to the objectMonitor, all
duke@435 1195 // the while preserving the hashCode stability invariants. If the owner
duke@435 1196 // decides to release the lock while the value is 0, the unlock will fail
duke@435 1197 // and control will eventually pass from slow_exit() to inflate. The owner
duke@435 1198 // will then spin, waiting for the 0 value to disappear. Put another way,
duke@435 1199 // the 0 causes the owner to stall if the owner happens to try to
duke@435 1200 // drop the lock (restoring the header from the basiclock to the object)
duke@435 1201 // while inflation is in-progress. This protocol avoids races that might
duke@435 1202 // would otherwise permit hashCode values to change or "flicker" for an object.
duke@435 1203 // Critically, while object->mark is 0 mark->displaced_mark_helper() is stable.
duke@435 1204 // 0 serves as a "BUSY" inflate-in-progress indicator.
duke@435 1205
duke@435 1206
duke@435 1207 // fetch the displaced mark from the owner's stack.
duke@435 1208 // The owner can't die or unwind past the lock while our INFLATING
duke@435 1209 // object is in the mark. Furthermore the owner can't complete
duke@435 1210 // an unlock on the object, either.
duke@435 1211 markOop dmw = mark->displaced_mark_helper() ;
duke@435 1212 assert (dmw->is_neutral(), "invariant") ;
duke@435 1213
duke@435 1214 // Setup monitor fields to proper values -- prepare the monitor
duke@435 1215 m->set_header(dmw) ;
duke@435 1216
duke@435 1217 // Optimization: if the mark->locker stack address is associated
duke@435 1218 // with this thread we could simply set m->_owner = Self and
xlu@1137 1219 // m->OwnerIsThread = 1. Note that a thread can inflate an object
duke@435 1220 // that it has stack-locked -- as might happen in wait() -- directly
duke@435 1221 // with CAS. That is, we can avoid the xchg-NULL .... ST idiom.
xlu@1137 1222 m->set_owner(mark->locker());
duke@435 1223 m->set_object(object);
duke@435 1224 // TODO-FIXME: assert BasicLock->dhw != 0.
duke@435 1225
duke@435 1226 // Must preserve store ordering. The monitor state must
duke@435 1227 // be stable at the time of publishing the monitor address.
duke@435 1228 guarantee (object->mark() == markOopDesc::INFLATING(), "invariant") ;
duke@435 1229 object->release_set_mark(markOopDesc::encode(m));
duke@435 1230
duke@435 1231 // Hopefully the performance counters are allocated on distinct cache lines
duke@435 1232 // to avoid false sharing on MP systems ...
duke@435 1233 if (_sync_Inflations != NULL) _sync_Inflations->inc() ;
duke@435 1234 TEVENT(Inflate: overwrite stacklock) ;
duke@435 1235 if (TraceMonitorInflation) {
duke@435 1236 if (object->is_instance()) {
duke@435 1237 ResourceMark rm;
duke@435 1238 tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
duke@435 1239 (intptr_t) object, (intptr_t) object->mark(),
duke@435 1240 Klass::cast(object->klass())->external_name());
duke@435 1241 }
duke@435 1242 }
duke@435 1243 return m ;
duke@435 1244 }
duke@435 1245
duke@435 1246 // CASE: neutral
duke@435 1247 // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
duke@435 1248 // If we know we're inflating for entry it's better to inflate by swinging a
duke@435 1249 // pre-locked objectMonitor pointer into the object header. A successful
duke@435 1250 // CAS inflates the object *and* confers ownership to the inflating thread.
duke@435 1251 // In the current implementation we use a 2-step mechanism where we CAS()
duke@435 1252 // to inflate and then CAS() again to try to swing _owner from NULL to Self.
duke@435 1253 // An inflateTry() method that we could call from fast_enter() and slow_enter()
duke@435 1254 // would be useful.
duke@435 1255
duke@435 1256 assert (mark->is_neutral(), "invariant");
duke@435 1257 ObjectMonitor * m = omAlloc (Self) ;
duke@435 1258 // prepare m for installation - set monitor to initial state
duke@435 1259 m->Recycle();
duke@435 1260 m->set_header(mark);
duke@435 1261 m->set_owner(NULL);
duke@435 1262 m->set_object(object);
duke@435 1263 m->OwnerIsThread = 1 ;
duke@435 1264 m->_recursions = 0 ;
duke@435 1265 m->FreeNext = NULL ;
duke@435 1266 m->_Responsible = NULL ;
duke@435 1267 m->_SpinDuration = Knob_SpinLimit ; // consider: keep metastats by type/class
duke@435 1268
duke@435 1269 if (Atomic::cmpxchg_ptr (markOopDesc::encode(m), object->mark_addr(), mark) != mark) {
duke@435 1270 m->set_object (NULL) ;
duke@435 1271 m->set_owner (NULL) ;
duke@435 1272 m->OwnerIsThread = 0 ;
duke@435 1273 m->Recycle() ;
duke@435 1274 omRelease (Self, m) ;
duke@435 1275 m = NULL ;
duke@435 1276 continue ;
duke@435 1277 // interference - the markword changed - just retry.
duke@435 1278 // The state-transitions are one-way, so there's no chance of
duke@435 1279 // live-lock -- "Inflated" is an absorbing state.
duke@435 1280 }
duke@435 1281
duke@435 1282 // Hopefully the performance counters are allocated on distinct
duke@435 1283 // cache lines to avoid false sharing on MP systems ...
duke@435 1284 if (_sync_Inflations != NULL) _sync_Inflations->inc() ;
duke@435 1285 TEVENT(Inflate: overwrite neutral) ;
duke@435 1286 if (TraceMonitorInflation) {
duke@435 1287 if (object->is_instance()) {
duke@435 1288 ResourceMark rm;
duke@435 1289 tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
duke@435 1290 (intptr_t) object, (intptr_t) object->mark(),
duke@435 1291 Klass::cast(object->klass())->external_name());
duke@435 1292 }
duke@435 1293 }
duke@435 1294 return m ;
duke@435 1295 }
duke@435 1296 }
duke@435 1297
duke@435 1298
duke@435 1299 // This the fast monitor enter. The interpreter and compiler use
duke@435 1300 // some assembly copies of this code. Make sure update those code
duke@435 1301 // if the following function is changed. The implementation is
duke@435 1302 // extremely sensitive to race condition. Be careful.
duke@435 1303
duke@435 1304 void ObjectSynchronizer::fast_enter(Handle obj, BasicLock* lock, bool attempt_rebias, TRAPS) {
duke@435 1305 if (UseBiasedLocking) {
duke@435 1306 if (!SafepointSynchronize::is_at_safepoint()) {
duke@435 1307 BiasedLocking::Condition cond = BiasedLocking::revoke_and_rebias(obj, attempt_rebias, THREAD);
duke@435 1308 if (cond == BiasedLocking::BIAS_REVOKED_AND_REBIASED) {
duke@435 1309 return;
duke@435 1310 }
duke@435 1311 } else {
duke@435 1312 assert(!attempt_rebias, "can not rebias toward VM thread");
duke@435 1313 BiasedLocking::revoke_at_safepoint(obj);
duke@435 1314 }
duke@435 1315 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
xlu@1137 1316 }
xlu@1137 1317
xlu@1137 1318 slow_enter (obj, lock, THREAD) ;
duke@435 1319 }
duke@435 1320
duke@435 1321 void ObjectSynchronizer::fast_exit(oop object, BasicLock* lock, TRAPS) {
duke@435 1322 assert(!object->mark()->has_bias_pattern(), "should not see bias pattern here");
duke@435 1323 // if displaced header is null, the previous enter is recursive enter, no-op
duke@435 1324 markOop dhw = lock->displaced_header();
duke@435 1325 markOop mark ;
duke@435 1326 if (dhw == NULL) {
duke@435 1327 // Recursive stack-lock.
duke@435 1328 // Diagnostics -- Could be: stack-locked, inflating, inflated.
duke@435 1329 mark = object->mark() ;
duke@435 1330 assert (!mark->is_neutral(), "invariant") ;
duke@435 1331 if (mark->has_locker() && mark != markOopDesc::INFLATING()) {
duke@435 1332 assert(THREAD->is_lock_owned((address)mark->locker()), "invariant") ;
duke@435 1333 }
duke@435 1334 if (mark->has_monitor()) {
duke@435 1335 ObjectMonitor * m = mark->monitor() ;
duke@435 1336 assert(((oop)(m->object()))->mark() == mark, "invariant") ;
duke@435 1337 assert(m->is_entered(THREAD), "invariant") ;
duke@435 1338 }
duke@435 1339 return ;
duke@435 1340 }
duke@435 1341
duke@435 1342 mark = object->mark() ;
duke@435 1343
duke@435 1344 // If the object is stack-locked by the current thread, try to
duke@435 1345 // swing the displaced header from the box back to the mark.
duke@435 1346 if (mark == (markOop) lock) {
duke@435 1347 assert (dhw->is_neutral(), "invariant") ;
duke@435 1348 if ((markOop) Atomic::cmpxchg_ptr (dhw, object->mark_addr(), mark) == mark) {
duke@435 1349 TEVENT (fast_exit: release stacklock) ;
duke@435 1350 return;
duke@435 1351 }
duke@435 1352 }
duke@435 1353
duke@435 1354 ObjectSynchronizer::inflate(THREAD, object)->exit (THREAD) ;
duke@435 1355 }
duke@435 1356
duke@435 1357 // This routine is used to handle interpreter/compiler slow case
duke@435 1358 // We don't need to use fast path here, because it must have been
duke@435 1359 // failed in the interpreter/compiler code.
duke@435 1360 void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) {
duke@435 1361 markOop mark = obj->mark();
duke@435 1362 assert(!mark->has_bias_pattern(), "should not see bias pattern here");
duke@435 1363
duke@435 1364 if (mark->is_neutral()) {
duke@435 1365 // Anticipate successful CAS -- the ST of the displaced mark must
duke@435 1366 // be visible <= the ST performed by the CAS.
duke@435 1367 lock->set_displaced_header(mark);
duke@435 1368 if (mark == (markOop) Atomic::cmpxchg_ptr(lock, obj()->mark_addr(), mark)) {
duke@435 1369 TEVENT (slow_enter: release stacklock) ;
duke@435 1370 return ;
duke@435 1371 }
duke@435 1372 // Fall through to inflate() ...
duke@435 1373 } else
duke@435 1374 if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
duke@435 1375 assert(lock != mark->locker(), "must not re-lock the same lock");
duke@435 1376 assert(lock != (BasicLock*)obj->mark(), "don't relock with same BasicLock");
duke@435 1377 lock->set_displaced_header(NULL);
duke@435 1378 return;
duke@435 1379 }
duke@435 1380
duke@435 1381 #if 0
duke@435 1382 // The following optimization isn't particularly useful.
duke@435 1383 if (mark->has_monitor() && mark->monitor()->is_entered(THREAD)) {
duke@435 1384 lock->set_displaced_header (NULL) ;
duke@435 1385 return ;
duke@435 1386 }
duke@435 1387 #endif
duke@435 1388
duke@435 1389 // The object header will never be displaced to this lock,
duke@435 1390 // so it does not matter what the value is, except that it
duke@435 1391 // must be non-zero to avoid looking like a re-entrant lock,
duke@435 1392 // and must not look locked either.
duke@435 1393 lock->set_displaced_header(markOopDesc::unused_mark());
duke@435 1394 ObjectSynchronizer::inflate(THREAD, obj())->enter(THREAD);
duke@435 1395 }
duke@435 1396
duke@435 1397 // This routine is used to handle interpreter/compiler slow case
duke@435 1398 // We don't need to use fast path here, because it must have
duke@435 1399 // failed in the interpreter/compiler code. Simply use the heavy
duke@435 1400 // weight monitor should be ok, unless someone find otherwise.
duke@435 1401 void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) {
duke@435 1402 fast_exit (object, lock, THREAD) ;
duke@435 1403 }
duke@435 1404
duke@435 1405 // NOTE: must use heavy weight monitor to handle jni monitor enter
duke@435 1406 void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) { // possible entry from jni enter
duke@435 1407 // the current locking is from JNI instead of Java code
duke@435 1408 TEVENT (jni_enter) ;
duke@435 1409 if (UseBiasedLocking) {
duke@435 1410 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
duke@435 1411 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
duke@435 1412 }
duke@435 1413 THREAD->set_current_pending_monitor_is_from_java(false);
duke@435 1414 ObjectSynchronizer::inflate(THREAD, obj())->enter(THREAD);
duke@435 1415 THREAD->set_current_pending_monitor_is_from_java(true);
duke@435 1416 }
duke@435 1417
duke@435 1418 // NOTE: must use heavy weight monitor to handle jni monitor enter
duke@435 1419 bool ObjectSynchronizer::jni_try_enter(Handle obj, Thread* THREAD) {
duke@435 1420 if (UseBiasedLocking) {
duke@435 1421 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
duke@435 1422 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
duke@435 1423 }
duke@435 1424
duke@435 1425 ObjectMonitor* monitor = ObjectSynchronizer::inflate_helper(obj());
duke@435 1426 return monitor->try_enter(THREAD);
duke@435 1427 }
duke@435 1428
duke@435 1429
duke@435 1430 // NOTE: must use heavy weight monitor to handle jni monitor exit
duke@435 1431 void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) {
duke@435 1432 TEVENT (jni_exit) ;
duke@435 1433 if (UseBiasedLocking) {
duke@435 1434 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
duke@435 1435 }
duke@435 1436 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
duke@435 1437
duke@435 1438 ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj);
duke@435 1439 // If this thread has locked the object, exit the monitor. Note: can't use
duke@435 1440 // monitor->check(CHECK); must exit even if an exception is pending.
duke@435 1441 if (monitor->check(THREAD)) {
duke@435 1442 monitor->exit(THREAD);
duke@435 1443 }
duke@435 1444 }
duke@435 1445
duke@435 1446 // complete_exit()/reenter() are used to wait on a nested lock
duke@435 1447 // i.e. to give up an outer lock completely and then re-enter
duke@435 1448 // Used when holding nested locks - lock acquisition order: lock1 then lock2
duke@435 1449 // 1) complete_exit lock1 - saving recursion count
duke@435 1450 // 2) wait on lock2
duke@435 1451 // 3) when notified on lock2, unlock lock2
duke@435 1452 // 4) reenter lock1 with original recursion count
duke@435 1453 // 5) lock lock2
duke@435 1454 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
duke@435 1455 intptr_t ObjectSynchronizer::complete_exit(Handle obj, TRAPS) {
duke@435 1456 TEVENT (complete_exit) ;
duke@435 1457 if (UseBiasedLocking) {
duke@435 1458 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
duke@435 1459 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
duke@435 1460 }
duke@435 1461
duke@435 1462 ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj());
duke@435 1463
duke@435 1464 return monitor->complete_exit(THREAD);
duke@435 1465 }
duke@435 1466
duke@435 1467 // NOTE: must use heavy weight monitor to handle complete_exit/reenter()
duke@435 1468 void ObjectSynchronizer::reenter(Handle obj, intptr_t recursion, TRAPS) {
duke@435 1469 TEVENT (reenter) ;
duke@435 1470 if (UseBiasedLocking) {
duke@435 1471 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
duke@435 1472 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
duke@435 1473 }
duke@435 1474
duke@435 1475 ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj());
duke@435 1476
duke@435 1477 monitor->reenter(recursion, THREAD);
duke@435 1478 }
duke@435 1479
duke@435 1480 // This exists only as a workaround of dtrace bug 6254741
duke@435 1481 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) {
duke@435 1482 DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
duke@435 1483 return 0;
duke@435 1484 }
duke@435 1485
duke@435 1486 // NOTE: must use heavy weight monitor to handle wait()
duke@435 1487 void ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
duke@435 1488 if (UseBiasedLocking) {
duke@435 1489 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
duke@435 1490 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
duke@435 1491 }
duke@435 1492 if (millis < 0) {
duke@435 1493 TEVENT (wait - throw IAX) ;
duke@435 1494 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
duke@435 1495 }
duke@435 1496 ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj());
duke@435 1497 DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis);
duke@435 1498 monitor->wait(millis, true, THREAD);
duke@435 1499
duke@435 1500 /* This dummy call is in place to get around dtrace bug 6254741. Once
duke@435 1501 that's fixed we can uncomment the following line and remove the call */
duke@435 1502 // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
duke@435 1503 dtrace_waited_probe(monitor, obj, THREAD);
duke@435 1504 }
duke@435 1505
duke@435 1506 void ObjectSynchronizer::waitUninterruptibly (Handle obj, jlong millis, TRAPS) {
duke@435 1507 if (UseBiasedLocking) {
duke@435 1508 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
duke@435 1509 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
duke@435 1510 }
duke@435 1511 if (millis < 0) {
duke@435 1512 TEVENT (wait - throw IAX) ;
duke@435 1513 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
duke@435 1514 }
duke@435 1515 ObjectSynchronizer::inflate(THREAD, obj()) -> wait(millis, false, THREAD) ;
duke@435 1516 }
duke@435 1517
duke@435 1518 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
duke@435 1519 if (UseBiasedLocking) {
duke@435 1520 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
duke@435 1521 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
duke@435 1522 }
duke@435 1523
duke@435 1524 markOop mark = obj->mark();
duke@435 1525 if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
duke@435 1526 return;
duke@435 1527 }
duke@435 1528 ObjectSynchronizer::inflate(THREAD, obj())->notify(THREAD);
duke@435 1529 }
duke@435 1530
duke@435 1531 // NOTE: see comment of notify()
duke@435 1532 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
duke@435 1533 if (UseBiasedLocking) {
duke@435 1534 BiasedLocking::revoke_and_rebias(obj, false, THREAD);
duke@435 1535 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
duke@435 1536 }
duke@435 1537
duke@435 1538 markOop mark = obj->mark();
duke@435 1539 if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) {
duke@435 1540 return;
duke@435 1541 }
duke@435 1542 ObjectSynchronizer::inflate(THREAD, obj())->notifyAll(THREAD);
duke@435 1543 }
duke@435 1544
duke@435 1545 intptr_t ObjectSynchronizer::FastHashCode (Thread * Self, oop obj) {
duke@435 1546 if (UseBiasedLocking) {
duke@435 1547 // NOTE: many places throughout the JVM do not expect a safepoint
duke@435 1548 // to be taken here, in particular most operations on perm gen
duke@435 1549 // objects. However, we only ever bias Java instances and all of
duke@435 1550 // the call sites of identity_hash that might revoke biases have
duke@435 1551 // been checked to make sure they can handle a safepoint. The
duke@435 1552 // added check of the bias pattern is to avoid useless calls to
duke@435 1553 // thread-local storage.
duke@435 1554 if (obj->mark()->has_bias_pattern()) {
duke@435 1555 // Box and unbox the raw reference just in case we cause a STW safepoint.
duke@435 1556 Handle hobj (Self, obj) ;
duke@435 1557 // Relaxing assertion for bug 6320749.
duke@435 1558 assert (Universe::verify_in_progress() ||
duke@435 1559 !SafepointSynchronize::is_at_safepoint(),
duke@435 1560 "biases should not be seen by VM thread here");
duke@435 1561 BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current());
duke@435 1562 obj = hobj() ;
duke@435 1563 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
duke@435 1564 }
duke@435 1565 }
duke@435 1566
duke@435 1567 // hashCode() is a heap mutator ...
duke@435 1568 // Relaxing assertion for bug 6320749.
duke@435 1569 assert (Universe::verify_in_progress() ||
duke@435 1570 !SafepointSynchronize::is_at_safepoint(), "invariant") ;
duke@435 1571 assert (Universe::verify_in_progress() ||
duke@435 1572 Self->is_Java_thread() , "invariant") ;
duke@435 1573 assert (Universe::verify_in_progress() ||
duke@435 1574 ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant") ;
duke@435 1575
duke@435 1576 ObjectMonitor* monitor = NULL;
duke@435 1577 markOop temp, test;
duke@435 1578 intptr_t hash;
duke@435 1579 markOop mark = ReadStableMark (obj);
duke@435 1580
duke@435 1581 // object should remain ineligible for biased locking
duke@435 1582 assert (!mark->has_bias_pattern(), "invariant") ;
duke@435 1583
duke@435 1584 if (mark->is_neutral()) {
duke@435 1585 hash = mark->hash(); // this is a normal header
duke@435 1586 if (hash) { // if it has hash, just return it
duke@435 1587 return hash;
duke@435 1588 }
duke@435 1589 hash = get_next_hash(Self, obj); // allocate a new hash code
duke@435 1590 temp = mark->copy_set_hash(hash); // merge the hash code into header
duke@435 1591 // use (machine word version) atomic operation to install the hash
duke@435 1592 test = (markOop) Atomic::cmpxchg_ptr(temp, obj->mark_addr(), mark);
duke@435 1593 if (test == mark) {
duke@435 1594 return hash;
duke@435 1595 }
duke@435 1596 // If atomic operation failed, we must inflate the header
duke@435 1597 // into heavy weight monitor. We could add more code here
duke@435 1598 // for fast path, but it does not worth the complexity.
duke@435 1599 } else if (mark->has_monitor()) {
duke@435 1600 monitor = mark->monitor();
duke@435 1601 temp = monitor->header();
duke@435 1602 assert (temp->is_neutral(), "invariant") ;
duke@435 1603 hash = temp->hash();
duke@435 1604 if (hash) {
duke@435 1605 return hash;
duke@435 1606 }
duke@435 1607 // Skip to the following code to reduce code size
duke@435 1608 } else if (Self->is_lock_owned((address)mark->locker())) {
duke@435 1609 temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned
duke@435 1610 assert (temp->is_neutral(), "invariant") ;
duke@435 1611 hash = temp->hash(); // by current thread, check if the displaced
duke@435 1612 if (hash) { // header contains hash code
duke@435 1613 return hash;
duke@435 1614 }
duke@435 1615 // WARNING:
duke@435 1616 // The displaced header is strictly immutable.
duke@435 1617 // It can NOT be changed in ANY cases. So we have
duke@435 1618 // to inflate the header into heavyweight monitor
duke@435 1619 // even the current thread owns the lock. The reason
duke@435 1620 // is the BasicLock (stack slot) will be asynchronously
duke@435 1621 // read by other threads during the inflate() function.
duke@435 1622 // Any change to stack may not propagate to other threads
duke@435 1623 // correctly.
duke@435 1624 }
duke@435 1625
duke@435 1626 // Inflate the monitor to set hash code
duke@435 1627 monitor = ObjectSynchronizer::inflate(Self, obj);
duke@435 1628 // Load displaced header and check it has hash code
duke@435 1629 mark = monitor->header();
duke@435 1630 assert (mark->is_neutral(), "invariant") ;
duke@435 1631 hash = mark->hash();
duke@435 1632 if (hash == 0) {
duke@435 1633 hash = get_next_hash(Self, obj);
duke@435 1634 temp = mark->copy_set_hash(hash); // merge hash code into header
duke@435 1635 assert (temp->is_neutral(), "invariant") ;
duke@435 1636 test = (markOop) Atomic::cmpxchg_ptr(temp, monitor, mark);
duke@435 1637 if (test != mark) {
duke@435 1638 // The only update to the header in the monitor (outside GC)
duke@435 1639 // is install the hash code. If someone add new usage of
duke@435 1640 // displaced header, please update this code
duke@435 1641 hash = test->hash();
duke@435 1642 assert (test->is_neutral(), "invariant") ;
duke@435 1643 assert (hash != 0, "Trivial unexpected object/monitor header usage.");
duke@435 1644 }
duke@435 1645 }
duke@435 1646 // We finally get the hash
duke@435 1647 return hash;
duke@435 1648 }
duke@435 1649
duke@435 1650 // Deprecated -- use FastHashCode() instead.
duke@435 1651
duke@435 1652 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) {
duke@435 1653 return FastHashCode (Thread::current(), obj()) ;
duke@435 1654 }
duke@435 1655
duke@435 1656 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread,
duke@435 1657 Handle h_obj) {
duke@435 1658 if (UseBiasedLocking) {
duke@435 1659 BiasedLocking::revoke_and_rebias(h_obj, false, thread);
duke@435 1660 assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
duke@435 1661 }
duke@435 1662
duke@435 1663 assert(thread == JavaThread::current(), "Can only be called on current thread");
duke@435 1664 oop obj = h_obj();
duke@435 1665
duke@435 1666 markOop mark = ReadStableMark (obj) ;
duke@435 1667
duke@435 1668 // Uncontended case, header points to stack
duke@435 1669 if (mark->has_locker()) {
duke@435 1670 return thread->is_lock_owned((address)mark->locker());
duke@435 1671 }
duke@435 1672 // Contended case, header points to ObjectMonitor (tagged pointer)
duke@435 1673 if (mark->has_monitor()) {
duke@435 1674 ObjectMonitor* monitor = mark->monitor();
duke@435 1675 return monitor->is_entered(thread) != 0 ;
duke@435 1676 }
duke@435 1677 // Unlocked case, header in place
duke@435 1678 assert(mark->is_neutral(), "sanity check");
duke@435 1679 return false;
duke@435 1680 }
duke@435 1681
duke@435 1682 // Be aware of this method could revoke bias of the lock object.
duke@435 1683 // This method querys the ownership of the lock handle specified by 'h_obj'.
duke@435 1684 // If the current thread owns the lock, it returns owner_self. If no
duke@435 1685 // thread owns the lock, it returns owner_none. Otherwise, it will return
duke@435 1686 // ower_other.
duke@435 1687 ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership
duke@435 1688 (JavaThread *self, Handle h_obj) {
duke@435 1689 // The caller must beware this method can revoke bias, and
duke@435 1690 // revocation can result in a safepoint.
duke@435 1691 assert (!SafepointSynchronize::is_at_safepoint(), "invariant") ;
duke@435 1692 assert (self->thread_state() != _thread_blocked , "invariant") ;
duke@435 1693
duke@435 1694 // Possible mark states: neutral, biased, stack-locked, inflated
duke@435 1695
duke@435 1696 if (UseBiasedLocking && h_obj()->mark()->has_bias_pattern()) {
duke@435 1697 // CASE: biased
duke@435 1698 BiasedLocking::revoke_and_rebias(h_obj, false, self);
duke@435 1699 assert(!h_obj->mark()->has_bias_pattern(),
duke@435 1700 "biases should be revoked by now");
duke@435 1701 }
duke@435 1702
duke@435 1703 assert(self == JavaThread::current(), "Can only be called on current thread");
duke@435 1704 oop obj = h_obj();
duke@435 1705 markOop mark = ReadStableMark (obj) ;
duke@435 1706
duke@435 1707 // CASE: stack-locked. Mark points to a BasicLock on the owner's stack.
duke@435 1708 if (mark->has_locker()) {
duke@435 1709 return self->is_lock_owned((address)mark->locker()) ?
duke@435 1710 owner_self : owner_other;
duke@435 1711 }
duke@435 1712
duke@435 1713 // CASE: inflated. Mark (tagged pointer) points to an objectMonitor.
duke@435 1714 // The Object:ObjectMonitor relationship is stable as long as we're
duke@435 1715 // not at a safepoint.
duke@435 1716 if (mark->has_monitor()) {
duke@435 1717 void * owner = mark->monitor()->_owner ;
duke@435 1718 if (owner == NULL) return owner_none ;
duke@435 1719 return (owner == self ||
duke@435 1720 self->is_lock_owned((address)owner)) ? owner_self : owner_other;
duke@435 1721 }
duke@435 1722
duke@435 1723 // CASE: neutral
duke@435 1724 assert(mark->is_neutral(), "sanity check");
duke@435 1725 return owner_none ; // it's unlocked
duke@435 1726 }
duke@435 1727
duke@435 1728 // FIXME: jvmti should call this
duke@435 1729 JavaThread* ObjectSynchronizer::get_lock_owner(Handle h_obj, bool doLock) {
duke@435 1730 if (UseBiasedLocking) {
duke@435 1731 if (SafepointSynchronize::is_at_safepoint()) {
duke@435 1732 BiasedLocking::revoke_at_safepoint(h_obj);
duke@435 1733 } else {
duke@435 1734 BiasedLocking::revoke_and_rebias(h_obj, false, JavaThread::current());
duke@435 1735 }
duke@435 1736 assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now");
duke@435 1737 }
duke@435 1738
duke@435 1739 oop obj = h_obj();
duke@435 1740 address owner = NULL;
duke@435 1741
duke@435 1742 markOop mark = ReadStableMark (obj) ;
duke@435 1743
duke@435 1744 // Uncontended case, header points to stack
duke@435 1745 if (mark->has_locker()) {
duke@435 1746 owner = (address) mark->locker();
duke@435 1747 }
duke@435 1748
duke@435 1749 // Contended case, header points to ObjectMonitor (tagged pointer)
duke@435 1750 if (mark->has_monitor()) {
duke@435 1751 ObjectMonitor* monitor = mark->monitor();
duke@435 1752 assert(monitor != NULL, "monitor should be non-null");
duke@435 1753 owner = (address) monitor->owner();
duke@435 1754 }
duke@435 1755
duke@435 1756 if (owner != NULL) {
duke@435 1757 return Threads::owning_thread_from_monitor_owner(owner, doLock);
duke@435 1758 }
duke@435 1759
duke@435 1760 // Unlocked case, header in place
duke@435 1761 // Cannot have assertion since this object may have been
duke@435 1762 // locked by another thread when reaching here.
duke@435 1763 // assert(mark->is_neutral(), "sanity check");
duke@435 1764
duke@435 1765 return NULL;
duke@435 1766 }
duke@435 1767
duke@435 1768 // Iterate through monitor cache and attempt to release thread's monitors
duke@435 1769 // Gives up on a particular monitor if an exception occurs, but continues
duke@435 1770 // the overall iteration, swallowing the exception.
duke@435 1771 class ReleaseJavaMonitorsClosure: public MonitorClosure {
duke@435 1772 private:
duke@435 1773 TRAPS;
duke@435 1774
duke@435 1775 public:
duke@435 1776 ReleaseJavaMonitorsClosure(Thread* thread) : THREAD(thread) {}
duke@435 1777 void do_monitor(ObjectMonitor* mid) {
duke@435 1778 if (mid->owner() == THREAD) {
duke@435 1779 (void)mid->complete_exit(CHECK);
duke@435 1780 }
duke@435 1781 }
duke@435 1782 };
duke@435 1783
duke@435 1784 // Release all inflated monitors owned by THREAD. Lightweight monitors are
duke@435 1785 // ignored. This is meant to be called during JNI thread detach which assumes
duke@435 1786 // all remaining monitors are heavyweight. All exceptions are swallowed.
duke@435 1787 // Scanning the extant monitor list can be time consuming.
duke@435 1788 // A simple optimization is to add a per-thread flag that indicates a thread
duke@435 1789 // called jni_monitorenter() during its lifetime.
duke@435 1790 //
duke@435 1791 // Instead of No_Savepoint_Verifier it might be cheaper to
duke@435 1792 // use an idiom of the form:
duke@435 1793 // auto int tmp = SafepointSynchronize::_safepoint_counter ;
duke@435 1794 // <code that must not run at safepoint>
duke@435 1795 // guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ;
duke@435 1796 // Since the tests are extremely cheap we could leave them enabled
duke@435 1797 // for normal product builds.
duke@435 1798
duke@435 1799 void ObjectSynchronizer::release_monitors_owned_by_thread(TRAPS) {
duke@435 1800 assert(THREAD == JavaThread::current(), "must be current Java thread");
duke@435 1801 No_Safepoint_Verifier nsv ;
duke@435 1802 ReleaseJavaMonitorsClosure rjmc(THREAD);
duke@435 1803 Thread::muxAcquire(&ListLock, "release_monitors_owned_by_thread");
duke@435 1804 ObjectSynchronizer::monitors_iterate(&rjmc);
duke@435 1805 Thread::muxRelease(&ListLock);
duke@435 1806 THREAD->clear_pending_exception();
duke@435 1807 }
duke@435 1808
duke@435 1809 // Visitors ...
duke@435 1810
duke@435 1811 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure) {
duke@435 1812 ObjectMonitor* block = gBlockList;
duke@435 1813 ObjectMonitor* mid;
duke@435 1814 while (block) {
duke@435 1815 assert(block->object() == CHAINMARKER, "must be a block header");
duke@435 1816 for (int i = _BLOCKSIZE - 1; i > 0; i--) {
duke@435 1817 mid = block + i;
duke@435 1818 oop object = (oop) mid->object();
duke@435 1819 if (object != NULL) {
duke@435 1820 closure->do_monitor(mid);
duke@435 1821 }
duke@435 1822 }
duke@435 1823 block = (ObjectMonitor*) block->FreeNext;
duke@435 1824 }
duke@435 1825 }
duke@435 1826
duke@435 1827 void ObjectSynchronizer::oops_do(OopClosure* f) {
duke@435 1828 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
duke@435 1829 for (ObjectMonitor* block = gBlockList; block != NULL; block = next(block)) {
duke@435 1830 assert(block->object() == CHAINMARKER, "must be a block header");
duke@435 1831 for (int i = 1; i < _BLOCKSIZE; i++) {
duke@435 1832 ObjectMonitor* mid = &block[i];
duke@435 1833 if (mid->object() != NULL) {
duke@435 1834 f->do_oop((oop*)mid->object_addr());
duke@435 1835 }
duke@435 1836 }
duke@435 1837 }
duke@435 1838 }
duke@435 1839
duke@435 1840 // Deflate_idle_monitors() is called at all safepoints, immediately
duke@435 1841 // after all mutators are stopped, but before any objects have moved.
duke@435 1842 // It traverses the list of known monitors, deflating where possible.
duke@435 1843 // The scavenged monitor are returned to the monitor free list.
duke@435 1844 //
duke@435 1845 // Beware that we scavenge at *every* stop-the-world point.
duke@435 1846 // Having a large number of monitors in-circulation negatively
duke@435 1847 // impacts the performance of some applications (e.g., PointBase).
duke@435 1848 // Broadly, we want to minimize the # of monitors in circulation.
acorn@1942 1849 //
acorn@1942 1850 // We have added a flag, MonitorInUseLists, which creates a list
acorn@1942 1851 // of active monitors for each thread. deflate_idle_monitors()
acorn@1942 1852 // only scans the per-thread inuse lists. omAlloc() puts all
acorn@1942 1853 // assigned monitors on the per-thread list. deflate_idle_monitors()
acorn@1942 1854 // returns the non-busy monitors to the global free list.
acorn@1942 1855 // An alternative could have used a single global inuse list. The
acorn@1942 1856 // downside would have been the additional cost of acquiring the global list lock
acorn@1942 1857 // for every omAlloc().
duke@435 1858 //
duke@435 1859 // Perversely, the heap size -- and thus the STW safepoint rate --
duke@435 1860 // typically drives the scavenge rate. Large heaps can mean infrequent GC,
duke@435 1861 // which in turn can mean large(r) numbers of objectmonitors in circulation.
duke@435 1862 // This is an unfortunate aspect of this design.
duke@435 1863 //
duke@435 1864 // Another refinement would be to refrain from calling deflate_idle_monitors()
duke@435 1865 // except at stop-the-world points associated with garbage collections.
duke@435 1866 //
duke@435 1867 // An even better solution would be to deflate on-the-fly, aggressively,
duke@435 1868 // at monitorexit-time as is done in EVM's metalock or Relaxed Locks.
duke@435 1869
acorn@1942 1870
acorn@1942 1871 // Deflate a single monitor if not in use
acorn@1942 1872 // Return true if deflated, false if in use
acorn@1942 1873 bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj,
acorn@1942 1874 ObjectMonitor** FreeHeadp, ObjectMonitor** FreeTailp) {
acorn@1942 1875 bool deflated;
acorn@1942 1876 // Normal case ... The monitor is associated with obj.
acorn@1942 1877 guarantee (obj->mark() == markOopDesc::encode(mid), "invariant") ;
acorn@1942 1878 guarantee (mid == obj->mark()->monitor(), "invariant");
acorn@1942 1879 guarantee (mid->header()->is_neutral(), "invariant");
acorn@1942 1880
acorn@1942 1881 if (mid->is_busy()) {
acorn@1942 1882 if (ClearResponsibleAtSTW) mid->_Responsible = NULL ;
acorn@1942 1883 deflated = false;
acorn@1942 1884 } else {
acorn@1942 1885 // Deflate the monitor if it is no longer being used
acorn@1942 1886 // It's idle - scavenge and return to the global free list
acorn@1942 1887 // plain old deflation ...
acorn@1942 1888 TEVENT (deflate_idle_monitors - scavenge1) ;
acorn@1942 1889 if (TraceMonitorInflation) {
acorn@1942 1890 if (obj->is_instance()) {
acorn@1942 1891 ResourceMark rm;
acorn@1942 1892 tty->print_cr("Deflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s",
acorn@1942 1893 (intptr_t) obj, (intptr_t) obj->mark(), Klass::cast(obj->klass())->external_name());
acorn@1942 1894 }
acorn@1942 1895 }
acorn@1942 1896
acorn@1942 1897 // Restore the header back to obj
acorn@1942 1898 obj->release_set_mark(mid->header());
acorn@1942 1899 mid->clear();
acorn@1942 1900
acorn@1942 1901 assert (mid->object() == NULL, "invariant") ;
acorn@1942 1902
acorn@1942 1903 // Move the object to the working free list defined by FreeHead,FreeTail.
acorn@1942 1904 if (*FreeHeadp == NULL) *FreeHeadp = mid;
acorn@1942 1905 if (*FreeTailp != NULL) {
acorn@1942 1906 ObjectMonitor * prevtail = *FreeTailp;
acorn@1942 1907 prevtail->FreeNext = mid;
acorn@1942 1908 }
acorn@1942 1909 *FreeTailp = mid;
acorn@1942 1910 deflated = true;
acorn@1942 1911 }
acorn@1942 1912 return deflated;
acorn@1942 1913 }
acorn@1942 1914
duke@435 1915 void ObjectSynchronizer::deflate_idle_monitors() {
duke@435 1916 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
duke@435 1917 int nInuse = 0 ; // currently associated with objects
duke@435 1918 int nInCirculation = 0 ; // extant
duke@435 1919 int nScavenged = 0 ; // reclaimed
acorn@1942 1920 bool deflated = false;
duke@435 1921
duke@435 1922 ObjectMonitor * FreeHead = NULL ; // Local SLL of scavenged monitors
duke@435 1923 ObjectMonitor * FreeTail = NULL ;
duke@435 1924
acorn@1942 1925 TEVENT (deflate_idle_monitors) ;
acorn@1942 1926 // Prevent omFlush from changing mids in Thread dtor's during deflation
acorn@1942 1927 // And in case the vm thread is acquiring a lock during a safepoint
acorn@1942 1928 // See e.g. 6320749
acorn@1942 1929 Thread::muxAcquire (&ListLock, "scavenge - return") ;
acorn@1942 1930
acorn@1942 1931 if (MonitorInUseLists) {
acorn@1942 1932 ObjectMonitor* mid;
acorn@1942 1933 ObjectMonitor* next;
acorn@1942 1934 ObjectMonitor* curmidinuse;
acorn@1942 1935 for (JavaThread* cur = Threads::first(); cur != NULL; cur = cur->next()) {
acorn@1942 1936 curmidinuse = NULL;
acorn@1942 1937 for (mid = cur->omInUseList; mid != NULL; ) {
acorn@1942 1938 oop obj = (oop) mid->object();
acorn@1942 1939 deflated = false;
acorn@1942 1940 if (obj != NULL) {
acorn@1942 1941 deflated = deflate_monitor(mid, obj, &FreeHead, &FreeTail);
acorn@1942 1942 }
acorn@1942 1943 if (deflated) {
acorn@1942 1944 // extract from per-thread in-use-list
acorn@1942 1945 if (mid == cur->omInUseList) {
acorn@1942 1946 cur->omInUseList = mid->FreeNext;
acorn@1942 1947 } else if (curmidinuse != NULL) {
acorn@1942 1948 curmidinuse->FreeNext = mid->FreeNext; // maintain the current thread inuselist
acorn@1942 1949 }
acorn@1942 1950 next = mid->FreeNext;
acorn@1942 1951 mid->FreeNext = NULL; // This mid is current tail in the FreeHead list
acorn@1942 1952 mid = next;
acorn@1942 1953 cur->omInUseCount--;
acorn@1942 1954 nScavenged ++ ;
acorn@1942 1955 } else {
acorn@1942 1956 curmidinuse = mid;
acorn@1942 1957 mid = mid->FreeNext;
acorn@1942 1958 nInuse ++;
acorn@1942 1959 }
acorn@1942 1960 }
acorn@1942 1961 }
acorn@1942 1962 } else for (ObjectMonitor* block = gBlockList; block != NULL; block = next(block)) {
duke@435 1963 // Iterate over all extant monitors - Scavenge all idle monitors.
duke@435 1964 assert(block->object() == CHAINMARKER, "must be a block header");
duke@435 1965 nInCirculation += _BLOCKSIZE ;
duke@435 1966 for (int i = 1 ; i < _BLOCKSIZE; i++) {
duke@435 1967 ObjectMonitor* mid = &block[i];
duke@435 1968 oop obj = (oop) mid->object();
duke@435 1969
duke@435 1970 if (obj == NULL) {
duke@435 1971 // The monitor is not associated with an object.
duke@435 1972 // The monitor should either be a thread-specific private
duke@435 1973 // free list or the global free list.
duke@435 1974 // obj == NULL IMPLIES mid->is_busy() == 0
duke@435 1975 guarantee (!mid->is_busy(), "invariant") ;
duke@435 1976 continue ;
duke@435 1977 }
acorn@1942 1978 deflated = deflate_monitor(mid, obj, &FreeHead, &FreeTail);
acorn@1942 1979
acorn@1942 1980 if (deflated) {
acorn@1942 1981 mid->FreeNext = NULL ;
acorn@1942 1982 nScavenged ++ ;
duke@435 1983 } else {
acorn@1942 1984 nInuse ++;
duke@435 1985 }
duke@435 1986 }
duke@435 1987 }
duke@435 1988
acorn@1942 1989 MonitorFreeCount += nScavenged;
acorn@1942 1990
acorn@1942 1991 // Consider: audit gFreeList to ensure that MonitorFreeCount and list agree.
acorn@1942 1992
acorn@1942 1993 if (Knob_Verbose) {
acorn@1942 1994 ::printf ("Deflate: InCirc=%d InUse=%d Scavenged=%d ForceMonitorScavenge=%d : pop=%d free=%d\n",
acorn@1942 1995 nInCirculation, nInuse, nScavenged, ForceMonitorScavenge,
acorn@1942 1996 MonitorPopulation, MonitorFreeCount) ;
acorn@1942 1997 ::fflush(stdout) ;
acorn@1942 1998 }
acorn@1942 1999
acorn@1942 2000 ForceMonitorScavenge = 0; // Reset
acorn@1942 2001
duke@435 2002 // Move the scavenged monitors back to the global free list.
duke@435 2003 if (FreeHead != NULL) {
duke@435 2004 guarantee (FreeTail != NULL && nScavenged > 0, "invariant") ;
duke@435 2005 assert (FreeTail->FreeNext == NULL, "invariant") ;
duke@435 2006 // constant-time list splice - prepend scavenged segment to gFreeList
duke@435 2007 FreeTail->FreeNext = gFreeList ;
duke@435 2008 gFreeList = FreeHead ;
duke@435 2009 }
acorn@1942 2010 Thread::muxRelease (&ListLock) ;
duke@435 2011
duke@435 2012 if (_sync_Deflations != NULL) _sync_Deflations->inc(nScavenged) ;
duke@435 2013 if (_sync_MonExtant != NULL) _sync_MonExtant ->set_value(nInCirculation);
duke@435 2014
duke@435 2015 // TODO: Add objectMonitor leak detection.
duke@435 2016 // Audit/inventory the objectMonitors -- make sure they're all accounted for.
duke@435 2017 GVars.stwRandom = os::random() ;
duke@435 2018 GVars.stwCycle ++ ;
duke@435 2019 }
duke@435 2020
duke@435 2021 // A macro is used below because there may already be a pending
duke@435 2022 // exception which should not abort the execution of the routines
duke@435 2023 // which use this (which is why we don't put this into check_slow and
duke@435 2024 // call it with a CHECK argument).
duke@435 2025
duke@435 2026 #define CHECK_OWNER() \
duke@435 2027 do { \
duke@435 2028 if (THREAD != _owner) { \
duke@435 2029 if (THREAD->is_lock_owned((address) _owner)) { \
duke@435 2030 _owner = THREAD ; /* Convert from basiclock addr to Thread addr */ \
duke@435 2031 _recursions = 0; \
duke@435 2032 OwnerIsThread = 1 ; \
duke@435 2033 } else { \
duke@435 2034 TEVENT (Throw IMSX) ; \
duke@435 2035 THROW(vmSymbols::java_lang_IllegalMonitorStateException()); \
duke@435 2036 } \
duke@435 2037 } \
duke@435 2038 } while (false)
duke@435 2039
duke@435 2040 // TODO-FIXME: eliminate ObjectWaiters. Replace this visitor/enumerator
duke@435 2041 // interface with a simple FirstWaitingThread(), NextWaitingThread() interface.
duke@435 2042
duke@435 2043 ObjectWaiter* ObjectMonitor::first_waiter() {
duke@435 2044 return _WaitSet;
duke@435 2045 }
duke@435 2046
duke@435 2047 ObjectWaiter* ObjectMonitor::next_waiter(ObjectWaiter* o) {
duke@435 2048 return o->_next;
duke@435 2049 }
duke@435 2050
duke@435 2051 Thread* ObjectMonitor::thread_of_waiter(ObjectWaiter* o) {
duke@435 2052 return o->_thread;
duke@435 2053 }
duke@435 2054
duke@435 2055 // initialize the monitor, exception the semaphore, all other fields
duke@435 2056 // are simple integers or pointers
duke@435 2057 ObjectMonitor::ObjectMonitor() {
duke@435 2058 _header = NULL;
duke@435 2059 _count = 0;
duke@435 2060 _waiters = 0,
duke@435 2061 _recursions = 0;
duke@435 2062 _object = NULL;
duke@435 2063 _owner = NULL;
duke@435 2064 _WaitSet = NULL;
duke@435 2065 _WaitSetLock = 0 ;
duke@435 2066 _Responsible = NULL ;
duke@435 2067 _succ = NULL ;
duke@435 2068 _cxq = NULL ;
duke@435 2069 FreeNext = NULL ;
duke@435 2070 _EntryList = NULL ;
duke@435 2071 _SpinFreq = 0 ;
duke@435 2072 _SpinClock = 0 ;
duke@435 2073 OwnerIsThread = 0 ;
duke@435 2074 }
duke@435 2075
duke@435 2076 ObjectMonitor::~ObjectMonitor() {
duke@435 2077 // TODO: Add asserts ...
duke@435 2078 // _cxq == 0 _succ == NULL _owner == NULL _waiters == 0
duke@435 2079 // _count == 0 _EntryList == NULL etc
duke@435 2080 }
duke@435 2081
duke@435 2082 intptr_t ObjectMonitor::is_busy() const {
duke@435 2083 // TODO-FIXME: merge _count and _waiters.
duke@435 2084 // TODO-FIXME: assert _owner == null implies _recursions = 0
duke@435 2085 // TODO-FIXME: assert _WaitSet != null implies _count > 0
duke@435 2086 return _count|_waiters|intptr_t(_owner)|intptr_t(_cxq)|intptr_t(_EntryList ) ;
duke@435 2087 }
duke@435 2088
duke@435 2089 void ObjectMonitor::Recycle () {
duke@435 2090 // TODO: add stronger asserts ...
duke@435 2091 // _cxq == 0 _succ == NULL _owner == NULL _waiters == 0
duke@435 2092 // _count == 0 EntryList == NULL
duke@435 2093 // _recursions == 0 _WaitSet == NULL
duke@435 2094 // TODO: assert (is_busy()|_recursions) == 0
duke@435 2095 _succ = NULL ;
duke@435 2096 _EntryList = NULL ;
duke@435 2097 _cxq = NULL ;
duke@435 2098 _WaitSet = NULL ;
duke@435 2099 _recursions = 0 ;
duke@435 2100 _SpinFreq = 0 ;
duke@435 2101 _SpinClock = 0 ;
duke@435 2102 OwnerIsThread = 0 ;
duke@435 2103 }
duke@435 2104
duke@435 2105 // WaitSet management ...
duke@435 2106
duke@435 2107 inline void ObjectMonitor::AddWaiter(ObjectWaiter* node) {
duke@435 2108 assert(node != NULL, "should not dequeue NULL node");
duke@435 2109 assert(node->_prev == NULL, "node already in list");
duke@435 2110 assert(node->_next == NULL, "node already in list");
duke@435 2111 // put node at end of queue (circular doubly linked list)
duke@435 2112 if (_WaitSet == NULL) {
duke@435 2113 _WaitSet = node;
duke@435 2114 node->_prev = node;
duke@435 2115 node->_next = node;
duke@435 2116 } else {
duke@435 2117 ObjectWaiter* head = _WaitSet ;
duke@435 2118 ObjectWaiter* tail = head->_prev;
duke@435 2119 assert(tail->_next == head, "invariant check");
duke@435 2120 tail->_next = node;
duke@435 2121 head->_prev = node;
duke@435 2122 node->_next = head;
duke@435 2123 node->_prev = tail;
duke@435 2124 }
duke@435 2125 }
duke@435 2126
duke@435 2127 inline ObjectWaiter* ObjectMonitor::DequeueWaiter() {
duke@435 2128 // dequeue the very first waiter
duke@435 2129 ObjectWaiter* waiter = _WaitSet;
duke@435 2130 if (waiter) {
duke@435 2131 DequeueSpecificWaiter(waiter);
duke@435 2132 }
duke@435 2133 return waiter;
duke@435 2134 }
duke@435 2135
duke@435 2136 inline void ObjectMonitor::DequeueSpecificWaiter(ObjectWaiter* node) {
duke@435 2137 assert(node != NULL, "should not dequeue NULL node");
duke@435 2138 assert(node->_prev != NULL, "node already removed from list");
duke@435 2139 assert(node->_next != NULL, "node already removed from list");
duke@435 2140 // when the waiter has woken up because of interrupt,
duke@435 2141 // timeout or other spurious wake-up, dequeue the
duke@435 2142 // waiter from waiting list
duke@435 2143 ObjectWaiter* next = node->_next;
duke@435 2144 if (next == node) {
duke@435 2145 assert(node->_prev == node, "invariant check");
duke@435 2146 _WaitSet = NULL;
duke@435 2147 } else {
duke@435 2148 ObjectWaiter* prev = node->_prev;
duke@435 2149 assert(prev->_next == node, "invariant check");
duke@435 2150 assert(next->_prev == node, "invariant check");
duke@435 2151 next->_prev = prev;
duke@435 2152 prev->_next = next;
duke@435 2153 if (_WaitSet == node) {
duke@435 2154 _WaitSet = next;
duke@435 2155 }
duke@435 2156 }
duke@435 2157 node->_next = NULL;
duke@435 2158 node->_prev = NULL;
duke@435 2159 }
duke@435 2160
duke@435 2161 static char * kvGet (char * kvList, const char * Key) {
duke@435 2162 if (kvList == NULL) return NULL ;
duke@435 2163 size_t n = strlen (Key) ;
duke@435 2164 char * Search ;
duke@435 2165 for (Search = kvList ; *Search ; Search += strlen(Search) + 1) {
duke@435 2166 if (strncmp (Search, Key, n) == 0) {
duke@435 2167 if (Search[n] == '=') return Search + n + 1 ;
duke@435 2168 if (Search[n] == 0) return (char *) "1" ;
duke@435 2169 }
duke@435 2170 }
duke@435 2171 return NULL ;
duke@435 2172 }
duke@435 2173
duke@435 2174 static int kvGetInt (char * kvList, const char * Key, int Default) {
duke@435 2175 char * v = kvGet (kvList, Key) ;
duke@435 2176 int rslt = v ? ::strtol (v, NULL, 0) : Default ;
duke@435 2177 if (Knob_ReportSettings && v != NULL) {
duke@435 2178 ::printf (" SyncKnob: %s %d(%d)\n", Key, rslt, Default) ;
duke@435 2179 ::fflush (stdout) ;
duke@435 2180 }
duke@435 2181 return rslt ;
duke@435 2182 }
duke@435 2183
duke@435 2184 // By convention we unlink a contending thread from EntryList|cxq immediately
duke@435 2185 // after the thread acquires the lock in ::enter(). Equally, we could defer
duke@435 2186 // unlinking the thread until ::exit()-time.
duke@435 2187
duke@435 2188 void ObjectMonitor::UnlinkAfterAcquire (Thread * Self, ObjectWaiter * SelfNode)
duke@435 2189 {
duke@435 2190 assert (_owner == Self, "invariant") ;
duke@435 2191 assert (SelfNode->_thread == Self, "invariant") ;
duke@435 2192
duke@435 2193 if (SelfNode->TState == ObjectWaiter::TS_ENTER) {
duke@435 2194 // Normal case: remove Self from the DLL EntryList .
duke@435 2195 // This is a constant-time operation.
duke@435 2196 ObjectWaiter * nxt = SelfNode->_next ;
duke@435 2197 ObjectWaiter * prv = SelfNode->_prev ;
duke@435 2198 if (nxt != NULL) nxt->_prev = prv ;
duke@435 2199 if (prv != NULL) prv->_next = nxt ;
duke@435 2200 if (SelfNode == _EntryList ) _EntryList = nxt ;
duke@435 2201 assert (nxt == NULL || nxt->TState == ObjectWaiter::TS_ENTER, "invariant") ;
duke@435 2202 assert (prv == NULL || prv->TState == ObjectWaiter::TS_ENTER, "invariant") ;
duke@435 2203 TEVENT (Unlink from EntryList) ;
duke@435 2204 } else {
duke@435 2205 guarantee (SelfNode->TState == ObjectWaiter::TS_CXQ, "invariant") ;
duke@435 2206 // Inopportune interleaving -- Self is still on the cxq.
duke@435 2207 // This usually means the enqueue of self raced an exiting thread.
duke@435 2208 // Normally we'll find Self near the front of the cxq, so
duke@435 2209 // dequeueing is typically fast. If needbe we can accelerate
duke@435 2210 // this with some MCS/CHL-like bidirectional list hints and advisory
duke@435 2211 // back-links so dequeueing from the interior will normally operate
duke@435 2212 // in constant-time.
duke@435 2213 // Dequeue Self from either the head (with CAS) or from the interior
duke@435 2214 // with a linear-time scan and normal non-atomic memory operations.
duke@435 2215 // CONSIDER: if Self is on the cxq then simply drain cxq into EntryList
duke@435 2216 // and then unlink Self from EntryList. We have to drain eventually,
duke@435 2217 // so it might as well be now.
duke@435 2218
duke@435 2219 ObjectWaiter * v = _cxq ;
duke@435 2220 assert (v != NULL, "invariant") ;
duke@435 2221 if (v != SelfNode || Atomic::cmpxchg_ptr (SelfNode->_next, &_cxq, v) != v) {
duke@435 2222 // The CAS above can fail from interference IFF a "RAT" arrived.
duke@435 2223 // In that case Self must be in the interior and can no longer be
duke@435 2224 // at the head of cxq.
duke@435 2225 if (v == SelfNode) {
duke@435 2226 assert (_cxq != v, "invariant") ;
duke@435 2227 v = _cxq ; // CAS above failed - start scan at head of list
duke@435 2228 }
duke@435 2229 ObjectWaiter * p ;
duke@435 2230 ObjectWaiter * q = NULL ;
duke@435 2231 for (p = v ; p != NULL && p != SelfNode; p = p->_next) {
duke@435 2232 q = p ;
duke@435 2233 assert (p->TState == ObjectWaiter::TS_CXQ, "invariant") ;
duke@435 2234 }
duke@435 2235 assert (v != SelfNode, "invariant") ;
duke@435 2236 assert (p == SelfNode, "Node not found on cxq") ;
duke@435 2237 assert (p != _cxq, "invariant") ;
duke@435 2238 assert (q != NULL, "invariant") ;
duke@435 2239 assert (q->_next == p, "invariant") ;
duke@435 2240 q->_next = p->_next ;
duke@435 2241 }
duke@435 2242 TEVENT (Unlink from cxq) ;
duke@435 2243 }
duke@435 2244
duke@435 2245 // Diagnostic hygiene ...
duke@435 2246 SelfNode->_prev = (ObjectWaiter *) 0xBAD ;
duke@435 2247 SelfNode->_next = (ObjectWaiter *) 0xBAD ;
duke@435 2248 SelfNode->TState = ObjectWaiter::TS_RUN ;
duke@435 2249 }
duke@435 2250
duke@435 2251 // Caveat: TryLock() is not necessarily serializing if it returns failure.
duke@435 2252 // Callers must compensate as needed.
duke@435 2253
duke@435 2254 int ObjectMonitor::TryLock (Thread * Self) {
duke@435 2255 for (;;) {
duke@435 2256 void * own = _owner ;
duke@435 2257 if (own != NULL) return 0 ;
duke@435 2258 if (Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) {
duke@435 2259 // Either guarantee _recursions == 0 or set _recursions = 0.
duke@435 2260 assert (_recursions == 0, "invariant") ;
duke@435 2261 assert (_owner == Self, "invariant") ;
duke@435 2262 // CONSIDER: set or assert that OwnerIsThread == 1
duke@435 2263 return 1 ;
duke@435 2264 }
duke@435 2265 // The lock had been free momentarily, but we lost the race to the lock.
duke@435 2266 // Interference -- the CAS failed.
duke@435 2267 // We can either return -1 or retry.
duke@435 2268 // Retry doesn't make as much sense because the lock was just acquired.
duke@435 2269 if (true) return -1 ;
duke@435 2270 }
duke@435 2271 }
duke@435 2272
duke@435 2273 // NotRunnable() -- informed spinning
duke@435 2274 //
duke@435 2275 // Don't bother spinning if the owner is not eligible to drop the lock.
duke@435 2276 // Peek at the owner's schedctl.sc_state and Thread._thread_values and
duke@435 2277 // spin only if the owner thread is _thread_in_Java or _thread_in_vm.
duke@435 2278 // The thread must be runnable in order to drop the lock in timely fashion.
duke@435 2279 // If the _owner is not runnable then spinning will not likely be
duke@435 2280 // successful (profitable).
duke@435 2281 //
duke@435 2282 // Beware -- the thread referenced by _owner could have died
duke@435 2283 // so a simply fetch from _owner->_thread_state might trap.
duke@435 2284 // Instead, we use SafeFetchXX() to safely LD _owner->_thread_state.
duke@435 2285 // Because of the lifecycle issues the schedctl and _thread_state values
duke@435 2286 // observed by NotRunnable() might be garbage. NotRunnable must
duke@435 2287 // tolerate this and consider the observed _thread_state value
duke@435 2288 // as advisory.
duke@435 2289 //
duke@435 2290 // Beware too, that _owner is sometimes a BasicLock address and sometimes
duke@435 2291 // a thread pointer. We differentiate the two cases with OwnerIsThread.
duke@435 2292 // Alternately, we might tag the type (thread pointer vs basiclock pointer)
duke@435 2293 // with the LSB of _owner. Another option would be to probablistically probe
duke@435 2294 // the putative _owner->TypeTag value.
duke@435 2295 //
duke@435 2296 // Checking _thread_state isn't perfect. Even if the thread is
duke@435 2297 // in_java it might be blocked on a page-fault or have been preempted
duke@435 2298 // and sitting on a ready/dispatch queue. _thread state in conjunction
duke@435 2299 // with schedctl.sc_state gives us a good picture of what the
duke@435 2300 // thread is doing, however.
duke@435 2301 //
duke@435 2302 // TODO: check schedctl.sc_state.
duke@435 2303 // We'll need to use SafeFetch32() to read from the schedctl block.
duke@435 2304 // See RFE #5004247 and http://sac.sfbay.sun.com/Archives/CaseLog/arc/PSARC/2005/351/
duke@435 2305 //
duke@435 2306 // The return value from NotRunnable() is *advisory* -- the
duke@435 2307 // result is based on sampling and is not necessarily coherent.
duke@435 2308 // The caller must tolerate false-negative and false-positive errors.
duke@435 2309 // Spinning, in general, is probabilistic anyway.
duke@435 2310
duke@435 2311
duke@435 2312 int ObjectMonitor::NotRunnable (Thread * Self, Thread * ox) {
duke@435 2313 // Check either OwnerIsThread or ox->TypeTag == 2BAD.
duke@435 2314 if (!OwnerIsThread) return 0 ;
duke@435 2315
duke@435 2316 if (ox == NULL) return 0 ;
duke@435 2317
duke@435 2318 // Avoid transitive spinning ...
duke@435 2319 // Say T1 spins or blocks trying to acquire L. T1._Stalled is set to L.
duke@435 2320 // Immediately after T1 acquires L it's possible that T2, also
duke@435 2321 // spinning on L, will see L.Owner=T1 and T1._Stalled=L.
duke@435 2322 // This occurs transiently after T1 acquired L but before
duke@435 2323 // T1 managed to clear T1.Stalled. T2 does not need to abort
duke@435 2324 // its spin in this circumstance.
duke@435 2325 intptr_t BlockedOn = SafeFetchN ((intptr_t *) &ox->_Stalled, intptr_t(1)) ;
duke@435 2326
duke@435 2327 if (BlockedOn == 1) return 1 ;
duke@435 2328 if (BlockedOn != 0) {
duke@435 2329 return BlockedOn != intptr_t(this) && _owner == ox ;
duke@435 2330 }
duke@435 2331
duke@435 2332 assert (sizeof(((JavaThread *)ox)->_thread_state == sizeof(int)), "invariant") ;
duke@435 2333 int jst = SafeFetch32 ((int *) &((JavaThread *) ox)->_thread_state, -1) ; ;
duke@435 2334 // consider also: jst != _thread_in_Java -- but that's overspecific.
duke@435 2335 return jst == _thread_blocked || jst == _thread_in_native ;
duke@435 2336 }
duke@435 2337
duke@435 2338
duke@435 2339 // Adaptive spin-then-block - rational spinning
duke@435 2340 //
duke@435 2341 // Note that we spin "globally" on _owner with a classic SMP-polite TATAS
duke@435 2342 // algorithm. On high order SMP systems it would be better to start with
duke@435 2343 // a brief global spin and then revert to spinning locally. In the spirit of MCS/CLH,
duke@435 2344 // a contending thread could enqueue itself on the cxq and then spin locally
duke@435 2345 // on a thread-specific variable such as its ParkEvent._Event flag.
duke@435 2346 // That's left as an exercise for the reader. Note that global spinning is
duke@435 2347 // not problematic on Niagara, as the L2$ serves the interconnect and has both
duke@435 2348 // low latency and massive bandwidth.
duke@435 2349 //
duke@435 2350 // Broadly, we can fix the spin frequency -- that is, the % of contended lock
duke@435 2351 // acquisition attempts where we opt to spin -- at 100% and vary the spin count
duke@435 2352 // (duration) or we can fix the count at approximately the duration of
duke@435 2353 // a context switch and vary the frequency. Of course we could also
duke@435 2354 // vary both satisfying K == Frequency * Duration, where K is adaptive by monitor.
duke@435 2355 // See http://j2se.east/~dice/PERSIST/040824-AdaptiveSpinning.html.
duke@435 2356 //
duke@435 2357 // This implementation varies the duration "D", where D varies with
duke@435 2358 // the success rate of recent spin attempts. (D is capped at approximately
duke@435 2359 // length of a round-trip context switch). The success rate for recent
duke@435 2360 // spin attempts is a good predictor of the success rate of future spin
duke@435 2361 // attempts. The mechanism adapts automatically to varying critical
duke@435 2362 // section length (lock modality), system load and degree of parallelism.
duke@435 2363 // D is maintained per-monitor in _SpinDuration and is initialized
duke@435 2364 // optimistically. Spin frequency is fixed at 100%.
duke@435 2365 //
duke@435 2366 // Note that _SpinDuration is volatile, but we update it without locks
duke@435 2367 // or atomics. The code is designed so that _SpinDuration stays within
duke@435 2368 // a reasonable range even in the presence of races. The arithmetic
duke@435 2369 // operations on _SpinDuration are closed over the domain of legal values,
duke@435 2370 // so at worst a race will install and older but still legal value.
duke@435 2371 // At the very worst this introduces some apparent non-determinism.
duke@435 2372 // We might spin when we shouldn't or vice-versa, but since the spin
duke@435 2373 // count are relatively short, even in the worst case, the effect is harmless.
duke@435 2374 //
duke@435 2375 // Care must be taken that a low "D" value does not become an
duke@435 2376 // an absorbing state. Transient spinning failures -- when spinning
duke@435 2377 // is overall profitable -- should not cause the system to converge
duke@435 2378 // on low "D" values. We want spinning to be stable and predictable
duke@435 2379 // and fairly responsive to change and at the same time we don't want
duke@435 2380 // it to oscillate, become metastable, be "too" non-deterministic,
duke@435 2381 // or converge on or enter undesirable stable absorbing states.
duke@435 2382 //
duke@435 2383 // We implement a feedback-based control system -- using past behavior
duke@435 2384 // to predict future behavior. We face two issues: (a) if the
duke@435 2385 // input signal is random then the spin predictor won't provide optimal
duke@435 2386 // results, and (b) if the signal frequency is too high then the control
duke@435 2387 // system, which has some natural response lag, will "chase" the signal.
duke@435 2388 // (b) can arise from multimodal lock hold times. Transient preemption
duke@435 2389 // can also result in apparent bimodal lock hold times.
duke@435 2390 // Although sub-optimal, neither condition is particularly harmful, as
duke@435 2391 // in the worst-case we'll spin when we shouldn't or vice-versa.
duke@435 2392 // The maximum spin duration is rather short so the failure modes aren't bad.
duke@435 2393 // To be conservative, I've tuned the gain in system to bias toward
duke@435 2394 // _not spinning. Relatedly, the system can sometimes enter a mode where it
duke@435 2395 // "rings" or oscillates between spinning and not spinning. This happens
duke@435 2396 // when spinning is just on the cusp of profitability, however, so the
duke@435 2397 // situation is not dire. The state is benign -- there's no need to add
duke@435 2398 // hysteresis control to damp the transition rate between spinning and
duke@435 2399 // not spinning.
duke@435 2400 //
duke@435 2401 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
duke@435 2402 //
duke@435 2403 // Spin-then-block strategies ...
duke@435 2404 //
duke@435 2405 // Thoughts on ways to improve spinning :
duke@435 2406 //
duke@435 2407 // * Periodically call {psr_}getloadavg() while spinning, and
duke@435 2408 // permit unbounded spinning if the load average is <
duke@435 2409 // the number of processors. Beware, however, that getloadavg()
duke@435 2410 // is exceptionally fast on solaris (about 1/10 the cost of a full
duke@435 2411 // spin cycle, but quite expensive on linux. Beware also, that
duke@435 2412 // multiple JVMs could "ring" or oscillate in a feedback loop.
duke@435 2413 // Sufficient damping would solve that problem.
duke@435 2414 //
duke@435 2415 // * We currently use spin loops with iteration counters to approximate
duke@435 2416 // spinning for some interval. Given the availability of high-precision
duke@435 2417 // time sources such as gethrtime(), %TICK, %STICK, RDTSC, etc., we should
duke@435 2418 // someday reimplement the spin loops to duration-based instead of iteration-based.
duke@435 2419 //
duke@435 2420 // * Don't spin if there are more than N = (CPUs/2) threads
duke@435 2421 // currently spinning on the monitor (or globally).
duke@435 2422 // That is, limit the number of concurrent spinners.
duke@435 2423 // We might also limit the # of spinners in the JVM, globally.
duke@435 2424 //
duke@435 2425 // * If a spinning thread observes _owner change hands it should
duke@435 2426 // abort the spin (and park immediately) or at least debit
duke@435 2427 // the spin counter by a large "penalty".
duke@435 2428 //
duke@435 2429 // * Classically, the spin count is either K*(CPUs-1) or is a
duke@435 2430 // simple constant that approximates the length of a context switch.
duke@435 2431 // We currently use a value -- computed by a special utility -- that
duke@435 2432 // approximates round-trip context switch times.
duke@435 2433 //
duke@435 2434 // * Normally schedctl_start()/_stop() is used to advise the kernel
duke@435 2435 // to avoid preempting threads that are running in short, bounded
duke@435 2436 // critical sections. We could use the schedctl hooks in an inverted
duke@435 2437 // sense -- spinners would set the nopreempt flag, but poll the preempt
duke@435 2438 // pending flag. If a spinner observed a pending preemption it'd immediately
duke@435 2439 // abort the spin and park. As such, the schedctl service acts as
duke@435 2440 // a preemption warning mechanism.
duke@435 2441 //
duke@435 2442 // * In lieu of spinning, if the system is running below saturation
duke@435 2443 // (that is, loadavg() << #cpus), we can instead suppress futile
duke@435 2444 // wakeup throttling, or even wake more than one successor at exit-time.
duke@435 2445 // The net effect is largely equivalent to spinning. In both cases,
duke@435 2446 // contending threads go ONPROC and opportunistically attempt to acquire
duke@435 2447 // the lock, decreasing lock handover latency at the expense of wasted
duke@435 2448 // cycles and context switching.
duke@435 2449 //
duke@435 2450 // * We might to spin less after we've parked as the thread will
duke@435 2451 // have less $ and TLB affinity with the processor.
duke@435 2452 // Likewise, we might spin less if we come ONPROC on a different
duke@435 2453 // processor or after a long period (>> rechose_interval).
duke@435 2454 //
duke@435 2455 // * A table-driven state machine similar to Solaris' dispadmin scheduling
duke@435 2456 // tables might be a better design. Instead of encoding information in
duke@435 2457 // _SpinDuration, _SpinFreq and _SpinClock we'd just use explicit,
duke@435 2458 // discrete states. Success or failure during a spin would drive
duke@435 2459 // state transitions, and each state node would contain a spin count.
duke@435 2460 //
duke@435 2461 // * If the processor is operating in a mode intended to conserve power
duke@435 2462 // (such as Intel's SpeedStep) or to reduce thermal output (thermal
duke@435 2463 // step-down mode) then the Java synchronization subsystem should
duke@435 2464 // forgo spinning.
duke@435 2465 //
duke@435 2466 // * The minimum spin duration should be approximately the worst-case
duke@435 2467 // store propagation latency on the platform. That is, the time
duke@435 2468 // it takes a store on CPU A to become visible on CPU B, where A and
duke@435 2469 // B are "distant".
duke@435 2470 //
duke@435 2471 // * We might want to factor a thread's priority in the spin policy.
duke@435 2472 // Threads with a higher priority might spin for slightly longer.
duke@435 2473 // Similarly, if we use back-off in the TATAS loop, lower priority
duke@435 2474 // threads might back-off longer. We don't currently use a
duke@435 2475 // thread's priority when placing it on the entry queue. We may
duke@435 2476 // want to consider doing so in future releases.
duke@435 2477 //
duke@435 2478 // * We might transiently drop a thread's scheduling priority while it spins.
duke@435 2479 // SCHED_BATCH on linux and FX scheduling class at priority=0 on Solaris
duke@435 2480 // would suffice. We could even consider letting the thread spin indefinitely at
duke@435 2481 // a depressed or "idle" priority. This brings up fairness issues, however --
duke@435 2482 // in a saturated system a thread would with a reduced priority could languish
duke@435 2483 // for extended periods on the ready queue.
duke@435 2484 //
duke@435 2485 // * While spinning try to use the otherwise wasted time to help the VM make
duke@435 2486 // progress:
duke@435 2487 //
duke@435 2488 // -- YieldTo() the owner, if the owner is OFFPROC but ready
duke@435 2489 // Done our remaining quantum directly to the ready thread.
duke@435 2490 // This helps "push" the lock owner through the critical section.
duke@435 2491 // It also tends to improve affinity/locality as the lock
duke@435 2492 // "migrates" less frequently between CPUs.
duke@435 2493 // -- Walk our own stack in anticipation of blocking. Memoize the roots.
duke@435 2494 // -- Perform strand checking for other thread. Unpark potential strandees.
duke@435 2495 // -- Help GC: trace or mark -- this would need to be a bounded unit of work.
duke@435 2496 // Unfortunately this will pollute our $ and TLBs. Recall that we
duke@435 2497 // spin to avoid context switching -- context switching has an
duke@435 2498 // immediate cost in latency, a disruptive cost to other strands on a CMT
duke@435 2499 // processor, and an amortized cost because of the D$ and TLB cache
duke@435 2500 // reload transient when the thread comes back ONPROC and repopulates
duke@435 2501 // $s and TLBs.
duke@435 2502 // -- call getloadavg() to see if the system is saturated. It'd probably
duke@435 2503 // make sense to call getloadavg() half way through the spin.
duke@435 2504 // If the system isn't at full capacity the we'd simply reset
duke@435 2505 // the spin counter to and extend the spin attempt.
duke@435 2506 // -- Doug points out that we should use the same "helping" policy
duke@435 2507 // in thread.yield().
duke@435 2508 //
duke@435 2509 // * Try MONITOR-MWAIT on systems that support those instructions.
duke@435 2510 //
duke@435 2511 // * The spin statistics that drive spin decisions & frequency are
duke@435 2512 // maintained in the objectmonitor structure so if we deflate and reinflate
duke@435 2513 // we lose spin state. In practice this is not usually a concern
duke@435 2514 // as the default spin state after inflation is aggressive (optimistic)
duke@435 2515 // and tends toward spinning. So in the worst case for a lock where
duke@435 2516 // spinning is not profitable we may spin unnecessarily for a brief
duke@435 2517 // period. But then again, if a lock is contended it'll tend not to deflate
duke@435 2518 // in the first place.
duke@435 2519
duke@435 2520
duke@435 2521 intptr_t ObjectMonitor::SpinCallbackArgument = 0 ;
duke@435 2522 int (*ObjectMonitor::SpinCallbackFunction)(intptr_t, int) = NULL ;
duke@435 2523
duke@435 2524 // Spinning: Fixed frequency (100%), vary duration
duke@435 2525
duke@435 2526 int ObjectMonitor::TrySpin_VaryDuration (Thread * Self) {
duke@435 2527
duke@435 2528 // Dumb, brutal spin. Good for comparative measurements against adaptive spinning.
duke@435 2529 int ctr = Knob_FixedSpin ;
duke@435 2530 if (ctr != 0) {
duke@435 2531 while (--ctr >= 0) {
duke@435 2532 if (TryLock (Self) > 0) return 1 ;
duke@435 2533 SpinPause () ;
duke@435 2534 }
duke@435 2535 return 0 ;
duke@435 2536 }
duke@435 2537
duke@435 2538 for (ctr = Knob_PreSpin + 1; --ctr >= 0 ; ) {
duke@435 2539 if (TryLock(Self) > 0) {
duke@435 2540 // Increase _SpinDuration ...
duke@435 2541 // Note that we don't clamp SpinDuration precisely at SpinLimit.
duke@435 2542 // Raising _SpurDuration to the poverty line is key.
duke@435 2543 int x = _SpinDuration ;
duke@435 2544 if (x < Knob_SpinLimit) {
duke@435 2545 if (x < Knob_Poverty) x = Knob_Poverty ;
duke@435 2546 _SpinDuration = x + Knob_BonusB ;
duke@435 2547 }
duke@435 2548 return 1 ;
duke@435 2549 }
duke@435 2550 SpinPause () ;
duke@435 2551 }
duke@435 2552
duke@435 2553 // Admission control - verify preconditions for spinning
duke@435 2554 //
duke@435 2555 // We always spin a little bit, just to prevent _SpinDuration == 0 from
duke@435 2556 // becoming an absorbing state. Put another way, we spin briefly to
duke@435 2557 // sample, just in case the system load, parallelism, contention, or lock
duke@435 2558 // modality changed.
duke@435 2559 //
duke@435 2560 // Consider the following alternative:
duke@435 2561 // Periodically set _SpinDuration = _SpinLimit and try a long/full
duke@435 2562 // spin attempt. "Periodically" might mean after a tally of
duke@435 2563 // the # of failed spin attempts (or iterations) reaches some threshold.
duke@435 2564 // This takes us into the realm of 1-out-of-N spinning, where we
duke@435 2565 // hold the duration constant but vary the frequency.
duke@435 2566
duke@435 2567 ctr = _SpinDuration ;
duke@435 2568 if (ctr < Knob_SpinBase) ctr = Knob_SpinBase ;
duke@435 2569 if (ctr <= 0) return 0 ;
duke@435 2570
duke@435 2571 if (Knob_SuccRestrict && _succ != NULL) return 0 ;
duke@435 2572 if (Knob_OState && NotRunnable (Self, (Thread *) _owner)) {
duke@435 2573 TEVENT (Spin abort - notrunnable [TOP]);
duke@435 2574 return 0 ;
duke@435 2575 }
duke@435 2576
duke@435 2577 int MaxSpin = Knob_MaxSpinners ;
duke@435 2578 if (MaxSpin >= 0) {
duke@435 2579 if (_Spinner > MaxSpin) {
duke@435 2580 TEVENT (Spin abort -- too many spinners) ;
duke@435 2581 return 0 ;
duke@435 2582 }
duke@435 2583 // Slighty racy, but benign ...
duke@435 2584 Adjust (&_Spinner, 1) ;
duke@435 2585 }
duke@435 2586
duke@435 2587 // We're good to spin ... spin ingress.
duke@435 2588 // CONSIDER: use Prefetch::write() to avoid RTS->RTO upgrades
duke@435 2589 // when preparing to LD...CAS _owner, etc and the CAS is likely
duke@435 2590 // to succeed.
duke@435 2591 int hits = 0 ;
duke@435 2592 int msk = 0 ;
duke@435 2593 int caspty = Knob_CASPenalty ;
duke@435 2594 int oxpty = Knob_OXPenalty ;
duke@435 2595 int sss = Knob_SpinSetSucc ;
duke@435 2596 if (sss && _succ == NULL ) _succ = Self ;
duke@435 2597 Thread * prv = NULL ;
duke@435 2598
duke@435 2599 // There are three ways to exit the following loop:
duke@435 2600 // 1. A successful spin where this thread has acquired the lock.
duke@435 2601 // 2. Spin failure with prejudice
duke@435 2602 // 3. Spin failure without prejudice
duke@435 2603
duke@435 2604 while (--ctr >= 0) {
duke@435 2605
duke@435 2606 // Periodic polling -- Check for pending GC
duke@435 2607 // Threads may spin while they're unsafe.
duke@435 2608 // We don't want spinning threads to delay the JVM from reaching
duke@435 2609 // a stop-the-world safepoint or to steal cycles from GC.
duke@435 2610 // If we detect a pending safepoint we abort in order that
duke@435 2611 // (a) this thread, if unsafe, doesn't delay the safepoint, and (b)
duke@435 2612 // this thread, if safe, doesn't steal cycles from GC.
duke@435 2613 // This is in keeping with the "no loitering in runtime" rule.
duke@435 2614 // We periodically check to see if there's a safepoint pending.
duke@435 2615 if ((ctr & 0xFF) == 0) {
duke@435 2616 if (SafepointSynchronize::do_call_back()) {
duke@435 2617 TEVENT (Spin: safepoint) ;
duke@435 2618 goto Abort ; // abrupt spin egress
duke@435 2619 }
duke@435 2620 if (Knob_UsePause & 1) SpinPause () ;
duke@435 2621
duke@435 2622 int (*scb)(intptr_t,int) = SpinCallbackFunction ;
duke@435 2623 if (hits > 50 && scb != NULL) {
duke@435 2624 int abend = (*scb)(SpinCallbackArgument, 0) ;
duke@435 2625 }
duke@435 2626 }
duke@435 2627
duke@435 2628 if (Knob_UsePause & 2) SpinPause() ;
duke@435 2629
duke@435 2630 // Exponential back-off ... Stay off the bus to reduce coherency traffic.
duke@435 2631 // This is useful on classic SMP systems, but is of less utility on
duke@435 2632 // N1-style CMT platforms.
duke@435 2633 //
duke@435 2634 // Trade-off: lock acquisition latency vs coherency bandwidth.
duke@435 2635 // Lock hold times are typically short. A histogram
duke@435 2636 // of successful spin attempts shows that we usually acquire
duke@435 2637 // the lock early in the spin. That suggests we want to
duke@435 2638 // sample _owner frequently in the early phase of the spin,
duke@435 2639 // but then back-off and sample less frequently as the spin
duke@435 2640 // progresses. The back-off makes a good citizen on SMP big
duke@435 2641 // SMP systems. Oversampling _owner can consume excessive
duke@435 2642 // coherency bandwidth. Relatedly, if we _oversample _owner we
duke@435 2643 // can inadvertently interfere with the the ST m->owner=null.
duke@435 2644 // executed by the lock owner.
duke@435 2645 if (ctr & msk) continue ;
duke@435 2646 ++hits ;
duke@435 2647 if ((hits & 0xF) == 0) {
duke@435 2648 // The 0xF, above, corresponds to the exponent.
duke@435 2649 // Consider: (msk+1)|msk
duke@435 2650 msk = ((msk << 2)|3) & BackOffMask ;
duke@435 2651 }
duke@435 2652
duke@435 2653 // Probe _owner with TATAS
duke@435 2654 // If this thread observes the monitor transition or flicker
duke@435 2655 // from locked to unlocked to locked, then the odds that this
duke@435 2656 // thread will acquire the lock in this spin attempt go down
duke@435 2657 // considerably. The same argument applies if the CAS fails
duke@435 2658 // or if we observe _owner change from one non-null value to
duke@435 2659 // another non-null value. In such cases we might abort
duke@435 2660 // the spin without prejudice or apply a "penalty" to the
duke@435 2661 // spin count-down variable "ctr", reducing it by 100, say.
duke@435 2662
duke@435 2663 Thread * ox = (Thread *) _owner ;
duke@435 2664 if (ox == NULL) {
duke@435 2665 ox = (Thread *) Atomic::cmpxchg_ptr (Self, &_owner, NULL) ;
duke@435 2666 if (ox == NULL) {
duke@435 2667 // The CAS succeeded -- this thread acquired ownership
duke@435 2668 // Take care of some bookkeeping to exit spin state.
duke@435 2669 if (sss && _succ == Self) {
duke@435 2670 _succ = NULL ;
duke@435 2671 }
duke@435 2672 if (MaxSpin > 0) Adjust (&_Spinner, -1) ;
duke@435 2673
duke@435 2674 // Increase _SpinDuration :
duke@435 2675 // The spin was successful (profitable) so we tend toward
duke@435 2676 // longer spin attempts in the future.
duke@435 2677 // CONSIDER: factor "ctr" into the _SpinDuration adjustment.
duke@435 2678 // If we acquired the lock early in the spin cycle it
duke@435 2679 // makes sense to increase _SpinDuration proportionally.
duke@435 2680 // Note that we don't clamp SpinDuration precisely at SpinLimit.
duke@435 2681 int x = _SpinDuration ;
duke@435 2682 if (x < Knob_SpinLimit) {
duke@435 2683 if (x < Knob_Poverty) x = Knob_Poverty ;
duke@435 2684 _SpinDuration = x + Knob_Bonus ;
duke@435 2685 }
duke@435 2686 return 1 ;
duke@435 2687 }
duke@435 2688
duke@435 2689 // The CAS failed ... we can take any of the following actions:
duke@435 2690 // * penalize: ctr -= Knob_CASPenalty
duke@435 2691 // * exit spin with prejudice -- goto Abort;
duke@435 2692 // * exit spin without prejudice.
duke@435 2693 // * Since CAS is high-latency, retry again immediately.
duke@435 2694 prv = ox ;
duke@435 2695 TEVENT (Spin: cas failed) ;
duke@435 2696 if (caspty == -2) break ;
duke@435 2697 if (caspty == -1) goto Abort ;
duke@435 2698 ctr -= caspty ;
duke@435 2699 continue ;
duke@435 2700 }
duke@435 2701
duke@435 2702 // Did lock ownership change hands ?
duke@435 2703 if (ox != prv && prv != NULL ) {
duke@435 2704 TEVENT (spin: Owner changed)
duke@435 2705 if (oxpty == -2) break ;
duke@435 2706 if (oxpty == -1) goto Abort ;
duke@435 2707 ctr -= oxpty ;
duke@435 2708 }
duke@435 2709 prv = ox ;
duke@435 2710
duke@435 2711 // Abort the spin if the owner is not executing.
duke@435 2712 // The owner must be executing in order to drop the lock.
duke@435 2713 // Spinning while the owner is OFFPROC is idiocy.
duke@435 2714 // Consider: ctr -= RunnablePenalty ;
duke@435 2715 if (Knob_OState && NotRunnable (Self, ox)) {
duke@435 2716 TEVENT (Spin abort - notrunnable);
duke@435 2717 goto Abort ;
duke@435 2718 }
duke@435 2719 if (sss && _succ == NULL ) _succ = Self ;
duke@435 2720 }
duke@435 2721
duke@435 2722 // Spin failed with prejudice -- reduce _SpinDuration.
duke@435 2723 // TODO: Use an AIMD-like policy to adjust _SpinDuration.
duke@435 2724 // AIMD is globally stable.
duke@435 2725 TEVENT (Spin failure) ;
duke@435 2726 {
duke@435 2727 int x = _SpinDuration ;
duke@435 2728 if (x > 0) {
duke@435 2729 // Consider an AIMD scheme like: x -= (x >> 3) + 100
duke@435 2730 // This is globally sample and tends to damp the response.
duke@435 2731 x -= Knob_Penalty ;
duke@435 2732 if (x < 0) x = 0 ;
duke@435 2733 _SpinDuration = x ;
duke@435 2734 }
duke@435 2735 }
duke@435 2736
duke@435 2737 Abort:
duke@435 2738 if (MaxSpin >= 0) Adjust (&_Spinner, -1) ;
duke@435 2739 if (sss && _succ == Self) {
duke@435 2740 _succ = NULL ;
duke@435 2741 // Invariant: after setting succ=null a contending thread
duke@435 2742 // must recheck-retry _owner before parking. This usually happens
duke@435 2743 // in the normal usage of TrySpin(), but it's safest
duke@435 2744 // to make TrySpin() as foolproof as possible.
duke@435 2745 OrderAccess::fence() ;
duke@435 2746 if (TryLock(Self) > 0) return 1 ;
duke@435 2747 }
duke@435 2748 return 0 ;
duke@435 2749 }
duke@435 2750
duke@435 2751 #define TrySpin TrySpin_VaryDuration
duke@435 2752
duke@435 2753 static void DeferredInitialize () {
duke@435 2754 if (InitDone > 0) return ;
duke@435 2755 if (Atomic::cmpxchg (-1, &InitDone, 0) != 0) {
duke@435 2756 while (InitDone != 1) ;
duke@435 2757 return ;
duke@435 2758 }
duke@435 2759
duke@435 2760 // One-shot global initialization ...
duke@435 2761 // The initialization is idempotent, so we don't need locks.
duke@435 2762 // In the future consider doing this via os::init_2().
duke@435 2763 // SyncKnobs consist of <Key>=<Value> pairs in the style
duke@435 2764 // of environment variables. Start by converting ':' to NUL.
duke@435 2765
duke@435 2766 if (SyncKnobs == NULL) SyncKnobs = "" ;
duke@435 2767
duke@435 2768 size_t sz = strlen (SyncKnobs) ;
duke@435 2769 char * knobs = (char *) malloc (sz + 2) ;
duke@435 2770 if (knobs == NULL) {
duke@435 2771 vm_exit_out_of_memory (sz + 2, "Parse SyncKnobs") ;
duke@435 2772 guarantee (0, "invariant") ;
duke@435 2773 }
duke@435 2774 strcpy (knobs, SyncKnobs) ;
duke@435 2775 knobs[sz+1] = 0 ;
duke@435 2776 for (char * p = knobs ; *p ; p++) {
duke@435 2777 if (*p == ':') *p = 0 ;
duke@435 2778 }
duke@435 2779
duke@435 2780 #define SETKNOB(x) { Knob_##x = kvGetInt (knobs, #x, Knob_##x); }
duke@435 2781 SETKNOB(ReportSettings) ;
duke@435 2782 SETKNOB(Verbose) ;
duke@435 2783 SETKNOB(FixedSpin) ;
duke@435 2784 SETKNOB(SpinLimit) ;
duke@435 2785 SETKNOB(SpinBase) ;
duke@435 2786 SETKNOB(SpinBackOff);
duke@435 2787 SETKNOB(CASPenalty) ;
duke@435 2788 SETKNOB(OXPenalty) ;
duke@435 2789 SETKNOB(LogSpins) ;
duke@435 2790 SETKNOB(SpinSetSucc) ;
duke@435 2791 SETKNOB(SuccEnabled) ;
duke@435 2792 SETKNOB(SuccRestrict) ;
duke@435 2793 SETKNOB(Penalty) ;
duke@435 2794 SETKNOB(Bonus) ;
duke@435 2795 SETKNOB(BonusB) ;
duke@435 2796 SETKNOB(Poverty) ;
duke@435 2797 SETKNOB(SpinAfterFutile) ;
duke@435 2798 SETKNOB(UsePause) ;
duke@435 2799 SETKNOB(SpinEarly) ;
duke@435 2800 SETKNOB(OState) ;
duke@435 2801 SETKNOB(MaxSpinners) ;
duke@435 2802 SETKNOB(PreSpin) ;
duke@435 2803 SETKNOB(ExitPolicy) ;
duke@435 2804 SETKNOB(QMode);
duke@435 2805 SETKNOB(ResetEvent) ;
duke@435 2806 SETKNOB(MoveNotifyee) ;
duke@435 2807 SETKNOB(FastHSSEC) ;
duke@435 2808 #undef SETKNOB
duke@435 2809
duke@435 2810 if (os::is_MP()) {
duke@435 2811 BackOffMask = (1 << Knob_SpinBackOff) - 1 ;
duke@435 2812 if (Knob_ReportSettings) ::printf ("BackOffMask=%X\n", BackOffMask) ;
duke@435 2813 // CONSIDER: BackOffMask = ROUNDUP_NEXT_POWER2 (ncpus-1)
duke@435 2814 } else {
duke@435 2815 Knob_SpinLimit = 0 ;
duke@435 2816 Knob_SpinBase = 0 ;
duke@435 2817 Knob_PreSpin = 0 ;
duke@435 2818 Knob_FixedSpin = -1 ;
duke@435 2819 }
duke@435 2820
duke@435 2821 if (Knob_LogSpins == 0) {
duke@435 2822 ObjectSynchronizer::_sync_FailedSpins = NULL ;
duke@435 2823 }
duke@435 2824
duke@435 2825 free (knobs) ;
duke@435 2826 OrderAccess::fence() ;
duke@435 2827 InitDone = 1 ;
duke@435 2828 }
duke@435 2829
duke@435 2830 // Theory of operations -- Monitors lists, thread residency, etc:
duke@435 2831 //
duke@435 2832 // * A thread acquires ownership of a monitor by successfully
duke@435 2833 // CAS()ing the _owner field from null to non-null.
duke@435 2834 //
duke@435 2835 // * Invariant: A thread appears on at most one monitor list --
duke@435 2836 // cxq, EntryList or WaitSet -- at any one time.
duke@435 2837 //
duke@435 2838 // * Contending threads "push" themselves onto the cxq with CAS
duke@435 2839 // and then spin/park.
duke@435 2840 //
duke@435 2841 // * After a contending thread eventually acquires the lock it must
duke@435 2842 // dequeue itself from either the EntryList or the cxq.
duke@435 2843 //
duke@435 2844 // * The exiting thread identifies and unparks an "heir presumptive"
duke@435 2845 // tentative successor thread on the EntryList. Critically, the
duke@435 2846 // exiting thread doesn't unlink the successor thread from the EntryList.
duke@435 2847 // After having been unparked, the wakee will recontend for ownership of
duke@435 2848 // the monitor. The successor (wakee) will either acquire the lock or
duke@435 2849 // re-park itself.
duke@435 2850 //
duke@435 2851 // Succession is provided for by a policy of competitive handoff.
duke@435 2852 // The exiting thread does _not_ grant or pass ownership to the
duke@435 2853 // successor thread. (This is also referred to as "handoff" succession").
duke@435 2854 // Instead the exiting thread releases ownership and possibly wakes
duke@435 2855 // a successor, so the successor can (re)compete for ownership of the lock.
duke@435 2856 // If the EntryList is empty but the cxq is populated the exiting
duke@435 2857 // thread will drain the cxq into the EntryList. It does so by
duke@435 2858 // by detaching the cxq (installing null with CAS) and folding
duke@435 2859 // the threads from the cxq into the EntryList. The EntryList is
duke@435 2860 // doubly linked, while the cxq is singly linked because of the
duke@435 2861 // CAS-based "push" used to enqueue recently arrived threads (RATs).
duke@435 2862 //
duke@435 2863 // * Concurrency invariants:
duke@435 2864 //
duke@435 2865 // -- only the monitor owner may access or mutate the EntryList.
duke@435 2866 // The mutex property of the monitor itself protects the EntryList
duke@435 2867 // from concurrent interference.
duke@435 2868 // -- Only the monitor owner may detach the cxq.
duke@435 2869 //
duke@435 2870 // * The monitor entry list operations avoid locks, but strictly speaking
duke@435 2871 // they're not lock-free. Enter is lock-free, exit is not.
duke@435 2872 // See http://j2se.east/~dice/PERSIST/040825-LockFreeQueues.html
duke@435 2873 //
duke@435 2874 // * The cxq can have multiple concurrent "pushers" but only one concurrent
duke@435 2875 // detaching thread. This mechanism is immune from the ABA corruption.
duke@435 2876 // More precisely, the CAS-based "push" onto cxq is ABA-oblivious.
duke@435 2877 //
duke@435 2878 // * Taken together, the cxq and the EntryList constitute or form a
duke@435 2879 // single logical queue of threads stalled trying to acquire the lock.
duke@435 2880 // We use two distinct lists to improve the odds of a constant-time
duke@435 2881 // dequeue operation after acquisition (in the ::enter() epilog) and
duke@435 2882 // to reduce heat on the list ends. (c.f. Michael Scott's "2Q" algorithm).
duke@435 2883 // A key desideratum is to minimize queue & monitor metadata manipulation
duke@435 2884 // that occurs while holding the monitor lock -- that is, we want to
duke@435 2885 // minimize monitor lock holds times. Note that even a small amount of
duke@435 2886 // fixed spinning will greatly reduce the # of enqueue-dequeue operations
duke@435 2887 // on EntryList|cxq. That is, spinning relieves contention on the "inner"
duke@435 2888 // locks and monitor metadata.
duke@435 2889 //
duke@435 2890 // Cxq points to the the set of Recently Arrived Threads attempting entry.
duke@435 2891 // Because we push threads onto _cxq with CAS, the RATs must take the form of
duke@435 2892 // a singly-linked LIFO. We drain _cxq into EntryList at unlock-time when
duke@435 2893 // the unlocking thread notices that EntryList is null but _cxq is != null.
duke@435 2894 //
duke@435 2895 // The EntryList is ordered by the prevailing queue discipline and
duke@435 2896 // can be organized in any convenient fashion, such as a doubly-linked list or
duke@435 2897 // a circular doubly-linked list. Critically, we want insert and delete operations
duke@435 2898 // to operate in constant-time. If we need a priority queue then something akin
duke@435 2899 // to Solaris' sleepq would work nicely. Viz.,
duke@435 2900 // http://agg.eng/ws/on10_nightly/source/usr/src/uts/common/os/sleepq.c.
duke@435 2901 // Queue discipline is enforced at ::exit() time, when the unlocking thread
duke@435 2902 // drains the cxq into the EntryList, and orders or reorders the threads on the
duke@435 2903 // EntryList accordingly.
duke@435 2904 //
duke@435 2905 // Barring "lock barging", this mechanism provides fair cyclic ordering,
duke@435 2906 // somewhat similar to an elevator-scan.
duke@435 2907 //
duke@435 2908 // * The monitor synchronization subsystem avoids the use of native
duke@435 2909 // synchronization primitives except for the narrow platform-specific
duke@435 2910 // park-unpark abstraction. See the comments in os_solaris.cpp regarding
duke@435 2911 // the semantics of park-unpark. Put another way, this monitor implementation
duke@435 2912 // depends only on atomic operations and park-unpark. The monitor subsystem
duke@435 2913 // manages all RUNNING->BLOCKED and BLOCKED->READY transitions while the
duke@435 2914 // underlying OS manages the READY<->RUN transitions.
duke@435 2915 //
duke@435 2916 // * Waiting threads reside on the WaitSet list -- wait() puts
duke@435 2917 // the caller onto the WaitSet.
duke@435 2918 //
duke@435 2919 // * notify() or notifyAll() simply transfers threads from the WaitSet to
duke@435 2920 // either the EntryList or cxq. Subsequent exit() operations will
duke@435 2921 // unpark the notifyee. Unparking a notifee in notify() is inefficient -
duke@435 2922 // it's likely the notifyee would simply impale itself on the lock held
duke@435 2923 // by the notifier.
duke@435 2924 //
duke@435 2925 // * An interesting alternative is to encode cxq as (List,LockByte) where
duke@435 2926 // the LockByte is 0 iff the monitor is owned. _owner is simply an auxiliary
duke@435 2927 // variable, like _recursions, in the scheme. The threads or Events that form
duke@435 2928 // the list would have to be aligned in 256-byte addresses. A thread would
duke@435 2929 // try to acquire the lock or enqueue itself with CAS, but exiting threads
duke@435 2930 // could use a 1-0 protocol and simply STB to set the LockByte to 0.
duke@435 2931 // Note that is is *not* word-tearing, but it does presume that full-word
duke@435 2932 // CAS operations are coherent with intermix with STB operations. That's true
duke@435 2933 // on most common processors.
duke@435 2934 //
duke@435 2935 // * See also http://blogs.sun.com/dave
duke@435 2936
duke@435 2937
duke@435 2938 void ATTR ObjectMonitor::EnterI (TRAPS) {
duke@435 2939 Thread * Self = THREAD ;
duke@435 2940 assert (Self->is_Java_thread(), "invariant") ;
duke@435 2941 assert (((JavaThread *) Self)->thread_state() == _thread_blocked , "invariant") ;
duke@435 2942
duke@435 2943 // Try the lock - TATAS
duke@435 2944 if (TryLock (Self) > 0) {
duke@435 2945 assert (_succ != Self , "invariant") ;
duke@435 2946 assert (_owner == Self , "invariant") ;
duke@435 2947 assert (_Responsible != Self , "invariant") ;
duke@435 2948 return ;
duke@435 2949 }
duke@435 2950
duke@435 2951 DeferredInitialize () ;
duke@435 2952
duke@435 2953 // We try one round of spinning *before* enqueueing Self.
duke@435 2954 //
duke@435 2955 // If the _owner is ready but OFFPROC we could use a YieldTo()
duke@435 2956 // operation to donate the remainder of this thread's quantum
duke@435 2957 // to the owner. This has subtle but beneficial affinity
duke@435 2958 // effects.
duke@435 2959
duke@435 2960 if (TrySpin (Self) > 0) {
duke@435 2961 assert (_owner == Self , "invariant") ;
duke@435 2962 assert (_succ != Self , "invariant") ;
duke@435 2963 assert (_Responsible != Self , "invariant") ;
duke@435 2964 return ;
duke@435 2965 }
duke@435 2966
duke@435 2967 // The Spin failed -- Enqueue and park the thread ...
duke@435 2968 assert (_succ != Self , "invariant") ;
duke@435 2969 assert (_owner != Self , "invariant") ;
duke@435 2970 assert (_Responsible != Self , "invariant") ;
duke@435 2971
duke@435 2972 // Enqueue "Self" on ObjectMonitor's _cxq.
duke@435 2973 //
duke@435 2974 // Node acts as a proxy for Self.
duke@435 2975 // As an aside, if were to ever rewrite the synchronization code mostly
duke@435 2976 // in Java, WaitNodes, ObjectMonitors, and Events would become 1st-class
duke@435 2977 // Java objects. This would avoid awkward lifecycle and liveness issues,
duke@435 2978 // as well as eliminate a subset of ABA issues.
duke@435 2979 // TODO: eliminate ObjectWaiter and enqueue either Threads or Events.
duke@435 2980 //
duke@435 2981
duke@435 2982 ObjectWaiter node(Self) ;
duke@435 2983 Self->_ParkEvent->reset() ;
duke@435 2984 node._prev = (ObjectWaiter *) 0xBAD ;
duke@435 2985 node.TState = ObjectWaiter::TS_CXQ ;
duke@435 2986
duke@435 2987 // Push "Self" onto the front of the _cxq.
duke@435 2988 // Once on cxq/EntryList, Self stays on-queue until it acquires the lock.
duke@435 2989 // Note that spinning tends to reduce the rate at which threads
duke@435 2990 // enqueue and dequeue on EntryList|cxq.
duke@435 2991 ObjectWaiter * nxt ;
duke@435 2992 for (;;) {
duke@435 2993 node._next = nxt = _cxq ;
duke@435 2994 if (Atomic::cmpxchg_ptr (&node, &_cxq, nxt) == nxt) break ;
duke@435 2995
duke@435 2996 // Interference - the CAS failed because _cxq changed. Just retry.
duke@435 2997 // As an optional optimization we retry the lock.
duke@435 2998 if (TryLock (Self) > 0) {
duke@435 2999 assert (_succ != Self , "invariant") ;
duke@435 3000 assert (_owner == Self , "invariant") ;
duke@435 3001 assert (_Responsible != Self , "invariant") ;
duke@435 3002 return ;
duke@435 3003 }
duke@435 3004 }
duke@435 3005
duke@435 3006 // Check for cxq|EntryList edge transition to non-null. This indicates
duke@435 3007 // the onset of contention. While contention persists exiting threads
duke@435 3008 // will use a ST:MEMBAR:LD 1-1 exit protocol. When contention abates exit
duke@435 3009 // operations revert to the faster 1-0 mode. This enter operation may interleave
duke@435 3010 // (race) a concurrent 1-0 exit operation, resulting in stranding, so we
duke@435 3011 // arrange for one of the contending thread to use a timed park() operations
duke@435 3012 // to detect and recover from the race. (Stranding is form of progress failure
duke@435 3013 // where the monitor is unlocked but all the contending threads remain parked).
duke@435 3014 // That is, at least one of the contended threads will periodically poll _owner.
duke@435 3015 // One of the contending threads will become the designated "Responsible" thread.
duke@435 3016 // The Responsible thread uses a timed park instead of a normal indefinite park
duke@435 3017 // operation -- it periodically wakes and checks for and recovers from potential
duke@435 3018 // strandings admitted by 1-0 exit operations. We need at most one Responsible
duke@435 3019 // thread per-monitor at any given moment. Only threads on cxq|EntryList may
duke@435 3020 // be responsible for a monitor.
duke@435 3021 //
duke@435 3022 // Currently, one of the contended threads takes on the added role of "Responsible".
duke@435 3023 // A viable alternative would be to use a dedicated "stranding checker" thread
duke@435 3024 // that periodically iterated over all the threads (or active monitors) and unparked
duke@435 3025 // successors where there was risk of stranding. This would help eliminate the
duke@435 3026 // timer scalability issues we see on some platforms as we'd only have one thread
duke@435 3027 // -- the checker -- parked on a timer.
duke@435 3028
duke@435 3029 if ((SyncFlags & 16) == 0 && nxt == NULL && _EntryList == NULL) {
duke@435 3030 // Try to assume the role of responsible thread for the monitor.
duke@435 3031 // CONSIDER: ST vs CAS vs { if (Responsible==null) Responsible=Self }
duke@435 3032 Atomic::cmpxchg_ptr (Self, &_Responsible, NULL) ;
duke@435 3033 }
duke@435 3034
duke@435 3035 // The lock have been released while this thread was occupied queueing
duke@435 3036 // itself onto _cxq. To close the race and avoid "stranding" and
duke@435 3037 // progress-liveness failure we must resample-retry _owner before parking.
duke@435 3038 // Note the Dekker/Lamport duality: ST cxq; MEMBAR; LD Owner.
duke@435 3039 // In this case the ST-MEMBAR is accomplished with CAS().
duke@435 3040 //
duke@435 3041 // TODO: Defer all thread state transitions until park-time.
duke@435 3042 // Since state transitions are heavy and inefficient we'd like
duke@435 3043 // to defer the state transitions until absolutely necessary,
duke@435 3044 // and in doing so avoid some transitions ...
duke@435 3045
duke@435 3046 TEVENT (Inflated enter - Contention) ;
duke@435 3047 int nWakeups = 0 ;
duke@435 3048 int RecheckInterval = 1 ;
duke@435 3049
duke@435 3050 for (;;) {
duke@435 3051
duke@435 3052 if (TryLock (Self) > 0) break ;
duke@435 3053 assert (_owner != Self, "invariant") ;
duke@435 3054
duke@435 3055 if ((SyncFlags & 2) && _Responsible == NULL) {
duke@435 3056 Atomic::cmpxchg_ptr (Self, &_Responsible, NULL) ;
duke@435 3057 }
duke@435 3058
duke@435 3059 // park self
duke@435 3060 if (_Responsible == Self || (SyncFlags & 1)) {
duke@435 3061 TEVENT (Inflated enter - park TIMED) ;
duke@435 3062 Self->_ParkEvent->park ((jlong) RecheckInterval) ;
duke@435 3063 // Increase the RecheckInterval, but clamp the value.
duke@435 3064 RecheckInterval *= 8 ;
duke@435 3065 if (RecheckInterval > 1000) RecheckInterval = 1000 ;
duke@435 3066 } else {
duke@435 3067 TEVENT (Inflated enter - park UNTIMED) ;
duke@435 3068 Self->_ParkEvent->park() ;
duke@435 3069 }
duke@435 3070
duke@435 3071 if (TryLock(Self) > 0) break ;
duke@435 3072
duke@435 3073 // The lock is still contested.
duke@435 3074 // Keep a tally of the # of futile wakeups.
duke@435 3075 // Note that the counter is not protected by a lock or updated by atomics.
duke@435 3076 // That is by design - we trade "lossy" counters which are exposed to
duke@435 3077 // races during updates for a lower probe effect.
duke@435 3078 TEVENT (Inflated enter - Futile wakeup) ;
duke@435 3079 if (ObjectSynchronizer::_sync_FutileWakeups != NULL) {
duke@435 3080 ObjectSynchronizer::_sync_FutileWakeups->inc() ;
duke@435 3081 }
duke@435 3082 ++ nWakeups ;
duke@435 3083
duke@435 3084 // Assuming this is not a spurious wakeup we'll normally find _succ == Self.
duke@435 3085 // We can defer clearing _succ until after the spin completes
duke@435 3086 // TrySpin() must tolerate being called with _succ == Self.
duke@435 3087 // Try yet another round of adaptive spinning.
duke@435 3088 if ((Knob_SpinAfterFutile & 1) && TrySpin (Self) > 0) break ;
duke@435 3089
duke@435 3090 // We can find that we were unpark()ed and redesignated _succ while
duke@435 3091 // we were spinning. That's harmless. If we iterate and call park(),
duke@435 3092 // park() will consume the event and return immediately and we'll
duke@435 3093 // just spin again. This pattern can repeat, leaving _succ to simply
duke@435 3094 // spin on a CPU. Enable Knob_ResetEvent to clear pending unparks().
duke@435 3095 // Alternately, we can sample fired() here, and if set, forgo spinning
duke@435 3096 // in the next iteration.
duke@435 3097
duke@435 3098 if ((Knob_ResetEvent & 1) && Self->_ParkEvent->fired()) {
duke@435 3099 Self->_ParkEvent->reset() ;
duke@435 3100 OrderAccess::fence() ;
duke@435 3101 }
duke@435 3102 if (_succ == Self) _succ = NULL ;
duke@435 3103
duke@435 3104 // Invariant: after clearing _succ a thread *must* retry _owner before parking.
duke@435 3105 OrderAccess::fence() ;
duke@435 3106 }
duke@435 3107
duke@435 3108 // Egress :
duke@435 3109 // Self has acquired the lock -- Unlink Self from the cxq or EntryList.
duke@435 3110 // Normally we'll find Self on the EntryList .
duke@435 3111 // From the perspective of the lock owner (this thread), the
duke@435 3112 // EntryList is stable and cxq is prepend-only.
duke@435 3113 // The head of cxq is volatile but the interior is stable.
duke@435 3114 // In addition, Self.TState is stable.
duke@435 3115
duke@435 3116 assert (_owner == Self , "invariant") ;
duke@435 3117 assert (object() != NULL , "invariant") ;
duke@435 3118 // I'd like to write:
duke@435 3119 // guarantee (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;
duke@435 3120 // but as we're at a safepoint that's not safe.
duke@435 3121
duke@435 3122 UnlinkAfterAcquire (Self, &node) ;
duke@435 3123 if (_succ == Self) _succ = NULL ;
duke@435 3124
duke@435 3125 assert (_succ != Self, "invariant") ;
duke@435 3126 if (_Responsible == Self) {
duke@435 3127 _Responsible = NULL ;
duke@435 3128 // Dekker pivot-point.
duke@435 3129 // Consider OrderAccess::storeload() here
duke@435 3130
duke@435 3131 // We may leave threads on cxq|EntryList without a designated
duke@435 3132 // "Responsible" thread. This is benign. When this thread subsequently
duke@435 3133 // exits the monitor it can "see" such preexisting "old" threads --
duke@435 3134 // threads that arrived on the cxq|EntryList before the fence, above --
duke@435 3135 // by LDing cxq|EntryList. Newly arrived threads -- that is, threads
duke@435 3136 // that arrive on cxq after the ST:MEMBAR, above -- will set Responsible
duke@435 3137 // non-null and elect a new "Responsible" timer thread.
duke@435 3138 //
duke@435 3139 // This thread executes:
duke@435 3140 // ST Responsible=null; MEMBAR (in enter epilog - here)
duke@435 3141 // LD cxq|EntryList (in subsequent exit)
duke@435 3142 //
duke@435 3143 // Entering threads in the slow/contended path execute:
duke@435 3144 // ST cxq=nonnull; MEMBAR; LD Responsible (in enter prolog)
duke@435 3145 // The (ST cxq; MEMBAR) is accomplished with CAS().
duke@435 3146 //
duke@435 3147 // The MEMBAR, above, prevents the LD of cxq|EntryList in the subsequent
duke@435 3148 // exit operation from floating above the ST Responsible=null.
duke@435 3149 //
duke@435 3150 // In *practice* however, EnterI() is always followed by some atomic
duke@435 3151 // operation such as the decrement of _count in ::enter(). Those atomics
duke@435 3152 // obviate the need for the explicit MEMBAR, above.
duke@435 3153 }
duke@435 3154
duke@435 3155 // We've acquired ownership with CAS().
duke@435 3156 // CAS is serializing -- it has MEMBAR/FENCE-equivalent semantics.
duke@435 3157 // But since the CAS() this thread may have also stored into _succ,
duke@435 3158 // EntryList, cxq or Responsible. These meta-data updates must be
duke@435 3159 // visible __before this thread subsequently drops the lock.
duke@435 3160 // Consider what could occur if we didn't enforce this constraint --
duke@435 3161 // STs to monitor meta-data and user-data could reorder with (become
duke@435 3162 // visible after) the ST in exit that drops ownership of the lock.
duke@435 3163 // Some other thread could then acquire the lock, but observe inconsistent
duke@435 3164 // or old monitor meta-data and heap data. That violates the JMM.
duke@435 3165 // To that end, the 1-0 exit() operation must have at least STST|LDST
duke@435 3166 // "release" barrier semantics. Specifically, there must be at least a
duke@435 3167 // STST|LDST barrier in exit() before the ST of null into _owner that drops
duke@435 3168 // the lock. The barrier ensures that changes to monitor meta-data and data
duke@435 3169 // protected by the lock will be visible before we release the lock, and
duke@435 3170 // therefore before some other thread (CPU) has a chance to acquire the lock.
duke@435 3171 // See also: http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
duke@435 3172 //
duke@435 3173 // Critically, any prior STs to _succ or EntryList must be visible before
duke@435 3174 // the ST of null into _owner in the *subsequent* (following) corresponding
duke@435 3175 // monitorexit. Recall too, that in 1-0 mode monitorexit does not necessarily
duke@435 3176 // execute a serializing instruction.
duke@435 3177
duke@435 3178 if (SyncFlags & 8) {
duke@435 3179 OrderAccess::fence() ;
duke@435 3180 }
duke@435 3181 return ;
duke@435 3182 }
duke@435 3183
duke@435 3184 // ExitSuspendEquivalent:
duke@435 3185 // A faster alternate to handle_special_suspend_equivalent_condition()
duke@435 3186 //
duke@435 3187 // handle_special_suspend_equivalent_condition() unconditionally
duke@435 3188 // acquires the SR_lock. On some platforms uncontended MutexLocker()
duke@435 3189 // operations have high latency. Note that in ::enter() we call HSSEC
duke@435 3190 // while holding the monitor, so we effectively lengthen the critical sections.
duke@435 3191 //
duke@435 3192 // There are a number of possible solutions:
duke@435 3193 //
duke@435 3194 // A. To ameliorate the problem we might also defer state transitions
duke@435 3195 // to as late as possible -- just prior to parking.
duke@435 3196 // Given that, we'd call HSSEC after having returned from park(),
duke@435 3197 // but before attempting to acquire the monitor. This is only a
duke@435 3198 // partial solution. It avoids calling HSSEC while holding the
duke@435 3199 // monitor (good), but it still increases successor reacquisition latency --
duke@435 3200 // the interval between unparking a successor and the time the successor
duke@435 3201 // resumes and retries the lock. See ReenterI(), which defers state transitions.
duke@435 3202 // If we use this technique we can also avoid EnterI()-exit() loop
duke@435 3203 // in ::enter() where we iteratively drop the lock and then attempt
duke@435 3204 // to reacquire it after suspending.
duke@435 3205 //
duke@435 3206 // B. In the future we might fold all the suspend bits into a
duke@435 3207 // composite per-thread suspend flag and then update it with CAS().
duke@435 3208 // Alternately, a Dekker-like mechanism with multiple variables
duke@435 3209 // would suffice:
duke@435 3210 // ST Self->_suspend_equivalent = false
duke@435 3211 // MEMBAR
duke@435 3212 // LD Self_>_suspend_flags
duke@435 3213 //
duke@435 3214
duke@435 3215
duke@435 3216 bool ObjectMonitor::ExitSuspendEquivalent (JavaThread * jSelf) {
duke@435 3217 int Mode = Knob_FastHSSEC ;
duke@435 3218 if (Mode && !jSelf->is_external_suspend()) {
duke@435 3219 assert (jSelf->is_suspend_equivalent(), "invariant") ;
duke@435 3220 jSelf->clear_suspend_equivalent() ;
duke@435 3221 if (2 == Mode) OrderAccess::storeload() ;
duke@435 3222 if (!jSelf->is_external_suspend()) return false ;
duke@435 3223 // We raced a suspension -- fall thru into the slow path
duke@435 3224 TEVENT (ExitSuspendEquivalent - raced) ;
duke@435 3225 jSelf->set_suspend_equivalent() ;
duke@435 3226 }
duke@435 3227 return jSelf->handle_special_suspend_equivalent_condition() ;
duke@435 3228 }
duke@435 3229
duke@435 3230
duke@435 3231 // ReenterI() is a specialized inline form of the latter half of the
duke@435 3232 // contended slow-path from EnterI(). We use ReenterI() only for
duke@435 3233 // monitor reentry in wait().
duke@435 3234 //
duke@435 3235 // In the future we should reconcile EnterI() and ReenterI(), adding
duke@435 3236 // Knob_Reset and Knob_SpinAfterFutile support and restructuring the
duke@435 3237 // loop accordingly.
duke@435 3238
duke@435 3239 void ATTR ObjectMonitor::ReenterI (Thread * Self, ObjectWaiter * SelfNode) {
duke@435 3240 assert (Self != NULL , "invariant") ;
duke@435 3241 assert (SelfNode != NULL , "invariant") ;
duke@435 3242 assert (SelfNode->_thread == Self , "invariant") ;
duke@435 3243 assert (_waiters > 0 , "invariant") ;
duke@435 3244 assert (((oop)(object()))->mark() == markOopDesc::encode(this) , "invariant") ;
duke@435 3245 assert (((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant") ;
duke@435 3246 JavaThread * jt = (JavaThread *) Self ;
duke@435 3247
duke@435 3248 int nWakeups = 0 ;
duke@435 3249 for (;;) {
duke@435 3250 ObjectWaiter::TStates v = SelfNode->TState ;
duke@435 3251 guarantee (v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant") ;
duke@435 3252 assert (_owner != Self, "invariant") ;
duke@435 3253
duke@435 3254 if (TryLock (Self) > 0) break ;
duke@435 3255 if (TrySpin (Self) > 0) break ;
duke@435 3256
duke@435 3257 TEVENT (Wait Reentry - parking) ;
duke@435 3258
duke@435 3259 // State transition wrappers around park() ...
duke@435 3260 // ReenterI() wisely defers state transitions until
duke@435 3261 // it's clear we must park the thread.
duke@435 3262 {
duke@435 3263 OSThreadContendState osts(Self->osthread());
duke@435 3264 ThreadBlockInVM tbivm(jt);
duke@435 3265
duke@435 3266 // cleared by handle_special_suspend_equivalent_condition()
duke@435 3267 // or java_suspend_self()
duke@435 3268 jt->set_suspend_equivalent();
duke@435 3269 if (SyncFlags & 1) {
duke@435 3270 Self->_ParkEvent->park ((jlong)1000) ;
duke@435 3271 } else {
duke@435 3272 Self->_ParkEvent->park () ;
duke@435 3273 }
duke@435 3274
duke@435 3275 // were we externally suspended while we were waiting?
duke@435 3276 for (;;) {
duke@435 3277 if (!ExitSuspendEquivalent (jt)) break ;
duke@435 3278 if (_succ == Self) { _succ = NULL; OrderAccess::fence(); }
duke@435 3279 jt->java_suspend_self();
duke@435 3280 jt->set_suspend_equivalent();
duke@435 3281 }
duke@435 3282 }
duke@435 3283
duke@435 3284 // Try again, but just so we distinguish between futile wakeups and
duke@435 3285 // successful wakeups. The following test isn't algorithmically
duke@435 3286 // necessary, but it helps us maintain sensible statistics.
duke@435 3287 if (TryLock(Self) > 0) break ;
duke@435 3288
duke@435 3289 // The lock is still contested.
duke@435 3290 // Keep a tally of the # of futile wakeups.
duke@435 3291 // Note that the counter is not protected by a lock or updated by atomics.
duke@435 3292 // That is by design - we trade "lossy" counters which are exposed to
duke@435 3293 // races during updates for a lower probe effect.
duke@435 3294 TEVENT (Wait Reentry - futile wakeup) ;
duke@435 3295 ++ nWakeups ;
duke@435 3296
duke@435 3297 // Assuming this is not a spurious wakeup we'll normally
duke@435 3298 // find that _succ == Self.
duke@435 3299 if (_succ == Self) _succ = NULL ;
duke@435 3300
duke@435 3301 // Invariant: after clearing _succ a contending thread
duke@435 3302 // *must* retry _owner before parking.
duke@435 3303 OrderAccess::fence() ;
duke@435 3304
duke@435 3305 if (ObjectSynchronizer::_sync_FutileWakeups != NULL) {
duke@435 3306 ObjectSynchronizer::_sync_FutileWakeups->inc() ;
duke@435 3307 }
duke@435 3308 }
duke@435 3309
duke@435 3310 // Self has acquired the lock -- Unlink Self from the cxq or EntryList .
duke@435 3311 // Normally we'll find Self on the EntryList.
duke@435 3312 // Unlinking from the EntryList is constant-time and atomic-free.
duke@435 3313 // From the perspective of the lock owner (this thread), the
duke@435 3314 // EntryList is stable and cxq is prepend-only.
duke@435 3315 // The head of cxq is volatile but the interior is stable.
duke@435 3316 // In addition, Self.TState is stable.
duke@435 3317
duke@435 3318 assert (_owner == Self, "invariant") ;
duke@435 3319 assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;
duke@435 3320 UnlinkAfterAcquire (Self, SelfNode) ;
duke@435 3321 if (_succ == Self) _succ = NULL ;
duke@435 3322 assert (_succ != Self, "invariant") ;
duke@435 3323 SelfNode->TState = ObjectWaiter::TS_RUN ;
duke@435 3324 OrderAccess::fence() ; // see comments at the end of EnterI()
duke@435 3325 }
duke@435 3326
duke@435 3327 bool ObjectMonitor::try_enter(Thread* THREAD) {
duke@435 3328 if (THREAD != _owner) {
duke@435 3329 if (THREAD->is_lock_owned ((address)_owner)) {
duke@435 3330 assert(_recursions == 0, "internal state error");
duke@435 3331 _owner = THREAD ;
duke@435 3332 _recursions = 1 ;
duke@435 3333 OwnerIsThread = 1 ;
duke@435 3334 return true;
duke@435 3335 }
duke@435 3336 if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) {
duke@435 3337 return false;
duke@435 3338 }
duke@435 3339 return true;
duke@435 3340 } else {
duke@435 3341 _recursions++;
duke@435 3342 return true;
duke@435 3343 }
duke@435 3344 }
duke@435 3345
duke@435 3346 void ATTR ObjectMonitor::enter(TRAPS) {
duke@435 3347 // The following code is ordered to check the most common cases first
duke@435 3348 // and to reduce RTS->RTO cache line upgrades on SPARC and IA32 processors.
duke@435 3349 Thread * const Self = THREAD ;
duke@435 3350 void * cur ;
duke@435 3351
duke@435 3352 cur = Atomic::cmpxchg_ptr (Self, &_owner, NULL) ;
duke@435 3353 if (cur == NULL) {
duke@435 3354 // Either ASSERT _recursions == 0 or explicitly set _recursions = 0.
duke@435 3355 assert (_recursions == 0 , "invariant") ;
duke@435 3356 assert (_owner == Self, "invariant") ;
duke@435 3357 // CONSIDER: set or assert OwnerIsThread == 1
duke@435 3358 return ;
duke@435 3359 }
duke@435 3360
duke@435 3361 if (cur == Self) {
duke@435 3362 // TODO-FIXME: check for integer overflow! BUGID 6557169.
duke@435 3363 _recursions ++ ;
duke@435 3364 return ;
duke@435 3365 }
duke@435 3366
duke@435 3367 if (Self->is_lock_owned ((address)cur)) {
duke@435 3368 assert (_recursions == 0, "internal state error");
duke@435 3369 _recursions = 1 ;
duke@435 3370 // Commute owner from a thread-specific on-stack BasicLockObject address to
duke@435 3371 // a full-fledged "Thread *".
duke@435 3372 _owner = Self ;
duke@435 3373 OwnerIsThread = 1 ;
duke@435 3374 return ;
duke@435 3375 }
duke@435 3376
duke@435 3377 // We've encountered genuine contention.
duke@435 3378 assert (Self->_Stalled == 0, "invariant") ;
duke@435 3379 Self->_Stalled = intptr_t(this) ;
duke@435 3380
duke@435 3381 // Try one round of spinning *before* enqueueing Self
duke@435 3382 // and before going through the awkward and expensive state
duke@435 3383 // transitions. The following spin is strictly optional ...
duke@435 3384 // Note that if we acquire the monitor from an initial spin
duke@435 3385 // we forgo posting JVMTI events and firing DTRACE probes.
duke@435 3386 if (Knob_SpinEarly && TrySpin (Self) > 0) {
duke@435 3387 assert (_owner == Self , "invariant") ;
duke@435 3388 assert (_recursions == 0 , "invariant") ;
duke@435 3389 assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;
duke@435 3390 Self->_Stalled = 0 ;
duke@435 3391 return ;
duke@435 3392 }
duke@435 3393
duke@435 3394 assert (_owner != Self , "invariant") ;
duke@435 3395 assert (_succ != Self , "invariant") ;
duke@435 3396 assert (Self->is_Java_thread() , "invariant") ;
duke@435 3397 JavaThread * jt = (JavaThread *) Self ;
duke@435 3398 assert (!SafepointSynchronize::is_at_safepoint(), "invariant") ;
duke@435 3399 assert (jt->thread_state() != _thread_blocked , "invariant") ;
duke@435 3400 assert (this->object() != NULL , "invariant") ;
duke@435 3401 assert (_count >= 0, "invariant") ;
duke@435 3402
duke@435 3403 // Prevent deflation at STW-time. See deflate_idle_monitors() and is_busy().
duke@435 3404 // Ensure the object-monitor relationship remains stable while there's contention.
duke@435 3405 Atomic::inc_ptr(&_count);
duke@435 3406
duke@435 3407 { // Change java thread status to indicate blocked on monitor enter.
duke@435 3408 JavaThreadBlockedOnMonitorEnterState jtbmes(jt, this);
duke@435 3409
duke@435 3410 DTRACE_MONITOR_PROBE(contended__enter, this, object(), jt);
duke@435 3411 if (JvmtiExport::should_post_monitor_contended_enter()) {
duke@435 3412 JvmtiExport::post_monitor_contended_enter(jt, this);
duke@435 3413 }
duke@435 3414
duke@435 3415 OSThreadContendState osts(Self->osthread());
duke@435 3416 ThreadBlockInVM tbivm(jt);
duke@435 3417
duke@435 3418 Self->set_current_pending_monitor(this);
duke@435 3419
duke@435 3420 // TODO-FIXME: change the following for(;;) loop to straight-line code.
duke@435 3421 for (;;) {
duke@435 3422 jt->set_suspend_equivalent();
duke@435 3423 // cleared by handle_special_suspend_equivalent_condition()
duke@435 3424 // or java_suspend_self()
duke@435 3425
duke@435 3426 EnterI (THREAD) ;
duke@435 3427
duke@435 3428 if (!ExitSuspendEquivalent(jt)) break ;
duke@435 3429
duke@435 3430 //
duke@435 3431 // We have acquired the contended monitor, but while we were
duke@435 3432 // waiting another thread suspended us. We don't want to enter
duke@435 3433 // the monitor while suspended because that would surprise the
duke@435 3434 // thread that suspended us.
duke@435 3435 //
duke@435 3436 _recursions = 0 ;
duke@435 3437 _succ = NULL ;
duke@435 3438 exit (Self) ;
duke@435 3439
duke@435 3440 jt->java_suspend_self();
duke@435 3441 }
duke@435 3442 Self->set_current_pending_monitor(NULL);
duke@435 3443 }
duke@435 3444
duke@435 3445 Atomic::dec_ptr(&_count);
duke@435 3446 assert (_count >= 0, "invariant") ;
duke@435 3447 Self->_Stalled = 0 ;
duke@435 3448
duke@435 3449 // Must either set _recursions = 0 or ASSERT _recursions == 0.
duke@435 3450 assert (_recursions == 0 , "invariant") ;
duke@435 3451 assert (_owner == Self , "invariant") ;
duke@435 3452 assert (_succ != Self , "invariant") ;
duke@435 3453 assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;
duke@435 3454
duke@435 3455 // The thread -- now the owner -- is back in vm mode.
duke@435 3456 // Report the glorious news via TI,DTrace and jvmstat.
duke@435 3457 // The probe effect is non-trivial. All the reportage occurs
duke@435 3458 // while we hold the monitor, increasing the length of the critical
duke@435 3459 // section. Amdahl's parallel speedup law comes vividly into play.
duke@435 3460 //
duke@435 3461 // Another option might be to aggregate the events (thread local or
duke@435 3462 // per-monitor aggregation) and defer reporting until a more opportune
duke@435 3463 // time -- such as next time some thread encounters contention but has
duke@435 3464 // yet to acquire the lock. While spinning that thread could
duke@435 3465 // spinning we could increment JVMStat counters, etc.
duke@435 3466
duke@435 3467 DTRACE_MONITOR_PROBE(contended__entered, this, object(), jt);
duke@435 3468 if (JvmtiExport::should_post_monitor_contended_entered()) {
duke@435 3469 JvmtiExport::post_monitor_contended_entered(jt, this);
duke@435 3470 }
duke@435 3471 if (ObjectSynchronizer::_sync_ContendedLockAttempts != NULL) {
duke@435 3472 ObjectSynchronizer::_sync_ContendedLockAttempts->inc() ;
duke@435 3473 }
duke@435 3474 }
duke@435 3475
duke@435 3476 void ObjectMonitor::ExitEpilog (Thread * Self, ObjectWaiter * Wakee) {
duke@435 3477 assert (_owner == Self, "invariant") ;
duke@435 3478
duke@435 3479 // Exit protocol:
duke@435 3480 // 1. ST _succ = wakee
duke@435 3481 // 2. membar #loadstore|#storestore;
duke@435 3482 // 2. ST _owner = NULL
duke@435 3483 // 3. unpark(wakee)
duke@435 3484
duke@435 3485 _succ = Knob_SuccEnabled ? Wakee->_thread : NULL ;
duke@435 3486 ParkEvent * Trigger = Wakee->_event ;
duke@435 3487
duke@435 3488 // Hygiene -- once we've set _owner = NULL we can't safely dereference Wakee again.
duke@435 3489 // The thread associated with Wakee may have grabbed the lock and "Wakee" may be
duke@435 3490 // out-of-scope (non-extant).
duke@435 3491 Wakee = NULL ;
duke@435 3492
duke@435 3493 // Drop the lock
duke@435 3494 OrderAccess::release_store_ptr (&_owner, NULL) ;
duke@435 3495 OrderAccess::fence() ; // ST _owner vs LD in unpark()
duke@435 3496
duke@435 3497 // TODO-FIXME:
duke@435 3498 // If there's a safepoint pending the best policy would be to
duke@435 3499 // get _this thread to a safepoint and only wake the successor
duke@435 3500 // after the safepoint completed. monitorexit uses a "leaf"
duke@435 3501 // state transition, however, so this thread can't become
duke@435 3502 // safe at this point in time. (Its stack isn't walkable).
duke@435 3503 // The next best thing is to defer waking the successor by
duke@435 3504 // adding to a list of thread to be unparked after at the
duke@435 3505 // end of the forthcoming STW).
duke@435 3506 if (SafepointSynchronize::do_call_back()) {
duke@435 3507 TEVENT (unpark before SAFEPOINT) ;
duke@435 3508 }
duke@435 3509
duke@435 3510 // Possible optimizations ...
duke@435 3511 //
duke@435 3512 // * Consider: set Wakee->UnparkTime = timeNow()
duke@435 3513 // When the thread wakes up it'll compute (timeNow() - Self->UnparkTime()).
duke@435 3514 // By measuring recent ONPROC latency we can approximate the
duke@435 3515 // system load. In turn, we can feed that information back
duke@435 3516 // into the spinning & succession policies.
duke@435 3517 // (ONPROC latency correlates strongly with load).
duke@435 3518 //
duke@435 3519 // * Pull affinity:
duke@435 3520 // If the wakee is cold then transiently setting it's affinity
duke@435 3521 // to the current CPU is a good idea.
duke@435 3522 // See http://j2se.east/~dice/PERSIST/050624-PullAffinity.txt
blacklion@913 3523 DTRACE_MONITOR_PROBE(contended__exit, this, object(), Self);
duke@435 3524 Trigger->unpark() ;
duke@435 3525
duke@435 3526 // Maintain stats and report events to JVMTI
duke@435 3527 if (ObjectSynchronizer::_sync_Parks != NULL) {
duke@435 3528 ObjectSynchronizer::_sync_Parks->inc() ;
duke@435 3529 }
duke@435 3530 }
duke@435 3531
duke@435 3532
duke@435 3533 // exit()
duke@435 3534 // ~~~~~~
duke@435 3535 // Note that the collector can't reclaim the objectMonitor or deflate
duke@435 3536 // the object out from underneath the thread calling ::exit() as the
duke@435 3537 // thread calling ::exit() never transitions to a stable state.
duke@435 3538 // This inhibits GC, which in turn inhibits asynchronous (and
duke@435 3539 // inopportune) reclamation of "this".
duke@435 3540 //
duke@435 3541 // We'd like to assert that: (THREAD->thread_state() != _thread_blocked) ;
duke@435 3542 // There's one exception to the claim above, however. EnterI() can call
duke@435 3543 // exit() to drop a lock if the acquirer has been externally suspended.
duke@435 3544 // In that case exit() is called with _thread_state as _thread_blocked,
duke@435 3545 // but the monitor's _count field is > 0, which inhibits reclamation.
duke@435 3546 //
duke@435 3547 // 1-0 exit
duke@435 3548 // ~~~~~~~~
duke@435 3549 // ::exit() uses a canonical 1-1 idiom with a MEMBAR although some of
duke@435 3550 // the fast-path operators have been optimized so the common ::exit()
duke@435 3551 // operation is 1-0. See i486.ad fast_unlock(), for instance.
duke@435 3552 // The code emitted by fast_unlock() elides the usual MEMBAR. This
duke@435 3553 // greatly improves latency -- MEMBAR and CAS having considerable local
duke@435 3554 // latency on modern processors -- but at the cost of "stranding". Absent the
duke@435 3555 // MEMBAR, a thread in fast_unlock() can race a thread in the slow
duke@435 3556 // ::enter() path, resulting in the entering thread being stranding
duke@435 3557 // and a progress-liveness failure. Stranding is extremely rare.
duke@435 3558 // We use timers (timed park operations) & periodic polling to detect
duke@435 3559 // and recover from stranding. Potentially stranded threads periodically
duke@435 3560 // wake up and poll the lock. See the usage of the _Responsible variable.
duke@435 3561 //
duke@435 3562 // The CAS() in enter provides for safety and exclusion, while the CAS or
duke@435 3563 // MEMBAR in exit provides for progress and avoids stranding. 1-0 locking
duke@435 3564 // eliminates the CAS/MEMBAR from the exist path, but it admits stranding.
duke@435 3565 // We detect and recover from stranding with timers.
duke@435 3566 //
duke@435 3567 // If a thread transiently strands it'll park until (a) another
duke@435 3568 // thread acquires the lock and then drops the lock, at which time the
duke@435 3569 // exiting thread will notice and unpark the stranded thread, or, (b)
duke@435 3570 // the timer expires. If the lock is high traffic then the stranding latency
duke@435 3571 // will be low due to (a). If the lock is low traffic then the odds of
duke@435 3572 // stranding are lower, although the worst-case stranding latency
duke@435 3573 // is longer. Critically, we don't want to put excessive load in the
duke@435 3574 // platform's timer subsystem. We want to minimize both the timer injection
duke@435 3575 // rate (timers created/sec) as well as the number of timers active at
duke@435 3576 // any one time. (more precisely, we want to minimize timer-seconds, which is
duke@435 3577 // the integral of the # of active timers at any instant over time).
duke@435 3578 // Both impinge on OS scalability. Given that, at most one thread parked on
duke@435 3579 // a monitor will use a timer.
duke@435 3580
duke@435 3581 void ATTR ObjectMonitor::exit(TRAPS) {
duke@435 3582 Thread * Self = THREAD ;
duke@435 3583 if (THREAD != _owner) {
duke@435 3584 if (THREAD->is_lock_owned((address) _owner)) {
duke@435 3585 // Transmute _owner from a BasicLock pointer to a Thread address.
duke@435 3586 // We don't need to hold _mutex for this transition.
duke@435 3587 // Non-null to Non-null is safe as long as all readers can
duke@435 3588 // tolerate either flavor.
duke@435 3589 assert (_recursions == 0, "invariant") ;
duke@435 3590 _owner = THREAD ;
duke@435 3591 _recursions = 0 ;
duke@435 3592 OwnerIsThread = 1 ;
duke@435 3593 } else {
duke@435 3594 // NOTE: we need to handle unbalanced monitor enter/exit
duke@435 3595 // in native code by throwing an exception.
duke@435 3596 // TODO: Throw an IllegalMonitorStateException ?
duke@435 3597 TEVENT (Exit - Throw IMSX) ;
duke@435 3598 assert(false, "Non-balanced monitor enter/exit!");
duke@435 3599 if (false) {
duke@435 3600 THROW(vmSymbols::java_lang_IllegalMonitorStateException());
duke@435 3601 }
duke@435 3602 return;
duke@435 3603 }
duke@435 3604 }
duke@435 3605
duke@435 3606 if (_recursions != 0) {
duke@435 3607 _recursions--; // this is simple recursive enter
duke@435 3608 TEVENT (Inflated exit - recursive) ;
duke@435 3609 return ;
duke@435 3610 }
duke@435 3611
duke@435 3612 // Invariant: after setting Responsible=null an thread must execute
duke@435 3613 // a MEMBAR or other serializing instruction before fetching EntryList|cxq.
duke@435 3614 if ((SyncFlags & 4) == 0) {
duke@435 3615 _Responsible = NULL ;
duke@435 3616 }
duke@435 3617
duke@435 3618 for (;;) {
duke@435 3619 assert (THREAD == _owner, "invariant") ;
duke@435 3620
duke@435 3621 // Fast-path monitor exit:
duke@435 3622 //
duke@435 3623 // Observe the Dekker/Lamport duality:
duke@435 3624 // A thread in ::exit() executes:
duke@435 3625 // ST Owner=null; MEMBAR; LD EntryList|cxq.
duke@435 3626 // A thread in the contended ::enter() path executes the complementary:
duke@435 3627 // ST EntryList|cxq = nonnull; MEMBAR; LD Owner.
duke@435 3628 //
duke@435 3629 // Note that there's a benign race in the exit path. We can drop the
duke@435 3630 // lock, another thread can reacquire the lock immediately, and we can
duke@435 3631 // then wake a thread unnecessarily (yet another flavor of futile wakeup).
duke@435 3632 // This is benign, and we've structured the code so the windows are short
duke@435 3633 // and the frequency of such futile wakeups is low.
duke@435 3634 //
duke@435 3635 // We could eliminate the race by encoding both the "LOCKED" state and
duke@435 3636 // the queue head in a single word. Exit would then use either CAS to
duke@435 3637 // clear the LOCKED bit/byte. This precludes the desirable 1-0 optimization,
duke@435 3638 // however.
duke@435 3639 //
duke@435 3640 // Possible fast-path ::exit() optimization:
duke@435 3641 // The current fast-path exit implementation fetches both cxq and EntryList.
duke@435 3642 // See also i486.ad fast_unlock(). Testing has shown that two LDs
duke@435 3643 // isn't measurably slower than a single LD on any platforms.
duke@435 3644 // Still, we could reduce the 2 LDs to one or zero by one of the following:
duke@435 3645 //
duke@435 3646 // - Use _count instead of cxq|EntryList
duke@435 3647 // We intend to eliminate _count, however, when we switch
duke@435 3648 // to on-the-fly deflation in ::exit() as is used in
duke@435 3649 // Metalocks and RelaxedLocks.
duke@435 3650 //
duke@435 3651 // - Establish the invariant that cxq == null implies EntryList == null.
duke@435 3652 // set cxq == EMPTY (1) to encode the state where cxq is empty
duke@435 3653 // by EntryList != null. EMPTY is a distinguished value.
duke@435 3654 // The fast-path exit() would fetch cxq but not EntryList.
duke@435 3655 //
duke@435 3656 // - Encode succ as follows:
duke@435 3657 // succ = t : Thread t is the successor -- t is ready or is spinning.
duke@435 3658 // Exiting thread does not need to wake a successor.
duke@435 3659 // succ = 0 : No successor required -> (EntryList|cxq) == null
duke@435 3660 // Exiting thread does not need to wake a successor
duke@435 3661 // succ = 1 : Successor required -> (EntryList|cxq) != null and
duke@435 3662 // logically succ == null.
duke@435 3663 // Exiting thread must wake a successor.
duke@435 3664 //
duke@435 3665 // The 1-1 fast-exit path would appear as :
duke@435 3666 // _owner = null ; membar ;
duke@435 3667 // if (_succ == 1 && CAS (&_owner, null, Self) == null) goto SlowPath
duke@435 3668 // goto FastPathDone ;
duke@435 3669 //
duke@435 3670 // and the 1-0 fast-exit path would appear as:
duke@435 3671 // if (_succ == 1) goto SlowPath
duke@435 3672 // Owner = null ;
duke@435 3673 // goto FastPathDone
duke@435 3674 //
duke@435 3675 // - Encode the LSB of _owner as 1 to indicate that exit()
duke@435 3676 // must use the slow-path and make a successor ready.
duke@435 3677 // (_owner & 1) == 0 IFF succ != null || (EntryList|cxq) == null
duke@435 3678 // (_owner & 1) == 0 IFF succ == null && (EntryList|cxq) != null (obviously)
duke@435 3679 // The 1-0 fast exit path would read:
duke@435 3680 // if (_owner != Self) goto SlowPath
duke@435 3681 // _owner = null
duke@435 3682 // goto FastPathDone
duke@435 3683
duke@435 3684 if (Knob_ExitPolicy == 0) {
duke@435 3685 // release semantics: prior loads and stores from within the critical section
duke@435 3686 // must not float (reorder) past the following store that drops the lock.
duke@435 3687 // On SPARC that requires MEMBAR #loadstore|#storestore.
duke@435 3688 // But of course in TSO #loadstore|#storestore is not required.
duke@435 3689 // I'd like to write one of the following:
duke@435 3690 // A. OrderAccess::release() ; _owner = NULL
duke@435 3691 // B. OrderAccess::loadstore(); OrderAccess::storestore(); _owner = NULL;
duke@435 3692 // Unfortunately OrderAccess::release() and OrderAccess::loadstore() both
duke@435 3693 // store into a _dummy variable. That store is not needed, but can result
duke@435 3694 // in massive wasteful coherency traffic on classic SMP systems.
duke@435 3695 // Instead, I use release_store(), which is implemented as just a simple
duke@435 3696 // ST on x64, x86 and SPARC.
duke@435 3697 OrderAccess::release_store_ptr (&_owner, NULL) ; // drop the lock
duke@435 3698 OrderAccess::storeload() ; // See if we need to wake a successor
duke@435 3699 if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != NULL) {
duke@435 3700 TEVENT (Inflated exit - simple egress) ;
duke@435 3701 return ;
duke@435 3702 }
duke@435 3703 TEVENT (Inflated exit - complex egress) ;
duke@435 3704
duke@435 3705 // Normally the exiting thread is responsible for ensuring succession,
duke@435 3706 // but if other successors are ready or other entering threads are spinning
duke@435 3707 // then this thread can simply store NULL into _owner and exit without
duke@435 3708 // waking a successor. The existence of spinners or ready successors
duke@435 3709 // guarantees proper succession (liveness). Responsibility passes to the
duke@435 3710 // ready or running successors. The exiting thread delegates the duty.
duke@435 3711 // More precisely, if a successor already exists this thread is absolved
duke@435 3712 // of the responsibility of waking (unparking) one.
duke@435 3713 //
duke@435 3714 // The _succ variable is critical to reducing futile wakeup frequency.
duke@435 3715 // _succ identifies the "heir presumptive" thread that has been made
duke@435 3716 // ready (unparked) but that has not yet run. We need only one such
duke@435 3717 // successor thread to guarantee progress.
duke@435 3718 // See http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf
duke@435 3719 // section 3.3 "Futile Wakeup Throttling" for details.
duke@435 3720 //
duke@435 3721 // Note that spinners in Enter() also set _succ non-null.
duke@435 3722 // In the current implementation spinners opportunistically set
duke@435 3723 // _succ so that exiting threads might avoid waking a successor.
duke@435 3724 // Another less appealing alternative would be for the exiting thread
duke@435 3725 // to drop the lock and then spin briefly to see if a spinner managed
duke@435 3726 // to acquire the lock. If so, the exiting thread could exit
duke@435 3727 // immediately without waking a successor, otherwise the exiting
duke@435 3728 // thread would need to dequeue and wake a successor.
duke@435 3729 // (Note that we'd need to make the post-drop spin short, but no
duke@435 3730 // shorter than the worst-case round-trip cache-line migration time.
duke@435 3731 // The dropped lock needs to become visible to the spinner, and then
duke@435 3732 // the acquisition of the lock by the spinner must become visible to
duke@435 3733 // the exiting thread).
duke@435 3734 //
duke@435 3735
duke@435 3736 // It appears that an heir-presumptive (successor) must be made ready.
duke@435 3737 // Only the current lock owner can manipulate the EntryList or
duke@435 3738 // drain _cxq, so we need to reacquire the lock. If we fail
duke@435 3739 // to reacquire the lock the responsibility for ensuring succession
duke@435 3740 // falls to the new owner.
duke@435 3741 //
duke@435 3742 if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) {
duke@435 3743 return ;
duke@435 3744 }
duke@435 3745 TEVENT (Exit - Reacquired) ;
duke@435 3746 } else {
duke@435 3747 if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != NULL) {
duke@435 3748 OrderAccess::release_store_ptr (&_owner, NULL) ; // drop the lock
duke@435 3749 OrderAccess::storeload() ;
duke@435 3750 // Ratify the previously observed values.
duke@435 3751 if (_cxq == NULL || _succ != NULL) {
duke@435 3752 TEVENT (Inflated exit - simple egress) ;
duke@435 3753 return ;
duke@435 3754 }
duke@435 3755
duke@435 3756 // inopportune interleaving -- the exiting thread (this thread)
duke@435 3757 // in the fast-exit path raced an entering thread in the slow-enter
duke@435 3758 // path.
duke@435 3759 // We have two choices:
duke@435 3760 // A. Try to reacquire the lock.
duke@435 3761 // If the CAS() fails return immediately, otherwise
duke@435 3762 // we either restart/rerun the exit operation, or simply
duke@435 3763 // fall-through into the code below which wakes a successor.
duke@435 3764 // B. If the elements forming the EntryList|cxq are TSM
duke@435 3765 // we could simply unpark() the lead thread and return
duke@435 3766 // without having set _succ.
duke@435 3767 if (Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) != NULL) {
duke@435 3768 TEVENT (Inflated exit - reacquired succeeded) ;
duke@435 3769 return ;
duke@435 3770 }
duke@435 3771 TEVENT (Inflated exit - reacquired failed) ;
duke@435 3772 } else {
duke@435 3773 TEVENT (Inflated exit - complex egress) ;
duke@435 3774 }
duke@435 3775 }
duke@435 3776
duke@435 3777 guarantee (_owner == THREAD, "invariant") ;
duke@435 3778
duke@435 3779 // Select an appropriate successor ("heir presumptive") from the EntryList
duke@435 3780 // and make it ready. Generally we just wake the head of EntryList .
duke@435 3781 // There's no algorithmic constraint that we use the head - it's just
duke@435 3782 // a policy decision. Note that the thread at head of the EntryList
duke@435 3783 // remains at the head until it acquires the lock. This means we'll
duke@435 3784 // repeatedly wake the same thread until it manages to grab the lock.
duke@435 3785 // This is generally a good policy - if we're seeing lots of futile wakeups
duke@435 3786 // at least we're waking/rewaking a thread that's like to be hot or warm
duke@435 3787 // (have residual D$ and TLB affinity).
duke@435 3788 //
duke@435 3789 // "Wakeup locality" optimization:
duke@435 3790 // http://j2se.east/~dice/PERSIST/040825-WakeLocality.txt
duke@435 3791 // In the future we'll try to bias the selection mechanism
duke@435 3792 // to preferentially pick a thread that recently ran on
duke@435 3793 // a processor element that shares cache with the CPU on which
duke@435 3794 // the exiting thread is running. We need access to Solaris'
duke@435 3795 // schedctl.sc_cpu to make that work.
duke@435 3796 //
duke@435 3797 ObjectWaiter * w = NULL ;
duke@435 3798 int QMode = Knob_QMode ;
duke@435 3799
duke@435 3800 if (QMode == 2 && _cxq != NULL) {
duke@435 3801 // QMode == 2 : cxq has precedence over EntryList.
duke@435 3802 // Try to directly wake a successor from the cxq.
duke@435 3803 // If successful, the successor will need to unlink itself from cxq.
duke@435 3804 w = _cxq ;
duke@435 3805 assert (w != NULL, "invariant") ;
duke@435 3806 assert (w->TState == ObjectWaiter::TS_CXQ, "Invariant") ;
duke@435 3807 ExitEpilog (Self, w) ;
duke@435 3808 return ;
duke@435 3809 }
duke@435 3810
duke@435 3811 if (QMode == 3 && _cxq != NULL) {
duke@435 3812 // Aggressively drain cxq into EntryList at the first opportunity.
duke@435 3813 // This policy ensure that recently-run threads live at the head of EntryList.
duke@435 3814 // Drain _cxq into EntryList - bulk transfer.
duke@435 3815 // First, detach _cxq.
duke@435 3816 // The following loop is tantamount to: w = swap (&cxq, NULL)
duke@435 3817 w = _cxq ;
duke@435 3818 for (;;) {
duke@435 3819 assert (w != NULL, "Invariant") ;
duke@435 3820 ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ;
duke@435 3821 if (u == w) break ;
duke@435 3822 w = u ;
duke@435 3823 }
duke@435 3824 assert (w != NULL , "invariant") ;
duke@435 3825
duke@435 3826 ObjectWaiter * q = NULL ;
duke@435 3827 ObjectWaiter * p ;
duke@435 3828 for (p = w ; p != NULL ; p = p->_next) {
duke@435 3829 guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ;
duke@435 3830 p->TState = ObjectWaiter::TS_ENTER ;
duke@435 3831 p->_prev = q ;
duke@435 3832 q = p ;
duke@435 3833 }
duke@435 3834
duke@435 3835 // Append the RATs to the EntryList
duke@435 3836 // TODO: organize EntryList as a CDLL so we can locate the tail in constant-time.
duke@435 3837 ObjectWaiter * Tail ;
duke@435 3838 for (Tail = _EntryList ; Tail != NULL && Tail->_next != NULL ; Tail = Tail->_next) ;
duke@435 3839 if (Tail == NULL) {
duke@435 3840 _EntryList = w ;
duke@435 3841 } else {
duke@435 3842 Tail->_next = w ;
duke@435 3843 w->_prev = Tail ;
duke@435 3844 }
duke@435 3845
duke@435 3846 // Fall thru into code that tries to wake a successor from EntryList
duke@435 3847 }
duke@435 3848
duke@435 3849 if (QMode == 4 && _cxq != NULL) {
duke@435 3850 // Aggressively drain cxq into EntryList at the first opportunity.
duke@435 3851 // This policy ensure that recently-run threads live at the head of EntryList.
duke@435 3852
duke@435 3853 // Drain _cxq into EntryList - bulk transfer.
duke@435 3854 // First, detach _cxq.
duke@435 3855 // The following loop is tantamount to: w = swap (&cxq, NULL)
duke@435 3856 w = _cxq ;
duke@435 3857 for (;;) {
duke@435 3858 assert (w != NULL, "Invariant") ;
duke@435 3859 ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ;
duke@435 3860 if (u == w) break ;
duke@435 3861 w = u ;
duke@435 3862 }
duke@435 3863 assert (w != NULL , "invariant") ;
duke@435 3864
duke@435 3865 ObjectWaiter * q = NULL ;
duke@435 3866 ObjectWaiter * p ;
duke@435 3867 for (p = w ; p != NULL ; p = p->_next) {
duke@435 3868 guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ;
duke@435 3869 p->TState = ObjectWaiter::TS_ENTER ;
duke@435 3870 p->_prev = q ;
duke@435 3871 q = p ;
duke@435 3872 }
duke@435 3873
duke@435 3874 // Prepend the RATs to the EntryList
duke@435 3875 if (_EntryList != NULL) {
duke@435 3876 q->_next = _EntryList ;
duke@435 3877 _EntryList->_prev = q ;
duke@435 3878 }
duke@435 3879 _EntryList = w ;
duke@435 3880
duke@435 3881 // Fall thru into code that tries to wake a successor from EntryList
duke@435 3882 }
duke@435 3883
duke@435 3884 w = _EntryList ;
duke@435 3885 if (w != NULL) {
duke@435 3886 // I'd like to write: guarantee (w->_thread != Self).
duke@435 3887 // But in practice an exiting thread may find itself on the EntryList.
duke@435 3888 // Lets say thread T1 calls O.wait(). Wait() enqueues T1 on O's waitset and
duke@435 3889 // then calls exit(). Exit release the lock by setting O._owner to NULL.
duke@435 3890 // Lets say T1 then stalls. T2 acquires O and calls O.notify(). The
duke@435 3891 // notify() operation moves T1 from O's waitset to O's EntryList. T2 then
duke@435 3892 // release the lock "O". T2 resumes immediately after the ST of null into
duke@435 3893 // _owner, above. T2 notices that the EntryList is populated, so it
duke@435 3894 // reacquires the lock and then finds itself on the EntryList.
duke@435 3895 // Given all that, we have to tolerate the circumstance where "w" is
duke@435 3896 // associated with Self.
duke@435 3897 assert (w->TState == ObjectWaiter::TS_ENTER, "invariant") ;
duke@435 3898 ExitEpilog (Self, w) ;
duke@435 3899 return ;
duke@435 3900 }
duke@435 3901
duke@435 3902 // If we find that both _cxq and EntryList are null then just
duke@435 3903 // re-run the exit protocol from the top.
duke@435 3904 w = _cxq ;
duke@435 3905 if (w == NULL) continue ;
duke@435 3906
duke@435 3907 // Drain _cxq into EntryList - bulk transfer.
duke@435 3908 // First, detach _cxq.
duke@435 3909 // The following loop is tantamount to: w = swap (&cxq, NULL)
duke@435 3910 for (;;) {
duke@435 3911 assert (w != NULL, "Invariant") ;
duke@435 3912 ObjectWaiter * u = (ObjectWaiter *) Atomic::cmpxchg_ptr (NULL, &_cxq, w) ;
duke@435 3913 if (u == w) break ;
duke@435 3914 w = u ;
duke@435 3915 }
duke@435 3916 TEVENT (Inflated exit - drain cxq into EntryList) ;
duke@435 3917
duke@435 3918 assert (w != NULL , "invariant") ;
duke@435 3919 assert (_EntryList == NULL , "invariant") ;
duke@435 3920
duke@435 3921 // Convert the LIFO SLL anchored by _cxq into a DLL.
duke@435 3922 // The list reorganization step operates in O(LENGTH(w)) time.
duke@435 3923 // It's critical that this step operate quickly as
duke@435 3924 // "Self" still holds the outer-lock, restricting parallelism
duke@435 3925 // and effectively lengthening the critical section.
duke@435 3926 // Invariant: s chases t chases u.
duke@435 3927 // TODO-FIXME: consider changing EntryList from a DLL to a CDLL so
duke@435 3928 // we have faster access to the tail.
duke@435 3929
duke@435 3930 if (QMode == 1) {
duke@435 3931 // QMode == 1 : drain cxq to EntryList, reversing order
duke@435 3932 // We also reverse the order of the list.
duke@435 3933 ObjectWaiter * s = NULL ;
duke@435 3934 ObjectWaiter * t = w ;
duke@435 3935 ObjectWaiter * u = NULL ;
duke@435 3936 while (t != NULL) {
duke@435 3937 guarantee (t->TState == ObjectWaiter::TS_CXQ, "invariant") ;
duke@435 3938 t->TState = ObjectWaiter::TS_ENTER ;
duke@435 3939 u = t->_next ;
duke@435 3940 t->_prev = u ;
duke@435 3941 t->_next = s ;
duke@435 3942 s = t;
duke@435 3943 t = u ;
duke@435 3944 }
duke@435 3945 _EntryList = s ;
duke@435 3946 assert (s != NULL, "invariant") ;
duke@435 3947 } else {
duke@435 3948 // QMode == 0 or QMode == 2
duke@435 3949 _EntryList = w ;
duke@435 3950 ObjectWaiter * q = NULL ;
duke@435 3951 ObjectWaiter * p ;
duke@435 3952 for (p = w ; p != NULL ; p = p->_next) {
duke@435 3953 guarantee (p->TState == ObjectWaiter::TS_CXQ, "Invariant") ;
duke@435 3954 p->TState = ObjectWaiter::TS_ENTER ;
duke@435 3955 p->_prev = q ;
duke@435 3956 q = p ;
duke@435 3957 }
duke@435 3958 }
duke@435 3959
duke@435 3960 // In 1-0 mode we need: ST EntryList; MEMBAR #storestore; ST _owner = NULL
duke@435 3961 // The MEMBAR is satisfied by the release_store() operation in ExitEpilog().
duke@435 3962
duke@435 3963 // See if we can abdicate to a spinner instead of waking a thread.
duke@435 3964 // A primary goal of the implementation is to reduce the
duke@435 3965 // context-switch rate.
duke@435 3966 if (_succ != NULL) continue;
duke@435 3967
duke@435 3968 w = _EntryList ;
duke@435 3969 if (w != NULL) {
duke@435 3970 guarantee (w->TState == ObjectWaiter::TS_ENTER, "invariant") ;
duke@435 3971 ExitEpilog (Self, w) ;
duke@435 3972 return ;
duke@435 3973 }
duke@435 3974 }
duke@435 3975 }
duke@435 3976 // complete_exit exits a lock returning recursion count
duke@435 3977 // complete_exit/reenter operate as a wait without waiting
duke@435 3978 // complete_exit requires an inflated monitor
duke@435 3979 // The _owner field is not always the Thread addr even with an
duke@435 3980 // inflated monitor, e.g. the monitor can be inflated by a non-owning
duke@435 3981 // thread due to contention.
duke@435 3982 intptr_t ObjectMonitor::complete_exit(TRAPS) {
duke@435 3983 Thread * const Self = THREAD;
duke@435 3984 assert(Self->is_Java_thread(), "Must be Java thread!");
duke@435 3985 JavaThread *jt = (JavaThread *)THREAD;
duke@435 3986
duke@435 3987 DeferredInitialize();
duke@435 3988
duke@435 3989 if (THREAD != _owner) {
duke@435 3990 if (THREAD->is_lock_owned ((address)_owner)) {
duke@435 3991 assert(_recursions == 0, "internal state error");
duke@435 3992 _owner = THREAD ; /* Convert from basiclock addr to Thread addr */
duke@435 3993 _recursions = 0 ;
duke@435 3994 OwnerIsThread = 1 ;
duke@435 3995 }
duke@435 3996 }
duke@435 3997
duke@435 3998 guarantee(Self == _owner, "complete_exit not owner");
duke@435 3999 intptr_t save = _recursions; // record the old recursion count
duke@435 4000 _recursions = 0; // set the recursion level to be 0
duke@435 4001 exit (Self) ; // exit the monitor
duke@435 4002 guarantee (_owner != Self, "invariant");
duke@435 4003 return save;
duke@435 4004 }
duke@435 4005
duke@435 4006 // reenter() enters a lock and sets recursion count
duke@435 4007 // complete_exit/reenter operate as a wait without waiting
duke@435 4008 void ObjectMonitor::reenter(intptr_t recursions, TRAPS) {
duke@435 4009 Thread * const Self = THREAD;
duke@435 4010 assert(Self->is_Java_thread(), "Must be Java thread!");
duke@435 4011 JavaThread *jt = (JavaThread *)THREAD;
duke@435 4012
duke@435 4013 guarantee(_owner != Self, "reenter already owner");
duke@435 4014 enter (THREAD); // enter the monitor
duke@435 4015 guarantee (_recursions == 0, "reenter recursion");
duke@435 4016 _recursions = recursions;
duke@435 4017 return;
duke@435 4018 }
duke@435 4019
duke@435 4020 // Note: a subset of changes to ObjectMonitor::wait()
duke@435 4021 // will need to be replicated in complete_exit above
duke@435 4022 void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) {
duke@435 4023 Thread * const Self = THREAD ;
duke@435 4024 assert(Self->is_Java_thread(), "Must be Java thread!");
duke@435 4025 JavaThread *jt = (JavaThread *)THREAD;
duke@435 4026
duke@435 4027 DeferredInitialize () ;
duke@435 4028
duke@435 4029 // Throw IMSX or IEX.
duke@435 4030 CHECK_OWNER();
duke@435 4031
duke@435 4032 // check for a pending interrupt
duke@435 4033 if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) {
duke@435 4034 // post monitor waited event. Note that this is past-tense, we are done waiting.
duke@435 4035 if (JvmtiExport::should_post_monitor_waited()) {
duke@435 4036 // Note: 'false' parameter is passed here because the
duke@435 4037 // wait was not timed out due to thread interrupt.
duke@435 4038 JvmtiExport::post_monitor_waited(jt, this, false);
duke@435 4039 }
duke@435 4040 TEVENT (Wait - Throw IEX) ;
duke@435 4041 THROW(vmSymbols::java_lang_InterruptedException());
duke@435 4042 return ;
duke@435 4043 }
duke@435 4044 TEVENT (Wait) ;
duke@435 4045
duke@435 4046 assert (Self->_Stalled == 0, "invariant") ;
duke@435 4047 Self->_Stalled = intptr_t(this) ;
duke@435 4048 jt->set_current_waiting_monitor(this);
duke@435 4049
duke@435 4050 // create a node to be put into the queue
duke@435 4051 // Critically, after we reset() the event but prior to park(), we must check
duke@435 4052 // for a pending interrupt.
duke@435 4053 ObjectWaiter node(Self);
duke@435 4054 node.TState = ObjectWaiter::TS_WAIT ;
duke@435 4055 Self->_ParkEvent->reset() ;
duke@435 4056 OrderAccess::fence(); // ST into Event; membar ; LD interrupted-flag
duke@435 4057
duke@435 4058 // Enter the waiting queue, which is a circular doubly linked list in this case
duke@435 4059 // but it could be a priority queue or any data structure.
duke@435 4060 // _WaitSetLock protects the wait queue. Normally the wait queue is accessed only
duke@435 4061 // by the the owner of the monitor *except* in the case where park()
duke@435 4062 // returns because of a timeout of interrupt. Contention is exceptionally rare
duke@435 4063 // so we use a simple spin-lock instead of a heavier-weight blocking lock.
duke@435 4064
duke@435 4065 Thread::SpinAcquire (&_WaitSetLock, "WaitSet - add") ;
duke@435 4066 AddWaiter (&node) ;
duke@435 4067 Thread::SpinRelease (&_WaitSetLock) ;
duke@435 4068
duke@435 4069 if ((SyncFlags & 4) == 0) {
duke@435 4070 _Responsible = NULL ;
duke@435 4071 }
duke@435 4072 intptr_t save = _recursions; // record the old recursion count
duke@435 4073 _waiters++; // increment the number of waiters
duke@435 4074 _recursions = 0; // set the recursion level to be 1
duke@435 4075 exit (Self) ; // exit the monitor
duke@435 4076 guarantee (_owner != Self, "invariant") ;
duke@435 4077
duke@435 4078 // As soon as the ObjectMonitor's ownership is dropped in the exit()
duke@435 4079 // call above, another thread can enter() the ObjectMonitor, do the
duke@435 4080 // notify(), and exit() the ObjectMonitor. If the other thread's
duke@435 4081 // exit() call chooses this thread as the successor and the unpark()
duke@435 4082 // call happens to occur while this thread is posting a
duke@435 4083 // MONITOR_CONTENDED_EXIT event, then we run the risk of the event
duke@435 4084 // handler using RawMonitors and consuming the unpark().
duke@435 4085 //
duke@435 4086 // To avoid the problem, we re-post the event. This does no harm
duke@435 4087 // even if the original unpark() was not consumed because we are the
duke@435 4088 // chosen successor for this monitor.
duke@435 4089 if (node._notified != 0 && _succ == Self) {
duke@435 4090 node._event->unpark();
duke@435 4091 }
duke@435 4092
duke@435 4093 // The thread is on the WaitSet list - now park() it.
duke@435 4094 // On MP systems it's conceivable that a brief spin before we park
duke@435 4095 // could be profitable.
duke@435 4096 //
duke@435 4097 // TODO-FIXME: change the following logic to a loop of the form
duke@435 4098 // while (!timeout && !interrupted && _notified == 0) park()
duke@435 4099
duke@435 4100 int ret = OS_OK ;
duke@435 4101 int WasNotified = 0 ;
duke@435 4102 { // State transition wrappers
duke@435 4103 OSThread* osthread = Self->osthread();
duke@435 4104 OSThreadWaitState osts(osthread, true);
duke@435 4105 {
duke@435 4106 ThreadBlockInVM tbivm(jt);
duke@435 4107 // Thread is in thread_blocked state and oop access is unsafe.
duke@435 4108 jt->set_suspend_equivalent();
duke@435 4109
duke@435 4110 if (interruptible && (Thread::is_interrupted(THREAD, false) || HAS_PENDING_EXCEPTION)) {
duke@435 4111 // Intentionally empty
duke@435 4112 } else
duke@435 4113 if (node._notified == 0) {
duke@435 4114 if (millis <= 0) {
duke@435 4115 Self->_ParkEvent->park () ;
duke@435 4116 } else {
duke@435 4117 ret = Self->_ParkEvent->park (millis) ;
duke@435 4118 }
duke@435 4119 }
duke@435 4120
duke@435 4121 // were we externally suspended while we were waiting?
duke@435 4122 if (ExitSuspendEquivalent (jt)) {
duke@435 4123 // TODO-FIXME: add -- if succ == Self then succ = null.
duke@435 4124 jt->java_suspend_self();
duke@435 4125 }
duke@435 4126
duke@435 4127 } // Exit thread safepoint: transition _thread_blocked -> _thread_in_vm
duke@435 4128
duke@435 4129
duke@435 4130 // Node may be on the WaitSet, the EntryList (or cxq), or in transition
duke@435 4131 // from the WaitSet to the EntryList.
duke@435 4132 // See if we need to remove Node from the WaitSet.
duke@435 4133 // We use double-checked locking to avoid grabbing _WaitSetLock
duke@435 4134 // if the thread is not on the wait queue.
duke@435 4135 //
duke@435 4136 // Note that we don't need a fence before the fetch of TState.
duke@435 4137 // In the worst case we'll fetch a old-stale value of TS_WAIT previously
duke@435 4138 // written by the is thread. (perhaps the fetch might even be satisfied
duke@435 4139 // by a look-aside into the processor's own store buffer, although given
duke@435 4140 // the length of the code path between the prior ST and this load that's
duke@435 4141 // highly unlikely). If the following LD fetches a stale TS_WAIT value
duke@435 4142 // then we'll acquire the lock and then re-fetch a fresh TState value.
duke@435 4143 // That is, we fail toward safety.
duke@435 4144
duke@435 4145 if (node.TState == ObjectWaiter::TS_WAIT) {
duke@435 4146 Thread::SpinAcquire (&_WaitSetLock, "WaitSet - unlink") ;
duke@435 4147 if (node.TState == ObjectWaiter::TS_WAIT) {
duke@435 4148 DequeueSpecificWaiter (&node) ; // unlink from WaitSet
duke@435 4149 assert(node._notified == 0, "invariant");
duke@435 4150 node.TState = ObjectWaiter::TS_RUN ;
duke@435 4151 }
duke@435 4152 Thread::SpinRelease (&_WaitSetLock) ;
duke@435 4153 }
duke@435 4154
duke@435 4155 // The thread is now either on off-list (TS_RUN),
duke@435 4156 // on the EntryList (TS_ENTER), or on the cxq (TS_CXQ).
duke@435 4157 // The Node's TState variable is stable from the perspective of this thread.
duke@435 4158 // No other threads will asynchronously modify TState.
duke@435 4159 guarantee (node.TState != ObjectWaiter::TS_WAIT, "invariant") ;
duke@435 4160 OrderAccess::loadload() ;
duke@435 4161 if (_succ == Self) _succ = NULL ;
duke@435 4162 WasNotified = node._notified ;
duke@435 4163
duke@435 4164 // Reentry phase -- reacquire the monitor.
duke@435 4165 // re-enter contended monitor after object.wait().
duke@435 4166 // retain OBJECT_WAIT state until re-enter successfully completes
duke@435 4167 // Thread state is thread_in_vm and oop access is again safe,
duke@435 4168 // although the raw address of the object may have changed.
duke@435 4169 // (Don't cache naked oops over safepoints, of course).
duke@435 4170
duke@435 4171 // post monitor waited event. Note that this is past-tense, we are done waiting.
duke@435 4172 if (JvmtiExport::should_post_monitor_waited()) {
duke@435 4173 JvmtiExport::post_monitor_waited(jt, this, ret == OS_TIMEOUT);
duke@435 4174 }
duke@435 4175 OrderAccess::fence() ;
duke@435 4176
duke@435 4177 assert (Self->_Stalled != 0, "invariant") ;
duke@435 4178 Self->_Stalled = 0 ;
duke@435 4179
duke@435 4180 assert (_owner != Self, "invariant") ;
duke@435 4181 ObjectWaiter::TStates v = node.TState ;
duke@435 4182 if (v == ObjectWaiter::TS_RUN) {
duke@435 4183 enter (Self) ;
duke@435 4184 } else {
duke@435 4185 guarantee (v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant") ;
duke@435 4186 ReenterI (Self, &node) ;
duke@435 4187 node.wait_reenter_end(this);
duke@435 4188 }
duke@435 4189
duke@435 4190 // Self has reacquired the lock.
duke@435 4191 // Lifecycle - the node representing Self must not appear on any queues.
duke@435 4192 // Node is about to go out-of-scope, but even if it were immortal we wouldn't
duke@435 4193 // want residual elements associated with this thread left on any lists.
duke@435 4194 guarantee (node.TState == ObjectWaiter::TS_RUN, "invariant") ;
duke@435 4195 assert (_owner == Self, "invariant") ;
duke@435 4196 assert (_succ != Self , "invariant") ;
duke@435 4197 } // OSThreadWaitState()
duke@435 4198
duke@435 4199 jt->set_current_waiting_monitor(NULL);
duke@435 4200
duke@435 4201 guarantee (_recursions == 0, "invariant") ;
duke@435 4202 _recursions = save; // restore the old recursion count
duke@435 4203 _waiters--; // decrement the number of waiters
duke@435 4204
duke@435 4205 // Verify a few postconditions
duke@435 4206 assert (_owner == Self , "invariant") ;
duke@435 4207 assert (_succ != Self , "invariant") ;
duke@435 4208 assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;
duke@435 4209
duke@435 4210 if (SyncFlags & 32) {
duke@435 4211 OrderAccess::fence() ;
duke@435 4212 }
duke@435 4213
duke@435 4214 // check if the notification happened
duke@435 4215 if (!WasNotified) {
duke@435 4216 // no, it could be timeout or Thread.interrupt() or both
duke@435 4217 // check for interrupt event, otherwise it is timeout
duke@435 4218 if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) {
duke@435 4219 TEVENT (Wait - throw IEX from epilog) ;
duke@435 4220 THROW(vmSymbols::java_lang_InterruptedException());
duke@435 4221 }
duke@435 4222 }
duke@435 4223
duke@435 4224 // NOTE: Spurious wake up will be consider as timeout.
duke@435 4225 // Monitor notify has precedence over thread interrupt.
duke@435 4226 }
duke@435 4227
duke@435 4228
duke@435 4229 // Consider:
duke@435 4230 // If the lock is cool (cxq == null && succ == null) and we're on an MP system
duke@435 4231 // then instead of transferring a thread from the WaitSet to the EntryList
duke@435 4232 // we might just dequeue a thread from the WaitSet and directly unpark() it.
duke@435 4233
duke@435 4234 void ObjectMonitor::notify(TRAPS) {
duke@435 4235 CHECK_OWNER();
duke@435 4236 if (_WaitSet == NULL) {
duke@435 4237 TEVENT (Empty-Notify) ;
duke@435 4238 return ;
duke@435 4239 }
duke@435 4240 DTRACE_MONITOR_PROBE(notify, this, object(), THREAD);
duke@435 4241
duke@435 4242 int Policy = Knob_MoveNotifyee ;
duke@435 4243
duke@435 4244 Thread::SpinAcquire (&_WaitSetLock, "WaitSet - notify") ;
duke@435 4245 ObjectWaiter * iterator = DequeueWaiter() ;
duke@435 4246 if (iterator != NULL) {
duke@435 4247 TEVENT (Notify1 - Transfer) ;
duke@435 4248 guarantee (iterator->TState == ObjectWaiter::TS_WAIT, "invariant") ;
duke@435 4249 guarantee (iterator->_notified == 0, "invariant") ;
duke@435 4250 // Disposition - what might we do with iterator ?
duke@435 4251 // a. add it directly to the EntryList - either tail or head.
duke@435 4252 // b. push it onto the front of the _cxq.
duke@435 4253 // For now we use (a).
duke@435 4254 if (Policy != 4) {
duke@435 4255 iterator->TState = ObjectWaiter::TS_ENTER ;
duke@435 4256 }
duke@435 4257 iterator->_notified = 1 ;
duke@435 4258
duke@435 4259 ObjectWaiter * List = _EntryList ;
duke@435 4260 if (List != NULL) {
duke@435 4261 assert (List->_prev == NULL, "invariant") ;
duke@435 4262 assert (List->TState == ObjectWaiter::TS_ENTER, "invariant") ;
duke@435 4263 assert (List != iterator, "invariant") ;
duke@435 4264 }
duke@435 4265
duke@435 4266 if (Policy == 0) { // prepend to EntryList
duke@435 4267 if (List == NULL) {
duke@435 4268 iterator->_next = iterator->_prev = NULL ;
duke@435 4269 _EntryList = iterator ;
duke@435 4270 } else {
duke@435 4271 List->_prev = iterator ;
duke@435 4272 iterator->_next = List ;
duke@435 4273 iterator->_prev = NULL ;
duke@435 4274 _EntryList = iterator ;
duke@435 4275 }
duke@435 4276 } else
duke@435 4277 if (Policy == 1) { // append to EntryList
duke@435 4278 if (List == NULL) {
duke@435 4279 iterator->_next = iterator->_prev = NULL ;
duke@435 4280 _EntryList = iterator ;
duke@435 4281 } else {
duke@435 4282 // CONSIDER: finding the tail currently requires a linear-time walk of
duke@435 4283 // the EntryList. We can make tail access constant-time by converting to
duke@435 4284 // a CDLL instead of using our current DLL.
duke@435 4285 ObjectWaiter * Tail ;
duke@435 4286 for (Tail = List ; Tail->_next != NULL ; Tail = Tail->_next) ;
duke@435 4287 assert (Tail != NULL && Tail->_next == NULL, "invariant") ;
duke@435 4288 Tail->_next = iterator ;
duke@435 4289 iterator->_prev = Tail ;
duke@435 4290 iterator->_next = NULL ;
duke@435 4291 }
duke@435 4292 } else
duke@435 4293 if (Policy == 2) { // prepend to cxq
duke@435 4294 // prepend to cxq
duke@435 4295 if (List == NULL) {
duke@435 4296 iterator->_next = iterator->_prev = NULL ;
duke@435 4297 _EntryList = iterator ;
duke@435 4298 } else {
duke@435 4299 iterator->TState = ObjectWaiter::TS_CXQ ;
duke@435 4300 for (;;) {
duke@435 4301 ObjectWaiter * Front = _cxq ;
duke@435 4302 iterator->_next = Front ;
duke@435 4303 if (Atomic::cmpxchg_ptr (iterator, &_cxq, Front) == Front) {
duke@435 4304 break ;
duke@435 4305 }
duke@435 4306 }
duke@435 4307 }
duke@435 4308 } else
duke@435 4309 if (Policy == 3) { // append to cxq
duke@435 4310 iterator->TState = ObjectWaiter::TS_CXQ ;
duke@435 4311 for (;;) {
duke@435 4312 ObjectWaiter * Tail ;
duke@435 4313 Tail = _cxq ;
duke@435 4314 if (Tail == NULL) {
duke@435 4315 iterator->_next = NULL ;
duke@435 4316 if (Atomic::cmpxchg_ptr (iterator, &_cxq, NULL) == NULL) {
duke@435 4317 break ;
duke@435 4318 }
duke@435 4319 } else {
duke@435 4320 while (Tail->_next != NULL) Tail = Tail->_next ;
duke@435 4321 Tail->_next = iterator ;
duke@435 4322 iterator->_prev = Tail ;
duke@435 4323 iterator->_next = NULL ;
duke@435 4324 break ;
duke@435 4325 }
duke@435 4326 }
duke@435 4327 } else {
duke@435 4328 ParkEvent * ev = iterator->_event ;
duke@435 4329 iterator->TState = ObjectWaiter::TS_RUN ;
duke@435 4330 OrderAccess::fence() ;
duke@435 4331 ev->unpark() ;
duke@435 4332 }
duke@435 4333
duke@435 4334 if (Policy < 4) {
duke@435 4335 iterator->wait_reenter_begin(this);
duke@435 4336 }
duke@435 4337
duke@435 4338 // _WaitSetLock protects the wait queue, not the EntryList. We could
duke@435 4339 // move the add-to-EntryList operation, above, outside the critical section
duke@435 4340 // protected by _WaitSetLock. In practice that's not useful. With the
duke@435 4341 // exception of wait() timeouts and interrupts the monitor owner
duke@435 4342 // is the only thread that grabs _WaitSetLock. There's almost no contention
duke@435 4343 // on _WaitSetLock so it's not profitable to reduce the length of the
duke@435 4344 // critical section.
duke@435 4345 }
duke@435 4346
duke@435 4347 Thread::SpinRelease (&_WaitSetLock) ;
duke@435 4348
duke@435 4349 if (iterator != NULL && ObjectSynchronizer::_sync_Notifications != NULL) {
duke@435 4350 ObjectSynchronizer::_sync_Notifications->inc() ;
duke@435 4351 }
duke@435 4352 }
duke@435 4353
duke@435 4354
duke@435 4355 void ObjectMonitor::notifyAll(TRAPS) {
duke@435 4356 CHECK_OWNER();
duke@435 4357 ObjectWaiter* iterator;
duke@435 4358 if (_WaitSet == NULL) {
duke@435 4359 TEVENT (Empty-NotifyAll) ;
duke@435 4360 return ;
duke@435 4361 }
duke@435 4362 DTRACE_MONITOR_PROBE(notifyAll, this, object(), THREAD);
duke@435 4363
duke@435 4364 int Policy = Knob_MoveNotifyee ;
duke@435 4365 int Tally = 0 ;
duke@435 4366 Thread::SpinAcquire (&_WaitSetLock, "WaitSet - notifyall") ;
duke@435 4367
duke@435 4368 for (;;) {
duke@435 4369 iterator = DequeueWaiter () ;
duke@435 4370 if (iterator == NULL) break ;
duke@435 4371 TEVENT (NotifyAll - Transfer1) ;
duke@435 4372 ++Tally ;
duke@435 4373
duke@435 4374 // Disposition - what might we do with iterator ?
duke@435 4375 // a. add it directly to the EntryList - either tail or head.
duke@435 4376 // b. push it onto the front of the _cxq.
duke@435 4377 // For now we use (a).
duke@435 4378 //
duke@435 4379 // TODO-FIXME: currently notifyAll() transfers the waiters one-at-a-time from the waitset
duke@435 4380 // to the EntryList. This could be done more efficiently with a single bulk transfer,
duke@435 4381 // but in practice it's not time-critical. Beware too, that in prepend-mode we invert the
duke@435 4382 // order of the waiters. Lets say that the waitset is "ABCD" and the EntryList is "XYZ".
duke@435 4383 // After a notifyAll() in prepend mode the waitset will be empty and the EntryList will
duke@435 4384 // be "DCBAXYZ".
duke@435 4385
duke@435 4386 guarantee (iterator->TState == ObjectWaiter::TS_WAIT, "invariant") ;
duke@435 4387 guarantee (iterator->_notified == 0, "invariant") ;
duke@435 4388 iterator->_notified = 1 ;
duke@435 4389 if (Policy != 4) {
duke@435 4390 iterator->TState = ObjectWaiter::TS_ENTER ;
duke@435 4391 }
duke@435 4392
duke@435 4393 ObjectWaiter * List = _EntryList ;
duke@435 4394 if (List != NULL) {
duke@435 4395 assert (List->_prev == NULL, "invariant") ;
duke@435 4396 assert (List->TState == ObjectWaiter::TS_ENTER, "invariant") ;
duke@435 4397 assert (List != iterator, "invariant") ;
duke@435 4398 }
duke@435 4399
duke@435 4400 if (Policy == 0) { // prepend to EntryList
duke@435 4401 if (List == NULL) {
duke@435 4402 iterator->_next = iterator->_prev = NULL ;
duke@435 4403 _EntryList = iterator ;
duke@435 4404 } else {
duke@435 4405 List->_prev = iterator ;
duke@435 4406 iterator->_next = List ;
duke@435 4407 iterator->_prev = NULL ;
duke@435 4408 _EntryList = iterator ;
duke@435 4409 }
duke@435 4410 } else
duke@435 4411 if (Policy == 1) { // append to EntryList
duke@435 4412 if (List == NULL) {
duke@435 4413 iterator->_next = iterator->_prev = NULL ;
duke@435 4414 _EntryList = iterator ;
duke@435 4415 } else {
duke@435 4416 // CONSIDER: finding the tail currently requires a linear-time walk of
duke@435 4417 // the EntryList. We can make tail access constant-time by converting to
duke@435 4418 // a CDLL instead of using our current DLL.
duke@435 4419 ObjectWaiter * Tail ;
duke@435 4420 for (Tail = List ; Tail->_next != NULL ; Tail = Tail->_next) ;
duke@435 4421 assert (Tail != NULL && Tail->_next == NULL, "invariant") ;
duke@435 4422 Tail->_next = iterator ;
duke@435 4423 iterator->_prev = Tail ;
duke@435 4424 iterator->_next = NULL ;
duke@435 4425 }
duke@435 4426 } else
duke@435 4427 if (Policy == 2) { // prepend to cxq
duke@435 4428 // prepend to cxq
duke@435 4429 iterator->TState = ObjectWaiter::TS_CXQ ;
duke@435 4430 for (;;) {
duke@435 4431 ObjectWaiter * Front = _cxq ;
duke@435 4432 iterator->_next = Front ;
duke@435 4433 if (Atomic::cmpxchg_ptr (iterator, &_cxq, Front) == Front) {
duke@435 4434 break ;
duke@435 4435 }
duke@435 4436 }
duke@435 4437 } else
duke@435 4438 if (Policy == 3) { // append to cxq
duke@435 4439 iterator->TState = ObjectWaiter::TS_CXQ ;
duke@435 4440 for (;;) {
duke@435 4441 ObjectWaiter * Tail ;
duke@435 4442 Tail = _cxq ;
duke@435 4443 if (Tail == NULL) {
duke@435 4444 iterator->_next = NULL ;
duke@435 4445 if (Atomic::cmpxchg_ptr (iterator, &_cxq, NULL) == NULL) {
duke@435 4446 break ;
duke@435 4447 }
duke@435 4448 } else {
duke@435 4449 while (Tail->_next != NULL) Tail = Tail->_next ;
duke@435 4450 Tail->_next = iterator ;
duke@435 4451 iterator->_prev = Tail ;
duke@435 4452 iterator->_next = NULL ;
duke@435 4453 break ;
duke@435 4454 }
duke@435 4455 }
duke@435 4456 } else {
duke@435 4457 ParkEvent * ev = iterator->_event ;
duke@435 4458 iterator->TState = ObjectWaiter::TS_RUN ;
duke@435 4459 OrderAccess::fence() ;
duke@435 4460 ev->unpark() ;
duke@435 4461 }
duke@435 4462
duke@435 4463 if (Policy < 4) {
duke@435 4464 iterator->wait_reenter_begin(this);
duke@435 4465 }
duke@435 4466
duke@435 4467 // _WaitSetLock protects the wait queue, not the EntryList. We could
duke@435 4468 // move the add-to-EntryList operation, above, outside the critical section
duke@435 4469 // protected by _WaitSetLock. In practice that's not useful. With the
duke@435 4470 // exception of wait() timeouts and interrupts the monitor owner
duke@435 4471 // is the only thread that grabs _WaitSetLock. There's almost no contention
duke@435 4472 // on _WaitSetLock so it's not profitable to reduce the length of the
duke@435 4473 // critical section.
duke@435 4474 }
duke@435 4475
duke@435 4476 Thread::SpinRelease (&_WaitSetLock) ;
duke@435 4477
duke@435 4478 if (Tally != 0 && ObjectSynchronizer::_sync_Notifications != NULL) {
duke@435 4479 ObjectSynchronizer::_sync_Notifications->inc(Tally) ;
duke@435 4480 }
duke@435 4481 }
duke@435 4482
duke@435 4483 // check_slow() is a misnomer. It's called to simply to throw an IMSX exception.
duke@435 4484 // TODO-FIXME: remove check_slow() -- it's likely dead.
duke@435 4485
duke@435 4486 void ObjectMonitor::check_slow(TRAPS) {
duke@435 4487 TEVENT (check_slow - throw IMSX) ;
duke@435 4488 assert(THREAD != _owner && !THREAD->is_lock_owned((address) _owner), "must not be owner");
duke@435 4489 THROW_MSG(vmSymbols::java_lang_IllegalMonitorStateException(), "current thread not owner");
duke@435 4490 }
duke@435 4491
duke@435 4492
duke@435 4493 // -------------------------------------------------------------------------
duke@435 4494 // The raw monitor subsystem is entirely distinct from normal
duke@435 4495 // java-synchronization or jni-synchronization. raw monitors are not
duke@435 4496 // associated with objects. They can be implemented in any manner
duke@435 4497 // that makes sense. The original implementors decided to piggy-back
duke@435 4498 // the raw-monitor implementation on the existing Java objectMonitor mechanism.
duke@435 4499 // This flaw needs to fixed. We should reimplement raw monitors as sui-generis.
duke@435 4500 // Specifically, we should not implement raw monitors via java monitors.
duke@435 4501 // Time permitting, we should disentangle and deconvolve the two implementations
duke@435 4502 // and move the resulting raw monitor implementation over to the JVMTI directories.
duke@435 4503 // Ideally, the raw monitor implementation would be built on top of
duke@435 4504 // park-unpark and nothing else.
duke@435 4505 //
duke@435 4506 // raw monitors are used mainly by JVMTI
duke@435 4507 // The raw monitor implementation borrows the ObjectMonitor structure,
duke@435 4508 // but the operators are degenerate and extremely simple.
duke@435 4509 //
duke@435 4510 // Mixed use of a single objectMonitor instance -- as both a raw monitor
duke@435 4511 // and a normal java monitor -- is not permissible.
duke@435 4512 //
duke@435 4513 // Note that we use the single RawMonitor_lock to protect queue operations for
duke@435 4514 // _all_ raw monitors. This is a scalability impediment, but since raw monitor usage
duke@435 4515 // is deprecated and rare, this is not of concern. The RawMonitor_lock can not
duke@435 4516 // be held indefinitely. The critical sections must be short and bounded.
duke@435 4517 //
duke@435 4518 // -------------------------------------------------------------------------
duke@435 4519
duke@435 4520 int ObjectMonitor::SimpleEnter (Thread * Self) {
duke@435 4521 for (;;) {
duke@435 4522 if (Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) {
duke@435 4523 return OS_OK ;
duke@435 4524 }
duke@435 4525
duke@435 4526 ObjectWaiter Node (Self) ;
duke@435 4527 Self->_ParkEvent->reset() ; // strictly optional
duke@435 4528 Node.TState = ObjectWaiter::TS_ENTER ;
duke@435 4529
duke@435 4530 RawMonitor_lock->lock_without_safepoint_check() ;
duke@435 4531 Node._next = _EntryList ;
duke@435 4532 _EntryList = &Node ;
duke@435 4533 OrderAccess::fence() ;
duke@435 4534 if (_owner == NULL && Atomic::cmpxchg_ptr (Self, &_owner, NULL) == NULL) {
duke@435 4535 _EntryList = Node._next ;
duke@435 4536 RawMonitor_lock->unlock() ;
duke@435 4537 return OS_OK ;
duke@435 4538 }
duke@435 4539 RawMonitor_lock->unlock() ;
duke@435 4540 while (Node.TState == ObjectWaiter::TS_ENTER) {
duke@435 4541 Self->_ParkEvent->park() ;
duke@435 4542 }
duke@435 4543 }
duke@435 4544 }
duke@435 4545
duke@435 4546 int ObjectMonitor::SimpleExit (Thread * Self) {
duke@435 4547 guarantee (_owner == Self, "invariant") ;
duke@435 4548 OrderAccess::release_store_ptr (&_owner, NULL) ;
duke@435 4549 OrderAccess::fence() ;
duke@435 4550 if (_EntryList == NULL) return OS_OK ;
duke@435 4551 ObjectWaiter * w ;
duke@435 4552
duke@435 4553 RawMonitor_lock->lock_without_safepoint_check() ;
duke@435 4554 w = _EntryList ;
duke@435 4555 if (w != NULL) {
duke@435 4556 _EntryList = w->_next ;
duke@435 4557 }
duke@435 4558 RawMonitor_lock->unlock() ;
duke@435 4559 if (w != NULL) {
duke@435 4560 guarantee (w ->TState == ObjectWaiter::TS_ENTER, "invariant") ;
duke@435 4561 ParkEvent * ev = w->_event ;
duke@435 4562 w->TState = ObjectWaiter::TS_RUN ;
duke@435 4563 OrderAccess::fence() ;
duke@435 4564 ev->unpark() ;
duke@435 4565 }
duke@435 4566 return OS_OK ;
duke@435 4567 }
duke@435 4568
duke@435 4569 int ObjectMonitor::SimpleWait (Thread * Self, jlong millis) {
duke@435 4570 guarantee (_owner == Self , "invariant") ;
duke@435 4571 guarantee (_recursions == 0, "invariant") ;
duke@435 4572
duke@435 4573 ObjectWaiter Node (Self) ;
duke@435 4574 Node._notified = 0 ;
duke@435 4575 Node.TState = ObjectWaiter::TS_WAIT ;
duke@435 4576
duke@435 4577 RawMonitor_lock->lock_without_safepoint_check() ;
duke@435 4578 Node._next = _WaitSet ;
duke@435 4579 _WaitSet = &Node ;
duke@435 4580 RawMonitor_lock->unlock() ;
duke@435 4581
duke@435 4582 SimpleExit (Self) ;
duke@435 4583 guarantee (_owner != Self, "invariant") ;
duke@435 4584
duke@435 4585 int ret = OS_OK ;
duke@435 4586 if (millis <= 0) {
duke@435 4587 Self->_ParkEvent->park();
duke@435 4588 } else {
duke@435 4589 ret = Self->_ParkEvent->park(millis);
duke@435 4590 }
duke@435 4591
duke@435 4592 // If thread still resides on the waitset then unlink it.
duke@435 4593 // Double-checked locking -- the usage is safe in this context
duke@435 4594 // as we TState is volatile and the lock-unlock operators are
duke@435 4595 // serializing (barrier-equivalent).
duke@435 4596
duke@435 4597 if (Node.TState == ObjectWaiter::TS_WAIT) {
duke@435 4598 RawMonitor_lock->lock_without_safepoint_check() ;
duke@435 4599 if (Node.TState == ObjectWaiter::TS_WAIT) {
duke@435 4600 // Simple O(n) unlink, but performance isn't critical here.
duke@435 4601 ObjectWaiter * p ;
duke@435 4602 ObjectWaiter * q = NULL ;
duke@435 4603 for (p = _WaitSet ; p != &Node; p = p->_next) {
duke@435 4604 q = p ;
duke@435 4605 }
duke@435 4606 guarantee (p == &Node, "invariant") ;
duke@435 4607 if (q == NULL) {
duke@435 4608 guarantee (p == _WaitSet, "invariant") ;
duke@435 4609 _WaitSet = p->_next ;
duke@435 4610 } else {
duke@435 4611 guarantee (p == q->_next, "invariant") ;
duke@435 4612 q->_next = p->_next ;
duke@435 4613 }
duke@435 4614 Node.TState = ObjectWaiter::TS_RUN ;
duke@435 4615 }
duke@435 4616 RawMonitor_lock->unlock() ;
duke@435 4617 }
duke@435 4618
duke@435 4619 guarantee (Node.TState == ObjectWaiter::TS_RUN, "invariant") ;
duke@435 4620 SimpleEnter (Self) ;
duke@435 4621
duke@435 4622 guarantee (_owner == Self, "invariant") ;
duke@435 4623 guarantee (_recursions == 0, "invariant") ;
duke@435 4624 return ret ;
duke@435 4625 }
duke@435 4626
duke@435 4627 int ObjectMonitor::SimpleNotify (Thread * Self, bool All) {
duke@435 4628 guarantee (_owner == Self, "invariant") ;
duke@435 4629 if (_WaitSet == NULL) return OS_OK ;
duke@435 4630
duke@435 4631 // We have two options:
duke@435 4632 // A. Transfer the threads from the WaitSet to the EntryList
duke@435 4633 // B. Remove the thread from the WaitSet and unpark() it.
duke@435 4634 //
duke@435 4635 // We use (B), which is crude and results in lots of futile
duke@435 4636 // context switching. In particular (B) induces lots of contention.
duke@435 4637
duke@435 4638 ParkEvent * ev = NULL ; // consider using a small auto array ...
duke@435 4639 RawMonitor_lock->lock_without_safepoint_check() ;
duke@435 4640 for (;;) {
duke@435 4641 ObjectWaiter * w = _WaitSet ;
duke@435 4642 if (w == NULL) break ;
duke@435 4643 _WaitSet = w->_next ;
duke@435 4644 if (ev != NULL) { ev->unpark(); ev = NULL; }
duke@435 4645 ev = w->_event ;
duke@435 4646 OrderAccess::loadstore() ;
duke@435 4647 w->TState = ObjectWaiter::TS_RUN ;
duke@435 4648 OrderAccess::storeload();
duke@435 4649 if (!All) break ;
duke@435 4650 }
duke@435 4651 RawMonitor_lock->unlock() ;
duke@435 4652 if (ev != NULL) ev->unpark();
duke@435 4653 return OS_OK ;
duke@435 4654 }
duke@435 4655
duke@435 4656 // Any JavaThread will enter here with state _thread_blocked
duke@435 4657 int ObjectMonitor::raw_enter(TRAPS) {
duke@435 4658 TEVENT (raw_enter) ;
duke@435 4659 void * Contended ;
duke@435 4660
duke@435 4661 // don't enter raw monitor if thread is being externally suspended, it will
duke@435 4662 // surprise the suspender if a "suspended" thread can still enter monitor
duke@435 4663 JavaThread * jt = (JavaThread *)THREAD;
duke@435 4664 if (THREAD->is_Java_thread()) {
duke@435 4665 jt->SR_lock()->lock_without_safepoint_check();
duke@435 4666 while (jt->is_external_suspend()) {
duke@435 4667 jt->SR_lock()->unlock();
duke@435 4668 jt->java_suspend_self();
duke@435 4669 jt->SR_lock()->lock_without_safepoint_check();
duke@435 4670 }
duke@435 4671 // guarded by SR_lock to avoid racing with new external suspend requests.
duke@435 4672 Contended = Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) ;
duke@435 4673 jt->SR_lock()->unlock();
duke@435 4674 } else {
duke@435 4675 Contended = Atomic::cmpxchg_ptr (THREAD, &_owner, NULL) ;
duke@435 4676 }
duke@435 4677
duke@435 4678 if (Contended == THREAD) {
duke@435 4679 _recursions ++ ;
duke@435 4680 return OM_OK ;
duke@435 4681 }
duke@435 4682
duke@435 4683 if (Contended == NULL) {
duke@435 4684 guarantee (_owner == THREAD, "invariant") ;
duke@435 4685 guarantee (_recursions == 0, "invariant") ;
duke@435 4686 return OM_OK ;
duke@435 4687 }
duke@435 4688
duke@435 4689 THREAD->set_current_pending_monitor(this);
duke@435 4690
duke@435 4691 if (!THREAD->is_Java_thread()) {
duke@435 4692 // No other non-Java threads besides VM thread would acquire
duke@435 4693 // a raw monitor.
duke@435 4694 assert(THREAD->is_VM_thread(), "must be VM thread");
duke@435 4695 SimpleEnter (THREAD) ;
duke@435 4696 } else {
duke@435 4697 guarantee (jt->thread_state() == _thread_blocked, "invariant") ;
duke@435 4698 for (;;) {
duke@435 4699 jt->set_suspend_equivalent();
duke@435 4700 // cleared by handle_special_suspend_equivalent_condition() or
duke@435 4701 // java_suspend_self()
duke@435 4702 SimpleEnter (THREAD) ;
duke@435 4703
duke@435 4704 // were we externally suspended while we were waiting?
duke@435 4705 if (!jt->handle_special_suspend_equivalent_condition()) break ;
duke@435 4706
duke@435 4707 // This thread was externally suspended
duke@435 4708 //
duke@435 4709 // This logic isn't needed for JVMTI raw monitors,
duke@435 4710 // but doesn't hurt just in case the suspend rules change. This
duke@435 4711 // logic is needed for the ObjectMonitor.wait() reentry phase.
duke@435 4712 // We have reentered the contended monitor, but while we were
duke@435 4713 // waiting another thread suspended us. We don't want to reenter
duke@435 4714 // the monitor while suspended because that would surprise the
duke@435 4715 // thread that suspended us.
duke@435 4716 //
duke@435 4717 // Drop the lock -
duke@435 4718 SimpleExit (THREAD) ;
duke@435 4719
duke@435 4720 jt->java_suspend_self();
duke@435 4721 }
duke@435 4722
duke@435 4723 assert(_owner == THREAD, "Fatal error with monitor owner!");
duke@435 4724 assert(_recursions == 0, "Fatal error with monitor recursions!");
duke@435 4725 }
duke@435 4726
duke@435 4727 THREAD->set_current_pending_monitor(NULL);
duke@435 4728 guarantee (_recursions == 0, "invariant") ;
duke@435 4729 return OM_OK;
duke@435 4730 }
duke@435 4731
duke@435 4732 // Used mainly for JVMTI raw monitor implementation
duke@435 4733 // Also used for ObjectMonitor::wait().
duke@435 4734 int ObjectMonitor::raw_exit(TRAPS) {
duke@435 4735 TEVENT (raw_exit) ;
duke@435 4736 if (THREAD != _owner) {
duke@435 4737 return OM_ILLEGAL_MONITOR_STATE;
duke@435 4738 }
duke@435 4739 if (_recursions > 0) {
duke@435 4740 --_recursions ;
duke@435 4741 return OM_OK ;
duke@435 4742 }
duke@435 4743
duke@435 4744 void * List = _EntryList ;
duke@435 4745 SimpleExit (THREAD) ;
duke@435 4746
duke@435 4747 return OM_OK;
duke@435 4748 }
duke@435 4749
duke@435 4750 // Used for JVMTI raw monitor implementation.
duke@435 4751 // All JavaThreads will enter here with state _thread_blocked
duke@435 4752
duke@435 4753 int ObjectMonitor::raw_wait(jlong millis, bool interruptible, TRAPS) {
duke@435 4754 TEVENT (raw_wait) ;
duke@435 4755 if (THREAD != _owner) {
duke@435 4756 return OM_ILLEGAL_MONITOR_STATE;
duke@435 4757 }
duke@435 4758
duke@435 4759 // To avoid spurious wakeups we reset the parkevent -- This is strictly optional.
duke@435 4760 // The caller must be able to tolerate spurious returns from raw_wait().
duke@435 4761 THREAD->_ParkEvent->reset() ;
duke@435 4762 OrderAccess::fence() ;
duke@435 4763
duke@435 4764 // check interrupt event
duke@435 4765 if (interruptible && Thread::is_interrupted(THREAD, true)) {
duke@435 4766 return OM_INTERRUPTED;
duke@435 4767 }
duke@435 4768
duke@435 4769 intptr_t save = _recursions ;
duke@435 4770 _recursions = 0 ;
duke@435 4771 _waiters ++ ;
duke@435 4772 if (THREAD->is_Java_thread()) {
duke@435 4773 guarantee (((JavaThread *) THREAD)->thread_state() == _thread_blocked, "invariant") ;
duke@435 4774 ((JavaThread *)THREAD)->set_suspend_equivalent();
duke@435 4775 }
duke@435 4776 int rv = SimpleWait (THREAD, millis) ;
duke@435 4777 _recursions = save ;
duke@435 4778 _waiters -- ;
duke@435 4779
duke@435 4780 guarantee (THREAD == _owner, "invariant") ;
duke@435 4781 if (THREAD->is_Java_thread()) {
duke@435 4782 JavaThread * jSelf = (JavaThread *) THREAD ;
duke@435 4783 for (;;) {
duke@435 4784 if (!jSelf->handle_special_suspend_equivalent_condition()) break ;
duke@435 4785 SimpleExit (THREAD) ;
duke@435 4786 jSelf->java_suspend_self();
duke@435 4787 SimpleEnter (THREAD) ;
duke@435 4788 jSelf->set_suspend_equivalent() ;
duke@435 4789 }
duke@435 4790 }
duke@435 4791 guarantee (THREAD == _owner, "invariant") ;
duke@435 4792
duke@435 4793 if (interruptible && Thread::is_interrupted(THREAD, true)) {
duke@435 4794 return OM_INTERRUPTED;
duke@435 4795 }
duke@435 4796 return OM_OK ;
duke@435 4797 }
duke@435 4798
duke@435 4799 int ObjectMonitor::raw_notify(TRAPS) {
duke@435 4800 TEVENT (raw_notify) ;
duke@435 4801 if (THREAD != _owner) {
duke@435 4802 return OM_ILLEGAL_MONITOR_STATE;
duke@435 4803 }
duke@435 4804 SimpleNotify (THREAD, false) ;
duke@435 4805 return OM_OK;
duke@435 4806 }
duke@435 4807
duke@435 4808 int ObjectMonitor::raw_notifyAll(TRAPS) {
duke@435 4809 TEVENT (raw_notifyAll) ;
duke@435 4810 if (THREAD != _owner) {
duke@435 4811 return OM_ILLEGAL_MONITOR_STATE;
duke@435 4812 }
duke@435 4813 SimpleNotify (THREAD, true) ;
duke@435 4814 return OM_OK;
duke@435 4815 }
duke@435 4816
duke@435 4817 #ifndef PRODUCT
duke@435 4818 void ObjectMonitor::verify() {
duke@435 4819 }
duke@435 4820
duke@435 4821 void ObjectMonitor::print() {
duke@435 4822 }
duke@435 4823 #endif
duke@435 4824
duke@435 4825 //------------------------------------------------------------------------------
duke@435 4826 // Non-product code
duke@435 4827
duke@435 4828 #ifndef PRODUCT
duke@435 4829
duke@435 4830 void ObjectSynchronizer::trace_locking(Handle locking_obj, bool is_compiled,
duke@435 4831 bool is_method, bool is_locking) {
duke@435 4832 // Don't know what to do here
duke@435 4833 }
duke@435 4834
duke@435 4835 // Verify all monitors in the monitor cache, the verification is weak.
duke@435 4836 void ObjectSynchronizer::verify() {
duke@435 4837 ObjectMonitor* block = gBlockList;
duke@435 4838 ObjectMonitor* mid;
duke@435 4839 while (block) {
duke@435 4840 assert(block->object() == CHAINMARKER, "must be a block header");
duke@435 4841 for (int i = 1; i < _BLOCKSIZE; i++) {
duke@435 4842 mid = block + i;
duke@435 4843 oop object = (oop) mid->object();
duke@435 4844 if (object != NULL) {
duke@435 4845 mid->verify();
duke@435 4846 }
duke@435 4847 }
duke@435 4848 block = (ObjectMonitor*) block->FreeNext;
duke@435 4849 }
duke@435 4850 }
duke@435 4851
duke@435 4852 // Check if monitor belongs to the monitor cache
duke@435 4853 // The list is grow-only so it's *relatively* safe to traverse
duke@435 4854 // the list of extant blocks without taking a lock.
duke@435 4855
duke@435 4856 int ObjectSynchronizer::verify_objmon_isinpool(ObjectMonitor *monitor) {
duke@435 4857 ObjectMonitor* block = gBlockList;
duke@435 4858
duke@435 4859 while (block) {
duke@435 4860 assert(block->object() == CHAINMARKER, "must be a block header");
duke@435 4861 if (monitor > &block[0] && monitor < &block[_BLOCKSIZE]) {
duke@435 4862 address mon = (address) monitor;
duke@435 4863 address blk = (address) block;
duke@435 4864 size_t diff = mon - blk;
duke@435 4865 assert((diff % sizeof(ObjectMonitor)) == 0, "check");
duke@435 4866 return 1;
duke@435 4867 }
duke@435 4868 block = (ObjectMonitor*) block->FreeNext;
duke@435 4869 }
duke@435 4870 return 0;
duke@435 4871 }
duke@435 4872
duke@435 4873 #endif

mercurial