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