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