1 /* 2 * Copyright (c) 1998, 2019, 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 "logging/log.hpp" 28 #include "logging/logStream.hpp" 29 #include "jfr/jfrEvents.hpp" 30 #include "memory/allocation.inline.hpp" 31 #include "memory/metaspaceShared.hpp" 32 #include "memory/padded.hpp" 33 #include "memory/resourceArea.hpp" 34 #include "memory/universe.hpp" 35 #include "oops/markOop.hpp" 36 #include "oops/oop.inline.hpp" 37 #include "runtime/atomic.hpp" 38 #include "runtime/biasedLocking.hpp" 39 #include "runtime/handles.inline.hpp" 40 #include "runtime/interfaceSupport.inline.hpp" 41 #include "runtime/mutexLocker.hpp" 42 #include "runtime/objectMonitor.hpp" 43 #include "runtime/objectMonitor.inline.hpp" 44 #include "runtime/osThread.hpp" 45 #include "runtime/safepointVerifiers.hpp" 46 #include "runtime/sharedRuntime.hpp" 47 #include "runtime/stubRoutines.hpp" 48 #include "runtime/synchronizer.hpp" 49 #include "runtime/thread.inline.hpp" 50 #include "runtime/timer.hpp" 51 #include "runtime/vframe.hpp" 52 #include "runtime/vmThread.hpp" 53 #include "utilities/align.hpp" 54 #include "utilities/dtrace.hpp" 55 #include "utilities/events.hpp" 56 #include "utilities/preserveException.hpp" 57 58 // The "core" versions of monitor enter and exit reside in this file. 59 // The interpreter and compilers contain specialized transliterated 60 // variants of the enter-exit fast-path operations. See i486.ad fast_lock(), 61 // for instance. If you make changes here, make sure to modify the 62 // interpreter, and both C1 and C2 fast-path inline locking code emission. 63 // 64 // ----------------------------------------------------------------------------- 65 66 #ifdef DTRACE_ENABLED 67 68 // Only bother with this argument setup if dtrace is available 69 // TODO-FIXME: probes should not fire when caller is _blocked. assert() accordingly. 70 71 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread) \ 72 char* bytes = NULL; \ 73 int len = 0; \ 74 jlong jtid = SharedRuntime::get_java_tid(thread); \ 75 Symbol* klassname = ((oop)(obj))->klass()->name(); \ 76 if (klassname != NULL) { \ 77 bytes = (char*)klassname->bytes(); \ 78 len = klassname->utf8_length(); \ 79 } 80 81 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis) \ 82 { \ 83 if (DTraceMonitorProbes) { \ 84 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \ 85 HOTSPOT_MONITOR_WAIT(jtid, \ 86 (uintptr_t)(monitor), bytes, len, (millis)); \ 87 } \ 88 } 89 90 #define HOTSPOT_MONITOR_PROBE_notify HOTSPOT_MONITOR_NOTIFY 91 #define HOTSPOT_MONITOR_PROBE_notifyAll HOTSPOT_MONITOR_NOTIFYALL 92 #define HOTSPOT_MONITOR_PROBE_waited HOTSPOT_MONITOR_WAITED 93 94 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread) \ 95 { \ 96 if (DTraceMonitorProbes) { \ 97 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \ 98 HOTSPOT_MONITOR_PROBE_##probe(jtid, /* probe = waited */ \ 99 (uintptr_t)(monitor), bytes, len); \ 100 } \ 101 } 102 103 #else // ndef DTRACE_ENABLED 104 105 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon) {;} 106 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon) {;} 107 108 #endif // ndef DTRACE_ENABLED 109 110 // This exists only as a workaround of dtrace bug 6254741 111 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) { 112 DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr); 113 return 0; 114 } 115 116 #define NINFLATIONLOCKS 256 117 static volatile intptr_t gInflationLocks[NINFLATIONLOCKS]; 118 119 // global list of blocks of monitors 120 PaddedEnd<ObjectMonitor> * volatile ObjectSynchronizer::gBlockList = NULL; 121 // global monitor free list 122 ObjectMonitor * volatile ObjectSynchronizer::gFreeList = NULL; 123 // global monitor in-use list, for moribund threads, 124 // monitors they inflated need to be scanned for deflation 125 ObjectMonitor * volatile ObjectSynchronizer::gOmInUseList = NULL; 126 // count of entries in gOmInUseList 127 int ObjectSynchronizer::gOmInUseCount = 0; 128 bool volatile ObjectSynchronizer::_is_async_deflation_requested = false; 129 bool volatile ObjectSynchronizer::_is_special_deflation_requested = false; 130 jlong ObjectSynchronizer::_last_async_deflation_time_ns = 0; 131 132 static volatile intptr_t gListLock = 0; // protects global monitor lists 133 static volatile int gMonitorFreeCount = 0; // # on gFreeList 134 static volatile int gMonitorPopulation = 0; // # Extant -- in circulation 135 136 #define CHAINMARKER (cast_to_oop<intptr_t>(-1)) 137 138 139 // =====================> Quick functions 140 141 // The quick_* forms are special fast-path variants used to improve 142 // performance. In the simplest case, a "quick_*" implementation could 143 // simply return false, in which case the caller will perform the necessary 144 // state transitions and call the slow-path form. 145 // The fast-path is designed to handle frequently arising cases in an efficient 146 // manner and is just a degenerate "optimistic" variant of the slow-path. 147 // returns true -- to indicate the call was satisfied. 148 // returns false -- to indicate the call needs the services of the slow-path. 149 // A no-loitering ordinance is in effect for code in the quick_* family 150 // operators: safepoints or indefinite blocking (blocking that might span a 151 // safepoint) are forbidden. Generally the thread_state() is _in_Java upon 152 // entry. 153 // 154 // Consider: An interesting optimization is to have the JIT recognize the 155 // following common idiom: 156 // synchronized (someobj) { .... ; notify(); } 157 // That is, we find a notify() or notifyAll() call that immediately precedes 158 // the monitorexit operation. In that case the JIT could fuse the operations 159 // into a single notifyAndExit() runtime primitive. 160 161 bool ObjectSynchronizer::quick_notify(oopDesc * obj, Thread * self, bool all) { 162 assert(!SafepointSynchronize::is_at_safepoint(), "invariant"); 163 assert(self->is_Java_thread(), "invariant"); 164 assert(((JavaThread *) self)->thread_state() == _thread_in_Java, "invariant"); 165 NoSafepointVerifier nsv; 166 if (obj == NULL) return false; // slow-path for invalid obj 167 const markOop mark = obj->mark(); 168 169 if (mark->has_locker() && self->is_lock_owned((address)mark->locker())) { 170 // Degenerate notify 171 // stack-locked by caller so by definition the implied waitset is empty. 172 return true; 173 } 174 175 if (mark->has_monitor()) { 176 ObjectMonitor * const mon = mark->monitor(); 177 assert(oopDesc::equals((oop) mon->object(), obj), "invariant"); 178 if (mon->owner() != self) return false; // slow-path for IMS exception 179 180 if (mon->first_waiter() != NULL) { 181 // We have one or more waiters. Since this is an inflated monitor 182 // that we own, we can transfer one or more threads from the waitset 183 // to the entrylist here and now, avoiding the slow-path. 184 if (all) { 185 DTRACE_MONITOR_PROBE(notifyAll, mon, obj, self); 186 } else { 187 DTRACE_MONITOR_PROBE(notify, mon, obj, self); 188 } 189 int tally = 0; 190 do { 191 mon->INotify(self); 192 ++tally; 193 } while (mon->first_waiter() != NULL && all); 194 OM_PERFDATA_OP(Notifications, inc(tally)); 195 } 196 return true; 197 } 198 199 // biased locking and any other IMS exception states take the slow-path 200 return false; 201 } 202 203 204 // The LockNode emitted directly at the synchronization site would have 205 // been too big if it were to have included support for the cases of inflated 206 // recursive enter and exit, so they go here instead. 207 // Note that we can't safely call AsyncPrintJavaStack() from within 208 // quick_enter() as our thread state remains _in_Java. 209 210 bool ObjectSynchronizer::quick_enter(oop obj, Thread * Self, 211 BasicLock * lock) { 212 assert(!SafepointSynchronize::is_at_safepoint(), "invariant"); 213 assert(Self->is_Java_thread(), "invariant"); 214 assert(((JavaThread *) Self)->thread_state() == _thread_in_Java, "invariant"); 215 NoSafepointVerifier nsv; 216 if (obj == NULL) return false; // Need to throw NPE 217 218 while (true) { 219 const markOop mark = obj->mark(); 220 221 if (mark->has_monitor()) { 222 ObjectMonitorHandle omh; 223 if (!omh.save_om_ptr(obj, mark)) { 224 // Lost a race with async deflation so try again. 225 assert(AsyncDeflateIdleMonitors, "sanity check"); 226 continue; 227 } 228 ObjectMonitor * const m = omh.om_ptr(); 229 assert(oopDesc::equals((oop) m->object(), obj), "invariant"); 230 Thread * const owner = (Thread *) m->_owner; 231 232 // Lock contention and Transactional Lock Elision (TLE) diagnostics 233 // and observability 234 // Case: light contention possibly amenable to TLE 235 // Case: TLE inimical operations such as nested/recursive synchronization 236 237 if (owner == Self) { 238 m->_recursions++; 239 return true; 240 } 241 242 // This Java Monitor is inflated so obj's header will never be 243 // displaced to this thread's BasicLock. Make the displaced header 244 // non-NULL so this BasicLock is not seen as recursive nor as 245 // being locked. We do this unconditionally so that this thread's 246 // BasicLock cannot be mis-interpreted by any stack walkers. For 247 // performance reasons, stack walkers generally first check for 248 // Biased Locking in the object's header, the second check is for 249 // stack-locking in the object's header, the third check is for 250 // recursive stack-locking in the displaced header in the BasicLock, 251 // and last are the inflated Java Monitor (ObjectMonitor) checks. 252 lock->set_displaced_header(markOopDesc::unused_mark()); 253 254 if (owner == NULL && Atomic::replace_if_null(Self, &(m->_owner))) { 255 assert(m->_recursions == 0, "invariant"); 256 return true; 257 } 258 259 if (AsyncDeflateIdleMonitors && 260 Atomic::cmpxchg(Self, &m->_owner, DEFLATER_MARKER) == DEFLATER_MARKER) { 261 // The deflation protocol finished the first part (setting owner), 262 // but it failed the second part (making ref_count negative) and 263 // bailed. Or the ObjectMonitor was async deflated and reused. 264 // Acquired the monitor. 265 assert(m->_recursions == 0, "invariant"); 266 return true; 267 } 268 } 269 break; 270 } 271 272 // Note that we could inflate in quick_enter. 273 // This is likely a useful optimization 274 // Critically, in quick_enter() we must not: 275 // -- perform bias revocation, or 276 // -- block indefinitely, or 277 // -- reach a safepoint 278 279 return false; // revert to slow-path 280 } 281 282 // ----------------------------------------------------------------------------- 283 // Fast Monitor Enter/Exit 284 // This the fast monitor enter. The interpreter and compiler use 285 // some assembly copies of this code. Make sure update those code 286 // if the following function is changed. The implementation is 287 // extremely sensitive to race condition. Be careful. 288 289 void ObjectSynchronizer::fast_enter(Handle obj, BasicLock* lock, 290 bool attempt_rebias, TRAPS) { 291 if (UseBiasedLocking) { 292 if (!SafepointSynchronize::is_at_safepoint()) { 293 BiasedLocking::Condition cond = BiasedLocking::revoke_and_rebias(obj, attempt_rebias, THREAD); 294 if (cond == BiasedLocking::BIAS_REVOKED_AND_REBIASED) { 295 return; 296 } 297 } else { 298 assert(!attempt_rebias, "can not rebias toward VM thread"); 299 BiasedLocking::revoke_at_safepoint(obj); 300 } 301 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 302 } 303 304 slow_enter(obj, lock, THREAD); 305 } 306 307 void ObjectSynchronizer::fast_exit(oop object, BasicLock* lock, TRAPS) { 308 markOop mark = object->mark(); 309 // We cannot check for Biased Locking if we are racing an inflation. 310 assert(mark == markOopDesc::INFLATING() || 311 !mark->has_bias_pattern(), "should not see bias pattern here"); 312 313 markOop dhw = lock->displaced_header(); 314 if (dhw == NULL) { 315 // If the displaced header is NULL, then this exit matches up with 316 // a recursive enter. No real work to do here except for diagnostics. 317 #ifndef PRODUCT 318 if (mark != markOopDesc::INFLATING()) { 319 // Only do diagnostics if we are not racing an inflation. Simply 320 // exiting a recursive enter of a Java Monitor that is being 321 // inflated is safe; see the has_monitor() comment below. 322 assert(!mark->is_neutral(), "invariant"); 323 assert(!mark->has_locker() || 324 THREAD->is_lock_owned((address)mark->locker()), "invariant"); 325 if (mark->has_monitor()) { 326 // The BasicLock's displaced_header is marked as a recursive 327 // enter and we have an inflated Java Monitor (ObjectMonitor). 328 // This is a special case where the Java Monitor was inflated 329 // after this thread entered the stack-lock recursively. When a 330 // Java Monitor is inflated, we cannot safely walk the Java 331 // Monitor owner's stack and update the BasicLocks because a 332 // Java Monitor can be asynchronously inflated by a thread that 333 // does not own the Java Monitor. 334 ObjectMonitor * m = mark->monitor(); 335 assert(((oop)(m->object()))->mark() == mark, "invariant"); 336 assert(m->is_entered(THREAD), "invariant"); 337 } 338 } 339 #endif 340 return; 341 } 342 343 if (mark == (markOop) lock) { 344 // If the object is stack-locked by the current thread, try to 345 // swing the displaced header from the BasicLock back to the mark. 346 assert(dhw->is_neutral(), "invariant"); 347 if (object->cas_set_mark(dhw, mark) == mark) { 348 return; 349 } 350 } 351 352 // We have to take the slow-path of possible inflation and then exit. 353 ObjectMonitorHandle omh; 354 inflate(&omh, THREAD, object, inflate_cause_vm_internal); 355 omh.om_ptr()->exit(true, THREAD); 356 } 357 358 // ----------------------------------------------------------------------------- 359 // Interpreter/Compiler Slow Case 360 // This routine is used to handle interpreter/compiler slow case 361 // We don't need to use fast path here, because it must have been 362 // failed in the interpreter/compiler code. 363 void ObjectSynchronizer::slow_enter(Handle obj, BasicLock* lock, TRAPS) { 364 markOop mark = obj->mark(); 365 assert(!mark->has_bias_pattern(), "should not see bias pattern here"); 366 367 if (mark->is_neutral()) { 368 // Anticipate successful CAS -- the ST of the displaced mark must 369 // be visible <= the ST performed by the CAS. 370 lock->set_displaced_header(mark); 371 if (mark == obj()->cas_set_mark((markOop) lock, mark)) { 372 return; 373 } 374 // Fall through to inflate() ... 375 } else if (mark->has_locker() && 376 THREAD->is_lock_owned((address)mark->locker())) { 377 assert(lock != mark->locker(), "must not re-lock the same lock"); 378 assert(lock != (BasicLock*)obj->mark(), "don't relock with same BasicLock"); 379 lock->set_displaced_header(NULL); 380 return; 381 } 382 383 // The object header will never be displaced to this lock, 384 // so it does not matter what the value is, except that it 385 // must be non-zero to avoid looking like a re-entrant lock, 386 // and must not look locked either. 387 lock->set_displaced_header(markOopDesc::unused_mark()); 388 ObjectMonitorHandle omh; 389 inflate(&omh, THREAD, obj(), inflate_cause_monitor_enter); 390 omh.om_ptr()->enter(THREAD); 391 } 392 393 // This routine is used to handle interpreter/compiler slow case 394 // We don't need to use fast path here, because it must have 395 // failed in the interpreter/compiler code. Simply use the heavy 396 // weight monitor should be ok, unless someone find otherwise. 397 void ObjectSynchronizer::slow_exit(oop object, BasicLock* lock, TRAPS) { 398 fast_exit(object, lock, THREAD); 399 } 400 401 // ----------------------------------------------------------------------------- 402 // Class Loader support to workaround deadlocks on the class loader lock objects 403 // Also used by GC 404 // complete_exit()/reenter() are used to wait on a nested lock 405 // i.e. to give up an outer lock completely and then re-enter 406 // Used when holding nested locks - lock acquisition order: lock1 then lock2 407 // 1) complete_exit lock1 - saving recursion count 408 // 2) wait on lock2 409 // 3) when notified on lock2, unlock lock2 410 // 4) reenter lock1 with original recursion count 411 // 5) lock lock2 412 // NOTE: must use heavy weight monitor to handle complete_exit/reenter() 413 intptr_t ObjectSynchronizer::complete_exit(Handle obj, TRAPS) { 414 if (UseBiasedLocking) { 415 BiasedLocking::revoke_and_rebias(obj, false, THREAD); 416 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 417 } 418 419 ObjectMonitorHandle omh; 420 inflate(&omh, THREAD, obj(), inflate_cause_vm_internal); 421 intptr_t ret_code = omh.om_ptr()->complete_exit(THREAD); 422 return ret_code; 423 } 424 425 // NOTE: must use heavy weight monitor to handle complete_exit/reenter() 426 void ObjectSynchronizer::reenter(Handle obj, intptr_t recursion, 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 ObjectMonitorHandle omh; 433 inflate(&omh, THREAD, obj(), inflate_cause_vm_internal); 434 omh.om_ptr()->reenter(recursion, THREAD); 435 } 436 // ----------------------------------------------------------------------------- 437 // JNI locks on java objects 438 // NOTE: must use heavy weight monitor to handle jni monitor enter 439 void ObjectSynchronizer::jni_enter(Handle obj, TRAPS) { 440 // the current locking is from JNI instead of Java code 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 THREAD->set_current_pending_monitor_is_from_java(false); 446 ObjectMonitorHandle omh; 447 inflate(&omh, THREAD, obj(), inflate_cause_jni_enter); 448 omh.om_ptr()->enter(THREAD); 449 THREAD->set_current_pending_monitor_is_from_java(true); 450 } 451 452 // NOTE: must use heavy weight monitor to handle jni monitor exit 453 void ObjectSynchronizer::jni_exit(oop obj, Thread* THREAD) { 454 if (UseBiasedLocking) { 455 Handle h_obj(THREAD, obj); 456 BiasedLocking::revoke_and_rebias(h_obj, false, THREAD); 457 obj = h_obj(); 458 } 459 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 460 461 ObjectMonitorHandle omh; 462 inflate(&omh, THREAD, obj, inflate_cause_jni_exit); 463 ObjectMonitor * monitor = omh.om_ptr(); 464 // If this thread has locked the object, exit the monitor. Note: can't use 465 // monitor->check(CHECK); must exit even if an exception is pending. 466 if (monitor->check(THREAD)) { 467 monitor->exit(true, THREAD); 468 } 469 } 470 471 // ----------------------------------------------------------------------------- 472 // Internal VM locks on java objects 473 // standard constructor, allows locking failures 474 ObjectLocker::ObjectLocker(Handle obj, Thread* thread, bool doLock) { 475 _dolock = doLock; 476 _thread = thread; 477 debug_only(if (StrictSafepointChecks) _thread->check_for_valid_safepoint_state(false);) 478 _obj = obj; 479 480 if (_dolock) { 481 ObjectSynchronizer::fast_enter(_obj, &_lock, false, _thread); 482 } 483 } 484 485 ObjectLocker::~ObjectLocker() { 486 if (_dolock) { 487 ObjectSynchronizer::fast_exit(_obj(), &_lock, _thread); 488 } 489 } 490 491 492 // ----------------------------------------------------------------------------- 493 // Wait/Notify/NotifyAll 494 // NOTE: must use heavy weight monitor to handle wait() 495 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) { 496 if (UseBiasedLocking) { 497 BiasedLocking::revoke_and_rebias(obj, false, THREAD); 498 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 499 } 500 if (millis < 0) { 501 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative"); 502 } 503 ObjectMonitorHandle omh; 504 inflate(&omh, THREAD, obj(), inflate_cause_wait); 505 ObjectMonitor * monitor = omh.om_ptr(); 506 507 DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis); 508 monitor->wait(millis, true, THREAD); 509 510 // This dummy call is in place to get around dtrace bug 6254741. Once 511 // that's fixed we can uncomment the following line, remove the call 512 // and change this function back into a "void" func. 513 // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD); 514 int ret_code = dtrace_waited_probe(monitor, obj, THREAD); 515 return ret_code; 516 } 517 518 void ObjectSynchronizer::waitUninterruptibly(Handle obj, jlong millis, TRAPS) { 519 if (UseBiasedLocking) { 520 BiasedLocking::revoke_and_rebias(obj, false, THREAD); 521 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 522 } 523 if (millis < 0) { 524 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative"); 525 } 526 ObjectMonitorHandle omh; 527 inflate(&omh, THREAD, obj(), inflate_cause_wait); 528 omh.om_ptr()->wait(millis, false, THREAD); 529 } 530 531 void ObjectSynchronizer::notify(Handle obj, TRAPS) { 532 if (UseBiasedLocking) { 533 BiasedLocking::revoke_and_rebias(obj, false, THREAD); 534 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 535 } 536 537 markOop mark = obj->mark(); 538 if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) { 539 return; 540 } 541 ObjectMonitorHandle omh; 542 inflate(&omh, THREAD, obj(), inflate_cause_notify); 543 omh.om_ptr()->notify(THREAD); 544 } 545 546 // NOTE: see comment of notify() 547 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) { 548 if (UseBiasedLocking) { 549 BiasedLocking::revoke_and_rebias(obj, false, THREAD); 550 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 551 } 552 553 markOop mark = obj->mark(); 554 if (mark->has_locker() && THREAD->is_lock_owned((address)mark->locker())) { 555 return; 556 } 557 ObjectMonitorHandle omh; 558 inflate(&omh, THREAD, obj(), inflate_cause_notify); 559 omh.om_ptr()->notifyAll(THREAD); 560 } 561 562 // ----------------------------------------------------------------------------- 563 // Hash Code handling 564 // 565 // Performance concern: 566 // OrderAccess::storestore() calls release() which at one time stored 0 567 // into the global volatile OrderAccess::dummy variable. This store was 568 // unnecessary for correctness. Many threads storing into a common location 569 // causes considerable cache migration or "sloshing" on large SMP systems. 570 // As such, I avoided using OrderAccess::storestore(). In some cases 571 // OrderAccess::fence() -- which incurs local latency on the executing 572 // processor -- is a better choice as it scales on SMP systems. 573 // 574 // See http://blogs.oracle.com/dave/entry/biased_locking_in_hotspot for 575 // a discussion of coherency costs. Note that all our current reference 576 // platforms provide strong ST-ST order, so the issue is moot on IA32, 577 // x64, and SPARC. 578 // 579 // As a general policy we use "volatile" to control compiler-based reordering 580 // and explicit fences (barriers) to control for architectural reordering 581 // performed by the CPU(s) or platform. 582 583 struct SharedGlobals { 584 char _pad_prefix[DEFAULT_CACHE_LINE_SIZE]; 585 // These are highly shared mostly-read variables. 586 // To avoid false-sharing they need to be the sole occupants of a cache line. 587 volatile int stwRandom; 588 volatile int stwCycle; 589 DEFINE_PAD_MINUS_SIZE(1, DEFAULT_CACHE_LINE_SIZE, sizeof(volatile int) * 2); 590 // Hot RW variable -- Sequester to avoid false-sharing 591 volatile int hcSequence; 592 DEFINE_PAD_MINUS_SIZE(2, DEFAULT_CACHE_LINE_SIZE, sizeof(volatile int)); 593 }; 594 595 static SharedGlobals GVars; 596 static int MonitorScavengeThreshold = 1000000; 597 static volatile int ForceMonitorScavenge = 0; // Scavenge required and pending 598 599 static markOop ReadStableMark(oop obj) { 600 markOop mark = obj->mark(); 601 if (!mark->is_being_inflated()) { 602 return mark; // normal fast-path return 603 } 604 605 int its = 0; 606 for (;;) { 607 markOop mark = obj->mark(); 608 if (!mark->is_being_inflated()) { 609 return mark; // normal fast-path return 610 } 611 612 // The object is being inflated by some other thread. 613 // The caller of ReadStableMark() must wait for inflation to complete. 614 // Avoid live-lock 615 // TODO: consider calling SafepointSynchronize::do_call_back() while 616 // spinning to see if there's a safepoint pending. If so, immediately 617 // yielding or blocking would be appropriate. Avoid spinning while 618 // there is a safepoint pending. 619 // TODO: add inflation contention performance counters. 620 // TODO: restrict the aggregate number of spinners. 621 622 ++its; 623 if (its > 10000 || !os::is_MP()) { 624 if (its & 1) { 625 os::naked_yield(); 626 } else { 627 // Note that the following code attenuates the livelock problem but is not 628 // a complete remedy. A more complete solution would require that the inflating 629 // thread hold the associated inflation lock. The following code simply restricts 630 // the number of spinners to at most one. We'll have N-2 threads blocked 631 // on the inflationlock, 1 thread holding the inflation lock and using 632 // a yield/park strategy, and 1 thread in the midst of inflation. 633 // A more refined approach would be to change the encoding of INFLATING 634 // to allow encapsulation of a native thread pointer. Threads waiting for 635 // inflation to complete would use CAS to push themselves onto a singly linked 636 // list rooted at the markword. Once enqueued, they'd loop, checking a per-thread flag 637 // and calling park(). When inflation was complete the thread that accomplished inflation 638 // would detach the list and set the markword to inflated with a single CAS and 639 // then for each thread on the list, set the flag and unpark() the thread. 640 // This is conceptually similar to muxAcquire-muxRelease, except that muxRelease 641 // wakes at most one thread whereas we need to wake the entire list. 642 int ix = (cast_from_oop<intptr_t>(obj) >> 5) & (NINFLATIONLOCKS-1); 643 int YieldThenBlock = 0; 644 assert(ix >= 0 && ix < NINFLATIONLOCKS, "invariant"); 645 assert((NINFLATIONLOCKS & (NINFLATIONLOCKS-1)) == 0, "invariant"); 646 Thread::muxAcquire(gInflationLocks + ix, "gInflationLock"); 647 while (obj->mark() == markOopDesc::INFLATING()) { 648 // Beware: NakedYield() is advisory and has almost no effect on some platforms 649 // so we periodically call Self->_ParkEvent->park(1). 650 // We use a mixed spin/yield/block mechanism. 651 if ((YieldThenBlock++) >= 16) { 652 Thread::current()->_ParkEvent->park(1); 653 } else { 654 os::naked_yield(); 655 } 656 } 657 Thread::muxRelease(gInflationLocks + ix); 658 } 659 } else { 660 SpinPause(); // SMP-polite spinning 661 } 662 } 663 } 664 665 // hashCode() generation : 666 // 667 // Possibilities: 668 // * MD5Digest of {obj,stwRandom} 669 // * CRC32 of {obj,stwRandom} or any linear-feedback shift register function. 670 // * A DES- or AES-style SBox[] mechanism 671 // * One of the Phi-based schemes, such as: 672 // 2654435761 = 2^32 * Phi (golden ratio) 673 // HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stwRandom ; 674 // * A variation of Marsaglia's shift-xor RNG scheme. 675 // * (obj ^ stwRandom) is appealing, but can result 676 // in undesirable regularity in the hashCode values of adjacent objects 677 // (objects allocated back-to-back, in particular). This could potentially 678 // result in hashtable collisions and reduced hashtable efficiency. 679 // There are simple ways to "diffuse" the middle address bits over the 680 // generated hashCode values: 681 682 static inline intptr_t get_next_hash(Thread * Self, oop obj) { 683 intptr_t value = 0; 684 if (hashCode == 0) { 685 // This form uses global Park-Miller RNG. 686 // On MP system we'll have lots of RW access to a global, so the 687 // mechanism induces lots of coherency traffic. 688 value = os::random(); 689 } else if (hashCode == 1) { 690 // This variation has the property of being stable (idempotent) 691 // between STW operations. This can be useful in some of the 1-0 692 // synchronization schemes. 693 intptr_t addrBits = cast_from_oop<intptr_t>(obj) >> 3; 694 value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom; 695 } else if (hashCode == 2) { 696 value = 1; // for sensitivity testing 697 } else if (hashCode == 3) { 698 value = ++GVars.hcSequence; 699 } else if (hashCode == 4) { 700 value = cast_from_oop<intptr_t>(obj); 701 } else { 702 // Marsaglia's xor-shift scheme with thread-specific state 703 // This is probably the best overall implementation -- we'll 704 // likely make this the default in future releases. 705 unsigned t = Self->_hashStateX; 706 t ^= (t << 11); 707 Self->_hashStateX = Self->_hashStateY; 708 Self->_hashStateY = Self->_hashStateZ; 709 Self->_hashStateZ = Self->_hashStateW; 710 unsigned v = Self->_hashStateW; 711 v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)); 712 Self->_hashStateW = v; 713 value = v; 714 } 715 716 value &= markOopDesc::hash_mask; 717 if (value == 0) value = 0xBAD; 718 assert(value != markOopDesc::no_hash, "invariant"); 719 return value; 720 } 721 722 intptr_t ObjectSynchronizer::FastHashCode(Thread * Self, oop obj) { 723 if (UseBiasedLocking) { 724 // NOTE: many places throughout the JVM do not expect a safepoint 725 // to be taken here, in particular most operations on perm gen 726 // objects. However, we only ever bias Java instances and all of 727 // the call sites of identity_hash that might revoke biases have 728 // been checked to make sure they can handle a safepoint. The 729 // added check of the bias pattern is to avoid useless calls to 730 // thread-local storage. 731 if (obj->mark()->has_bias_pattern()) { 732 // Handle for oop obj in case of STW safepoint 733 Handle hobj(Self, obj); 734 // Relaxing assertion for bug 6320749. 735 assert(Universe::verify_in_progress() || 736 !SafepointSynchronize::is_at_safepoint(), 737 "biases should not be seen by VM thread here"); 738 BiasedLocking::revoke_and_rebias(hobj, false, JavaThread::current()); 739 obj = hobj(); 740 assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 741 } 742 } 743 744 // hashCode() is a heap mutator ... 745 // Relaxing assertion for bug 6320749. 746 assert(Universe::verify_in_progress() || DumpSharedSpaces || 747 !SafepointSynchronize::is_at_safepoint(), "invariant"); 748 assert(Universe::verify_in_progress() || DumpSharedSpaces || 749 Self->is_Java_thread() , "invariant"); 750 assert(Universe::verify_in_progress() || DumpSharedSpaces || 751 ((JavaThread *)Self)->thread_state() != _thread_blocked, "invariant"); 752 753 while (true) { 754 ObjectMonitor* monitor = NULL; 755 markOop temp, test; 756 intptr_t hash; 757 markOop mark = ReadStableMark(obj); 758 759 // object should remain ineligible for biased locking 760 assert(!mark->has_bias_pattern(), "invariant"); 761 762 if (mark->is_neutral()) { 763 hash = mark->hash(); // this is a normal header 764 if (hash != 0) { // if it has hash, just return it 765 return hash; 766 } 767 hash = get_next_hash(Self, obj); // allocate a new hash code 768 temp = mark->copy_set_hash(hash); // merge the hash code into header 769 // use (machine word version) atomic operation to install the hash 770 test = obj->cas_set_mark(temp, mark); 771 if (test == mark) { 772 return hash; 773 } 774 // If atomic operation failed, we must inflate the header 775 // into heavy weight monitor. We could add more code here 776 // for fast path, but it does not worth the complexity. 777 } else if (mark->has_monitor()) { 778 ObjectMonitorHandle omh; 779 if (!omh.save_om_ptr(obj, mark)) { 780 // Lost a race with async deflation so try again. 781 assert(AsyncDeflateIdleMonitors, "sanity check"); 782 continue; 783 } 784 monitor = omh.om_ptr(); 785 temp = monitor->header(); 786 assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp)); 787 hash = temp->hash(); 788 if (hash != 0) { 789 return hash; 790 } 791 // Skip to the following code to reduce code size 792 } else if (Self->is_lock_owned((address)mark->locker())) { 793 temp = mark->displaced_mark_helper(); // this is a lightweight monitor owned 794 assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp)); 795 hash = temp->hash(); // by current thread, check if the displaced 796 if (hash != 0) { // header contains hash code 797 return hash; 798 } 799 // WARNING: 800 // The displaced header in the BasicLock on a thread's stack 801 // is strictly immutable. It CANNOT be changed in ANY cases. 802 // So we have to inflate the stack lock into an ObjectMonitor 803 // even if the current thread owns the lock. The BasicLock on 804 // a thread's stack can be asynchronously read by other threads 805 // during an inflate() call so any change to that stack memory 806 // may not propagate to other threads correctly. 807 } 808 809 // Inflate the monitor to set hash code 810 ObjectMonitorHandle omh; 811 inflate(&omh, Self, obj, inflate_cause_hash_code); 812 monitor = omh.om_ptr(); 813 // Load displaced header and check it has hash code 814 mark = monitor->header(); 815 assert(mark->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(mark)); 816 hash = mark->hash(); 817 if (hash == 0) { 818 hash = get_next_hash(Self, obj); 819 temp = mark->copy_set_hash(hash); // merge hash code into header 820 assert(temp->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(temp)); 821 test = Atomic::cmpxchg(temp, monitor->header_addr(), mark); 822 if (test != mark) { 823 // The only non-deflation update to the ObjectMonitor's 824 // header/dmw field is to merge in the hash code. If someone 825 // adds a new usage of the header/dmw field, please update 826 // this code. 827 // ObjectMonitor::install_displaced_markword_in_object() 828 // does mark the header/dmw field as part of async deflation, 829 // but that protocol cannot happen now due to the 830 // ObjectMonitorHandle above. 831 hash = test->hash(); 832 assert(test->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(test)); 833 assert(hash != 0, "Trivial unexpected object/monitor header usage."); 834 } 835 } 836 // We finally get the hash 837 return hash; 838 } 839 } 840 841 // Deprecated -- use FastHashCode() instead. 842 843 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) { 844 return FastHashCode(Thread::current(), obj()); 845 } 846 847 848 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* thread, 849 Handle h_obj) { 850 if (UseBiasedLocking) { 851 BiasedLocking::revoke_and_rebias(h_obj, false, thread); 852 assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 853 } 854 855 assert(thread == JavaThread::current(), "Can only be called on current thread"); 856 oop obj = h_obj(); 857 858 while (true) { 859 markOop mark = ReadStableMark(obj); 860 861 // Uncontended case, header points to stack 862 if (mark->has_locker()) { 863 return thread->is_lock_owned((address)mark->locker()); 864 } 865 // Contended case, header points to ObjectMonitor (tagged pointer) 866 if (mark->has_monitor()) { 867 ObjectMonitorHandle omh; 868 if (!omh.save_om_ptr(obj, mark)) { 869 // Lost a race with async deflation so try again. 870 assert(AsyncDeflateIdleMonitors, "sanity check"); 871 continue; 872 } 873 bool ret_code = omh.om_ptr()->is_entered(thread) != 0; 874 return ret_code; 875 } 876 // Unlocked case, header in place 877 assert(mark->is_neutral(), "sanity check"); 878 return false; 879 } 880 } 881 882 // Be aware of this method could revoke bias of the lock object. 883 // This method queries the ownership of the lock handle specified by 'h_obj'. 884 // If the current thread owns the lock, it returns owner_self. If no 885 // thread owns the lock, it returns owner_none. Otherwise, it will return 886 // owner_other. 887 ObjectSynchronizer::LockOwnership ObjectSynchronizer::query_lock_ownership 888 (JavaThread *self, Handle h_obj) { 889 // The caller must beware this method can revoke bias, and 890 // revocation can result in a safepoint. 891 assert(!SafepointSynchronize::is_at_safepoint(), "invariant"); 892 assert(self->thread_state() != _thread_blocked, "invariant"); 893 894 // Possible mark states: neutral, biased, stack-locked, inflated 895 896 if (UseBiasedLocking && h_obj()->mark()->has_bias_pattern()) { 897 // CASE: biased 898 BiasedLocking::revoke_and_rebias(h_obj, false, self); 899 assert(!h_obj->mark()->has_bias_pattern(), 900 "biases should be revoked by now"); 901 } 902 903 assert(self == JavaThread::current(), "Can only be called on current thread"); 904 oop obj = h_obj(); 905 906 while (true) { 907 markOop mark = ReadStableMark(obj); 908 909 // CASE: stack-locked. Mark points to a BasicLock on the owner's stack. 910 if (mark->has_locker()) { 911 return self->is_lock_owned((address)mark->locker()) ? 912 owner_self : owner_other; 913 } 914 915 // CASE: inflated. Mark (tagged pointer) points to an ObjectMonitor. 916 // The Object:ObjectMonitor relationship is stable as long as we're 917 // not at a safepoint and AsyncDeflateIdleMonitors is false. 918 if (mark->has_monitor()) { 919 ObjectMonitorHandle omh; 920 if (!omh.save_om_ptr(obj, mark)) { 921 // Lost a race with async deflation so try again. 922 assert(AsyncDeflateIdleMonitors, "sanity check"); 923 continue; 924 } 925 ObjectMonitor * monitor = omh.om_ptr(); 926 void * owner = monitor->_owner; 927 if (owner == NULL) return owner_none; 928 return (owner == self || 929 self->is_lock_owned((address)owner)) ? owner_self : owner_other; 930 } 931 932 // CASE: neutral 933 assert(mark->is_neutral(), "sanity check"); 934 return owner_none; // it's unlocked 935 } 936 } 937 938 // FIXME: jvmti should call this 939 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) { 940 if (UseBiasedLocking) { 941 if (SafepointSynchronize::is_at_safepoint()) { 942 BiasedLocking::revoke_at_safepoint(h_obj); 943 } else { 944 BiasedLocking::revoke_and_rebias(h_obj, false, JavaThread::current()); 945 } 946 assert(!h_obj->mark()->has_bias_pattern(), "biases should be revoked by now"); 947 } 948 949 oop obj = h_obj(); 950 951 while (true) { 952 address owner = NULL; 953 markOop mark = ReadStableMark(obj); 954 955 // Uncontended case, header points to stack 956 if (mark->has_locker()) { 957 owner = (address) mark->locker(); 958 } 959 960 // Contended case, header points to ObjectMonitor (tagged pointer) 961 else if (mark->has_monitor()) { 962 ObjectMonitorHandle omh; 963 if (!omh.save_om_ptr(obj, mark)) { 964 // Lost a race with async deflation so try again. 965 assert(AsyncDeflateIdleMonitors, "sanity check"); 966 continue; 967 } 968 ObjectMonitor* monitor = omh.om_ptr(); 969 assert(monitor != NULL, "monitor should be non-null"); 970 owner = (address) monitor->owner(); 971 } 972 973 if (owner != NULL) { 974 // owning_thread_from_monitor_owner() may also return NULL here 975 return Threads::owning_thread_from_monitor_owner(t_list, owner); 976 } 977 978 // Unlocked case, header in place 979 // Cannot have assertion since this object may have been 980 // locked by another thread when reaching here. 981 // assert(mark->is_neutral(), "sanity check"); 982 983 return NULL; 984 } 985 } 986 987 // Visitors ... 988 989 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure) { 990 PaddedEnd<ObjectMonitor> * block = OrderAccess::load_acquire(&gBlockList); 991 while (block != NULL) { 992 assert(block->object() == CHAINMARKER, "must be a block header"); 993 for (int i = _BLOCKSIZE - 1; i > 0; i--) { 994 ObjectMonitor* mid = (ObjectMonitor *)(block + i); 995 if (mid->is_active()) { 996 ObjectMonitorHandle omh(mid); 997 998 if (mid->object() == NULL || 999 (AsyncDeflateIdleMonitors && mid->_owner == DEFLATER_MARKER)) { 1000 // Only process with closure if the object is set. 1001 // For async deflation, race here if monitor is not owned! 1002 // The above ref_count bump (in ObjectMonitorHandle ctr) 1003 // will cause subsequent async deflation to skip it. 1004 // However, previous or concurrent async deflation is a race. 1005 continue; 1006 } 1007 closure->do_monitor(mid); 1008 } 1009 } 1010 block = (PaddedEnd<ObjectMonitor> *)block->FreeNext; 1011 } 1012 } 1013 1014 // Get the next block in the block list. 1015 static inline PaddedEnd<ObjectMonitor>* next(PaddedEnd<ObjectMonitor>* block) { 1016 assert(block->object() == CHAINMARKER, "must be a block header"); 1017 block = (PaddedEnd<ObjectMonitor>*) block->FreeNext; 1018 assert(block == NULL || block->object() == CHAINMARKER, "must be a block header"); 1019 return block; 1020 } 1021 1022 static bool monitors_used_above_threshold() { 1023 if (gMonitorPopulation == 0) { 1024 return false; 1025 } 1026 if (MonitorUsedDeflationThreshold > 0) { 1027 int monitors_used = gMonitorPopulation - gMonitorFreeCount; 1028 int monitor_usage = (monitors_used * 100LL) / gMonitorPopulation; 1029 return monitor_usage > MonitorUsedDeflationThreshold; 1030 } 1031 return false; 1032 } 1033 1034 // Returns true if MonitorBound is set (> 0) and if the specified 1035 // cnt is > MonitorBound. Otherwise returns false. 1036 static bool is_MonitorBound_exceeded(const int cnt) { 1037 const int mx = MonitorBound; 1038 return mx > 0 && cnt > mx; 1039 } 1040 1041 bool ObjectSynchronizer::is_async_deflation_needed() { 1042 if (!AsyncDeflateIdleMonitors) { 1043 return false; 1044 } 1045 if (is_async_deflation_requested()) { 1046 // Async deflation request. 1047 return true; 1048 } 1049 if (AsyncDeflationInterval > 0 && 1050 time_since_last_async_deflation_ms() > AsyncDeflationInterval && 1051 monitors_used_above_threshold()) { 1052 // It's been longer than our specified deflate interval and there 1053 // are too many monitors in use. We don't deflate more frequently 1054 // than AsyncDeflationInterval (unless is_async_deflation_requested) 1055 // in order to not swamp the ServiceThread. 1056 _last_async_deflation_time_ns = os::javaTimeNanos(); 1057 return true; 1058 } 1059 if (is_MonitorBound_exceeded(gMonitorPopulation - gMonitorFreeCount)) { 1060 // Not enough ObjectMonitors on the global free list. 1061 return true; 1062 } 1063 return false; 1064 } 1065 1066 bool ObjectSynchronizer::is_safepoint_deflation_needed() { 1067 if (!AsyncDeflateIdleMonitors) { 1068 if (monitors_used_above_threshold()) { 1069 // Too many monitors in use. 1070 return true; 1071 } 1072 return false; 1073 } 1074 if (is_special_deflation_requested()) { 1075 // For AsyncDeflateIdleMonitors only do a safepoint deflation 1076 // if there is a special deflation request. 1077 return true; 1078 } 1079 return false; 1080 } 1081 1082 jlong ObjectSynchronizer::time_since_last_async_deflation_ms() { 1083 return (os::javaTimeNanos() - _last_async_deflation_time_ns) / (NANOUNITS / MILLIUNITS); 1084 } 1085 1086 void ObjectSynchronizer::oops_do(OopClosure* f) { 1087 // We only scan the global used list here (for moribund threads), and 1088 // the thread-local monitors in Thread::oops_do(). 1089 global_used_oops_do(f); 1090 } 1091 1092 void ObjectSynchronizer::global_used_oops_do(OopClosure* f) { 1093 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1094 list_oops_do(gOmInUseList, f); 1095 } 1096 1097 void ObjectSynchronizer::thread_local_used_oops_do(Thread* thread, OopClosure* f) { 1098 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1099 list_oops_do(thread->omInUseList, f); 1100 } 1101 1102 void ObjectSynchronizer::list_oops_do(ObjectMonitor* list, OopClosure* f) { 1103 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1104 ObjectMonitor* mid; 1105 for (mid = list; mid != NULL; mid = mid->FreeNext) { 1106 if (mid->object() != NULL) { 1107 f->do_oop((oop*)mid->object_addr()); 1108 } 1109 } 1110 } 1111 1112 1113 // ----------------------------------------------------------------------------- 1114 // ObjectMonitor Lifecycle 1115 // ----------------------- 1116 // Inflation unlinks monitors from the global gFreeList and 1117 // associates them with objects. Deflation -- which occurs at 1118 // STW-time -- disassociates idle monitors from objects. Such 1119 // scavenged monitors are returned to the gFreeList. 1120 // 1121 // The global list is protected by gListLock. All the critical sections 1122 // are short and operate in constant-time. 1123 // 1124 // ObjectMonitors reside in type-stable memory (TSM) and are immortal. 1125 // 1126 // Lifecycle: 1127 // -- unassigned and on the global free list 1128 // -- unassigned and on a thread's private omFreeList 1129 // -- assigned to an object. The object is inflated and the mark refers 1130 // to the objectmonitor. 1131 1132 1133 // Constraining monitor pool growth via MonitorBound ... 1134 // 1135 // If MonitorBound is not set (<= 0), MonitorBound checks are disabled. 1136 // 1137 // When safepoint deflation is being used (!AsyncDeflateIdleMonitors): 1138 // The monitor pool is grow-only. We scavenge at STW safepoint-time, but the 1139 // the rate of scavenging is driven primarily by GC. As such, we can find 1140 // an inordinate number of monitors in circulation. 1141 // To avoid that scenario we can artificially induce a STW safepoint 1142 // if the pool appears to be growing past some reasonable bound. 1143 // Generally we favor time in space-time tradeoffs, but as there's no 1144 // natural back-pressure on the # of extant monitors we need to impose some 1145 // type of limit. Beware that if MonitorBound is set to too low a value 1146 // we could just loop. In addition, if MonitorBound is set to a low value 1147 // we'll incur more safepoints, which are harmful to performance. 1148 // See also: GuaranteedSafepointInterval 1149 // 1150 // The current implementation uses asynchronous VM operations. 1151 // 1152 // When safepoint deflation is being used and MonitorBound is set, the 1153 // boundry applies to (gMonitorPopulation - gMonitorFreeCount), i.e., 1154 // if there are not enough ObjectMonitors on the global free list, then 1155 // a safepoint deflation is induced. Picking a good MonitorBound value 1156 // is non-trivial. 1157 // 1158 // When async deflation is being used: 1159 // The monitor pool is still grow-only. Async deflation is requested 1160 // by a safepoint's cleanup phase or by the ServiceThread at periodic 1161 // intervals when is_async_deflation_needed() returns true. In 1162 // addition to other policies that are checked, if there are not 1163 // enough ObjectMonitors on the global free list, then 1164 // is_async_deflation_needed() will return true. The ServiceThread 1165 // calls deflate_global_idle_monitors_using_JT() and also sets the 1166 // per-thread omShouldDeflateIdleMonitors flag as needed. 1167 1168 static void InduceScavenge(Thread * Self, const char * Whence) { 1169 assert(!AsyncDeflateIdleMonitors, "is not used by async deflation"); 1170 1171 // Induce STW safepoint to trim monitors 1172 // Ultimately, this results in a call to deflate_idle_monitors() in the near future. 1173 // More precisely, trigger an asynchronous STW safepoint as the number 1174 // of active monitors passes the specified threshold. 1175 // TODO: assert thread state is reasonable 1176 1177 if (ForceMonitorScavenge == 0 && Atomic::xchg (1, &ForceMonitorScavenge) == 0) { 1178 // Induce a 'null' safepoint to scavenge monitors 1179 // Must VM_Operation instance be heap allocated as the op will be enqueue and posted 1180 // to the VMthread and have a lifespan longer than that of this activation record. 1181 // The VMThread will delete the op when completed. 1182 VMThread::execute(new VM_ScavengeMonitors()); 1183 } 1184 } 1185 1186 ObjectMonitor* ObjectSynchronizer::omAlloc(Thread * Self, 1187 const InflateCause cause) { 1188 // A large MAXPRIVATE value reduces both list lock contention 1189 // and list coherency traffic, but also tends to increase the 1190 // number of objectMonitors in circulation as well as the STW 1191 // scavenge costs. As usual, we lean toward time in space-time 1192 // tradeoffs. 1193 const int MAXPRIVATE = 1024; 1194 1195 if (AsyncDeflateIdleMonitors) { 1196 JavaThread * jt = (JavaThread *)Self; 1197 if (jt->omShouldDeflateIdleMonitors && jt->omInUseCount > 0 && 1198 cause != inflate_cause_vm_internal) { 1199 // Deflate any per-thread idle monitors for this JavaThread if 1200 // this is not an internal inflation; internal inflations can 1201 // occur in places where it is not safe to pause for a safepoint. 1202 // Clean up your own mess (Gibbs Rule 45). Otherwise, skip this 1203 // deflation. deflate_global_idle_monitors_using_JT() is called 1204 // by the ServiceThread. Per-thread async deflation is triggered 1205 // by the ServiceThread via omShouldDeflateIdleMonitors. 1206 debug_only(jt->check_for_valid_safepoint_state(false);) 1207 ObjectSynchronizer::deflate_per_thread_idle_monitors_using_JT(); 1208 } 1209 } 1210 1211 stringStream ss; 1212 for (;;) { 1213 ObjectMonitor * m; 1214 1215 // 1: try to allocate from the thread's local omFreeList. 1216 // Threads will attempt to allocate first from their local list, then 1217 // from the global list, and only after those attempts fail will the thread 1218 // attempt to instantiate new monitors. Thread-local free lists take 1219 // heat off the gListLock and improve allocation latency, as well as reducing 1220 // coherency traffic on the shared global list. 1221 m = Self->omFreeList; 1222 if (m != NULL) { 1223 Self->omFreeList = m->FreeNext; 1224 Self->omFreeCount--; 1225 guarantee(m->object() == NULL, "invariant"); 1226 m->set_allocation_state(ObjectMonitor::New); 1227 m->FreeNext = Self->omInUseList; 1228 Self->omInUseList = m; 1229 Self->omInUseCount++; 1230 return m; 1231 } 1232 1233 // 2: try to allocate from the global gFreeList 1234 // CONSIDER: use muxTry() instead of muxAcquire(). 1235 // If the muxTry() fails then drop immediately into case 3. 1236 // If we're using thread-local free lists then try 1237 // to reprovision the caller's free list. 1238 if (gFreeList != NULL) { 1239 // Reprovision the thread's omFreeList. 1240 // Use bulk transfers to reduce the allocation rate and heat 1241 // on various locks. 1242 Thread::muxAcquire(&gListLock, "omAlloc(1)"); 1243 for (int i = Self->omFreeProvision; --i >= 0 && gFreeList != NULL;) { 1244 gMonitorFreeCount--; 1245 ObjectMonitor * take = gFreeList; 1246 gFreeList = take->FreeNext; 1247 guarantee(take->object() == NULL, "invariant"); 1248 if (AsyncDeflateIdleMonitors) { 1249 // We allowed 3 field values to linger during async deflation. 1250 // We clear header and restore ref_count here, but we leave 1251 // owner == DEFLATER_MARKER so the simple C2 ObjectMonitor 1252 // enter optimization can no longer race with async deflation 1253 // and reuse. 1254 take->_header = NULL; 1255 if (take->ref_count() < 0) { 1256 // Add back max_jint to restore the ref_count field to its 1257 // proper value. 1258 Atomic::add(max_jint, &take->_ref_count); 1259 1260 assert(take->ref_count() >= 0, "must not be negative: ref_count=%d", 1261 take->ref_count()); 1262 } 1263 } 1264 take->Recycle(); 1265 assert(take->is_free(), "invariant"); 1266 omRelease(Self, take, false); 1267 } 1268 Thread::muxRelease(&gListLock); 1269 Self->omFreeProvision += 1 + (Self->omFreeProvision/2); 1270 if (Self->omFreeProvision > MAXPRIVATE) Self->omFreeProvision = MAXPRIVATE; 1271 1272 if (!AsyncDeflateIdleMonitors && 1273 is_MonitorBound_exceeded(gMonitorPopulation - gMonitorFreeCount)) { 1274 // Not enough ObjectMonitors on the global free list. 1275 // We can't safely induce a STW safepoint from omAlloc() as our thread 1276 // state may not be appropriate for such activities and callers may hold 1277 // naked oops, so instead we defer the action. 1278 InduceScavenge(Self, "omAlloc"); 1279 } 1280 continue; 1281 } 1282 1283 // 3: allocate a block of new ObjectMonitors 1284 // Both the local and global free lists are empty -- resort to malloc(). 1285 // In the current implementation objectMonitors are TSM - immortal. 1286 // Ideally, we'd write "new ObjectMonitor[_BLOCKSIZE], but we want 1287 // each ObjectMonitor to start at the beginning of a cache line, 1288 // so we use align_up(). 1289 // A better solution would be to use C++ placement-new. 1290 // BEWARE: As it stands currently, we don't run the ctors! 1291 assert(_BLOCKSIZE > 1, "invariant"); 1292 size_t neededsize = sizeof(PaddedEnd<ObjectMonitor>) * _BLOCKSIZE; 1293 PaddedEnd<ObjectMonitor> * temp; 1294 size_t aligned_size = neededsize + (DEFAULT_CACHE_LINE_SIZE - 1); 1295 void* real_malloc_addr = (void *)NEW_C_HEAP_ARRAY(char, aligned_size, 1296 mtInternal); 1297 temp = (PaddedEnd<ObjectMonitor> *) 1298 align_up(real_malloc_addr, DEFAULT_CACHE_LINE_SIZE); 1299 1300 // NOTE: (almost) no way to recover if allocation failed. 1301 // We might be able to induce a STW safepoint and scavenge enough 1302 // objectMonitors to permit progress. 1303 if (temp == NULL) { 1304 vm_exit_out_of_memory(neededsize, OOM_MALLOC_ERROR, 1305 "Allocate ObjectMonitors"); 1306 } 1307 (void)memset((void *) temp, 0, neededsize); 1308 1309 // Format the block. 1310 // initialize the linked list, each monitor points to its next 1311 // forming the single linked free list, the very first monitor 1312 // will points to next block, which forms the block list. 1313 // The trick of using the 1st element in the block as gBlockList 1314 // linkage should be reconsidered. A better implementation would 1315 // look like: class Block { Block * next; int N; ObjectMonitor Body [N] ; } 1316 1317 for (int i = 1; i < _BLOCKSIZE; i++) { 1318 temp[i].FreeNext = (ObjectMonitor *)&temp[i+1]; 1319 assert(temp[i].is_free(), "invariant"); 1320 } 1321 1322 // terminate the last monitor as the end of list 1323 temp[_BLOCKSIZE - 1].FreeNext = NULL; 1324 1325 // Element [0] is reserved for global list linkage 1326 temp[0].set_object(CHAINMARKER); 1327 1328 // Consider carving out this thread's current request from the 1329 // block in hand. This avoids some lock traffic and redundant 1330 // list activity. 1331 1332 // Acquire the gListLock to manipulate gBlockList and gFreeList. 1333 // An Oyama-Taura-Yonezawa scheme might be more efficient. 1334 Thread::muxAcquire(&gListLock, "omAlloc(2)"); 1335 gMonitorPopulation += _BLOCKSIZE-1; 1336 gMonitorFreeCount += _BLOCKSIZE-1; 1337 1338 // Add the new block to the list of extant blocks (gBlockList). 1339 // The very first objectMonitor in a block is reserved and dedicated. 1340 // It serves as blocklist "next" linkage. 1341 temp[0].FreeNext = gBlockList; 1342 // There are lock-free uses of gBlockList so make sure that 1343 // the previous stores happen before we update gBlockList. 1344 OrderAccess::release_store(&gBlockList, temp); 1345 1346 // Add the new string of objectMonitors to the global free list 1347 temp[_BLOCKSIZE - 1].FreeNext = gFreeList; 1348 gFreeList = temp + 1; 1349 Thread::muxRelease(&gListLock); 1350 } 1351 } 1352 1353 // Place "m" on the caller's private per-thread omFreeList. 1354 // In practice there's no need to clamp or limit the number of 1355 // monitors on a thread's omFreeList as the only time we'll call 1356 // omRelease is to return a monitor to the free list after a CAS 1357 // attempt failed. This doesn't allow unbounded #s of monitors to 1358 // accumulate on a thread's free list. 1359 // 1360 // Key constraint: all ObjectMonitors on a thread's free list and the global 1361 // free list must have their object field set to null. This prevents the 1362 // scavenger -- deflate_monitor_list() or deflate_monitor_list_using_JT() 1363 // -- from reclaiming them while we are trying to release them. 1364 1365 void ObjectSynchronizer::omRelease(Thread * Self, ObjectMonitor * m, 1366 bool fromPerThreadAlloc) { 1367 guarantee(m->header() == NULL, "invariant"); 1368 guarantee(m->object() == NULL, "invariant"); 1369 stringStream ss; 1370 guarantee((m->is_busy() | m->_recursions) == 0, "freeing in-use monitor: " 1371 "%s, recursions=" INTPTR_FORMAT, m->is_busy_to_string(&ss), 1372 m->_recursions); 1373 m->set_allocation_state(ObjectMonitor::Free); 1374 // Remove from omInUseList 1375 if (fromPerThreadAlloc) { 1376 ObjectMonitor* cur_mid_in_use = NULL; 1377 bool extracted = false; 1378 for (ObjectMonitor* mid = Self->omInUseList; mid != NULL; cur_mid_in_use = mid, mid = mid->FreeNext) { 1379 if (m == mid) { 1380 // extract from per-thread in-use list 1381 if (mid == Self->omInUseList) { 1382 Self->omInUseList = mid->FreeNext; 1383 } else if (cur_mid_in_use != NULL) { 1384 cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list 1385 } 1386 extracted = true; 1387 Self->omInUseCount--; 1388 break; 1389 } 1390 } 1391 assert(extracted, "Should have extracted from in-use list"); 1392 } 1393 1394 // FreeNext is used for both omInUseList and omFreeList, so clear old before setting new 1395 m->FreeNext = Self->omFreeList; 1396 guarantee(m->is_free(), "invariant"); 1397 Self->omFreeList = m; 1398 Self->omFreeCount++; 1399 } 1400 1401 // Return the monitors of a moribund thread's local free list to 1402 // the global free list. Typically a thread calls omFlush() when 1403 // it's dying. We could also consider having the VM thread steal 1404 // monitors from threads that have not run java code over a few 1405 // consecutive STW safepoints. Relatedly, we might decay 1406 // omFreeProvision at STW safepoints. 1407 // 1408 // Also return the monitors of a moribund thread's omInUseList to 1409 // a global gOmInUseList under the global list lock so these 1410 // will continue to be scanned. 1411 // 1412 // We currently call omFlush() from Threads::remove() _before the thread 1413 // has been excised from the thread list and is no longer a mutator. 1414 // This means that omFlush() cannot run concurrently with a safepoint and 1415 // interleave with the deflate_idle_monitors scavenge operator. In particular, 1416 // this ensures that the thread's monitors are scanned by a GC safepoint, 1417 // either via Thread::oops_do() (if safepoint happens before omFlush()) or via 1418 // ObjectSynchronizer::oops_do() (if it happens after omFlush() and the thread's 1419 // monitors have been transferred to the global in-use list). 1420 // 1421 // With AsyncDeflateIdleMonitors, deflate_global_idle_monitors_using_JT() 1422 // and deflate_per_thread_idle_monitors_using_JT() (in another thread) can 1423 // run at the same time as omFlush() so we have to be careful. 1424 1425 void ObjectSynchronizer::omFlush(Thread * Self) { 1426 ObjectMonitor * list = Self->omFreeList; // Null-terminated SLL 1427 ObjectMonitor * tail = NULL; 1428 int tally = 0; 1429 if (list != NULL) { 1430 ObjectMonitor * s; 1431 // The thread is going away. Set 'tail' to the last per-thread free 1432 // monitor which will be linked to gFreeList below under the gListLock. 1433 stringStream ss; 1434 for (s = list; s != NULL; s = s->FreeNext) { 1435 tally++; 1436 tail = s; 1437 guarantee(s->object() == NULL, "invariant"); 1438 guarantee(!s->is_busy(), "must be !is_busy: %s", s->is_busy_to_string(&ss)); 1439 } 1440 guarantee(tail != NULL, "invariant"); 1441 ADIM_guarantee(Self->omFreeCount == tally, "free-count off"); 1442 Self->omFreeList = NULL; 1443 Self->omFreeCount = 0; 1444 } 1445 1446 ObjectMonitor * inUseList = Self->omInUseList; 1447 ObjectMonitor * inUseTail = NULL; 1448 int inUseTally = 0; 1449 if (inUseList != NULL) { 1450 ObjectMonitor *cur_om; 1451 // The thread is going away, however the omInUseList inflated 1452 // monitors may still be in-use by other threads. 1453 // Link them to inUseTail, which will be linked into the global in-use list 1454 // gOmInUseList below, under the gListLock 1455 for (cur_om = inUseList; cur_om != NULL; cur_om = cur_om->FreeNext) { 1456 inUseTail = cur_om; 1457 inUseTally++; 1458 ADIM_guarantee(cur_om->is_active(), "invariant"); 1459 } 1460 guarantee(inUseTail != NULL, "invariant"); 1461 ADIM_guarantee(Self->omInUseCount == inUseTally, "in-use count off"); 1462 Self->omInUseList = NULL; 1463 Self->omInUseCount = 0; 1464 } 1465 1466 Thread::muxAcquire(&gListLock, "omFlush"); 1467 if (tail != NULL) { 1468 tail->FreeNext = gFreeList; 1469 gFreeList = list; 1470 gMonitorFreeCount += tally; 1471 } 1472 1473 if (inUseTail != NULL) { 1474 inUseTail->FreeNext = gOmInUseList; 1475 gOmInUseList = inUseList; 1476 gOmInUseCount += inUseTally; 1477 } 1478 1479 Thread::muxRelease(&gListLock); 1480 1481 LogStreamHandle(Debug, monitorinflation) lsh_debug; 1482 LogStreamHandle(Info, monitorinflation) lsh_info; 1483 LogStream * ls = NULL; 1484 if (log_is_enabled(Debug, monitorinflation)) { 1485 ls = &lsh_debug; 1486 } else if ((tally != 0 || inUseTally != 0) && 1487 log_is_enabled(Info, monitorinflation)) { 1488 ls = &lsh_info; 1489 } 1490 if (ls != NULL) { 1491 ls->print_cr("omFlush: jt=" INTPTR_FORMAT ", free_monitor_tally=%d" 1492 ", in_use_monitor_tally=%d" ", omFreeProvision=%d", 1493 p2i(Self), tally, inUseTally, Self->omFreeProvision); 1494 } 1495 } 1496 1497 static void post_monitor_inflate_event(EventJavaMonitorInflate* event, 1498 const oop obj, 1499 ObjectSynchronizer::InflateCause cause) { 1500 assert(event != NULL, "invariant"); 1501 assert(event->should_commit(), "invariant"); 1502 event->set_monitorClass(obj->klass()); 1503 event->set_address((uintptr_t)(void*)obj); 1504 event->set_cause((u1)cause); 1505 event->commit(); 1506 } 1507 1508 // Fast path code shared by multiple functions 1509 void ObjectSynchronizer::inflate_helper(ObjectMonitorHandle * omh_p, oop obj) { 1510 while (true) { 1511 markOop mark = obj->mark(); 1512 if (mark->has_monitor()) { 1513 if (!omh_p->save_om_ptr(obj, mark)) { 1514 // Lost a race with async deflation so try again. 1515 assert(AsyncDeflateIdleMonitors, "sanity check"); 1516 continue; 1517 } 1518 ObjectMonitor * monitor = omh_p->om_ptr(); 1519 assert(ObjectSynchronizer::verify_objmon_isinpool(monitor), "monitor is invalid"); 1520 markOop dmw = monitor->header(); 1521 assert(dmw->is_neutral(), "sanity check: header=" INTPTR_FORMAT, p2i(dmw)); 1522 return; 1523 } 1524 inflate(omh_p, Thread::current(), obj, inflate_cause_vm_internal); 1525 return; 1526 } 1527 } 1528 1529 void ObjectSynchronizer::inflate(ObjectMonitorHandle * omh_p, Thread * Self, 1530 oop object, const InflateCause cause) { 1531 // Inflate mutates the heap ... 1532 // Relaxing assertion for bug 6320749. 1533 assert(Universe::verify_in_progress() || 1534 !SafepointSynchronize::is_at_safepoint(), "invariant"); 1535 1536 EventJavaMonitorInflate event; 1537 1538 for (;;) { 1539 const markOop mark = object->mark(); 1540 assert(!mark->has_bias_pattern(), "invariant"); 1541 1542 // The mark can be in one of the following states: 1543 // * Inflated - just return 1544 // * Stack-locked - coerce it to inflated 1545 // * INFLATING - busy wait for conversion to complete 1546 // * Neutral - aggressively inflate the object. 1547 // * BIASED - Illegal. We should never see this 1548 1549 // CASE: inflated 1550 if (mark->has_monitor()) { 1551 if (!omh_p->save_om_ptr(object, mark)) { 1552 // Lost a race with async deflation so try again. 1553 assert(AsyncDeflateIdleMonitors, "sanity check"); 1554 continue; 1555 } 1556 ObjectMonitor * inf = omh_p->om_ptr(); 1557 markOop dmw = inf->header(); 1558 assert(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw)); 1559 assert(oopDesc::equals((oop) inf->object(), object), "invariant"); 1560 assert(ObjectSynchronizer::verify_objmon_isinpool(inf), "monitor is invalid"); 1561 return; 1562 } 1563 1564 // CASE: inflation in progress - inflating over a stack-lock. 1565 // Some other thread is converting from stack-locked to inflated. 1566 // Only that thread can complete inflation -- other threads must wait. 1567 // The INFLATING value is transient. 1568 // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish. 1569 // We could always eliminate polling by parking the thread on some auxiliary list. 1570 if (mark == markOopDesc::INFLATING()) { 1571 ReadStableMark(object); 1572 continue; 1573 } 1574 1575 // CASE: stack-locked 1576 // Could be stack-locked either by this thread or by some other thread. 1577 // 1578 // Note that we allocate the objectmonitor speculatively, _before_ attempting 1579 // to install INFLATING into the mark word. We originally installed INFLATING, 1580 // allocated the objectmonitor, and then finally STed the address of the 1581 // objectmonitor into the mark. This was correct, but artificially lengthened 1582 // the interval in which INFLATED appeared in the mark, thus increasing 1583 // the odds of inflation contention. 1584 // 1585 // We now use per-thread private objectmonitor free lists. 1586 // These list are reprovisioned from the global free list outside the 1587 // critical INFLATING...ST interval. A thread can transfer 1588 // multiple objectmonitors en-mass from the global free list to its local free list. 1589 // This reduces coherency traffic and lock contention on the global free list. 1590 // Using such local free lists, it doesn't matter if the omAlloc() call appears 1591 // before or after the CAS(INFLATING) operation. 1592 // See the comments in omAlloc(). 1593 1594 LogStreamHandle(Trace, monitorinflation) lsh; 1595 1596 if (mark->has_locker()) { 1597 ObjectMonitor * m; 1598 if (!AsyncDeflateIdleMonitors || cause == inflate_cause_vm_internal) { 1599 // If !AsyncDeflateIdleMonitors or if an internal inflation, then 1600 // we won't stop for a potential safepoint in omAlloc. 1601 m = omAlloc(Self, cause); 1602 } else { 1603 // If AsyncDeflateIdleMonitors and not an internal inflation, then 1604 // we may stop for a safepoint in omAlloc() so protect object. 1605 Handle h_obj(Self, object); 1606 m = omAlloc(Self, cause); 1607 object = h_obj(); // Refresh object. 1608 } 1609 // Optimistically prepare the objectmonitor - anticipate successful CAS 1610 // We do this before the CAS in order to minimize the length of time 1611 // in which INFLATING appears in the mark. 1612 m->Recycle(); 1613 m->_Responsible = NULL; 1614 m->_SpinDuration = ObjectMonitor::Knob_SpinLimit; // Consider: maintain by type/class 1615 1616 markOop cmp = object->cas_set_mark(markOopDesc::INFLATING(), mark); 1617 if (cmp != mark) { 1618 omRelease(Self, m, true); 1619 continue; // Interference -- just retry 1620 } 1621 1622 // We've successfully installed INFLATING (0) into the mark-word. 1623 // This is the only case where 0 will appear in a mark-word. 1624 // Only the singular thread that successfully swings the mark-word 1625 // to 0 can perform (or more precisely, complete) inflation. 1626 // 1627 // Why do we CAS a 0 into the mark-word instead of just CASing the 1628 // mark-word from the stack-locked value directly to the new inflated state? 1629 // Consider what happens when a thread unlocks a stack-locked object. 1630 // It attempts to use CAS to swing the displaced header value from the 1631 // on-stack basiclock back into the object header. Recall also that the 1632 // header value (hash code, etc) can reside in (a) the object header, or 1633 // (b) a displaced header associated with the stack-lock, or (c) a displaced 1634 // header in an objectMonitor. The inflate() routine must copy the header 1635 // value from the basiclock on the owner's stack to the objectMonitor, all 1636 // the while preserving the hashCode stability invariants. If the owner 1637 // decides to release the lock while the value is 0, the unlock will fail 1638 // and control will eventually pass from slow_exit() to inflate. The owner 1639 // will then spin, waiting for the 0 value to disappear. Put another way, 1640 // the 0 causes the owner to stall if the owner happens to try to 1641 // drop the lock (restoring the header from the basiclock to the object) 1642 // while inflation is in-progress. This protocol avoids races that might 1643 // would otherwise permit hashCode values to change or "flicker" for an object. 1644 // Critically, while object->mark is 0 mark->displaced_mark_helper() is stable. 1645 // 0 serves as a "BUSY" inflate-in-progress indicator. 1646 1647 1648 // fetch the displaced mark from the owner's stack. 1649 // The owner can't die or unwind past the lock while our INFLATING 1650 // object is in the mark. Furthermore the owner can't complete 1651 // an unlock on the object, either. 1652 markOop dmw = mark->displaced_mark_helper(); 1653 // Catch if the object's header is not neutral (not locked and 1654 // not marked is what we care about here). 1655 ADIM_guarantee(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw)); 1656 1657 // Setup monitor fields to proper values -- prepare the monitor 1658 m->set_header(dmw); 1659 1660 // Optimization: if the mark->locker stack address is associated 1661 // with this thread we could simply set m->_owner = Self. 1662 // Note that a thread can inflate an object 1663 // that it has stack-locked -- as might happen in wait() -- directly 1664 // with CAS. That is, we can avoid the xchg-NULL .... ST idiom. 1665 m->set_owner(mark->locker()); 1666 m->set_object(object); 1667 // TODO-FIXME: assert BasicLock->dhw != 0. 1668 1669 omh_p->set_om_ptr(m); 1670 assert(m->is_new(), "freshly allocated monitor must be new"); 1671 m->set_allocation_state(ObjectMonitor::Old); 1672 1673 // Must preserve store ordering. The monitor state must 1674 // be stable at the time of publishing the monitor address. 1675 guarantee(object->mark() == markOopDesc::INFLATING(), "invariant"); 1676 object->release_set_mark(markOopDesc::encode(m)); 1677 1678 // Hopefully the performance counters are allocated on distinct cache lines 1679 // to avoid false sharing on MP systems ... 1680 OM_PERFDATA_OP(Inflations, inc()); 1681 if (log_is_enabled(Trace, monitorinflation)) { 1682 ResourceMark rm(Self); 1683 lsh.print_cr("inflate(has_locker): object=" INTPTR_FORMAT ", mark=" 1684 INTPTR_FORMAT ", type='%s'", p2i(object), 1685 p2i(object->mark()), object->klass()->external_name()); 1686 } 1687 if (event.should_commit()) { 1688 post_monitor_inflate_event(&event, object, cause); 1689 } 1690 ADIM_guarantee(!m->is_free(), "inflated monitor to be returned cannot be free"); 1691 return; 1692 } 1693 1694 // CASE: neutral 1695 // TODO-FIXME: for entry we currently inflate and then try to CAS _owner. 1696 // If we know we're inflating for entry it's better to inflate by swinging a 1697 // pre-locked objectMonitor pointer into the object header. A successful 1698 // CAS inflates the object *and* confers ownership to the inflating thread. 1699 // In the current implementation we use a 2-step mechanism where we CAS() 1700 // to inflate and then CAS() again to try to swing _owner from NULL to Self. 1701 // An inflateTry() method that we could call from fast_enter() and slow_enter() 1702 // would be useful. 1703 1704 // Catch if the object's header is not neutral (not locked and 1705 // not marked is what we care about here). 1706 ADIM_guarantee(mark->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(mark)); 1707 ObjectMonitor * m; 1708 if (!AsyncDeflateIdleMonitors || cause == inflate_cause_vm_internal) { 1709 // If !AsyncDeflateIdleMonitors or if an internal inflation, then 1710 // we won't stop for a potential safepoint in omAlloc. 1711 m = omAlloc(Self, cause); 1712 } else { 1713 // If AsyncDeflateIdleMonitors and not an internal inflation, then 1714 // we may stop for a safepoint in omAlloc() so protect object. 1715 Handle h_obj(Self, object); 1716 m = omAlloc(Self, cause); 1717 object = h_obj(); // Refresh object. 1718 } 1719 // prepare m for installation - set monitor to initial state 1720 m->Recycle(); 1721 m->set_header(mark); 1722 // If we leave _owner == DEFLATER_MARKER here, then the simple C2 1723 // ObjectMonitor enter optimization can no longer race with async 1724 // deflation and reuse. 1725 m->set_object(object); 1726 m->_Responsible = NULL; 1727 m->_SpinDuration = ObjectMonitor::Knob_SpinLimit; // consider: keep metastats by type/class 1728 1729 omh_p->set_om_ptr(m); 1730 assert(m->is_new(), "freshly allocated monitor must be new"); 1731 m->set_allocation_state(ObjectMonitor::Old); 1732 1733 if (object->cas_set_mark(markOopDesc::encode(m), mark) != mark) { 1734 m->set_header(NULL); 1735 m->set_object(NULL); 1736 m->Recycle(); 1737 omh_p->set_om_ptr(NULL); 1738 // omRelease() will reset the allocation state 1739 omRelease(Self, m, true); 1740 m = NULL; 1741 continue; 1742 // interference - the markword changed - just retry. 1743 // The state-transitions are one-way, so there's no chance of 1744 // live-lock -- "Inflated" is an absorbing state. 1745 } 1746 1747 // Hopefully the performance counters are allocated on distinct 1748 // cache lines to avoid false sharing on MP systems ... 1749 OM_PERFDATA_OP(Inflations, inc()); 1750 if (log_is_enabled(Trace, monitorinflation)) { 1751 ResourceMark rm(Self); 1752 lsh.print_cr("inflate(neutral): object=" INTPTR_FORMAT ", mark=" 1753 INTPTR_FORMAT ", type='%s'", p2i(object), 1754 p2i(object->mark()), object->klass()->external_name()); 1755 } 1756 if (event.should_commit()) { 1757 post_monitor_inflate_event(&event, object, cause); 1758 } 1759 ADIM_guarantee(!m->is_free(), "inflated monitor to be returned cannot be free"); 1760 return; 1761 } 1762 } 1763 1764 1765 // We maintain a list of in-use monitors for each thread. 1766 // 1767 // For safepoint based deflation: 1768 // deflate_thread_local_monitors() scans a single thread's in-use list, while 1769 // deflate_idle_monitors() scans only a global list of in-use monitors which 1770 // is populated only as a thread dies (see omFlush()). 1771 // 1772 // These operations are called at all safepoints, immediately after mutators 1773 // are stopped, but before any objects have moved. Collectively they traverse 1774 // the population of in-use monitors, deflating where possible. The scavenged 1775 // monitors are returned to the global monitor free list. 1776 // 1777 // Beware that we scavenge at *every* stop-the-world point. Having a large 1778 // number of monitors in-use could negatively impact performance. We also want 1779 // to minimize the total # of monitors in circulation, as they incur a small 1780 // footprint penalty. 1781 // 1782 // Perversely, the heap size -- and thus the STW safepoint rate -- 1783 // typically drives the scavenge rate. Large heaps can mean infrequent GC, 1784 // which in turn can mean large(r) numbers of ObjectMonitors in circulation. 1785 // This is an unfortunate aspect of this design. 1786 // 1787 // For async deflation: 1788 // If a special deflation request is made, then the safepoint based 1789 // deflation mechanism is used. Otherwise, an async deflation request 1790 // is registered with the ServiceThread and it is notified. 1791 1792 void ObjectSynchronizer::do_safepoint_work(DeflateMonitorCounters* _counters) { 1793 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1794 1795 // The per-thread in-use lists are handled in 1796 // ParallelSPCleanupThreadClosure::do_thread(). 1797 1798 if (!AsyncDeflateIdleMonitors || is_special_deflation_requested()) { 1799 // Use the older mechanism for the global in-use list or if a 1800 // special deflation has been requested before the safepoint. 1801 ObjectSynchronizer::deflate_idle_monitors(_counters); 1802 return; 1803 } 1804 1805 log_debug(monitorinflation)("requesting async deflation of idle monitors."); 1806 // Request deflation of idle monitors by the ServiceThread: 1807 set_is_async_deflation_requested(true); 1808 MonitorLocker ml(Service_lock, Mutex::_no_safepoint_check_flag); 1809 ml.notify_all(); 1810 } 1811 1812 // Deflate a single monitor if not in-use 1813 // Return true if deflated, false if in-use 1814 bool ObjectSynchronizer::deflate_monitor(ObjectMonitor* mid, oop obj, 1815 ObjectMonitor** freeHeadp, 1816 ObjectMonitor** freeTailp) { 1817 bool deflated; 1818 // Normal case ... The monitor is associated with obj. 1819 const markOop mark = obj->mark(); 1820 guarantee(mark == markOopDesc::encode(mid), "should match: mark=" 1821 INTPTR_FORMAT ", encoded mid=" INTPTR_FORMAT, p2i(mark), 1822 p2i(markOopDesc::encode(mid))); 1823 // Make sure that mark->monitor() and markOopDesc::encode() agree: 1824 guarantee(mark->monitor() == mid, "should match: monitor()=" INTPTR_FORMAT 1825 ", mid=" INTPTR_FORMAT, p2i(mark->monitor()), p2i(mid)); 1826 const markOop dmw = mid->header(); 1827 guarantee(dmw->is_neutral(), "invariant: header=" INTPTR_FORMAT, p2i(dmw)); 1828 1829 if (mid->is_busy() || mid->ref_count() != 0) { 1830 // Easy checks are first - the ObjectMonitor is busy or ObjectMonitor* 1831 // is in use so no deflation. 1832 deflated = false; 1833 } else { 1834 // Deflate the monitor if it is no longer being used 1835 // It's idle - scavenge and return to the global free list 1836 // plain old deflation ... 1837 if (log_is_enabled(Trace, monitorinflation)) { 1838 ResourceMark rm; 1839 log_trace(monitorinflation)("deflate_monitor: " 1840 "object=" INTPTR_FORMAT ", mark=" 1841 INTPTR_FORMAT ", type='%s'", p2i(obj), 1842 p2i(mark), obj->klass()->external_name()); 1843 } 1844 1845 // Restore the header back to obj 1846 obj->release_set_mark(dmw); 1847 if (AsyncDeflateIdleMonitors) { 1848 // clear() expects the owner field to be NULL and we won't race 1849 // with the simple C2 ObjectMonitor enter optimization since 1850 // we're at a safepoint. 1851 mid->set_owner(NULL); 1852 } 1853 mid->clear(); 1854 1855 assert(mid->object() == NULL, "invariant: object=" INTPTR_FORMAT, 1856 p2i(mid->object())); 1857 assert(mid->is_free(), "invariant"); 1858 1859 // Move the object to the working free list defined by freeHeadp, freeTailp 1860 if (*freeHeadp == NULL) *freeHeadp = mid; 1861 if (*freeTailp != NULL) { 1862 ObjectMonitor * prevtail = *freeTailp; 1863 assert(prevtail->FreeNext == NULL, "cleaned up deflated?"); 1864 prevtail->FreeNext = mid; 1865 } 1866 *freeTailp = mid; 1867 deflated = true; 1868 } 1869 return deflated; 1870 } 1871 1872 // Deflate the specified ObjectMonitor if not in-use using a JavaThread. 1873 // Returns true if it was deflated and false otherwise. 1874 // 1875 // The async deflation protocol sets owner to DEFLATER_MARKER and 1876 // makes ref_count negative as signals to contending threads that 1877 // an async deflation is in progress. There are a number of checks 1878 // as part of the protocol to make sure that the calling thread has 1879 // not lost the race to a contending thread or to a thread that just 1880 // wants to use the ObjectMonitor*. 1881 // 1882 // The ObjectMonitor has been successfully async deflated when: 1883 // (owner == DEFLATER_MARKER && ref_count < 0) 1884 // Contending threads or ObjectMonitor* using threads that see those 1885 // values know to retry their operation. 1886 // 1887 bool ObjectSynchronizer::deflate_monitor_using_JT(ObjectMonitor* mid, 1888 ObjectMonitor** freeHeadp, 1889 ObjectMonitor** freeTailp) { 1890 assert(AsyncDeflateIdleMonitors, "sanity check"); 1891 assert(Thread::current()->is_Java_thread(), "precondition"); 1892 // A newly allocated ObjectMonitor should not be seen here so we 1893 // avoid an endless inflate/deflate cycle. 1894 assert(mid->is_old(), "must be old: allocation_state=%d", 1895 (int) mid->allocation_state()); 1896 1897 if (mid->is_busy() || mid->ref_count() != 0) { 1898 // Easy checks are first - the ObjectMonitor is busy or ObjectMonitor* 1899 // is in use so no deflation. 1900 return false; 1901 } 1902 1903 if (Atomic::replace_if_null(DEFLATER_MARKER, &(mid->_owner))) { 1904 // ObjectMonitor is not owned by another thread. Our setting 1905 // owner to DEFLATER_MARKER forces any contending thread through 1906 // the slow path. This is just the first part of the async 1907 // deflation dance. 1908 1909 if (mid->_contentions != 0 || mid->_waiters != 0) { 1910 // Another thread has raced to enter the ObjectMonitor after 1911 // mid->is_busy() above or has already entered and waited on 1912 // it which makes it busy so no deflation. Restore owner to 1913 // NULL if it is still DEFLATER_MARKER. 1914 Atomic::cmpxchg((void*)NULL, &mid->_owner, DEFLATER_MARKER); 1915 return false; 1916 } 1917 1918 if (Atomic::cmpxchg(-max_jint, &mid->_ref_count, (jint)0) == 0) { 1919 // Make ref_count negative to force any contending threads or 1920 // ObjectMonitor* using threads to retry. This is the second 1921 // part of the async deflation dance. 1922 1923 if (mid->owner_is_DEFLATER_MARKER()) { 1924 // If owner is still DEFLATER_MARKER, then we have successfully 1925 // signaled any contending threads to retry. If it is not, then we 1926 // have lost the race to an entering thread and the ObjectMonitor 1927 // is now busy. This is the third and final part of the async 1928 // deflation dance. 1929 // Note: This owner check solves the ABA problem with ref_count 1930 // where another thread acquired the ObjectMonitor, finished 1931 // using it and restored the ref_count to zero. 1932 1933 // Sanity checks for the races: 1934 guarantee(mid->_contentions == 0, "must be 0: contentions=%d", 1935 mid->_contentions); 1936 guarantee(mid->_waiters == 0, "must be 0: waiters=%d", mid->_waiters); 1937 guarantee(mid->_cxq == NULL, "must be no contending threads: cxq=" 1938 INTPTR_FORMAT, p2i(mid->_cxq)); 1939 guarantee(mid->_EntryList == NULL, 1940 "must be no entering threads: EntryList=" INTPTR_FORMAT, 1941 p2i(mid->_EntryList)); 1942 1943 const oop obj = (oop) mid->object(); 1944 if (log_is_enabled(Trace, monitorinflation)) { 1945 ResourceMark rm; 1946 log_trace(monitorinflation)("deflate_monitor_using_JT: " 1947 "object=" INTPTR_FORMAT ", mark=" 1948 INTPTR_FORMAT ", type='%s'", 1949 p2i(obj), p2i(obj->mark()), 1950 obj->klass()->external_name()); 1951 } 1952 1953 // Install the old mark word if nobody else has already done it. 1954 mid->install_displaced_markword_in_object(obj); 1955 mid->clear_using_JT(); 1956 1957 assert(mid->object() == NULL, "must be NULL: object=" INTPTR_FORMAT, 1958 p2i(mid->object())); 1959 assert(mid->is_free(), "must be free: allocation_state=%d", 1960 (int) mid->allocation_state()); 1961 1962 // Move the deflated ObjectMonitor to the working free list 1963 // defined by freeHeadp and freeTailp. 1964 if (*freeHeadp == NULL) { 1965 // First one on the list. 1966 *freeHeadp = mid; 1967 } 1968 if (*freeTailp != NULL) { 1969 // We append to the list so the caller can use mid->FreeNext 1970 // to fix the linkages in its context. 1971 ObjectMonitor * prevtail = *freeTailp; 1972 // Should have been cleaned up by the caller: 1973 assert(prevtail->FreeNext == NULL, "must be NULL: FreeNext=" 1974 INTPTR_FORMAT, p2i(prevtail->FreeNext)); 1975 prevtail->FreeNext = mid; 1976 } 1977 *freeTailp = mid; 1978 1979 // At this point, mid->FreeNext still refers to its current 1980 // value and another ObjectMonitor's FreeNext field still 1981 // refers to this ObjectMonitor. Those linkages have to be 1982 // cleaned up by the caller who has the complete context. 1983 1984 // We leave owner == DEFLATER_MARKER and ref_count < 0 1985 // to force any racing threads to retry. 1986 return true; // Success, ObjectMonitor has been deflated. 1987 } 1988 1989 // The owner was changed from DEFLATER_MARKER so we lost the 1990 // race since the ObjectMonitor is now busy. 1991 1992 // Add back max_jint to restore the ref_count field to its 1993 // proper value (which may not be what we saw above): 1994 Atomic::add(max_jint, &mid->_ref_count); 1995 1996 assert(mid->ref_count() >= 0, "must not be negative: ref_count=%d", 1997 mid->ref_count()); 1998 return false; 1999 } 2000 2001 // The ref_count was no longer 0 so we lost the race since the 2002 // ObjectMonitor is now busy or the ObjectMonitor* is now is use. 2003 // Restore owner to NULL if it is still DEFLATER_MARKER: 2004 Atomic::cmpxchg((void*)NULL, &mid->_owner, DEFLATER_MARKER); 2005 } 2006 2007 // The owner field is no longer NULL so we lost the race since the 2008 // ObjectMonitor is now busy. 2009 return false; 2010 } 2011 2012 // Walk a given monitor list, and deflate idle monitors 2013 // The given list could be a per-thread list or a global list 2014 // Caller acquires gListLock as needed. 2015 // 2016 // In the case of parallel processing of thread local monitor lists, 2017 // work is done by Threads::parallel_threads_do() which ensures that 2018 // each Java thread is processed by exactly one worker thread, and 2019 // thus avoid conflicts that would arise when worker threads would 2020 // process the same monitor lists concurrently. 2021 // 2022 // See also ParallelSPCleanupTask and 2023 // SafepointSynchronize::do_cleanup_tasks() in safepoint.cpp and 2024 // Threads::parallel_java_threads_do() in thread.cpp. 2025 int ObjectSynchronizer::deflate_monitor_list(ObjectMonitor** listHeadp, 2026 ObjectMonitor** freeHeadp, 2027 ObjectMonitor** freeTailp) { 2028 ObjectMonitor* mid; 2029 ObjectMonitor* next; 2030 ObjectMonitor* cur_mid_in_use = NULL; 2031 int deflated_count = 0; 2032 2033 for (mid = *listHeadp; mid != NULL;) { 2034 oop obj = (oop) mid->object(); 2035 if (obj != NULL && deflate_monitor(mid, obj, freeHeadp, freeTailp)) { 2036 // if deflate_monitor succeeded, 2037 // extract from per-thread in-use list 2038 if (mid == *listHeadp) { 2039 *listHeadp = mid->FreeNext; 2040 } else if (cur_mid_in_use != NULL) { 2041 cur_mid_in_use->FreeNext = mid->FreeNext; // maintain the current thread in-use list 2042 } 2043 next = mid->FreeNext; 2044 mid->FreeNext = NULL; // This mid is current tail in the freeHeadp list 2045 mid = next; 2046 deflated_count++; 2047 } else { 2048 cur_mid_in_use = mid; 2049 mid = mid->FreeNext; 2050 } 2051 } 2052 return deflated_count; 2053 } 2054 2055 // Walk a given ObjectMonitor list and deflate idle ObjectMonitors using 2056 // a JavaThread. Returns the number of deflated ObjectMonitors. The given 2057 // list could be a per-thread in-use list or the global in-use list. 2058 // Caller acquires gListLock as appropriate. If a safepoint has started, 2059 // then we save state via savedMidInUsep and return to the caller to 2060 // honor the safepoint. 2061 // 2062 int ObjectSynchronizer::deflate_monitor_list_using_JT(ObjectMonitor** listHeadp, 2063 ObjectMonitor** freeHeadp, 2064 ObjectMonitor** freeTailp, 2065 ObjectMonitor** savedMidInUsep) { 2066 assert(AsyncDeflateIdleMonitors, "sanity check"); 2067 assert(Thread::current()->is_Java_thread(), "precondition"); 2068 2069 ObjectMonitor* mid; 2070 ObjectMonitor* next; 2071 ObjectMonitor* cur_mid_in_use = NULL; 2072 int deflated_count = 0; 2073 2074 if (*savedMidInUsep == NULL) { 2075 // No saved state so start at the beginning. 2076 mid = *listHeadp; 2077 } else { 2078 // We're restarting after a safepoint so restore the necessary state 2079 // before we resume. 2080 cur_mid_in_use = *savedMidInUsep; 2081 mid = cur_mid_in_use->FreeNext; 2082 } 2083 while (mid != NULL) { 2084 // Only try to deflate if there is an associated Java object and if 2085 // mid is old (is not newly allocated and is not newly freed). 2086 if (mid->object() != NULL && mid->is_old() && 2087 deflate_monitor_using_JT(mid, freeHeadp, freeTailp)) { 2088 // Deflation succeeded so update the in-use list. 2089 if (mid == *listHeadp) { 2090 *listHeadp = mid->FreeNext; 2091 } else if (cur_mid_in_use != NULL) { 2092 // Maintain the current in-use list. 2093 cur_mid_in_use->FreeNext = mid->FreeNext; 2094 } 2095 next = mid->FreeNext; 2096 mid->FreeNext = NULL; 2097 // At this point mid is disconnected from the in-use list 2098 // and is the current tail in the freeHeadp list. 2099 mid = next; 2100 deflated_count++; 2101 } else { 2102 // mid is considered in-use if it does not have an associated 2103 // Java object or mid is not old or deflation did not succeed. 2104 // A mid->is_new() node can be seen here when it is freshly 2105 // returned by omAlloc() (and skips the deflation code path). 2106 // A mid->is_old() node can be seen here when deflation failed. 2107 // A mid->is_free() node can be seen here when a fresh node from 2108 // omAlloc() is released by omRelease() due to losing the race 2109 // in inflate(). 2110 2111 cur_mid_in_use = mid; 2112 mid = mid->FreeNext; 2113 2114 if (SafepointSynchronize::is_synchronizing() && 2115 cur_mid_in_use != *listHeadp && cur_mid_in_use->is_old()) { 2116 // If a safepoint has started and cur_mid_in_use is not the list 2117 // head and is old, then it is safe to use as saved state. Return 2118 // to the caller so gListLock can be dropped as appropriate 2119 // before blocking. 2120 *savedMidInUsep = cur_mid_in_use; 2121 return deflated_count; 2122 } 2123 } 2124 } 2125 // We finished the list without a safepoint starting so there's 2126 // no need to save state. 2127 *savedMidInUsep = NULL; 2128 return deflated_count; 2129 } 2130 2131 void ObjectSynchronizer::prepare_deflate_idle_monitors(DeflateMonitorCounters* counters) { 2132 counters->nInuse = 0; // currently associated with objects 2133 counters->nInCirculation = 0; // extant 2134 counters->nScavenged = 0; // reclaimed (global and per-thread) 2135 counters->perThreadScavenged = 0; // per-thread scavenge total 2136 counters->perThreadTimes = 0.0; // per-thread scavenge times 2137 } 2138 2139 void ObjectSynchronizer::deflate_idle_monitors(DeflateMonitorCounters* counters) { 2140 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 2141 2142 if (AsyncDeflateIdleMonitors) { 2143 // Nothing to do when global idle ObjectMonitors are deflated using 2144 // a JavaThread unless a special deflation has been requested. 2145 if (!is_special_deflation_requested()) { 2146 return; 2147 } 2148 } 2149 2150 bool deflated = false; 2151 2152 ObjectMonitor * freeHeadp = NULL; // Local SLL of scavenged monitors 2153 ObjectMonitor * freeTailp = NULL; 2154 elapsedTimer timer; 2155 2156 if (log_is_enabled(Info, monitorinflation)) { 2157 timer.start(); 2158 } 2159 2160 // Prevent omFlush from changing mids in Thread dtor's during deflation 2161 // And in case the vm thread is acquiring a lock during a safepoint 2162 // See e.g. 6320749 2163 Thread::muxAcquire(&gListLock, "deflate_idle_monitors"); 2164 2165 // Note: the thread-local monitors lists get deflated in 2166 // a separate pass. See deflate_thread_local_monitors(). 2167 2168 // For moribund threads, scan gOmInUseList 2169 int deflated_count = 0; 2170 if (gOmInUseList) { 2171 counters->nInCirculation += gOmInUseCount; 2172 deflated_count = deflate_monitor_list((ObjectMonitor **)&gOmInUseList, &freeHeadp, &freeTailp); 2173 gOmInUseCount -= deflated_count; 2174 counters->nScavenged += deflated_count; 2175 counters->nInuse += gOmInUseCount; 2176 } 2177 2178 // Move the scavenged monitors back to the global free list. 2179 if (freeHeadp != NULL) { 2180 guarantee(freeTailp != NULL && counters->nScavenged > 0, "invariant"); 2181 assert(freeTailp->FreeNext == NULL, "invariant"); 2182 // constant-time list splice - prepend scavenged segment to gFreeList 2183 freeTailp->FreeNext = gFreeList; 2184 gFreeList = freeHeadp; 2185 } 2186 Thread::muxRelease(&gListLock); 2187 timer.stop(); 2188 2189 LogStreamHandle(Debug, monitorinflation) lsh_debug; 2190 LogStreamHandle(Info, monitorinflation) lsh_info; 2191 LogStream * ls = NULL; 2192 if (log_is_enabled(Debug, monitorinflation)) { 2193 ls = &lsh_debug; 2194 } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) { 2195 ls = &lsh_info; 2196 } 2197 if (ls != NULL) { 2198 ls->print_cr("deflating global idle monitors, %3.7f secs, %d monitors", timer.seconds(), deflated_count); 2199 } 2200 } 2201 2202 // Deflate global idle ObjectMonitors using a JavaThread. 2203 // 2204 void ObjectSynchronizer::deflate_global_idle_monitors_using_JT() { 2205 assert(AsyncDeflateIdleMonitors, "sanity check"); 2206 assert(Thread::current()->is_Java_thread(), "precondition"); 2207 JavaThread * self = JavaThread::current(); 2208 2209 deflate_common_idle_monitors_using_JT(true /* is_global */, self); 2210 } 2211 2212 // Deflate per-thread idle ObjectMonitors using a JavaThread. 2213 // 2214 void ObjectSynchronizer::deflate_per_thread_idle_monitors_using_JT() { 2215 assert(AsyncDeflateIdleMonitors, "sanity check"); 2216 assert(Thread::current()->is_Java_thread(), "precondition"); 2217 JavaThread * self = JavaThread::current(); 2218 2219 self->omShouldDeflateIdleMonitors = false; 2220 2221 deflate_common_idle_monitors_using_JT(false /* !is_global */, self); 2222 } 2223 2224 // Deflate global or per-thread idle ObjectMonitors using a JavaThread. 2225 // 2226 void ObjectSynchronizer::deflate_common_idle_monitors_using_JT(bool is_global, JavaThread * self) { 2227 int deflated_count = 0; 2228 ObjectMonitor * freeHeadp = NULL; // Local SLL of scavenged ObjectMonitors 2229 ObjectMonitor * freeTailp = NULL; 2230 ObjectMonitor * savedMidInUsep = NULL; 2231 elapsedTimer timer; 2232 2233 if (log_is_enabled(Info, monitorinflation)) { 2234 timer.start(); 2235 } 2236 2237 if (is_global) { 2238 Thread::muxAcquire(&gListLock, "deflate_global_idle_monitors_using_JT(1)"); 2239 OM_PERFDATA_OP(MonExtant, set_value(gOmInUseCount)); 2240 } else { 2241 OM_PERFDATA_OP(MonExtant, inc(self->omInUseCount)); 2242 } 2243 2244 do { 2245 int local_deflated_count; 2246 if (is_global) { 2247 local_deflated_count = deflate_monitor_list_using_JT((ObjectMonitor **)&gOmInUseList, &freeHeadp, &freeTailp, &savedMidInUsep); 2248 gOmInUseCount -= local_deflated_count; 2249 } else { 2250 local_deflated_count = deflate_monitor_list_using_JT(self->omInUseList_addr(), &freeHeadp, &freeTailp, &savedMidInUsep); 2251 self->omInUseCount -= local_deflated_count; 2252 } 2253 deflated_count += local_deflated_count; 2254 2255 if (freeHeadp != NULL) { 2256 // Move the scavenged ObjectMonitors to the global free list. 2257 guarantee(freeTailp != NULL && local_deflated_count > 0, "freeTailp=" INTPTR_FORMAT ", local_deflated_count=%d", p2i(freeTailp), local_deflated_count); 2258 assert(freeTailp->FreeNext == NULL, "invariant"); 2259 2260 if (!is_global) { 2261 Thread::muxAcquire(&gListLock, "deflate_per_thread_idle_monitors_using_JT(2)"); 2262 } 2263 // Constant-time list splice - prepend scavenged segment to gFreeList. 2264 freeTailp->FreeNext = gFreeList; 2265 gFreeList = freeHeadp; 2266 2267 gMonitorFreeCount += local_deflated_count; 2268 OM_PERFDATA_OP(Deflations, inc(local_deflated_count)); 2269 if (!is_global) { 2270 Thread::muxRelease(&gListLock); 2271 } 2272 } 2273 2274 if (savedMidInUsep != NULL) { 2275 // deflate_monitor_list_using_JT() detected a safepoint starting. 2276 if (is_global) { 2277 Thread::muxRelease(&gListLock); 2278 } 2279 timer.stop(); 2280 { 2281 if (is_global) { 2282 log_debug(monitorinflation)("pausing deflation of global idle monitors for a safepoint."); 2283 } else { 2284 log_debug(monitorinflation)("jt=" INTPTR_FORMAT ": pausing deflation of per-thread idle monitors for a safepoint.", p2i(self)); 2285 } 2286 assert(SafepointSynchronize::is_synchronizing(), "sanity check"); 2287 ThreadBlockInVM blocker(self); 2288 } 2289 // Prepare for another loop after the safepoint. 2290 freeHeadp = NULL; 2291 freeTailp = NULL; 2292 if (log_is_enabled(Info, monitorinflation)) { 2293 timer.start(); 2294 } 2295 if (is_global) { 2296 Thread::muxAcquire(&gListLock, "deflate_global_idle_monitors_using_JT(3)"); 2297 } 2298 } 2299 } while (savedMidInUsep != NULL); 2300 if (is_global) { 2301 Thread::muxRelease(&gListLock); 2302 } 2303 timer.stop(); 2304 2305 LogStreamHandle(Debug, monitorinflation) lsh_debug; 2306 LogStreamHandle(Info, monitorinflation) lsh_info; 2307 LogStream * ls = NULL; 2308 if (log_is_enabled(Debug, monitorinflation)) { 2309 ls = &lsh_debug; 2310 } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) { 2311 ls = &lsh_info; 2312 } 2313 if (ls != NULL) { 2314 if (is_global) { 2315 ls->print_cr("async-deflating global idle monitors, %3.7f secs, %d monitors", timer.seconds(), deflated_count); 2316 } else { 2317 ls->print_cr("jt=" INTPTR_FORMAT ": async-deflating per-thread idle monitors, %3.7f secs, %d monitors", p2i(self), timer.seconds(), deflated_count); 2318 } 2319 } 2320 } 2321 2322 void ObjectSynchronizer::finish_deflate_idle_monitors(DeflateMonitorCounters* counters) { 2323 // Report the cumulative time for deflating each thread's idle 2324 // monitors. Note: if the work is split among more than one 2325 // worker thread, then the reported time will likely be more 2326 // than a beginning to end measurement of the phase. 2327 // Note: AsyncDeflateIdleMonitors only deflates per-thread idle 2328 // monitors at a safepoint when a special deflation has been requested. 2329 log_info(safepoint, cleanup)("deflating per-thread idle monitors, %3.7f secs, monitors=%d", counters->perThreadTimes, counters->perThreadScavenged); 2330 2331 bool needs_special_deflation = is_special_deflation_requested(); 2332 if (!AsyncDeflateIdleMonitors || needs_special_deflation) { 2333 // AsyncDeflateIdleMonitors does not use these counters unless 2334 // there is a special deflation request. 2335 2336 gMonitorFreeCount += counters->nScavenged; 2337 2338 OM_PERFDATA_OP(Deflations, inc(counters->nScavenged)); 2339 OM_PERFDATA_OP(MonExtant, set_value(counters->nInCirculation)); 2340 } 2341 2342 if (log_is_enabled(Debug, monitorinflation)) { 2343 // exit_globals()'s call to audit_and_print_stats() is done 2344 // at the Info level. 2345 ObjectSynchronizer::audit_and_print_stats(false /* on_exit */); 2346 } else if (log_is_enabled(Info, monitorinflation)) { 2347 Thread::muxAcquire(&gListLock, "finish_deflate_idle_monitors"); 2348 log_info(monitorinflation)("gMonitorPopulation=%d, gOmInUseCount=%d, " 2349 "gMonitorFreeCount=%d", gMonitorPopulation, 2350 gOmInUseCount, gMonitorFreeCount); 2351 Thread::muxRelease(&gListLock); 2352 } 2353 2354 ForceMonitorScavenge = 0; // Reset 2355 GVars.stwRandom = os::random(); 2356 GVars.stwCycle++; 2357 if (needs_special_deflation) { 2358 set_is_special_deflation_requested(false); // special deflation is done 2359 } 2360 } 2361 2362 void ObjectSynchronizer::deflate_thread_local_monitors(Thread* thread, DeflateMonitorCounters* counters) { 2363 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 2364 2365 if (AsyncDeflateIdleMonitors) { 2366 if (!is_special_deflation_requested()) { 2367 // Mark the JavaThread for idle monitor deflation if a special 2368 // deflation has NOT been requested. 2369 if (thread->omInUseCount > 0) { 2370 // This JavaThread is using monitors so mark it. 2371 thread->omShouldDeflateIdleMonitors = true; 2372 } 2373 return; 2374 } 2375 } 2376 2377 ObjectMonitor * freeHeadp = NULL; // Local SLL of scavenged monitors 2378 ObjectMonitor * freeTailp = NULL; 2379 elapsedTimer timer; 2380 2381 if (log_is_enabled(Info, safepoint, cleanup) || 2382 log_is_enabled(Info, monitorinflation)) { 2383 timer.start(); 2384 } 2385 2386 int deflated_count = deflate_monitor_list(thread->omInUseList_addr(), &freeHeadp, &freeTailp); 2387 2388 Thread::muxAcquire(&gListLock, "deflate_thread_local_monitors"); 2389 2390 // Adjust counters 2391 counters->nInCirculation += thread->omInUseCount; 2392 thread->omInUseCount -= deflated_count; 2393 counters->nScavenged += deflated_count; 2394 counters->nInuse += thread->omInUseCount; 2395 counters->perThreadScavenged += deflated_count; 2396 2397 // Move the scavenged monitors back to the global free list. 2398 if (freeHeadp != NULL) { 2399 guarantee(freeTailp != NULL && deflated_count > 0, "invariant"); 2400 assert(freeTailp->FreeNext == NULL, "invariant"); 2401 2402 // constant-time list splice - prepend scavenged segment to gFreeList 2403 freeTailp->FreeNext = gFreeList; 2404 gFreeList = freeHeadp; 2405 } 2406 2407 timer.stop(); 2408 // Safepoint logging cares about cumulative perThreadTimes and 2409 // we'll capture most of the cost, but not the muxRelease() which 2410 // should be cheap. 2411 counters->perThreadTimes += timer.seconds(); 2412 2413 Thread::muxRelease(&gListLock); 2414 2415 LogStreamHandle(Debug, monitorinflation) lsh_debug; 2416 LogStreamHandle(Info, monitorinflation) lsh_info; 2417 LogStream * ls = NULL; 2418 if (log_is_enabled(Debug, monitorinflation)) { 2419 ls = &lsh_debug; 2420 } else if (deflated_count != 0 && log_is_enabled(Info, monitorinflation)) { 2421 ls = &lsh_info; 2422 } 2423 if (ls != NULL) { 2424 ls->print_cr("jt=" INTPTR_FORMAT ": deflating per-thread idle monitors, %3.7f secs, %d monitors", p2i(thread), timer.seconds(), deflated_count); 2425 } 2426 } 2427 2428 // Monitor cleanup on JavaThread::exit 2429 2430 // Iterate through monitor cache and attempt to release thread's monitors 2431 // Gives up on a particular monitor if an exception occurs, but continues 2432 // the overall iteration, swallowing the exception. 2433 class ReleaseJavaMonitorsClosure: public MonitorClosure { 2434 private: 2435 TRAPS; 2436 2437 public: 2438 ReleaseJavaMonitorsClosure(Thread* thread) : THREAD(thread) {} 2439 void do_monitor(ObjectMonitor* mid) { 2440 if (mid->owner() == THREAD) { 2441 (void)mid->complete_exit(CHECK); 2442 } 2443 } 2444 }; 2445 2446 // Release all inflated monitors owned by THREAD. Lightweight monitors are 2447 // ignored. This is meant to be called during JNI thread detach which assumes 2448 // all remaining monitors are heavyweight. All exceptions are swallowed. 2449 // Scanning the extant monitor list can be time consuming. 2450 // A simple optimization is to add a per-thread flag that indicates a thread 2451 // called jni_monitorenter() during its lifetime. 2452 // 2453 // Instead of No_Savepoint_Verifier it might be cheaper to 2454 // use an idiom of the form: 2455 // auto int tmp = SafepointSynchronize::_safepoint_counter ; 2456 // <code that must not run at safepoint> 2457 // guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ; 2458 // Since the tests are extremely cheap we could leave them enabled 2459 // for normal product builds. 2460 2461 void ObjectSynchronizer::release_monitors_owned_by_thread(TRAPS) { 2462 assert(THREAD == JavaThread::current(), "must be current Java thread"); 2463 NoSafepointVerifier nsv; 2464 ReleaseJavaMonitorsClosure rjmc(THREAD); 2465 Thread::muxAcquire(&gListLock, "release_monitors_owned_by_thread"); 2466 ObjectSynchronizer::monitors_iterate(&rjmc); 2467 Thread::muxRelease(&gListLock); 2468 THREAD->clear_pending_exception(); 2469 } 2470 2471 const char* ObjectSynchronizer::inflate_cause_name(const InflateCause cause) { 2472 switch (cause) { 2473 case inflate_cause_vm_internal: return "VM Internal"; 2474 case inflate_cause_monitor_enter: return "Monitor Enter"; 2475 case inflate_cause_wait: return "Monitor Wait"; 2476 case inflate_cause_notify: return "Monitor Notify"; 2477 case inflate_cause_hash_code: return "Monitor Hash Code"; 2478 case inflate_cause_jni_enter: return "JNI Monitor Enter"; 2479 case inflate_cause_jni_exit: return "JNI Monitor Exit"; 2480 default: 2481 ShouldNotReachHere(); 2482 } 2483 return "Unknown"; 2484 } 2485 2486 //------------------------------------------------------------------------------ 2487 // Debugging code 2488 2489 u_char* ObjectSynchronizer::get_gvars_addr() { 2490 return (u_char*)&GVars; 2491 } 2492 2493 u_char* ObjectSynchronizer::get_gvars_hcSequence_addr() { 2494 return (u_char*)&GVars.hcSequence; 2495 } 2496 2497 size_t ObjectSynchronizer::get_gvars_size() { 2498 return sizeof(SharedGlobals); 2499 } 2500 2501 u_char* ObjectSynchronizer::get_gvars_stwRandom_addr() { 2502 return (u_char*)&GVars.stwRandom; 2503 } 2504 2505 void ObjectSynchronizer::audit_and_print_stats(bool on_exit) { 2506 assert(on_exit || SafepointSynchronize::is_at_safepoint(), "invariant"); 2507 2508 LogStreamHandle(Debug, monitorinflation) lsh_debug; 2509 LogStreamHandle(Info, monitorinflation) lsh_info; 2510 LogStreamHandle(Trace, monitorinflation) lsh_trace; 2511 LogStream * ls = NULL; 2512 if (log_is_enabled(Trace, monitorinflation)) { 2513 ls = &lsh_trace; 2514 } else if (log_is_enabled(Debug, monitorinflation)) { 2515 ls = &lsh_debug; 2516 } else if (log_is_enabled(Info, monitorinflation)) { 2517 ls = &lsh_info; 2518 } 2519 assert(ls != NULL, "sanity check"); 2520 2521 if (!on_exit) { 2522 // Not at VM exit so grab the global list lock. 2523 Thread::muxAcquire(&gListLock, "audit_and_print_stats"); 2524 } 2525 2526 // Log counts for the global and per-thread monitor lists: 2527 int chkMonitorPopulation = log_monitor_list_counts(ls); 2528 int error_cnt = 0; 2529 2530 ls->print_cr("Checking global lists:"); 2531 2532 // Check gMonitorPopulation: 2533 if (gMonitorPopulation == chkMonitorPopulation) { 2534 ls->print_cr("gMonitorPopulation=%d equals chkMonitorPopulation=%d", 2535 gMonitorPopulation, chkMonitorPopulation); 2536 } else { 2537 ls->print_cr("ERROR: gMonitorPopulation=%d is not equal to " 2538 "chkMonitorPopulation=%d", gMonitorPopulation, 2539 chkMonitorPopulation); 2540 error_cnt++; 2541 } 2542 2543 // Check gOmInUseList and gOmInUseCount: 2544 chk_global_in_use_list_and_count(ls, &error_cnt); 2545 2546 // Check gFreeList and gMonitorFreeCount: 2547 chk_global_free_list_and_count(ls, &error_cnt); 2548 2549 if (!on_exit) { 2550 Thread::muxRelease(&gListLock); 2551 } 2552 2553 ls->print_cr("Checking per-thread lists:"); 2554 2555 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) { 2556 // Check omInUseList and omInUseCount: 2557 chk_per_thread_in_use_list_and_count(jt, ls, &error_cnt); 2558 2559 // Check omFreeList and omFreeCount: 2560 chk_per_thread_free_list_and_count(jt, ls, &error_cnt); 2561 } 2562 2563 if (error_cnt == 0) { 2564 ls->print_cr("No errors found in monitor list checks."); 2565 } else { 2566 log_error(monitorinflation)("found monitor list errors: error_cnt=%d", error_cnt); 2567 } 2568 2569 if ((on_exit && log_is_enabled(Info, monitorinflation)) || 2570 (!on_exit && log_is_enabled(Trace, monitorinflation))) { 2571 // When exiting this log output is at the Info level. When called 2572 // at a safepoint, this log output is at the Trace level since 2573 // there can be a lot of it. 2574 log_in_use_monitor_details(ls, on_exit); 2575 } 2576 2577 ls->flush(); 2578 2579 guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt); 2580 } 2581 2582 // Check a free monitor entry; log any errors. 2583 void ObjectSynchronizer::chk_free_entry(JavaThread * jt, ObjectMonitor * n, 2584 outputStream * out, int *error_cnt_p) { 2585 stringStream ss; 2586 if (n->is_busy()) { 2587 if (jt != NULL) { 2588 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT 2589 ": free per-thread monitor must not be busy: %s", p2i(jt), 2590 p2i(n), n->is_busy_to_string(&ss)); 2591 } else { 2592 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor " 2593 "must not be busy: %s", p2i(n), n->is_busy_to_string(&ss)); 2594 } 2595 *error_cnt_p = *error_cnt_p + 1; 2596 } 2597 if (n->header() != NULL) { 2598 if (jt != NULL) { 2599 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT 2600 ": free per-thread monitor must have NULL _header " 2601 "field: _header=" INTPTR_FORMAT, p2i(jt), p2i(n), 2602 p2i(n->header())); 2603 *error_cnt_p = *error_cnt_p + 1; 2604 } else if (!AsyncDeflateIdleMonitors) { 2605 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor " 2606 "must have NULL _header field: _header=" INTPTR_FORMAT, 2607 p2i(n), p2i(n->header())); 2608 *error_cnt_p = *error_cnt_p + 1; 2609 } 2610 } 2611 if (n->object() != NULL) { 2612 if (jt != NULL) { 2613 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT 2614 ": free per-thread monitor must have NULL _object " 2615 "field: _object=" INTPTR_FORMAT, p2i(jt), p2i(n), 2616 p2i(n->object())); 2617 } else { 2618 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": free global monitor " 2619 "must have NULL _object field: _object=" INTPTR_FORMAT, 2620 p2i(n), p2i(n->object())); 2621 } 2622 *error_cnt_p = *error_cnt_p + 1; 2623 } 2624 } 2625 2626 // Check the global free list and count; log the results of the checks. 2627 void ObjectSynchronizer::chk_global_free_list_and_count(outputStream * out, 2628 int *error_cnt_p) { 2629 int chkMonitorFreeCount = 0; 2630 for (ObjectMonitor * n = gFreeList; n != NULL; n = n->FreeNext) { 2631 chk_free_entry(NULL /* jt */, n, out, error_cnt_p); 2632 chkMonitorFreeCount++; 2633 } 2634 if (gMonitorFreeCount == chkMonitorFreeCount) { 2635 out->print_cr("gMonitorFreeCount=%d equals chkMonitorFreeCount=%d", 2636 gMonitorFreeCount, chkMonitorFreeCount); 2637 } else { 2638 out->print_cr("ERROR: gMonitorFreeCount=%d is not equal to " 2639 "chkMonitorFreeCount=%d", gMonitorFreeCount, 2640 chkMonitorFreeCount); 2641 *error_cnt_p = *error_cnt_p + 1; 2642 } 2643 } 2644 2645 // Check the global in-use list and count; log the results of the checks. 2646 void ObjectSynchronizer::chk_global_in_use_list_and_count(outputStream * out, 2647 int *error_cnt_p) { 2648 int chkOmInUseCount = 0; 2649 for (ObjectMonitor * n = gOmInUseList; n != NULL; n = n->FreeNext) { 2650 chk_in_use_entry(NULL /* jt */, n, out, error_cnt_p); 2651 chkOmInUseCount++; 2652 } 2653 if (gOmInUseCount == chkOmInUseCount) { 2654 out->print_cr("gOmInUseCount=%d equals chkOmInUseCount=%d", gOmInUseCount, 2655 chkOmInUseCount); 2656 } else { 2657 out->print_cr("ERROR: gOmInUseCount=%d is not equal to chkOmInUseCount=%d", 2658 gOmInUseCount, chkOmInUseCount); 2659 *error_cnt_p = *error_cnt_p + 1; 2660 } 2661 } 2662 2663 // Check an in-use monitor entry; log any errors. 2664 void ObjectSynchronizer::chk_in_use_entry(JavaThread * jt, ObjectMonitor * n, 2665 outputStream * out, int *error_cnt_p) { 2666 if (n->header() == NULL) { 2667 if (jt != NULL) { 2668 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT 2669 ": in-use per-thread monitor must have non-NULL _header " 2670 "field.", p2i(jt), p2i(n)); 2671 } else { 2672 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global monitor " 2673 "must have non-NULL _header field.", p2i(n)); 2674 } 2675 *error_cnt_p = *error_cnt_p + 1; 2676 } 2677 if (n->object() == NULL) { 2678 if (jt != NULL) { 2679 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT 2680 ": in-use per-thread monitor must have non-NULL _object " 2681 "field.", p2i(jt), p2i(n)); 2682 } else { 2683 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global monitor " 2684 "must have non-NULL _object field.", p2i(n)); 2685 } 2686 *error_cnt_p = *error_cnt_p + 1; 2687 } 2688 const oop obj = (oop)n->object(); 2689 const markOop mark = obj->mark(); 2690 if (!mark->has_monitor()) { 2691 if (jt != NULL) { 2692 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT 2693 ": in-use per-thread monitor's object does not think " 2694 "it has a monitor: obj=" INTPTR_FORMAT ", mark=" 2695 INTPTR_FORMAT, p2i(jt), p2i(n), p2i(obj), p2i(mark)); 2696 } else { 2697 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global " 2698 "monitor's object does not think it has a monitor: obj=" 2699 INTPTR_FORMAT ", mark=" INTPTR_FORMAT, p2i(n), 2700 p2i(obj), p2i(mark)); 2701 } 2702 *error_cnt_p = *error_cnt_p + 1; 2703 } 2704 ObjectMonitor * const obj_mon = mark->monitor(); 2705 if (n != obj_mon) { 2706 if (jt != NULL) { 2707 out->print_cr("ERROR: jt=" INTPTR_FORMAT ", monitor=" INTPTR_FORMAT 2708 ": in-use per-thread monitor's object does not refer " 2709 "to the same monitor: obj=" INTPTR_FORMAT ", mark=" 2710 INTPTR_FORMAT ", obj_mon=" INTPTR_FORMAT, p2i(jt), 2711 p2i(n), p2i(obj), p2i(mark), p2i(obj_mon)); 2712 } else { 2713 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use global " 2714 "monitor's object does not refer to the same monitor: obj=" 2715 INTPTR_FORMAT ", mark=" INTPTR_FORMAT ", obj_mon=" 2716 INTPTR_FORMAT, p2i(n), p2i(obj), p2i(mark), p2i(obj_mon)); 2717 } 2718 *error_cnt_p = *error_cnt_p + 1; 2719 } 2720 } 2721 2722 // Check the thread's free list and count; log the results of the checks. 2723 void ObjectSynchronizer::chk_per_thread_free_list_and_count(JavaThread *jt, 2724 outputStream * out, 2725 int *error_cnt_p) { 2726 int chkOmFreeCount = 0; 2727 for (ObjectMonitor * n = jt->omFreeList; n != NULL; n = n->FreeNext) { 2728 chk_free_entry(jt, n, out, error_cnt_p); 2729 chkOmFreeCount++; 2730 } 2731 if (jt->omFreeCount == chkOmFreeCount) { 2732 out->print_cr("jt=" INTPTR_FORMAT ": omFreeCount=%d equals " 2733 "chkOmFreeCount=%d", p2i(jt), jt->omFreeCount, chkOmFreeCount); 2734 } else { 2735 out->print_cr("ERROR: jt=" INTPTR_FORMAT ": omFreeCount=%d is not " 2736 "equal to chkOmFreeCount=%d", p2i(jt), jt->omFreeCount, 2737 chkOmFreeCount); 2738 *error_cnt_p = *error_cnt_p + 1; 2739 } 2740 } 2741 2742 // Check the thread's in-use list and count; log the results of the checks. 2743 void ObjectSynchronizer::chk_per_thread_in_use_list_and_count(JavaThread *jt, 2744 outputStream * out, 2745 int *error_cnt_p) { 2746 int chkOmInUseCount = 0; 2747 for (ObjectMonitor * n = jt->omInUseList; n != NULL; n = n->FreeNext) { 2748 chk_in_use_entry(jt, n, out, error_cnt_p); 2749 chkOmInUseCount++; 2750 } 2751 if (jt->omInUseCount == chkOmInUseCount) { 2752 out->print_cr("jt=" INTPTR_FORMAT ": omInUseCount=%d equals " 2753 "chkOmInUseCount=%d", p2i(jt), jt->omInUseCount, 2754 chkOmInUseCount); 2755 } else { 2756 out->print_cr("ERROR: jt=" INTPTR_FORMAT ": omInUseCount=%d is not " 2757 "equal to chkOmInUseCount=%d", p2i(jt), jt->omInUseCount, 2758 chkOmInUseCount); 2759 *error_cnt_p = *error_cnt_p + 1; 2760 } 2761 } 2762 2763 // Log details about ObjectMonitors on the in-use lists. The 'BHL' 2764 // flags indicate why the entry is in-use, 'object' and 'object type' 2765 // indicate the associated object and its type. 2766 void ObjectSynchronizer::log_in_use_monitor_details(outputStream * out, 2767 bool on_exit) { 2768 if (!on_exit) { 2769 // Not at VM exit so grab the global list lock. 2770 Thread::muxAcquire(&gListLock, "log_in_use_monitor_details"); 2771 } 2772 2773 stringStream ss; 2774 if (gOmInUseCount > 0) { 2775 out->print_cr("In-use global monitor info:"); 2776 out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)"); 2777 out->print_cr("%18s %s %7s %18s %18s", 2778 "monitor", "BHL", "ref_cnt", "object", "object type"); 2779 out->print_cr("================== === ======= ================== =================="); 2780 for (ObjectMonitor * n = gOmInUseList; n != NULL; n = n->FreeNext) { 2781 const oop obj = (oop) n->object(); 2782 const markOop mark = n->header(); 2783 ResourceMark rm; 2784 out->print(INTPTR_FORMAT " %d%d%d %7d " INTPTR_FORMAT " %s", 2785 p2i(n), n->is_busy() != 0, mark->hash() != 0, 2786 n->owner() != NULL, (int)n->ref_count(), p2i(obj), 2787 obj->klass()->external_name()); 2788 if (n->is_busy() != 0) { 2789 out->print(" (%s)", n->is_busy_to_string(&ss)); 2790 ss.reset(); 2791 } 2792 out->cr(); 2793 } 2794 } 2795 2796 if (!on_exit) { 2797 Thread::muxRelease(&gListLock); 2798 } 2799 2800 out->print_cr("In-use per-thread monitor info:"); 2801 out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)"); 2802 out->print_cr("%18s %18s %s %7s %18s %18s", 2803 "jt", "monitor", "BHL", "ref_cnt", "object", "object type"); 2804 out->print_cr("================== ================== === ======= ================== =================="); 2805 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) { 2806 for (ObjectMonitor * n = jt->omInUseList; n != NULL; n = n->FreeNext) { 2807 const oop obj = (oop) n->object(); 2808 const markOop mark = n->header(); 2809 ResourceMark rm; 2810 out->print(INTPTR_FORMAT " " INTPTR_FORMAT " %d%d%d %7d " 2811 INTPTR_FORMAT " %s", p2i(jt), p2i(n), n->is_busy() != 0, 2812 mark->hash() != 0, n->owner() != NULL, (int)n->ref_count(), 2813 p2i(obj), obj->klass()->external_name()); 2814 if (n->is_busy() != 0) { 2815 out->print(" (%s)", n->is_busy_to_string(&ss)); 2816 ss.reset(); 2817 } 2818 out->cr(); 2819 } 2820 } 2821 2822 out->flush(); 2823 } 2824 2825 // Log counts for the global and per-thread monitor lists and return 2826 // the population count. 2827 int ObjectSynchronizer::log_monitor_list_counts(outputStream * out) { 2828 int popCount = 0; 2829 out->print_cr("%18s %10s %10s %10s", 2830 "Global Lists:", "InUse", "Free", "Total"); 2831 out->print_cr("================== ========== ========== =========="); 2832 out->print_cr("%18s %10d %10d %10d", "", 2833 gOmInUseCount, gMonitorFreeCount, gMonitorPopulation); 2834 popCount += gOmInUseCount + gMonitorFreeCount; 2835 2836 out->print_cr("%18s %10s %10s %10s", 2837 "Per-Thread Lists:", "InUse", "Free", "Provision"); 2838 out->print_cr("================== ========== ========== =========="); 2839 2840 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) { 2841 out->print_cr(INTPTR_FORMAT " %10d %10d %10d", p2i(jt), 2842 jt->omInUseCount, jt->omFreeCount, jt->omFreeProvision); 2843 popCount += jt->omInUseCount + jt->omFreeCount; 2844 } 2845 return popCount; 2846 } 2847 2848 #ifndef PRODUCT 2849 2850 // Check if monitor belongs to the monitor cache 2851 // The list is grow-only so it's *relatively* safe to traverse 2852 // the list of extant blocks without taking a lock. 2853 2854 int ObjectSynchronizer::verify_objmon_isinpool(ObjectMonitor *monitor) { 2855 PaddedEnd<ObjectMonitor> * block = OrderAccess::load_acquire(&gBlockList); 2856 while (block != NULL) { 2857 assert(block->object() == CHAINMARKER, "must be a block header"); 2858 if (monitor > &block[0] && monitor < &block[_BLOCKSIZE]) { 2859 address mon = (address)monitor; 2860 address blk = (address)block; 2861 size_t diff = mon - blk; 2862 assert((diff % sizeof(PaddedEnd<ObjectMonitor>)) == 0, "must be aligned"); 2863 return 1; 2864 } 2865 block = (PaddedEnd<ObjectMonitor> *)block->FreeNext; 2866 } 2867 return 0; 2868 } 2869 2870 #endif