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