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/padded.hpp" 28 #include "memory/resourceArea.hpp" 29 #include "oops/markOop.hpp" 30 #include "oops/oop.inline.hpp" 31 #include "runtime/atomic.inline.hpp" 32 #include "runtime/biasedLocking.hpp" 33 #include "runtime/handles.inline.hpp" 34 #include "runtime/interfaceSupport.hpp" 35 #include "runtime/mutexLocker.hpp" 36 #include "runtime/objectMonitor.hpp" 37 #include "runtime/objectMonitor.inline.hpp" 38 #include "runtime/osThread.hpp" 39 #include "runtime/stubRoutines.hpp" 40 #include "runtime/synchronizer.hpp" 41 #include "runtime/thread.inline.hpp" 42 #include "utilities/dtrace.hpp" 43 #include "utilities/events.hpp" 44 #include "utilities/preserveException.hpp" 45 46 #if defined(__GNUC__) && !defined(PPC64) 47 // Need to inhibit inlining for older versions of GCC to avoid build-time failures 48 #define NOINLINE __attribute__((noinline)) 49 #else 50 #define NOINLINE 51 #endif 52 53 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC 54 55 // The "core" versions of monitor enter and exit reside in this file. 56 // The interpreter and compilers contain specialized transliterated 57 // variants of the enter-exit fast-path operations. See i486.ad fast_lock(), 58 // for instance. If you make changes here, make sure to modify the 59 // interpreter, and both C1 and C2 fast-path inline locking code emission. 60 // 61 // ----------------------------------------------------------------------------- 62 63 #ifdef DTRACE_ENABLED 64 65 // Only bother with this argument setup if dtrace is available 66 // TODO-FIXME: probes should not fire when caller is _blocked. assert() accordingly. 67 68 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread) \ 69 char* bytes = NULL; \ 70 int len = 0; \ 71 jlong jtid = SharedRuntime::get_java_tid(thread); \ 72 Symbol* klassname = ((oop)(obj))->klass()->name(); \ 73 if (klassname != NULL) { \ 74 bytes = (char*)klassname->bytes(); \ 75 len = klassname->utf8_length(); \ 76 } 77 78 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis) \ 79 { \ 80 if (DTraceMonitorProbes) { \ 81 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \ 82 HOTSPOT_MONITOR_WAIT(jtid, \ 83 (uintptr_t)(monitor), bytes, len, (millis)); \ 84 } \ 85 } 86 87 #define HOTSPOT_MONITOR_PROBE_waited HOTSPOT_MONITOR_WAITED 88 89 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread) \ 90 { \ 91 if (DTraceMonitorProbes) { \ 92 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \ 93 HOTSPOT_MONITOR_PROBE_##probe(jtid, /* probe = waited */ \ 94 (uintptr_t)(monitor), bytes, len); \ 95 } \ 96 } 97 98 #else // ndef DTRACE_ENABLED 99 100 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon) {;} 101 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon) {;} 102 103 #endif // ndef DTRACE_ENABLED 104 105 // This exists only as a workaround of dtrace bug 6254741 106 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) { 107 DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr); 108 return 0; 109 } 110 111 #define NINFLATIONLOCKS 256 112 static volatile intptr_t gInflationLocks[NINFLATIONLOCKS]; 113 114 // global list of blocks of monitors 115 // gBlockList is really PaddedEnd<ObjectMonitor> *, but we don't 116 // want to expose the PaddedEnd template more than necessary. 117 ObjectMonitor * ObjectSynchronizer::gBlockList = NULL; 118 // global monitor free list 119 ObjectMonitor * volatile ObjectSynchronizer::gFreeList = NULL; 120 // global monitor in-use list, for moribund threads, 121 // monitors they inflated need to be scanned for deflation 122 ObjectMonitor * volatile ObjectSynchronizer::gOmInUseList = NULL; 123 // count of entries in gOmInUseList 124 int ObjectSynchronizer::gOmInUseCount = 0; 125 126 static volatile intptr_t gListLock = 0; // protects global monitor lists 127 static volatile int gMonitorFreeCount = 0; // # on gFreeList 128 static volatile int gMonitorPopulation = 0; // # Extant -- in circulation 129 130 #define CHAINMARKER (cast_to_oop<intptr_t>(-1)) 131 132 133 // =====================> Quick functions 134 135 // The quick_* forms are special fast-path variants used to improve 136 // performance. In the simplest case, a "quick_*" implementation could 137 // simply return false, in which case the caller will perform the necessary 138 // state transitions and call the slow-path form. 139 // The fast-path is designed to handle frequently arising cases in an efficient 140 // manner and is just a degenerate "optimistic" variant of the slow-path. 141 // returns true -- to indicate the call was satisfied. 142 // returns false -- to indicate the call needs the services of the slow-path. 143 // A no-loitering ordinance is in effect for code in the quick_* family 144 // operators: safepoints or indefinite blocking (blocking that might span a 145 // safepoint) are forbidden. Generally the thread_state() is _in_Java upon 146 // entry. 147 148 // The LockNode emitted directly at the synchronization site would have 149 // been too big if it were to have included support for the cases of inflated 150 // recursive enter and exit, so they go here instead. 151 // Note that we can't safely call AsyncPrintJavaStack() from within 152 // quick_enter() as our thread state remains _in_Java. 153 154 bool ObjectSynchronizer::quick_enter(oop obj, Thread * Self, 155 BasicLock * Lock) { 156 assert(!SafepointSynchronize::is_at_safepoint(), "invariant"); 157 assert(Self->is_Java_thread(), "invariant"); 158 assert(((JavaThread *) Self)->thread_state() == _thread_in_Java, "invariant"); 159 No_Safepoint_Verifier nsv; 160 if (obj == NULL) return false; // Need to throw NPE 161 const markOop mark = obj->mark(); 162 163 if (mark->has_monitor()) { 164 ObjectMonitor * const m = mark->monitor(); 165 assert(m->object() == obj, "invariant"); 166 Thread * const owner = (Thread *) m->_owner; 167 168 // Lock contention and Transactional Lock Elision (TLE) diagnostics 169 // and observability 170 // Case: light contention possibly amenable to TLE 171 // Case: TLE inimical operations such as nested/recursive synchronization 172 173 if (owner == Self) { 174 m->_recursions++; 175 return true; 176 } 177 178 if (owner == NULL && 179 Atomic::cmpxchg_ptr(Self, &(m->_owner), NULL) == NULL) { 180 assert(m->_recursions == 0, "invariant"); 181 assert(m->_owner == Self, "invariant"); 182 return true; 183 } 184 } 185 186 // Note that we could inflate in quick_enter. 187 // This is likely a useful optimization 188 // Critically, in quick_enter() we must not: 189 // -- perform bias revocation, or 190 // -- block indefinitely, or 191 // -- reach a safepoint 192 193 return false; // revert to slow-path 194 } 195 196 // ----------------------------------------------------------------------------- 197 // Fast Monitor Enter/Exit 198 // This the fast monitor enter. The interpreter and compiler use 199 // some assembly copies of this code. Make sure update those code 200 // if the following function is changed. The implementation is 201 // extremely sensitive to race condition. Be careful. 202 203 void ObjectSynchronizer::fast_enter(Handle obj, BasicLock* lock, 204 bool attempt_rebias, TRAPS) { 205 if (UseBiasedLocking) { 206 if (!SafepointSynchronize::is_at_safepoint()) { 207 BiasedLocking::Condition cond = BiasedLocking::revoke_and_rebias(obj, attempt_rebias, THREAD); 208 if (cond == BiasedLocking::BIAS_REVOKED_AND_REBIASED) { 209 return; 210 } 211 } else { 212 assert(!attempt_rebias, "can not rebias toward VM thread"); 213 BiasedLocking::revoke_at_safepoint(obj); 214 } 215 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 216 } 217 218 slow_enter(obj, lock, THREAD); 219 } 220 221 void ObjectSynchronizer::fast_exit(oop object, BasicLock* lock, TRAPS) { 222 assert(!object->mark()->has_bias_pattern(), "should not see bias pattern here"); 223 // if displaced header is null, the previous enter is recursive enter, no-op 224 markOop dhw = lock->displaced_header(); 225 markOop mark; 226 if (dhw == NULL) { 227 // Recursive stack-lock. 228 // Diagnostics -- Could be: stack-locked, inflating, inflated. 229 mark = object->mark(); 230 assert(!mark->is_neutral(), "invariant"); 231 if (mark->has_locker() && mark != markOopDesc::INFLATING()) { 232 assert(THREAD->is_lock_owned((address)mark->locker()), "invariant"); 233 } 234 if (mark->has_monitor()) { 235 ObjectMonitor * m = mark->monitor(); 236 assert(((oop)(m->object()))->mark() == mark, "invariant"); 237 assert(m->is_entered(THREAD), "invariant"); 238 } 239 return; 240 } 241 242 mark = object->mark(); 243 244 // If the object is stack-locked by the current thread, try to 245 // swing the displaced header from the box back to the mark. 246 if (mark == (markOop) lock) { 247 assert(dhw->is_neutral(), "invariant"); 248 if ((markOop) Atomic::cmpxchg_ptr (dhw, object->mark_addr(), mark) == mark) { 249 TEVENT(fast_exit: release stacklock); 250 return; 251 } 252 } 253 254 ObjectSynchronizer::inflate(THREAD, object)->exit(true, THREAD); 255 } 256 257 // ----------------------------------------------------------------------------- 258 // Interpreter/Compiler Slow Case 259 // This routine is used to handle interpreter/compiler slow case 260 // We don't need to use fast path here, because it must have been 261 // failed in the interpreter/compiler code. 262 void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) { 263 markOop mark = obj->mark(); 264 assert(!mark->has_bias_pattern(), "should not see bias pattern here"); 265 266 if (mark->is_neutral()) { 267 // Anticipate successful CAS -- the ST of the displaced mark must 268 // be visible <= the ST performed by the CAS. 269 lock->set_displaced_header(mark); 270 if (mark == (markOop) Atomic::cmpxchg_ptr(lock, obj()->mark_addr(), mark)) { 271 TEVENT(slow_enter: release stacklock); 272 return; 273 } 274 // Fall through to inflate() ... 275 } else if (mark->has_locker() && 276 THREAD->is_lock_owned((address)mark->locker())) { 277 assert(lock != mark->locker(), "must not re-lock the same lock"); 278 assert(lock != (BasicLock*)obj->mark(), "don't relock with same BasicLock"); 279 lock->set_displaced_header(NULL); 280 return; 281 } 282 283 // The object header will never be displaced to this lock, 284 // so it does not matter what the value is, except that it 285 // must be non-zero to avoid looking like a re-entrant lock, 286 // and must not look locked either. 287 lock->set_displaced_header(markOopDesc::unused_mark()); 288 ObjectSynchronizer::inflate(THREAD, obj())->enter(THREAD); 289 } 290 291 // This routine is used to handle interpreter/compiler slow case 292 // We don't need to use fast path here, because it must have 293 // failed in the interpreter/compiler code. Simply use the heavy 294 // weight monitor should be ok, unless someone find otherwise. 295 void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) { 296 fast_exit(object, lock, THREAD); 297 } 298 299 // ----------------------------------------------------------------------------- 300 // Class Loader support to workaround deadlocks on the class loader lock objects 301 // Also used by GC 302 // complete_exit()/reenter() are used to wait on a nested lock 303 // i.e. to give up an outer lock completely and then re-enter 304 // Used when holding nested locks - lock acquisition order: lock1 then lock2 305 // 1) complete_exit lock1 - saving recursion count 306 // 2) wait on lock2 307 // 3) when notified on lock2, unlock lock2 308 // 4) reenter lock1 with original recursion count 309 // 5) lock lock2 310 // NOTE: must use heavy weight monitor to handle complete_exit/reenter() 311 intptr_t ObjectSynchronizer::complete_exit(Handle obj, TRAPS) { 312 TEVENT(complete_exit); 313 if (UseBiasedLocking) { 314 BiasedLocking::revoke_and_rebias(obj, false, THREAD); 315 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 316 } 317 318 ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj()); 319 320 return monitor->complete_exit(THREAD); 321 } 322 323 // NOTE: must use heavy weight monitor to handle complete_exit/reenter() 324 void ObjectSynchronizer::reenter(Handle obj, intptr_t recursion, TRAPS) { 325 TEVENT(reenter); 326 if (UseBiasedLocking) { 327 BiasedLocking::revoke_and_rebias(obj, false, THREAD); 328 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 329 } 330 331 ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj()); 332 333 monitor->reenter(recursion, THREAD); 334 } 335 // ----------------------------------------------------------------------------- 336 // JNI locks on java objects 337 // NOTE: must use heavy weight monitor to handle jni monitor enter 338 void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) { 339 // the current locking is from JNI instead of Java code 340 TEVENT(jni_enter); 341 if (UseBiasedLocking) { 342 BiasedLocking::revoke_and_rebias(obj, false, THREAD); 343 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 344 } 345 THREAD->set_current_pending_monitor_is_from_java(false); 346 ObjectSynchronizer::inflate(THREAD, obj())->enter(THREAD); 347 THREAD->set_current_pending_monitor_is_from_java(true); 348 } 349 350 // NOTE: must use heavy weight monitor to handle jni monitor exit 351 void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) { 352 TEVENT(jni_exit); 353 if (UseBiasedLocking) { 354 Handle h_obj(THREAD, obj); 355 BiasedLocking::revoke_and_rebias(h_obj, false, THREAD); 356 obj = h_obj(); 357 } 358 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 359 360 ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj); 361 // If this thread has locked the object, exit the monitor. Note: can't use 362 // monitor->check(CHECK); must exit even if an exception is pending. 363 if (monitor->check(THREAD)) { 364 monitor->exit(true, THREAD); 365 } 366 } 367 368 // ----------------------------------------------------------------------------- 369 // Internal VM locks on java objects 370 // standard constructor, allows locking failures 371 ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool doLock) { 372 _dolock = doLock; 373 _thread = thread; 374 debug_only(if (StrictSafepointChecks) _thread->check_for_valid_safepoint_state(false);) 375 _obj = obj; 376 377 if (_dolock) { 378 TEVENT(ObjectLocker); 379 380 ObjectSynchronizer::fast_enter(_obj, &_lock, false, _thread); 381 } 382 } 383 384 ObjectLocker::~ObjectLocker() { 385 if (_dolock) { 386 ObjectSynchronizer::fast_exit(_obj(), &_lock, _thread); 387 } 388 } 389 390 391 // ----------------------------------------------------------------------------- 392 // Wait/Notify/NotifyAll 393 // NOTE: must use heavy weight monitor to handle wait() 394 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) { 395 if (UseBiasedLocking) { 396 BiasedLocking::revoke_and_rebias(obj, false, THREAD); 397 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 398 } 399 if (millis < 0) { 400 TEVENT(wait - throw IAX); 401 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative"); 402 } 403 ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj()); 404 DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis); 405 monitor->wait(millis, true, THREAD); 406 407 // This dummy call is in place to get around dtrace bug 6254741. Once 408 // that's fixed we can uncomment the following line, remove the call 409 // and change this function back into a "void" func. 410 // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD); 411 return dtrace_waited_probe(monitor, obj, THREAD); 412 } 413 414 void ObjectSynchronizer::waitUninterruptibly(Handle obj, jlong millis, TRAPS) { 415 if (UseBiasedLocking) { 416 BiasedLocking::revoke_and_rebias(obj, false, THREAD); 417 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 418 } 419 if (millis < 0) { 420 TEVENT(wait - throw IAX); 421 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative"); 422 } 423 ObjectSynchronizer::inflate(THREAD, obj()) -> wait(millis, false, THREAD); 424 } 425 426 void ObjectSynchronizer::notify(Handle obj, TRAPS) { 427 if (UseBiasedLocking) { 428 BiasedLocking::revoke_and_rebias(obj, false, THREAD); 429 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 430 } 431 432 markOop mark = obj->mark(); 433 if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) { 434 return; 435 } 436 ObjectSynchronizer::inflate(THREAD, obj())->notify(THREAD); 437 } 438 439 // NOTE: see comment of notify() 440 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) { 441 if (UseBiasedLocking) { 442 BiasedLocking::revoke_and_rebias(obj, false, THREAD); 443 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 444 } 445 446 markOop mark = obj->mark(); 447 if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) { 448 return; 449 } 450 ObjectSynchronizer::inflate(THREAD, obj())->notifyAll(THREAD); 451 } 452 453 // ----------------------------------------------------------------------------- 454 // Hash Code handling 455 // 456 // Performance concern: 457 // OrderAccess::storestore() calls release() which at one time stored 0 458 // into the global volatile OrderAccess::dummy variable. This store was 459 // unnecessary for correctness. Many threads storing into a common location 460 // causes considerable cache migration or "sloshing" on large SMP systems. 461 // As such, I avoided using OrderAccess::storestore(). In some cases 462 // OrderAccess::fence() -- which incurs local latency on the executing 463 // processor -- is a better choice as it scales on SMP systems. 464 // 465 // See http://blogs.oracle.com/dave/entry/biased_locking_in_hotspot for 466 // a discussion of coherency costs. Note that all our current reference 467 // platforms provide strong ST-ST order, so the issue is moot on IA32, 468 // x64, and SPARC. 469 // 470 // As a general policy we use "volatile" to control compiler-based reordering 471 // and explicit fences (barriers) to control for architectural reordering 472 // performed by the CPU(s) or platform. 473 474 struct SharedGlobals { 475 char _pad_prefix[DEFAULT_CACHE_LINE_SIZE]; 476 // These are highly shared mostly-read variables. 477 // To avoid false-sharing they need to be the sole occupants of a cache line. 478 volatile int stwRandom; 479 volatile int stwCycle; 480 DEFINE_PAD_MINUS_SIZE(1, DEFAULT_CACHE_LINE_SIZE, sizeof(volatile int) * 2); 481 // Hot RW variable -- Sequester to avoid false-sharing 482 volatile int hcSequence; 483 DEFINE_PAD_MINUS_SIZE(2, DEFAULT_CACHE_LINE_SIZE, sizeof(volatile int)); 484 }; 485 486 static SharedGlobals GVars; 487 static int MonitorScavengeThreshold = 1000000; 488 static volatile int ForceMonitorScavenge = 0; // Scavenge required and pending 489 490 static markOop ReadStableMark(oop obj) { 491 markOop mark = obj->mark(); 492 if (!mark->is_being_inflated()) { 493 return mark; // normal fast-path return 494 } 495 496 int its = 0; 497 for (;;) { 498 markOop mark = obj->mark(); 499 if (!mark->is_being_inflated()) { 500 return mark; // normal fast-path return 501 } 502 503 // The object is being inflated by some other thread. 504 // The caller of ReadStableMark() must wait for inflation to complete. 505 // Avoid live-lock 506 // TODO: consider calling SafepointSynchronize::do_call_back() while 507 // spinning to see if there's a safepoint pending. If so, immediately 508 // yielding or blocking would be appropriate. Avoid spinning while 509 // there is a safepoint pending. 510 // TODO: add inflation contention performance counters. 511 // TODO: restrict the aggregate number of spinners. 512 513 ++its; 514 if (its > 10000 || !os::is_MP()) { 515 if (its & 1) { 516 os::naked_yield(); 517 TEVENT(Inflate: INFLATING - yield); 518 } else { 519 // Note that the following code attenuates the livelock problem but is not 520 // a complete remedy. A more complete solution would require that the inflating 521 // thread hold the associated inflation lock. The following code simply restricts 522 // the number of spinners to at most one. We'll have N-2 threads blocked 523 // on the inflationlock, 1 thread holding the inflation lock and using 524 // a yield/park strategy, and 1 thread in the midst of inflation. 525 // A more refined approach would be to change the encoding of INFLATING 526 // to allow encapsulation of a native thread pointer. Threads waiting for 527 // inflation to complete would use CAS to push themselves onto a singly linked 528 // list rooted at the markword. Once enqueued, they'd loop, checking a per-thread flag 529 // and calling park(). When inflation was complete the thread that accomplished inflation 530 // would detach the list and set the markword to inflated with a single CAS and 531 // then for each thread on the list, set the flag and unpark() the thread. 532 // This is conceptually similar to muxAcquire-muxRelease, except that muxRelease 533 // wakes at most one thread whereas we need to wake the entire list. 534 int ix = (cast_from_oop<intptr_t>(obj) >> 5) & (NINFLATIONLOCKS-1); 535 int YieldThenBlock = 0; 536 assert(ix >= 0 && ix < NINFLATIONLOCKS, "invariant"); 537 assert((NINFLATIONLOCKS & (NINFLATIONLOCKS-1)) == 0, "invariant"); 538 Thread::muxAcquire(gInflationLocks + ix, "gInflationLock"); 539 while (obj->mark() == markOopDesc::INFLATING()) { 540 // Beware: NakedYield() is advisory and has almost no effect on some platforms 541 // so we periodically call Self->_ParkEvent->park(1). 542 // We use a mixed spin/yield/block mechanism. 543 if ((YieldThenBlock++) >= 16) { 544 Thread::current()->_ParkEvent->park(1); 545 } else { 546 os::naked_yield(); 547 } 548 } 549 Thread::muxRelease(gInflationLocks + ix); 550 TEVENT(Inflate: INFLATING - yield/park); 551 } 552 } else { 553 SpinPause(); // SMP-polite spinning 554 } 555 } 556 } 557 558 // hashCode() generation : 559 // 560 // Possibilities: 561 // * MD5Digest of {obj,stwRandom} 562 // * CRC32 of {obj,stwRandom} or any linear-feedback shift register function. 563 // * A DES- or AES-style SBox[] mechanism 564 // * One of the Phi-based schemes, such as: 565 // 2654435761 = 2^32 * Phi (golden ratio) 566 // HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stwRandom ; 567 // * A variation of Marsaglia's shift-xor RNG scheme. 568 // * (obj ^ stwRandom) is appealing, but can result 569 // in undesirable regularity in the hashCode values of adjacent objects 570 // (objects allocated back-to-back, in particular). This could potentially 571 // result in hashtable collisions and reduced hashtable efficiency. 572 // There are simple ways to "diffuse" the middle address bits over the 573 // generated hashCode values: 574 575 static inline intptr_t get_next_hash(Thread * Self, oop obj) { 576 intptr_t value = 0; 577 if (hashCode == 0) { 578 // This form uses an unguarded global Park-Miller RNG, 579 // so it's possible for two threads to race and generate the same RNG. 580 // On MP system we'll have lots of RW access to a global, so the 581 // mechanism induces lots of coherency traffic. 582 value = os::random(); 583 } else if (hashCode == 1) { 584 // This variation has the property of being stable (idempotent) 585 // between STW operations. This can be useful in some of the 1-0 586 // synchronization schemes. 587 intptr_t addrBits = cast_from_oop<intptr_t>(obj) >> 3; 588 value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom; 589 } else if (hashCode == 2) { 590 value = 1; // for sensitivity testing 591 } else if (hashCode == 3) { 592 value = ++GVars.hcSequence; 593 } else if (hashCode == 4) { 594 value = cast_from_oop<intptr_t>(obj); 595 } else { 596 // Marsaglia's xor-shift scheme with thread-specific state 597 // This is probably the best overall implementation -- we'll 598 // likely make this the default in future releases. 599 unsigned t = Self->_hashStateX; 600 t ^= (t << 11); 601 Self->_hashStateX = Self->_hashStateY; 602 Self->_hashStateY = Self->_hashStateZ; 603 Self->_hashStateZ = Self->_hashStateW; 604 unsigned v = Self->_hashStateW; 605 v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)); 606 Self->_hashStateW = v; 607 value = v; 608 } 609 610 value &= markOopDesc::hash_mask; 611 if (value == 0) value = 0xBAD; 612 assert(value != markOopDesc::no_hash, "invariant"); 613 TEVENT(hashCode: GENERATE); 614 return value; 615 } 616 617 intptr_t ObjectSynchronizer::FastHashCode(Thread * Self, oop obj) { 618 if (UseBiasedLocking) { 619 // NOTE: many places throughout the JVM do not expect a safepoint 620 // to be taken here, in particular most operations on perm gen 621 // objects. However, we only ever bias Java instances and all of 622 // the call sites of identity_hash that might revoke biases have 623 // been checked to make sure they can handle a safepoint. The 624 // added check of the bias pattern is to avoid useless calls to 625 // thread-local storage. 626 if (obj->mark()->has_bias_pattern()) { 627 // Handle for oop obj in case of STW safepoint 628 Handle hobj(Self, obj); 629 // Relaxing assertion for bug 6320749. 630 assert(Universe::verify_in_progress() || 631 !SafepointSynchronize::is_at_safepoint(), 632 "biases should not be seen by VM thread here"); 633 BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current()); 634 obj = hobj(); 635 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 636 } 637 } 638 639 // hashCode() is a heap mutator ... 640 // Relaxing assertion for bug 6320749. 641 assert(Universe::verify_in_progress() || 642 !SafepointSynchronize::is_at_safepoint(), "invariant"); 643 assert(Universe::verify_in_progress() || 644 Self->is_Java_thread() , "invariant"); 645 assert(Universe::verify_in_progress() || 646 ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant"); 647 648 ObjectMonitor* monitor = NULL; 649 markOop temp, test; 650 intptr_t hash; 651 markOop mark = ReadStableMark(obj); 652 653 // object should remain ineligible for biased locking 654 assert(!mark->has_bias_pattern(), "invariant"); 655 656 if (mark->is_neutral()) { 657 hash = mark->hash(); // this is a normal header 658 if (hash) { // if it has hash, just return it 659 return hash; 660 } 661 hash = get_next_hash(Self, obj); // allocate a new hash code 662 temp = mark->copy_set_hash(hash); // merge the hash code into header 663 // use (machine word version) atomic operation to install the hash 664 test = (markOop) Atomic::cmpxchg_ptr(temp, obj->mark_addr(), mark); 665 if (test == mark) { 666 return hash; 667 } 668 // If atomic operation failed, we must inflate the header 669 // into heavy weight monitor. We could add more code here 670 // for fast path, but it does not worth the complexity. 671 } else if (mark->has_monitor()) { 672 monitor = mark->monitor(); 673 temp = monitor->header(); 674 assert(temp->is_neutral(), "invariant"); 675 hash = temp->hash(); 676 if (hash) { 677 return hash; 678 } 679 // Skip to the following code to reduce code size 680 } else if (Self->is_lock_owned((address)mark->locker())) { 681 temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned 682 assert(temp->is_neutral(), "invariant"); 683 hash = temp->hash(); // by current thread, check if the displaced 684 if (hash) { // header contains hash code 685 return hash; 686 } 687 // WARNING: 688 // The displaced header is strictly immutable. 689 // It can NOT be changed in ANY cases. So we have 690 // to inflate the header into heavyweight monitor 691 // even the current thread owns the lock. The reason 692 // is the BasicLock (stack slot) will be asynchronously 693 // read by other threads during the inflate() function. 694 // Any change to stack may not propagate to other threads 695 // correctly. 696 } 697 698 // Inflate the monitor to set hash code 699 monitor = ObjectSynchronizer::inflate(Self, obj); 700 // Load displaced header and check it has hash code 701 mark = monitor->header(); 702 assert(mark->is_neutral(), "invariant"); 703 hash = mark->hash(); 704 if (hash == 0) { 705 hash = get_next_hash(Self, obj); 706 temp = mark->copy_set_hash(hash); // merge hash code into header 707 assert(temp->is_neutral(), "invariant"); 708 test = (markOop) Atomic::cmpxchg_ptr(temp, monitor, mark); 709 if (test != mark) { 710 // The only update to the header in the monitor (outside GC) 711 // is install the hash code. If someone add new usage of 712 // displaced header, please update this code 713 hash = test->hash(); 714 assert(test->is_neutral(), "invariant"); 715 assert(hash != 0, "Trivial unexpected object/monitor header usage."); 716 } 717 } 718 // We finally get the hash 719 return hash; 720 } 721 722 // Deprecated -- use FastHashCode() instead. 723 724 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) { 725 return FastHashCode(Thread::current(), obj()); 726 } 727 728 729 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread, 730 Handle h_obj) { 731 if (UseBiasedLocking) { 732 BiasedLocking::revoke_and_rebias(h_obj, false, thread); 733 assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 734 } 735 736 assert(thread == JavaThread::current(), "Can only be called on current thread"); 737 oop obj = h_obj(); 738 739 markOop mark = ReadStableMark(obj); 740 741 // Uncontended case, header points to stack 742 if (mark->has_locker()) { 743 return thread->is_lock_owned((address)mark->locker()); 744 } 745 // Contended case, header points to ObjectMonitor (tagged pointer) 746 if (mark->has_monitor()) { 747 ObjectMonitor* monitor = mark->monitor(); 748 return monitor->is_entered(thread) != 0; 749 } 750 // Unlocked case, header in place 751 assert(mark->is_neutral(), "sanity check"); 752 return false; 753 } 754 755 // Be aware of this method could revoke bias of the lock object. 756 // This method queries the ownership of the lock handle specified by 'h_obj'. 757 // If the current thread owns the lock, it returns owner_self. If no 758 // thread owns the lock, it returns owner_none. Otherwise, it will return 759 // owner_other. 760 ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership 761 (JavaThread *self, Handle h_obj) { 762 // The caller must beware this method can revoke bias, and 763 // revocation can result in a safepoint. 764 assert(!SafepointSynchronize::is_at_safepoint(), "invariant"); 765 assert(self->thread_state() != _thread_blocked, "invariant"); 766 767 // Possible mark states: neutral, biased, stack-locked, inflated 768 769 if (UseBiasedLocking && h_obj()->mark()->has_bias_pattern()) { 770 // CASE: biased 771 BiasedLocking::revoke_and_rebias(h_obj, false, self); 772 assert(!h_obj->mark()->has_bias_pattern(), 773 "biases should be revoked by now"); 774 } 775 776 assert(self == JavaThread::current(), "Can only be called on current thread"); 777 oop obj = h_obj(); 778 markOop mark = ReadStableMark(obj); 779 780 // CASE: stack-locked. Mark points to a BasicLock on the owner's stack. 781 if (mark->has_locker()) { 782 return self->is_lock_owned((address)mark->locker()) ? 783 owner_self : owner_other; 784 } 785 786 // CASE: inflated. Mark (tagged pointer) points to an objectMonitor. 787 // The Object:ObjectMonitor relationship is stable as long as we're 788 // not at a safepoint. 789 if (mark->has_monitor()) { 790 void * owner = mark->monitor()->_owner; 791 if (owner == NULL) return owner_none; 792 return (owner == self || 793 self->is_lock_owned((address)owner)) ? owner_self : owner_other; 794 } 795 796 // CASE: neutral 797 assert(mark->is_neutral(), "sanity check"); 798 return owner_none; // it's unlocked 799 } 800 801 // FIXME: jvmti should call this 802 JavaThread* ObjectSynchronizer::get_lock_owner(Handle h_obj, bool doLock) { 803 if (UseBiasedLocking) { 804 if (SafepointSynchronize::is_at_safepoint()) { 805 BiasedLocking::revoke_at_safepoint(h_obj); 806 } else { 807 BiasedLocking::revoke_and_rebias(h_obj, false, JavaThread::current()); 808 } 809 assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 810 } 811 812 oop obj = h_obj(); 813 address owner = NULL; 814 815 markOop mark = ReadStableMark(obj); 816 817 // Uncontended case, header points to stack 818 if (mark->has_locker()) { 819 owner = (address) mark->locker(); 820 } 821 822 // Contended case, header points to ObjectMonitor (tagged pointer) 823 if (mark->has_monitor()) { 824 ObjectMonitor* monitor = mark->monitor(); 825 assert(monitor != NULL, "monitor should be non-null"); 826 owner = (address) monitor->owner(); 827 } 828 829 if (owner != NULL) { 830 // owning_thread_from_monitor_owner() may also return NULL here 831 return Threads::owning_thread_from_monitor_owner(owner, doLock); 832 } 833 834 // Unlocked case, header in place 835 // Cannot have assertion since this object may have been 836 // locked by another thread when reaching here. 837 // assert(mark->is_neutral(), "sanity check"); 838 839 return NULL; 840 } 841 // Visitors ... 842 843 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure) { 844 PaddedEnd<ObjectMonitor> * block = (PaddedEnd<ObjectMonitor> *)gBlockList; 845 ObjectMonitor* mid; 846 while (block) { 847 assert(block->object() == CHAINMARKER, "must be a block header"); 848 for (int i = _BLOCKSIZE - 1; i > 0; i--) { 849 mid = (ObjectMonitor *)(block + i); 850 oop object = (oop) mid->object(); 851 if (object != NULL) { 852 closure->do_monitor(mid); 853 } 854 } 855 block = (PaddedEnd<ObjectMonitor> *) block->FreeNext; 856 } 857 } 858 859 // Get the next block in the block list. 860 static inline ObjectMonitor* next(ObjectMonitor* block) { 861 assert(block->object() == CHAINMARKER, "must be a block header"); 862 block = block->FreeNext; 863 assert(block == NULL || block->object() == CHAINMARKER, "must be a block header"); 864 return block; 865 } 866 867 868 void ObjectSynchronizer::oops_do(OopClosure* f) { 869 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 870 for (PaddedEnd<ObjectMonitor> * block = 871 (PaddedEnd<ObjectMonitor> *)gBlockList; block != NULL; 872 block = (PaddedEnd<ObjectMonitor> *)next(block)) { 873 assert(block->object() == CHAINMARKER, "must be a block header"); 874 for (int i = 1; i < _BLOCKSIZE; i++) { 875 ObjectMonitor* mid = (ObjectMonitor *)&block[i]; 876 if (mid->object() != NULL) { 877 f->do_oop((oop*)mid->object_addr()); 878 } 879 } 880 } 881 } 882 883 884 // ----------------------------------------------------------------------------- 885 // ObjectMonitor Lifecycle 886 // ----------------------- 887 // Inflation unlinks monitors from the global gFreeList and 888 // associates them with objects. Deflation -- which occurs at 889 // STW-time -- disassociates idle monitors from objects. Such 890 // scavenged monitors are returned to the gFreeList. 891 // 892 // The global list is protected by gListLock. All the critical sections 893 // are short and operate in constant-time. 894 // 895 // ObjectMonitors reside in type-stable memory (TSM) and are immortal. 896 // 897 // Lifecycle: 898 // -- unassigned and on the global free list 899 // -- unassigned and on a thread's private omFreeList 900 // -- assigned to an object. The object is inflated and the mark refers 901 // to the objectmonitor. 902 903 904 // Constraining monitor pool growth via MonitorBound ... 905 // 906 // The monitor pool is grow-only. We scavenge at STW safepoint-time, but the 907 // the rate of scavenging is driven primarily by GC. As such, we can find 908 // an inordinate number of monitors in circulation. 909 // To avoid that scenario we can artificially induce a STW safepoint 910 // if the pool appears to be growing past some reasonable bound. 911 // Generally we favor time in space-time tradeoffs, but as there's no 912 // natural back-pressure on the # of extant monitors we need to impose some 913 // type of limit. Beware that if MonitorBound is set to too low a value 914 // we could just loop. In addition, if MonitorBound is set to a low value 915 // we'll incur more safepoints, which are harmful to performance. 916 // See also: GuaranteedSafepointInterval 917 // 918 // The current implementation uses asynchronous VM operations. 919 920 static void InduceScavenge(Thread * Self, const char * Whence) { 921 // Induce STW safepoint to trim monitors 922 // Ultimately, this results in a call to deflate_idle_monitors() in the near future. 923 // More precisely, trigger an asynchronous STW safepoint as the number 924 // of active monitors passes the specified threshold. 925 // TODO: assert thread state is reasonable 926 927 if (ForceMonitorScavenge == 0 && Atomic::xchg (1, &ForceMonitorScavenge) == 0) { 928 if (ObjectMonitor::Knob_Verbose) { 929 ::printf ("Monitor scavenge - Induced STW @%s (%d)\n", Whence, ForceMonitorScavenge) ; 930 ::fflush(stdout); 931 } 932 // Induce a 'null' safepoint to scavenge monitors 933 // Must VM_Operation instance be heap allocated as the op will be enqueue and posted 934 // to the VMthread and have a lifespan longer than that of this activation record. 935 // The VMThread will delete the op when completed. 936 VMThread::execute(new VM_ForceAsyncSafepoint()); 937 938 if (ObjectMonitor::Knob_Verbose) { 939 ::printf ("Monitor scavenge - STW posted @%s (%d)\n", Whence, ForceMonitorScavenge) ; 940 ::fflush(stdout); 941 } 942 } 943 } 944 945 void ObjectSynchronizer::verifyInUse(Thread *Self) { 946 ObjectMonitor* mid; 947 int in_use_tally = 0; 948 for (mid = Self->omInUseList; mid != NULL; mid = mid->FreeNext) { 949 in_use_tally++; 950 } 951 assert(in_use_tally == Self->omInUseCount, "in-use count off"); 952 953 int free_tally = 0; 954 for (mid = Self->omFreeList; mid != NULL; mid = mid->FreeNext) { 955 free_tally++; 956 } 957 assert(free_tally == Self->omFreeCount, "free count off"); 958 } 959 960 ObjectMonitor * NOINLINE ObjectSynchronizer::omAlloc(Thread * Self) { 961 // A large MAXPRIVATE value reduces both list lock contention 962 // and list coherency traffic, but also tends to increase the 963 // number of objectMonitors in circulation as well as the STW 964 // scavenge costs. As usual, we lean toward time in space-time 965 // tradeoffs. 966 const int MAXPRIVATE = 1024; 967 for (;;) { 968 ObjectMonitor * m; 969 970 // 1: try to allocate from the thread's local omFreeList. 971 // Threads will attempt to allocate first from their local list, then 972 // from the global list, and only after those attempts fail will the thread 973 // attempt to instantiate new monitors. Thread-local free lists take 974 // heat off the gListLock and improve allocation latency, as well as reducing 975 // coherency traffic on the shared global list. 976 m = Self->omFreeList; 977 if (m != NULL) { 978 Self->omFreeList = m->FreeNext; 979 Self->omFreeCount--; 980 // CONSIDER: set m->FreeNext = BAD -- diagnostic hygiene 981 guarantee(m->object() == NULL, "invariant"); 982 if (MonitorInUseLists) { 983 m->FreeNext = Self->omInUseList; 984 Self->omInUseList = m; 985 Self->omInUseCount++; 986 if (ObjectMonitor::Knob_VerifyInUse) { 987 verifyInUse(Self); 988 } 989 } else { 990 m->FreeNext = NULL; 991 } 992 return m; 993 } 994 995 // 2: try to allocate from the global gFreeList 996 // CONSIDER: use muxTry() instead of muxAcquire(). 997 // If the muxTry() fails then drop immediately into case 3. 998 // If we're using thread-local free lists then try 999 // to reprovision the caller's free list. 1000 if (gFreeList != NULL) { 1001 // Reprovision the thread's omFreeList. 1002 // Use bulk transfers to reduce the allocation rate and heat 1003 // on various locks. 1004 Thread::muxAcquire(&gListLock, "omAlloc"); 1005 for (int i = Self->omFreeProvision; --i >= 0 && gFreeList != NULL;) { 1006 gMonitorFreeCount--; 1007 ObjectMonitor * take = gFreeList; 1008 gFreeList = take->FreeNext; 1009 guarantee(take->object() == NULL, "invariant"); 1010 guarantee(!take->is_busy(), "invariant"); 1011 take->Recycle(); 1012 omRelease(Self, take, false); 1013 } 1014 Thread::muxRelease(&gListLock); 1015 Self->omFreeProvision += 1 + (Self->omFreeProvision/2); 1016 if (Self->omFreeProvision > MAXPRIVATE) Self->omFreeProvision = MAXPRIVATE; 1017 TEVENT(omFirst - reprovision); 1018 1019 const int mx = MonitorBound; 1020 if (mx > 0 && (gMonitorPopulation-gMonitorFreeCount) > mx) { 1021 // We can't safely induce a STW safepoint from omAlloc() as our thread 1022 // state may not be appropriate for such activities and callers may hold 1023 // naked oops, so instead we defer the action. 1024 InduceScavenge(Self, "omAlloc"); 1025 } 1026 continue; 1027 } 1028 1029 // 3: allocate a block of new ObjectMonitors 1030 // Both the local and global free lists are empty -- resort to malloc(). 1031 // In the current implementation objectMonitors are TSM - immortal. 1032 // Ideally, we'd write "new ObjectMonitor[_BLOCKSIZE], but we want 1033 // each ObjectMonitor to start at the beginning of a cache line, 1034 // so we use align_size_up(). 1035 // A better solution would be to use C++ placement-new. 1036 // BEWARE: As it stands currently, we don't run the ctors! 1037 assert(_BLOCKSIZE > 1, "invariant"); 1038 size_t neededsize = sizeof(PaddedEnd<ObjectMonitor>) * _BLOCKSIZE; 1039 PaddedEnd<ObjectMonitor> * temp; 1040 size_t aligned_size = neededsize + (DEFAULT_CACHE_LINE_SIZE - 1); 1041 void* real_malloc_addr = (void *)NEW_C_HEAP_ARRAY(char, aligned_size, 1042 mtInternal); 1043 temp = (PaddedEnd<ObjectMonitor> *) 1044 align_size_up((intptr_t)real_malloc_addr, 1045 DEFAULT_CACHE_LINE_SIZE); 1046 1047 // NOTE: (almost) no way to recover if allocation failed. 1048 // We might be able to induce a STW safepoint and scavenge enough 1049 // objectMonitors to permit progress. 1050 if (temp == NULL) { 1051 vm_exit_out_of_memory(neededsize, OOM_MALLOC_ERROR, 1052 "Allocate ObjectMonitors"); 1053 } 1054 (void)memset((void *) temp, 0, neededsize); 1055 1056 // Format the block. 1057 // initialize the linked list, each monitor points to its next 1058 // forming the single linked free list, the very first monitor 1059 // will points to next block, which forms the block list. 1060 // The trick of using the 1st element in the block as gBlockList 1061 // linkage should be reconsidered. A better implementation would 1062 // look like: class Block { Block * next; int N; ObjectMonitor Body [N] ; } 1063 1064 for (int i = 1; i < _BLOCKSIZE; i++) { 1065 temp[i].FreeNext = (ObjectMonitor *)&temp[i+1]; 1066 } 1067 1068 // terminate the last monitor as the end of list 1069 temp[_BLOCKSIZE - 1].FreeNext = NULL; 1070 1071 // Element [0] is reserved for global list linkage 1072 temp[0].set_object(CHAINMARKER); 1073 1074 // Consider carving out this thread's current request from the 1075 // block in hand. This avoids some lock traffic and redundant 1076 // list activity. 1077 1078 // Acquire the gListLock to manipulate gBlockList and gFreeList. 1079 // An Oyama-Taura-Yonezawa scheme might be more efficient. 1080 Thread::muxAcquire(&gListLock, "omAlloc [2]"); 1081 gMonitorPopulation += _BLOCKSIZE-1; 1082 gMonitorFreeCount += _BLOCKSIZE-1; 1083 1084 // Add the new block to the list of extant blocks (gBlockList). 1085 // The very first objectMonitor in a block is reserved and dedicated. 1086 // It serves as blocklist "next" linkage. 1087 temp[0].FreeNext = gBlockList; 1088 gBlockList = temp; 1089 1090 // Add the new string of objectMonitors to the global free list 1091 temp[_BLOCKSIZE - 1].FreeNext = gFreeList; 1092 gFreeList = temp + 1; 1093 Thread::muxRelease(&gListLock); 1094 TEVENT(Allocate block of monitors); 1095 } 1096 } 1097 1098 // Place "m" on the caller's private per-thread omFreeList. 1099 // In practice there's no need to clamp or limit the number of 1100 // monitors on a thread's omFreeList as the only time we'll call 1101 // omRelease is to return a monitor to the free list after a CAS 1102 // attempt failed. This doesn't allow unbounded #s of monitors to 1103 // accumulate on a thread's free list. 1104 // 1105 // Key constraint: all ObjectMonitors on a thread's free list and the global 1106 // free list must have their object field set to null. This prevents the 1107 // scavenger -- deflate_idle_monitors -- from reclaiming them. 1108 1109 void ObjectSynchronizer::omRelease(Thread * Self, ObjectMonitor * m, 1110 bool fromPerThreadAlloc) { 1111 guarantee(m->object() == NULL, "invariant"); 1112 guarantee(((m->is_busy()|m->_recursions) == 0), "freeing in-use monitor"); 1113 // Remove from omInUseList 1114 if (MonitorInUseLists && fromPerThreadAlloc) { 1115 ObjectMonitor* cur_mid_in_use = NULL; 1116 bool extracted = false; 1117 for (ObjectMonitor* mid = Self->omInUseList; mid != NULL; cur_mid_in_use = mid, mid = mid->FreeNext) { 1118 if (m == mid) { 1119 // extract from per-thread in-use list 1120 if (mid == Self->omInUseList) { 1121 Self->omInUseList = mid->FreeNext; 1122 } else if (cur_mid_in_use != NULL) { 1123 cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list 1124 } 1125 extracted = true; 1126 Self->omInUseCount--; 1127 if (ObjectMonitor::Knob_VerifyInUse) { 1128 verifyInUse(Self); 1129 } 1130 break; 1131 } 1132 } 1133 assert(extracted, "Should have extracted from in-use list"); 1134 } 1135 1136 // FreeNext is used for both omInUseList and omFreeList, so clear old before setting new 1137 m->FreeNext = Self->omFreeList; 1138 Self->omFreeList = m; 1139 Self->omFreeCount++; 1140 } 1141 1142 // Return the monitors of a moribund thread's local free list to 1143 // the global free list. Typically a thread calls omFlush() when 1144 // it's dying. We could also consider having the VM thread steal 1145 // monitors from threads that have not run java code over a few 1146 // consecutive STW safepoints. Relatedly, we might decay 1147 // omFreeProvision at STW safepoints. 1148 // 1149 // Also return the monitors of a moribund thread's omInUseList to 1150 // a global gOmInUseList under the global list lock so these 1151 // will continue to be scanned. 1152 // 1153 // We currently call omFlush() from the Thread:: dtor _after the thread 1154 // has been excised from the thread list and is no longer a mutator. 1155 // That means that omFlush() can run concurrently with a safepoint and 1156 // the scavenge operator. Calling omFlush() from JavaThread::exit() might 1157 // be a better choice as we could safely reason that that the JVM is 1158 // not at a safepoint at the time of the call, and thus there could 1159 // be not inopportune interleavings between omFlush() and the scavenge 1160 // operator. 1161 1162 void ObjectSynchronizer::omFlush(Thread * Self) { 1163 ObjectMonitor * list = Self->omFreeList; // Null-terminated SLL 1164 Self->omFreeList = NULL; 1165 ObjectMonitor * tail = NULL; 1166 int tally = 0; 1167 if (list != NULL) { 1168 ObjectMonitor * s; 1169 // The thread is going away, the per-thread free monitors 1170 // are freed via set_owner(NULL) 1171 // Link them to tail, which will be linked into the global free list 1172 // gFreeList below, under the gListLock 1173 for (s = list; s != NULL; s = s->FreeNext) { 1174 tally++; 1175 tail = s; 1176 guarantee(s->object() == NULL, "invariant"); 1177 guarantee(!s->is_busy(), "invariant"); 1178 s->set_owner(NULL); // redundant but good hygiene 1179 TEVENT(omFlush - Move one); 1180 } 1181 guarantee(tail != NULL && list != NULL, "invariant"); 1182 } 1183 1184 ObjectMonitor * inUseList = Self->omInUseList; 1185 ObjectMonitor * inUseTail = NULL; 1186 int inUseTally = 0; 1187 if (inUseList != NULL) { 1188 Self->omInUseList = NULL; 1189 ObjectMonitor *cur_om; 1190 // The thread is going away, however the omInUseList inflated 1191 // monitors may still be in-use by other threads. 1192 // Link them to inUseTail, which will be linked into the global in-use list 1193 // gOmInUseList below, under the gListLock 1194 for (cur_om = inUseList; cur_om != NULL; cur_om = cur_om->FreeNext) { 1195 inUseTail = cur_om; 1196 inUseTally++; 1197 } 1198 assert(Self->omInUseCount == inUseTally, "in-use count off"); 1199 Self->omInUseCount = 0; 1200 guarantee(inUseTail != NULL && inUseList != NULL, "invariant"); 1201 } 1202 1203 Thread::muxAcquire(&gListLock, "omFlush"); 1204 if (tail != NULL) { 1205 tail->FreeNext = gFreeList; 1206 gFreeList = list; 1207 gMonitorFreeCount += tally; 1208 } 1209 1210 if (inUseTail != NULL) { 1211 inUseTail->FreeNext = gOmInUseList; 1212 gOmInUseList = inUseList; 1213 gOmInUseCount += inUseTally; 1214 } 1215 1216 Thread::muxRelease(&gListLock); 1217 TEVENT(omFlush); 1218 } 1219 1220 // Fast path code shared by multiple functions 1221 ObjectMonitor* ObjectSynchronizer::inflate_helper(oop obj) { 1222 markOop mark = obj->mark(); 1223 if (mark->has_monitor()) { 1224 assert(ObjectSynchronizer::verify_objmon_isinpool(mark->monitor()), "monitor is invalid"); 1225 assert(mark->monitor()->header()->is_neutral(), "monitor must record a good object header"); 1226 return mark->monitor(); 1227 } 1228 return ObjectSynchronizer::inflate(Thread::current(), obj); 1229 } 1230 1231 1232 ObjectMonitor * NOINLINE ObjectSynchronizer::inflate(Thread * Self, 1233 oop object) { 1234 // Inflate mutates the heap ... 1235 // Relaxing assertion for bug 6320749. 1236 assert(Universe::verify_in_progress() || 1237 !SafepointSynchronize::is_at_safepoint(), "invariant"); 1238 1239 for (;;) { 1240 const markOop mark = object->mark(); 1241 assert(!mark->has_bias_pattern(), "invariant"); 1242 1243 // The mark can be in one of the following states: 1244 // * Inflated - just return 1245 // * Stack-locked - coerce it to inflated 1246 // * INFLATING - busy wait for conversion to complete 1247 // * Neutral - aggressively inflate the object. 1248 // * BIASED - Illegal. We should never see this 1249 1250 // CASE: inflated 1251 if (mark->has_monitor()) { 1252 ObjectMonitor * inf = mark->monitor(); 1253 assert(inf->header()->is_neutral(), "invariant"); 1254 assert(inf->object() == object, "invariant"); 1255 assert(ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid"); 1256 return inf; 1257 } 1258 1259 // CASE: inflation in progress - inflating over a stack-lock. 1260 // Some other thread is converting from stack-locked to inflated. 1261 // Only that thread can complete inflation -- other threads must wait. 1262 // The INFLATING value is transient. 1263 // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish. 1264 // We could always eliminate polling by parking the thread on some auxiliary list. 1265 if (mark == markOopDesc::INFLATING()) { 1266 TEVENT(Inflate: spin while INFLATING); 1267 ReadStableMark(object); 1268 continue; 1269 } 1270 1271 // CASE: stack-locked 1272 // Could be stack-locked either by this thread or by some other thread. 1273 // 1274 // Note that we allocate the objectmonitor speculatively, _before_ attempting 1275 // to install INFLATING into the mark word. We originally installed INFLATING, 1276 // allocated the objectmonitor, and then finally STed the address of the 1277 // objectmonitor into the mark. This was correct, but artificially lengthened 1278 // the interval in which INFLATED appeared in the mark, thus increasing 1279 // the odds of inflation contention. 1280 // 1281 // We now use per-thread private objectmonitor free lists. 1282 // These list are reprovisioned from the global free list outside the 1283 // critical INFLATING...ST interval. A thread can transfer 1284 // multiple objectmonitors en-mass from the global free list to its local free list. 1285 // This reduces coherency traffic and lock contention on the global free list. 1286 // Using such local free lists, it doesn't matter if the omAlloc() call appears 1287 // before or after the CAS(INFLATING) operation. 1288 // See the comments in omAlloc(). 1289 1290 if (mark->has_locker()) { 1291 ObjectMonitor * m = omAlloc(Self); 1292 // Optimistically prepare the objectmonitor - anticipate successful CAS 1293 // We do this before the CAS in order to minimize the length of time 1294 // in which INFLATING appears in the mark. 1295 m->Recycle(); 1296 m->_Responsible = NULL; 1297 m->_recursions = 0; 1298 m->_SpinDuration = ObjectMonitor::Knob_SpinLimit; // Consider: maintain by type/class 1299 1300 markOop cmp = (markOop) Atomic::cmpxchg_ptr(markOopDesc::INFLATING(), object->mark_addr(), mark); 1301 if (cmp != mark) { 1302 omRelease(Self, m, true); 1303 continue; // Interference -- just retry 1304 } 1305 1306 // We've successfully installed INFLATING (0) into the mark-word. 1307 // This is the only case where 0 will appear in a mark-work. 1308 // Only the singular thread that successfully swings the mark-word 1309 // to 0 can perform (or more precisely, complete) inflation. 1310 // 1311 // Why do we CAS a 0 into the mark-word instead of just CASing the 1312 // mark-word from the stack-locked value directly to the new inflated state? 1313 // Consider what happens when a thread unlocks a stack-locked object. 1314 // It attempts to use CAS to swing the displaced header value from the 1315 // on-stack basiclock back into the object header. Recall also that the 1316 // header value (hashcode, etc) can reside in (a) the object header, or 1317 // (b) a displaced header associated with the stack-lock, or (c) a displaced 1318 // header in an objectMonitor. The inflate() routine must copy the header 1319 // value from the basiclock on the owner's stack to the objectMonitor, all 1320 // the while preserving the hashCode stability invariants. If the owner 1321 // decides to release the lock while the value is 0, the unlock will fail 1322 // and control will eventually pass from slow_exit() to inflate. The owner 1323 // will then spin, waiting for the 0 value to disappear. Put another way, 1324 // the 0 causes the owner to stall if the owner happens to try to 1325 // drop the lock (restoring the header from the basiclock to the object) 1326 // while inflation is in-progress. This protocol avoids races that might 1327 // would otherwise permit hashCode values to change or "flicker" for an object. 1328 // Critically, while object->mark is 0 mark->displaced_mark_helper() is stable. 1329 // 0 serves as a "BUSY" inflate-in-progress indicator. 1330 1331 1332 // fetch the displaced mark from the owner's stack. 1333 // The owner can't die or unwind past the lock while our INFLATING 1334 // object is in the mark. Furthermore the owner can't complete 1335 // an unlock on the object, either. 1336 markOop dmw = mark->displaced_mark_helper(); 1337 assert(dmw->is_neutral(), "invariant"); 1338 1339 // Setup monitor fields to proper values -- prepare the monitor 1340 m->set_header(dmw); 1341 1342 // Optimization: if the mark->locker stack address is associated 1343 // with this thread we could simply set m->_owner = Self. 1344 // Note that a thread can inflate an object 1345 // that it has stack-locked -- as might happen in wait() -- directly 1346 // with CAS. That is, we can avoid the xchg-NULL .... ST idiom. 1347 m->set_owner(mark->locker()); 1348 m->set_object(object); 1349 // TODO-FIXME: assert BasicLock->dhw != 0. 1350 1351 // Must preserve store ordering. The monitor state must 1352 // be stable at the time of publishing the monitor address. 1353 guarantee(object->mark() == markOopDesc::INFLATING(), "invariant"); 1354 object->release_set_mark(markOopDesc::encode(m)); 1355 1356 // Hopefully the performance counters are allocated on distinct cache lines 1357 // to avoid false sharing on MP systems ... 1358 if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc(); 1359 TEVENT(Inflate: overwrite stacklock); 1360 if (TraceMonitorInflation) { 1361 if (object->is_instance()) { 1362 ResourceMark rm; 1363 tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s", 1364 (void *) object, (intptr_t) object->mark(), 1365 object->klass()->external_name()); 1366 } 1367 } 1368 return m; 1369 } 1370 1371 // CASE: neutral 1372 // TODO-FIXME: for entry we currently inflate and then try to CAS _owner. 1373 // If we know we're inflating for entry it's better to inflate by swinging a 1374 // pre-locked objectMonitor pointer into the object header. A successful 1375 // CAS inflates the object *and* confers ownership to the inflating thread. 1376 // In the current implementation we use a 2-step mechanism where we CAS() 1377 // to inflate and then CAS() again to try to swing _owner from NULL to Self. 1378 // An inflateTry() method that we could call from fast_enter() and slow_enter() 1379 // would be useful. 1380 1381 assert(mark->is_neutral(), "invariant"); 1382 ObjectMonitor * m = omAlloc(Self); 1383 // prepare m for installation - set monitor to initial state 1384 m->Recycle(); 1385 m->set_header(mark); 1386 m->set_owner(NULL); 1387 m->set_object(object); 1388 m->_recursions = 0; 1389 m->_Responsible = NULL; 1390 m->_SpinDuration = ObjectMonitor::Knob_SpinLimit; // consider: keep metastats by type/class 1391 1392 if (Atomic::cmpxchg_ptr (markOopDesc::encode(m), object->mark_addr(), mark) != mark) { 1393 m->set_object(NULL); 1394 m->set_owner(NULL); 1395 m->Recycle(); 1396 omRelease(Self, m, true); 1397 m = NULL; 1398 continue; 1399 // interference - the markword changed - just retry. 1400 // The state-transitions are one-way, so there's no chance of 1401 // live-lock -- "Inflated" is an absorbing state. 1402 } 1403 1404 // Hopefully the performance counters are allocated on distinct 1405 // cache lines to avoid false sharing on MP systems ... 1406 if (ObjectMonitor::_sync_Inflations != NULL) ObjectMonitor::_sync_Inflations->inc(); 1407 TEVENT(Inflate: overwrite neutral); 1408 if (TraceMonitorInflation) { 1409 if (object->is_instance()) { 1410 ResourceMark rm; 1411 tty->print_cr("Inflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s", 1412 (void *) object, (intptr_t) object->mark(), 1413 object->klass()->external_name()); 1414 } 1415 } 1416 return m; 1417 } 1418 } 1419 1420 1421 // Deflate_idle_monitors() is called at all safepoints, immediately 1422 // after all mutators are stopped, but before any objects have moved. 1423 // It traverses the list of known monitors, deflating where possible. 1424 // The scavenged monitor are returned to the monitor free list. 1425 // 1426 // Beware that we scavenge at *every* stop-the-world point. 1427 // Having a large number of monitors in-circulation negatively 1428 // impacts the performance of some applications (e.g., PointBase). 1429 // Broadly, we want to minimize the # of monitors in circulation. 1430 // 1431 // We have added a flag, MonitorInUseLists, which creates a list 1432 // of active monitors for each thread. deflate_idle_monitors() 1433 // only scans the per-thread in-use lists. omAlloc() puts all 1434 // assigned monitors on the per-thread list. deflate_idle_monitors() 1435 // returns the non-busy monitors to the global free list. 1436 // When a thread dies, omFlush() adds the list of active monitors for 1437 // that thread to a global gOmInUseList acquiring the 1438 // global list lock. deflate_idle_monitors() acquires the global 1439 // list lock to scan for non-busy monitors to the global free list. 1440 // An alternative could have used a single global in-use list. The 1441 // downside would have been the additional cost of acquiring the global list lock 1442 // for every omAlloc(). 1443 // 1444 // Perversely, the heap size -- and thus the STW safepoint rate -- 1445 // typically drives the scavenge rate. Large heaps can mean infrequent GC, 1446 // which in turn can mean large(r) numbers of objectmonitors in circulation. 1447 // This is an unfortunate aspect of this design. 1448 1449 enum ManifestConstants { 1450 ClearResponsibleAtSTW = 0, 1451 MaximumRecheckInterval = 1000 1452 }; 1453 1454 // Deflate a single monitor if not in-use 1455 // Return true if deflated, false if in-use 1456 bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj, 1457 ObjectMonitor** freeHeadp, 1458 ObjectMonitor** freeTailp) { 1459 bool deflated; 1460 // Normal case ... The monitor is associated with obj. 1461 guarantee(obj->mark() == markOopDesc::encode(mid), "invariant"); 1462 guarantee(mid == obj->mark()->monitor(), "invariant"); 1463 guarantee(mid->header()->is_neutral(), "invariant"); 1464 1465 if (mid->is_busy()) { 1466 if (ClearResponsibleAtSTW) mid->_Responsible = NULL; 1467 deflated = false; 1468 } else { 1469 // Deflate the monitor if it is no longer being used 1470 // It's idle - scavenge and return to the global free list 1471 // plain old deflation ... 1472 TEVENT(deflate_idle_monitors - scavenge1); 1473 if (TraceMonitorInflation) { 1474 if (obj->is_instance()) { 1475 ResourceMark rm; 1476 tty->print_cr("Deflating object " INTPTR_FORMAT " , mark " INTPTR_FORMAT " , type %s", 1477 (void *) obj, (intptr_t) obj->mark(), obj->klass()->external_name()); 1478 } 1479 } 1480 1481 // Restore the header back to obj 1482 obj->release_set_mark(mid->header()); 1483 mid->clear(); 1484 1485 assert(mid->object() == NULL, "invariant"); 1486 1487 // Move the object to the working free list defined by freeHeadp, freeTailp 1488 if (*freeHeadp == NULL) *freeHeadp = mid; 1489 if (*freeTailp != NULL) { 1490 ObjectMonitor * prevtail = *freeTailp; 1491 assert(prevtail->FreeNext == NULL, "cleaned up deflated?"); 1492 prevtail->FreeNext = mid; 1493 } 1494 *freeTailp = mid; 1495 deflated = true; 1496 } 1497 return deflated; 1498 } 1499 1500 // Walk a given monitor list, and deflate idle monitors 1501 // The given list could be a per-thread list or a global list 1502 // Caller acquires gListLock 1503 int ObjectSynchronizer::deflate_monitor_list(ObjectMonitor** listHeadp, 1504 ObjectMonitor** freeHeadp, 1505 ObjectMonitor** freeTailp) { 1506 ObjectMonitor* mid; 1507 ObjectMonitor* next; 1508 ObjectMonitor* cur_mid_in_use = NULL; 1509 int deflated_count = 0; 1510 1511 for (mid = *listHeadp; mid != NULL;) { 1512 oop obj = (oop) mid->object(); 1513 if (obj != NULL && deflate_monitor(mid, obj, freeHeadp, freeTailp)) { 1514 // if deflate_monitor succeeded, 1515 // extract from per-thread in-use list 1516 if (mid == *listHeadp) { 1517 *listHeadp = mid->FreeNext; 1518 } else if (cur_mid_in_use != NULL) { 1519 cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list 1520 } 1521 next = mid->FreeNext; 1522 mid->FreeNext = NULL; // This mid is current tail in the freeHeadp list 1523 mid = next; 1524 deflated_count++; 1525 } else { 1526 cur_mid_in_use = mid; 1527 mid = mid->FreeNext; 1528 } 1529 } 1530 return deflated_count; 1531 } 1532 1533 void ObjectSynchronizer::deflate_idle_monitors() { 1534 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1535 int nInuse = 0; // currently associated with objects 1536 int nInCirculation = 0; // extant 1537 int nScavenged = 0; // reclaimed 1538 bool deflated = false; 1539 1540 ObjectMonitor * freeHeadp = NULL; // Local SLL of scavenged monitors 1541 ObjectMonitor * freeTailp = NULL; 1542 1543 TEVENT(deflate_idle_monitors); 1544 // Prevent omFlush from changing mids in Thread dtor's during deflation 1545 // And in case the vm thread is acquiring a lock during a safepoint 1546 // See e.g. 6320749 1547 Thread::muxAcquire(&gListLock, "scavenge - return"); 1548 1549 if (MonitorInUseLists) { 1550 int inUse = 0; 1551 for (JavaThread* cur = Threads::first(); cur != NULL; cur = cur->next()) { 1552 nInCirculation+= cur->omInUseCount; 1553 int deflated_count = deflate_monitor_list(cur->omInUseList_addr(), &freeHeadp, &freeTailp); 1554 cur->omInUseCount-= deflated_count; 1555 if (ObjectMonitor::Knob_VerifyInUse) { 1556 verifyInUse(cur); 1557 } 1558 nScavenged += deflated_count; 1559 nInuse += cur->omInUseCount; 1560 } 1561 1562 // For moribund threads, scan gOmInUseList 1563 if (gOmInUseList) { 1564 nInCirculation += gOmInUseCount; 1565 int deflated_count = deflate_monitor_list((ObjectMonitor **)&gOmInUseList, &freeHeadp, &freeTailp); 1566 gOmInUseCount-= deflated_count; 1567 nScavenged += deflated_count; 1568 nInuse += gOmInUseCount; 1569 } 1570 1571 } else for (PaddedEnd<ObjectMonitor> * block = 1572 (PaddedEnd<ObjectMonitor> *)gBlockList; block != NULL; 1573 block = (PaddedEnd<ObjectMonitor> *)next(block)) { 1574 // Iterate over all extant monitors - Scavenge all idle monitors. 1575 assert(block->object() == CHAINMARKER, "must be a block header"); 1576 nInCirculation += _BLOCKSIZE; 1577 for (int i = 1; i < _BLOCKSIZE; i++) { 1578 ObjectMonitor* mid = (ObjectMonitor*)&block[i]; 1579 oop obj = (oop) mid->object(); 1580 1581 if (obj == NULL) { 1582 // The monitor is not associated with an object. 1583 // The monitor should either be a thread-specific private 1584 // free list or the global free list. 1585 // obj == NULL IMPLIES mid->is_busy() == 0 1586 guarantee(!mid->is_busy(), "invariant"); 1587 continue; 1588 } 1589 deflated = deflate_monitor(mid, obj, &freeHeadp, &freeTailp); 1590 1591 if (deflated) { 1592 mid->FreeNext = NULL; 1593 nScavenged++; 1594 } else { 1595 nInuse++; 1596 } 1597 } 1598 } 1599 1600 gMonitorFreeCount += nScavenged; 1601 1602 // Consider: audit gFreeList to ensure that gMonitorFreeCount and list agree. 1603 1604 if (ObjectMonitor::Knob_Verbose) { 1605 ::printf("Deflate: InCirc=%d InUse=%d Scavenged=%d ForceMonitorScavenge=%d : pop=%d free=%d\n", 1606 nInCirculation, nInuse, nScavenged, ForceMonitorScavenge, 1607 gMonitorPopulation, gMonitorFreeCount); 1608 ::fflush(stdout); 1609 } 1610 1611 ForceMonitorScavenge = 0; // Reset 1612 1613 // Move the scavenged monitors back to the global free list. 1614 if (freeHeadp != NULL) { 1615 guarantee(freeTailp != NULL && nScavenged > 0, "invariant"); 1616 assert(freeTailp->FreeNext == NULL, "invariant"); 1617 // constant-time list splice - prepend scavenged segment to gFreeList 1618 freeTailp->FreeNext = gFreeList; 1619 gFreeList = freeHeadp; 1620 } 1621 Thread::muxRelease(&gListLock); 1622 1623 if (ObjectMonitor::_sync_Deflations != NULL) ObjectMonitor::_sync_Deflations->inc(nScavenged); 1624 if (ObjectMonitor::_sync_MonExtant != NULL) ObjectMonitor::_sync_MonExtant ->set_value(nInCirculation); 1625 1626 // TODO: Add objectMonitor leak detection. 1627 // Audit/inventory the objectMonitors -- make sure they're all accounted for. 1628 GVars.stwRandom = os::random(); 1629 GVars.stwCycle++; 1630 } 1631 1632 // Monitor cleanup on JavaThread::exit 1633 1634 // Iterate through monitor cache and attempt to release thread's monitors 1635 // Gives up on a particular monitor if an exception occurs, but continues 1636 // the overall iteration, swallowing the exception. 1637 class ReleaseJavaMonitorsClosure: public MonitorClosure { 1638 private: 1639 TRAPS; 1640 1641 public: 1642 ReleaseJavaMonitorsClosure(Thread* thread) : THREAD(thread) {} 1643 void do_monitor(ObjectMonitor* mid) { 1644 if (mid->owner() == THREAD) { 1645 (void)mid->complete_exit(CHECK); 1646 } 1647 } 1648 }; 1649 1650 // Release all inflated monitors owned by THREAD. Lightweight monitors are 1651 // ignored. This is meant to be called during JNI thread detach which assumes 1652 // all remaining monitors are heavyweight. All exceptions are swallowed. 1653 // Scanning the extant monitor list can be time consuming. 1654 // A simple optimization is to add a per-thread flag that indicates a thread 1655 // called jni_monitorenter() during its lifetime. 1656 // 1657 // Instead of No_Savepoint_Verifier it might be cheaper to 1658 // use an idiom of the form: 1659 // auto int tmp = SafepointSynchronize::_safepoint_counter ; 1660 // <code that must not run at safepoint> 1661 // guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ; 1662 // Since the tests are extremely cheap we could leave them enabled 1663 // for normal product builds. 1664 1665 void ObjectSynchronizer::release_monitors_owned_by_thread(TRAPS) { 1666 assert(THREAD == JavaThread::current(), "must be current Java thread"); 1667 No_Safepoint_Verifier nsv; 1668 ReleaseJavaMonitorsClosure rjmc(THREAD); 1669 Thread::muxAcquire(&gListLock, "release_monitors_owned_by_thread"); 1670 ObjectSynchronizer::monitors_iterate(&rjmc); 1671 Thread::muxRelease(&gListLock); 1672 THREAD->clear_pending_exception(); 1673 } 1674 1675 //------------------------------------------------------------------------------ 1676 // Debugging code 1677 1678 void ObjectSynchronizer::sanity_checks(const bool verbose, 1679 const uint cache_line_size, 1680 int *error_cnt_ptr, 1681 int *warning_cnt_ptr) { 1682 u_char *addr_begin = (u_char*)&GVars; 1683 u_char *addr_stwRandom = (u_char*)&GVars.stwRandom; 1684 u_char *addr_hcSequence = (u_char*)&GVars.hcSequence; 1685 1686 if (verbose) { 1687 tty->print_cr("INFO: sizeof(SharedGlobals)=" SIZE_FORMAT, 1688 sizeof(SharedGlobals)); 1689 } 1690 1691 uint offset_stwRandom = (uint)(addr_stwRandom - addr_begin); 1692 if (verbose) tty->print_cr("INFO: offset(stwRandom)=%u", offset_stwRandom); 1693 1694 uint offset_hcSequence = (uint)(addr_hcSequence - addr_begin); 1695 if (verbose) { 1696 tty->print_cr("INFO: offset(_hcSequence)=%u", offset_hcSequence); 1697 } 1698 1699 if (cache_line_size != 0) { 1700 // We were able to determine the L1 data cache line size so 1701 // do some cache line specific sanity checks 1702 1703 if (offset_stwRandom < cache_line_size) { 1704 tty->print_cr("WARNING: the SharedGlobals.stwRandom field is closer " 1705 "to the struct beginning than a cache line which permits " 1706 "false sharing."); 1707 (*warning_cnt_ptr)++; 1708 } 1709 1710 if ((offset_hcSequence - offset_stwRandom) < cache_line_size) { 1711 tty->print_cr("WARNING: the SharedGlobals.stwRandom and " 1712 "SharedGlobals.hcSequence fields are closer than a cache " 1713 "line which permits false sharing."); 1714 (*warning_cnt_ptr)++; 1715 } 1716 1717 if ((sizeof(SharedGlobals) - offset_hcSequence) < cache_line_size) { 1718 tty->print_cr("WARNING: the SharedGlobals.hcSequence field is closer " 1719 "to the struct end than a cache line which permits false " 1720 "sharing."); 1721 (*warning_cnt_ptr)++; 1722 } 1723 } 1724 } 1725 1726 #ifndef PRODUCT 1727 1728 // Verify all monitors in the monitor cache, the verification is weak. 1729 void ObjectSynchronizer::verify() { 1730 PaddedEnd<ObjectMonitor> * block = (PaddedEnd<ObjectMonitor> *)gBlockList; 1731 ObjectMonitor* mid; 1732 while (block) { 1733 assert(block->object() == CHAINMARKER, "must be a block header"); 1734 for (int i = 1; i < _BLOCKSIZE; i++) { 1735 mid = (ObjectMonitor *)(block + i); 1736 oop object = (oop) mid->object(); 1737 if (object != NULL) { 1738 mid->verify(); 1739 } 1740 } 1741 block = (PaddedEnd<ObjectMonitor> *) block->FreeNext; 1742 } 1743 } 1744 1745 // Check if monitor belongs to the monitor cache 1746 // The list is grow-only so it's *relatively* safe to traverse 1747 // the list of extant blocks without taking a lock. 1748 1749 int ObjectSynchronizer::verify_objmon_isinpool(ObjectMonitor *monitor) { 1750 PaddedEnd<ObjectMonitor> * block = (PaddedEnd<ObjectMonitor> *)gBlockList; 1751 1752 while (block) { 1753 assert(block->object() == CHAINMARKER, "must be a block header"); 1754 if (monitor > (ObjectMonitor *)&block[0] && 1755 monitor < (ObjectMonitor *)&block[_BLOCKSIZE]) { 1756 address mon = (address) monitor; 1757 address blk = (address) block; 1758 size_t diff = mon - blk; 1759 assert((diff % sizeof(PaddedEnd<ObjectMonitor>)) == 0, "check"); 1760 return 1; 1761 } 1762 block = (PaddedEnd<ObjectMonitor> *) block->FreeNext; 1763 } 1764 return 0; 1765 } 1766 1767 #endif