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