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