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