1 /* 2 * Copyright (c) 1998, 2021, 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 "jfr/jfrEvents.hpp" 28 #include "logging/log.hpp" 29 #include "logging/logStream.hpp" 30 #include "memory/allocation.inline.hpp" 31 #include "memory/padded.hpp" 32 #include "memory/resourceArea.hpp" 33 #include "memory/universe.hpp" 34 #include "oops/markWord.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/handshake.hpp" 40 #include "runtime/interfaceSupport.inline.hpp" 41 #include "runtime/mutexLocker.hpp" 42 #include "runtime/objectMonitor.hpp" 43 #include "runtime/objectMonitor.inline.hpp" 44 #include "runtime/os.inline.hpp" 45 #include "runtime/osThread.hpp" 46 #include "runtime/perfData.hpp" 47 #include "runtime/safepointMechanism.inline.hpp" 48 #include "runtime/safepointVerifiers.hpp" 49 #include "runtime/sharedRuntime.hpp" 50 #include "runtime/stubRoutines.hpp" 51 #include "runtime/synchronizer.hpp" 52 #include "runtime/thread.inline.hpp" 53 #include "runtime/timer.hpp" 54 #include "runtime/trimNativeHeap.hpp" 55 #include "runtime/vframe.hpp" 56 #include "runtime/vmThread.hpp" 57 #include "utilities/align.hpp" 58 #include "utilities/dtrace.hpp" 59 #include "utilities/events.hpp" 60 #include "utilities/preserveException.hpp" 61 62 void MonitorList::add(ObjectMonitor* m) { 63 ObjectMonitor* head; 64 do { 65 head = Atomic::load(&_head); 66 m->set_next_om(head); 67 } while (Atomic::cmpxchg(&_head, head, m) != head); 68 69 size_t count = Atomic::add(&_count, 1u); 70 if (count > max()) { 71 Atomic::inc(&_max); 72 } 73 } 74 75 size_t MonitorList::count() const { 76 return Atomic::load(&_count); 77 } 78 79 size_t MonitorList::max() const { 80 return Atomic::load(&_max); 81 } 82 83 // Walk the in-use list and unlink (at most MonitorDeflationMax) deflated 84 // ObjectMonitors. Returns the number of unlinked ObjectMonitors. 85 size_t MonitorList::unlink_deflated(Thread* current, LogStream* ls, 86 elapsedTimer* timer_p, 87 GrowableArray<ObjectMonitor*>* unlinked_list) { 88 size_t unlinked_count = 0; 89 ObjectMonitor* prev = NULL; 90 ObjectMonitor* head = Atomic::load_acquire(&_head); 91 ObjectMonitor* m = head; 92 // The in-use list head can be NULL during the final audit. 93 while (m != NULL) { 94 if (m->is_being_async_deflated()) { 95 // Find next live ObjectMonitor. 96 ObjectMonitor* next = m; 97 do { 98 ObjectMonitor* next_next = next->next_om(); 99 unlinked_count++; 100 unlinked_list->append(next); 101 next = next_next; 102 if (unlinked_count >= (size_t)MonitorDeflationMax) { 103 // Reached the max so bail out on the gathering loop. 104 break; 105 } 106 } while (next != NULL && next->is_being_async_deflated()); 107 if (prev == NULL) { 108 ObjectMonitor* prev_head = Atomic::cmpxchg(&_head, head, next); 109 if (prev_head != head) { 110 // Find new prev ObjectMonitor that just got inserted. 111 for (ObjectMonitor* n = prev_head; n != m; n = n->next_om()) { 112 prev = n; 113 } 114 prev->set_next_om(next); 115 } 116 } else { 117 prev->set_next_om(next); 118 } 119 if (unlinked_count >= (size_t)MonitorDeflationMax) { 120 // Reached the max so bail out on the searching loop. 121 break; 122 } 123 m = next; 124 } else { 125 prev = m; 126 m = m->next_om(); 127 } 128 129 if (current->is_Java_thread()) { 130 // A JavaThread must check for a safepoint/handshake and honor it. 131 ObjectSynchronizer::chk_for_block_req(current->as_Java_thread(), "unlinking", 132 "unlinked_count", unlinked_count, 133 ls, timer_p); 134 } 135 } 136 Atomic::sub(&_count, unlinked_count); 137 return unlinked_count; 138 } 139 140 MonitorList::Iterator MonitorList::iterator() const { 141 return Iterator(Atomic::load_acquire(&_head)); 142 } 143 144 ObjectMonitor* MonitorList::Iterator::next() { 145 ObjectMonitor* current = _current; 146 _current = current->next_om(); 147 return current; 148 } 149 150 // The "core" versions of monitor enter and exit reside in this file. 151 // The interpreter and compilers contain specialized transliterated 152 // variants of the enter-exit fast-path operations. See c2_MacroAssembler_x86.cpp 153 // fast_lock(...) for instance. If you make changes here, make sure to modify the 154 // interpreter, and both C1 and C2 fast-path inline locking code emission. 155 // 156 // ----------------------------------------------------------------------------- 157 158 #ifdef DTRACE_ENABLED 159 160 // Only bother with this argument setup if dtrace is available 161 // TODO-FIXME: probes should not fire when caller is _blocked. assert() accordingly. 162 163 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread) \ 164 char* bytes = NULL; \ 165 int len = 0; \ 166 jlong jtid = SharedRuntime::get_java_tid(thread); \ 167 Symbol* klassname = obj->klass()->name(); \ 168 if (klassname != NULL) { \ 169 bytes = (char*)klassname->bytes(); \ 170 len = klassname->utf8_length(); \ 171 } 172 173 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis) \ 174 { \ 175 if (DTraceMonitorProbes) { \ 176 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \ 177 HOTSPOT_MONITOR_WAIT(jtid, \ 178 (uintptr_t)(monitor), bytes, len, (millis)); \ 179 } \ 180 } 181 182 #define HOTSPOT_MONITOR_PROBE_notify HOTSPOT_MONITOR_NOTIFY 183 #define HOTSPOT_MONITOR_PROBE_notifyAll HOTSPOT_MONITOR_NOTIFYALL 184 #define HOTSPOT_MONITOR_PROBE_waited HOTSPOT_MONITOR_WAITED 185 186 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread) \ 187 { \ 188 if (DTraceMonitorProbes) { \ 189 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \ 190 HOTSPOT_MONITOR_PROBE_##probe(jtid, /* probe = waited */ \ 191 (uintptr_t)(monitor), bytes, len); \ 192 } \ 193 } 194 195 #else // ndef DTRACE_ENABLED 196 197 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon) {;} 198 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon) {;} 199 200 #endif // ndef DTRACE_ENABLED 201 202 // This exists only as a workaround of dtrace bug 6254741 203 int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, Thread* thr) { 204 DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr); 205 return 0; 206 } 207 208 static const int NINFLATIONLOCKS = 256; 209 static os::PlatformMutex* gInflationLocks[NINFLATIONLOCKS]; 210 211 void ObjectSynchronizer::initialize() { 212 for (int i = 0; i < NINFLATIONLOCKS; i++) { 213 gInflationLocks[i] = new os::PlatformMutex(); 214 } 215 // Start the ceiling with the estimate for one thread. 216 set_in_use_list_ceiling(AvgMonitorsPerThreadEstimate); 217 218 // Start the timer for deflations, so it does not trigger immediately. 219 _last_async_deflation_time_ns = os::javaTimeNanos(); 220 } 221 222 MonitorList ObjectSynchronizer::_in_use_list; 223 // monitors_used_above_threshold() policy is as follows: 224 // 225 // The ratio of the current _in_use_list count to the ceiling is used 226 // to determine if we are above MonitorUsedDeflationThreshold and need 227 // to do an async monitor deflation cycle. The ceiling is increased by 228 // AvgMonitorsPerThreadEstimate when a thread is added to the system 229 // and is decreased by AvgMonitorsPerThreadEstimate when a thread is 230 // removed from the system. 231 // 232 // Note: If the _in_use_list max exceeds the ceiling, then 233 // monitors_used_above_threshold() will use the in_use_list max instead 234 // of the thread count derived ceiling because we have used more 235 // ObjectMonitors than the estimated average. 236 // 237 // Note: If deflate_idle_monitors() has NoAsyncDeflationProgressMax 238 // no-progress async monitor deflation cycles in a row, then the ceiling 239 // is adjusted upwards by monitors_used_above_threshold(). 240 // 241 // Start the ceiling with the estimate for one thread in initialize() 242 // which is called after cmd line options are processed. 243 static size_t _in_use_list_ceiling = 0; 244 bool volatile ObjectSynchronizer::_is_async_deflation_requested = false; 245 bool volatile ObjectSynchronizer::_is_final_audit = false; 246 jlong ObjectSynchronizer::_last_async_deflation_time_ns = 0; 247 static uintx _no_progress_cnt = 0; 248 static bool _no_progress_skip_increment = false; 249 250 // =====================> Quick functions 251 252 // The quick_* forms are special fast-path variants used to improve 253 // performance. In the simplest case, a "quick_*" implementation could 254 // simply return false, in which case the caller will perform the necessary 255 // state transitions and call the slow-path form. 256 // The fast-path is designed to handle frequently arising cases in an efficient 257 // manner and is just a degenerate "optimistic" variant of the slow-path. 258 // returns true -- to indicate the call was satisfied. 259 // returns false -- to indicate the call needs the services of the slow-path. 260 // A no-loitering ordinance is in effect for code in the quick_* family 261 // operators: safepoints or indefinite blocking (blocking that might span a 262 // safepoint) are forbidden. Generally the thread_state() is _in_Java upon 263 // entry. 264 // 265 // Consider: An interesting optimization is to have the JIT recognize the 266 // following common idiom: 267 // synchronized (someobj) { .... ; notify(); } 268 // That is, we find a notify() or notifyAll() call that immediately precedes 269 // the monitorexit operation. In that case the JIT could fuse the operations 270 // into a single notifyAndExit() runtime primitive. 271 272 bool ObjectSynchronizer::quick_notify(oopDesc* obj, JavaThread* current, bool all) { 273 assert(current->thread_state() == _thread_in_Java, "invariant"); 274 NoSafepointVerifier nsv; 275 if (obj == NULL) return false; // slow-path for invalid obj 276 const markWord mark = obj->mark(); 277 278 if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) { 279 // Degenerate notify 280 // stack-locked by caller so by definition the implied waitset is empty. 281 return true; 282 } 283 284 if (mark.has_monitor()) { 285 ObjectMonitor* const mon = mark.monitor(); 286 assert(mon->object() == oop(obj), "invariant"); 287 if (mon->owner() != current) return false; // slow-path for IMS exception 288 289 if (mon->first_waiter() != NULL) { 290 // We have one or more waiters. Since this is an inflated monitor 291 // that we own, we can transfer one or more threads from the waitset 292 // to the entrylist here and now, avoiding the slow-path. 293 if (all) { 294 DTRACE_MONITOR_PROBE(notifyAll, mon, obj, current); 295 } else { 296 DTRACE_MONITOR_PROBE(notify, mon, obj, current); 297 } 298 int free_count = 0; 299 do { 300 mon->INotify(current); 301 ++free_count; 302 } while (mon->first_waiter() != NULL && all); 303 OM_PERFDATA_OP(Notifications, inc(free_count)); 304 } 305 return true; 306 } 307 308 // biased locking and any other IMS exception states take the slow-path 309 return false; 310 } 311 312 313 // The LockNode emitted directly at the synchronization site would have 314 // been too big if it were to have included support for the cases of inflated 315 // recursive enter and exit, so they go here instead. 316 // Note that we can't safely call AsyncPrintJavaStack() from within 317 // quick_enter() as our thread state remains _in_Java. 318 319 bool ObjectSynchronizer::quick_enter(oop obj, JavaThread* current, 320 BasicLock * lock) { 321 assert(current->thread_state() == _thread_in_Java, "invariant"); 322 NoSafepointVerifier nsv; 323 if (obj == NULL) return false; // Need to throw NPE 324 325 if (obj->klass()->is_value_based()) { 326 return false; 327 } 328 329 const markWord mark = obj->mark(); 330 331 if (mark.has_monitor()) { 332 ObjectMonitor* const m = mark.monitor(); 333 // An async deflation or GC can race us before we manage to make 334 // the ObjectMonitor busy by setting the owner below. If we detect 335 // that race we just bail out to the slow-path here. 336 if (m->object_peek() == NULL) { 337 return false; 338 } 339 JavaThread* const owner = (JavaThread*) m->owner_raw(); 340 341 // Lock contention and Transactional Lock Elision (TLE) diagnostics 342 // and observability 343 // Case: light contention possibly amenable to TLE 344 // Case: TLE inimical operations such as nested/recursive synchronization 345 346 if (owner == current) { 347 m->_recursions++; 348 return true; 349 } 350 351 // This Java Monitor is inflated so obj's header will never be 352 // displaced to this thread's BasicLock. Make the displaced header 353 // non-NULL so this BasicLock is not seen as recursive nor as 354 // being locked. We do this unconditionally so that this thread's 355 // BasicLock cannot be mis-interpreted by any stack walkers. For 356 // performance reasons, stack walkers generally first check for 357 // Biased Locking in the object's header, the second check is for 358 // stack-locking in the object's header, the third check is for 359 // recursive stack-locking in the displaced header in the BasicLock, 360 // and last are the inflated Java Monitor (ObjectMonitor) checks. 361 lock->set_displaced_header(markWord::unused_mark()); 362 363 if (owner == NULL && m->try_set_owner_from(NULL, current) == NULL) { 364 assert(m->_recursions == 0, "invariant"); 365 return true; 366 } 367 } 368 369 // Note that we could inflate in quick_enter. 370 // This is likely a useful optimization 371 // Critically, in quick_enter() we must not: 372 // -- perform bias revocation, or 373 // -- block indefinitely, or 374 // -- reach a safepoint 375 376 return false; // revert to slow-path 377 } 378 379 // Handle notifications when synchronizing on value based classes 380 void ObjectSynchronizer::handle_sync_on_value_based_class(Handle obj, JavaThread* current) { 381 frame last_frame = current->last_frame(); 382 bool bcp_was_adjusted = false; 383 // Don't decrement bcp if it points to the frame's first instruction. This happens when 384 // handle_sync_on_value_based_class() is called because of a synchronized method. There 385 // is no actual monitorenter instruction in the byte code in this case. 386 if (last_frame.is_interpreted_frame() && 387 (last_frame.interpreter_frame_method()->code_base() < last_frame.interpreter_frame_bcp())) { 388 // adjust bcp to point back to monitorenter so that we print the correct line numbers 389 last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() - 1); 390 bcp_was_adjusted = true; 391 } 392 393 if (DiagnoseSyncOnValueBasedClasses == FATAL_EXIT) { 394 ResourceMark rm(current); 395 stringStream ss; 396 current->print_stack_on(&ss); 397 char* base = (char*)strstr(ss.base(), "at"); 398 char* newline = (char*)strchr(ss.base(), '\n'); 399 if (newline != NULL) { 400 *newline = '\0'; 401 } 402 fatal("Synchronizing on object " INTPTR_FORMAT " of klass %s %s", p2i(obj()), obj->klass()->external_name(), base); 403 } else { 404 assert(DiagnoseSyncOnValueBasedClasses == LOG_WARNING, "invalid value for DiagnoseSyncOnValueBasedClasses"); 405 ResourceMark rm(current); 406 Log(valuebasedclasses) vblog; 407 408 vblog.info("Synchronizing on object " INTPTR_FORMAT " of klass %s", p2i(obj()), obj->klass()->external_name()); 409 if (current->has_last_Java_frame()) { 410 LogStream info_stream(vblog.info()); 411 current->print_stack_on(&info_stream); 412 } else { 413 vblog.info("Cannot find the last Java frame"); 414 } 415 416 EventSyncOnValueBasedClass event; 417 if (event.should_commit()) { 418 event.set_valueBasedClass(obj->klass()); 419 event.commit(); 420 } 421 } 422 423 if (bcp_was_adjusted) { 424 last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() + 1); 425 } 426 } 427 428 // ----------------------------------------------------------------------------- 429 // Monitor Enter/Exit 430 // The interpreter and compiler assembly code tries to lock using the fast path 431 // of this algorithm. Make sure to update that code if the following function is 432 // changed. The implementation is extremely sensitive to race condition. Be careful. 433 434 void ObjectSynchronizer::enter(Handle obj, BasicLock* lock, JavaThread* current) { 435 if (obj->klass()->is_value_based()) { 436 handle_sync_on_value_based_class(obj, current); 437 } 438 439 if (UseBiasedLocking) { 440 BiasedLocking::revoke(current, obj); 441 } 442 443 markWord mark = obj->mark(); 444 assert(!mark.has_bias_pattern(), "should not see bias pattern here"); 445 446 if (mark.is_neutral()) { 447 // Anticipate successful CAS -- the ST of the displaced mark must 448 // be visible <= the ST performed by the CAS. 449 lock->set_displaced_header(mark); 450 if (mark == obj()->cas_set_mark(markWord::from_pointer(lock), mark)) { 451 return; 452 } 453 // Fall through to inflate() ... 454 } else if (mark.has_locker() && 455 current->is_lock_owned((address)mark.locker())) { 456 assert(lock != mark.locker(), "must not re-lock the same lock"); 457 assert(lock != (BasicLock*)obj->mark().value(), "don't relock with same BasicLock"); 458 lock->set_displaced_header(markWord::from_pointer(NULL)); 459 return; 460 } 461 462 // The object header will never be displaced to this lock, 463 // so it does not matter what the value is, except that it 464 // must be non-zero to avoid looking like a re-entrant lock, 465 // and must not look locked either. 466 lock->set_displaced_header(markWord::unused_mark()); 467 // An async deflation can race after the inflate() call and before 468 // enter() can make the ObjectMonitor busy. enter() returns false if 469 // we have lost the race to async deflation and we simply try again. 470 while (true) { 471 ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_monitor_enter); 472 if (monitor->enter(current)) { 473 return; 474 } 475 } 476 } 477 478 void ObjectSynchronizer::exit(oop object, BasicLock* lock, JavaThread* current) { 479 markWord mark = object->mark(); 480 // We cannot check for Biased Locking if we are racing an inflation. 481 assert(mark == markWord::INFLATING() || 482 !mark.has_bias_pattern(), "should not see bias pattern here"); 483 484 markWord dhw = lock->displaced_header(); 485 if (dhw.value() == 0) { 486 // If the displaced header is NULL, then this exit matches up with 487 // a recursive enter. No real work to do here except for diagnostics. 488 #ifndef PRODUCT 489 if (mark != markWord::INFLATING()) { 490 // Only do diagnostics if we are not racing an inflation. Simply 491 // exiting a recursive enter of a Java Monitor that is being 492 // inflated is safe; see the has_monitor() comment below. 493 assert(!mark.is_neutral(), "invariant"); 494 assert(!mark.has_locker() || 495 current->is_lock_owned((address)mark.locker()), "invariant"); 496 if (mark.has_monitor()) { 497 // The BasicLock's displaced_header is marked as a recursive 498 // enter and we have an inflated Java Monitor (ObjectMonitor). 499 // This is a special case where the Java Monitor was inflated 500 // after this thread entered the stack-lock recursively. When a 501 // Java Monitor is inflated, we cannot safely walk the Java 502 // Monitor owner's stack and update the BasicLocks because a 503 // Java Monitor can be asynchronously inflated by a thread that 504 // does not own the Java Monitor. 505 ObjectMonitor* m = mark.monitor(); 506 assert(m->object()->mark() == mark, "invariant"); 507 assert(m->is_entered(current), "invariant"); 508 } 509 } 510 #endif 511 return; 512 } 513 514 if (mark == markWord::from_pointer(lock)) { 515 // If the object is stack-locked by the current thread, try to 516 // swing the displaced header from the BasicLock back to the mark. 517 assert(dhw.is_neutral(), "invariant"); 518 if (object->cas_set_mark(dhw, mark) == mark) { 519 return; 520 } 521 } 522 523 // We have to take the slow-path of possible inflation and then exit. 524 // The ObjectMonitor* can't be async deflated until ownership is 525 // dropped inside exit() and the ObjectMonitor* must be !is_busy(). 526 ObjectMonitor* monitor = inflate(current, object, inflate_cause_vm_internal); 527 monitor->exit(current); 528 } 529 530 // ----------------------------------------------------------------------------- 531 // Class Loader support to workaround deadlocks on the class loader lock objects 532 // Also used by GC 533 // complete_exit()/reenter() are used to wait on a nested lock 534 // i.e. to give up an outer lock completely and then re-enter 535 // Used when holding nested locks - lock acquisition order: lock1 then lock2 536 // 1) complete_exit lock1 - saving recursion count 537 // 2) wait on lock2 538 // 3) when notified on lock2, unlock lock2 539 // 4) reenter lock1 with original recursion count 540 // 5) lock lock2 541 // NOTE: must use heavy weight monitor to handle complete_exit/reenter() 542 intx ObjectSynchronizer::complete_exit(Handle obj, JavaThread* current) { 543 if (UseBiasedLocking) { 544 BiasedLocking::revoke(current, obj); 545 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 546 } 547 548 // The ObjectMonitor* can't be async deflated until ownership is 549 // dropped inside exit() and the ObjectMonitor* must be !is_busy(). 550 ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_vm_internal); 551 intptr_t ret_code = monitor->complete_exit(current); 552 return ret_code; 553 } 554 555 // NOTE: must use heavy weight monitor to handle complete_exit/reenter() 556 void ObjectSynchronizer::reenter(Handle obj, intx recursions, JavaThread* current) { 557 if (UseBiasedLocking) { 558 BiasedLocking::revoke(current, obj); 559 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 560 } 561 562 // An async deflation can race after the inflate() call and before 563 // reenter() -> enter() can make the ObjectMonitor busy. reenter() -> 564 // enter() returns false if we have lost the race to async deflation 565 // and we simply try again. 566 while (true) { 567 ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_vm_internal); 568 if (monitor->reenter(recursions, current)) { 569 return; 570 } 571 } 572 } 573 574 // ----------------------------------------------------------------------------- 575 // JNI locks on java objects 576 // NOTE: must use heavy weight monitor to handle jni monitor enter 577 void ObjectSynchronizer::jni_enter(Handle obj, JavaThread* current) { 578 if (obj->klass()->is_value_based()) { 579 handle_sync_on_value_based_class(obj, current); 580 } 581 582 // the current locking is from JNI instead of Java code 583 if (UseBiasedLocking) { 584 BiasedLocking::revoke(current, obj); 585 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 586 } 587 current->set_current_pending_monitor_is_from_java(false); 588 // An async deflation can race after the inflate() call and before 589 // enter() can make the ObjectMonitor busy. enter() returns false if 590 // we have lost the race to async deflation and we simply try again. 591 while (true) { 592 ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_jni_enter); 593 if (monitor->enter(current)) { 594 break; 595 } 596 } 597 current->set_current_pending_monitor_is_from_java(true); 598 } 599 600 // NOTE: must use heavy weight monitor to handle jni monitor exit 601 void ObjectSynchronizer::jni_exit(oop obj, TRAPS) { 602 JavaThread* current = THREAD; 603 if (UseBiasedLocking) { 604 Handle h_obj(current, obj); 605 BiasedLocking::revoke(current, h_obj); 606 obj = h_obj(); 607 } 608 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 609 610 // The ObjectMonitor* can't be async deflated until ownership is 611 // dropped inside exit() and the ObjectMonitor* must be !is_busy(). 612 ObjectMonitor* monitor = inflate(current, obj, inflate_cause_jni_exit); 613 // If this thread has locked the object, exit the monitor. We 614 // intentionally do not use CHECK on check_owner because we must exit the 615 // monitor even if an exception was already pending. 616 if (monitor->check_owner(THREAD)) { 617 monitor->exit(current); 618 } 619 } 620 621 // ----------------------------------------------------------------------------- 622 // Internal VM locks on java objects 623 // standard constructor, allows locking failures 624 ObjectLocker::ObjectLocker(Handle obj, JavaThread* thread) { 625 _thread = thread; 626 _thread->check_for_valid_safepoint_state(); 627 _obj = obj; 628 629 if (_obj() != NULL) { 630 ObjectSynchronizer::enter(_obj, &_lock, _thread); 631 } 632 } 633 634 ObjectLocker::~ObjectLocker() { 635 if (_obj() != NULL) { 636 ObjectSynchronizer::exit(_obj(), &_lock, _thread); 637 } 638 } 639 640 641 // ----------------------------------------------------------------------------- 642 // Wait/Notify/NotifyAll 643 // NOTE: must use heavy weight monitor to handle wait() 644 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) { 645 JavaThread* current = THREAD; 646 if (UseBiasedLocking) { 647 BiasedLocking::revoke(current, obj); 648 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 649 } 650 if (millis < 0) { 651 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative"); 652 } 653 // The ObjectMonitor* can't be async deflated because the _waiters 654 // field is incremented before ownership is dropped and decremented 655 // after ownership is regained. 656 ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_wait); 657 658 DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), current, millis); 659 monitor->wait(millis, true, THREAD); // Not CHECK as we need following code 660 661 // This dummy call is in place to get around dtrace bug 6254741. Once 662 // that's fixed we can uncomment the following line, remove the call 663 // and change this function back into a "void" func. 664 // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD); 665 int ret_code = dtrace_waited_probe(monitor, obj, THREAD); 666 return ret_code; 667 } 668 669 // No exception are possible in this case as we only use this internally when locking is 670 // correct and we have to wait until notified - so no interrupts or timeouts. 671 void ObjectSynchronizer::wait_uninterruptibly(Handle obj, JavaThread* current) { 672 if (UseBiasedLocking) { 673 BiasedLocking::revoke(current, obj); 674 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 675 } 676 // The ObjectMonitor* can't be async deflated because the _waiters 677 // field is incremented before ownership is dropped and decremented 678 // after ownership is regained. 679 ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_wait); 680 monitor->wait(0 /* wait-forever */, false /* not interruptible */, current); 681 } 682 683 void ObjectSynchronizer::notify(Handle obj, TRAPS) { 684 JavaThread* current = THREAD; 685 if (UseBiasedLocking) { 686 BiasedLocking::revoke(current, obj); 687 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 688 } 689 690 markWord mark = obj->mark(); 691 if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) { 692 // Not inflated so there can't be any waiters to notify. 693 return; 694 } 695 // The ObjectMonitor* can't be async deflated until ownership is 696 // dropped by the calling thread. 697 ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_notify); 698 monitor->notify(CHECK); 699 } 700 701 // NOTE: see comment of notify() 702 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) { 703 JavaThread* current = THREAD; 704 if (UseBiasedLocking) { 705 BiasedLocking::revoke(current, obj); 706 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 707 } 708 709 markWord mark = obj->mark(); 710 if (mark.has_locker() && current->is_lock_owned((address)mark.locker())) { 711 // Not inflated so there can't be any waiters to notify. 712 return; 713 } 714 // The ObjectMonitor* can't be async deflated until ownership is 715 // dropped by the calling thread. 716 ObjectMonitor* monitor = inflate(current, obj(), inflate_cause_notify); 717 monitor->notifyAll(CHECK); 718 } 719 720 // ----------------------------------------------------------------------------- 721 // Hash Code handling 722 723 struct SharedGlobals { 724 char _pad_prefix[OM_CACHE_LINE_SIZE]; 725 // This is a highly shared mostly-read variable. 726 // To avoid false-sharing it needs to be the sole occupant of a cache line. 727 volatile int stw_random; 728 DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(volatile int)); 729 // Hot RW variable -- Sequester to avoid false-sharing 730 volatile int hc_sequence; 731 DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(volatile int)); 732 }; 733 734 static SharedGlobals GVars; 735 736 static markWord read_stable_mark(oop obj) { 737 markWord mark = obj->mark_acquire(); 738 if (!mark.is_being_inflated()) { 739 return mark; // normal fast-path return 740 } 741 742 int its = 0; 743 for (;;) { 744 markWord mark = obj->mark_acquire(); 745 if (!mark.is_being_inflated()) { 746 return mark; // normal fast-path return 747 } 748 749 // The object is being inflated by some other thread. 750 // The caller of read_stable_mark() must wait for inflation to complete. 751 // Avoid live-lock. 752 753 ++its; 754 if (its > 10000 || !os::is_MP()) { 755 if (its & 1) { 756 os::naked_yield(); 757 } else { 758 // Note that the following code attenuates the livelock problem but is not 759 // a complete remedy. A more complete solution would require that the inflating 760 // thread hold the associated inflation lock. The following code simply restricts 761 // the number of spinners to at most one. We'll have N-2 threads blocked 762 // on the inflationlock, 1 thread holding the inflation lock and using 763 // a yield/park strategy, and 1 thread in the midst of inflation. 764 // A more refined approach would be to change the encoding of INFLATING 765 // to allow encapsulation of a native thread pointer. Threads waiting for 766 // inflation to complete would use CAS to push themselves onto a singly linked 767 // list rooted at the markword. Once enqueued, they'd loop, checking a per-thread flag 768 // and calling park(). When inflation was complete the thread that accomplished inflation 769 // would detach the list and set the markword to inflated with a single CAS and 770 // then for each thread on the list, set the flag and unpark() the thread. 771 772 // Index into the lock array based on the current object address. 773 static_assert(is_power_of_2(NINFLATIONLOCKS), "must be"); 774 int ix = (cast_from_oop<intptr_t>(obj) >> 5) & (NINFLATIONLOCKS-1); 775 int YieldThenBlock = 0; 776 assert(ix >= 0 && ix < NINFLATIONLOCKS, "invariant"); 777 gInflationLocks[ix]->lock(); 778 while (obj->mark_acquire() == markWord::INFLATING()) { 779 // Beware: naked_yield() is advisory and has almost no effect on some platforms 780 // so we periodically call current->_ParkEvent->park(1). 781 // We use a mixed spin/yield/block mechanism. 782 if ((YieldThenBlock++) >= 16) { 783 Thread::current()->_ParkEvent->park(1); 784 } else { 785 os::naked_yield(); 786 } 787 } 788 gInflationLocks[ix]->unlock(); 789 } 790 } else { 791 SpinPause(); // SMP-polite spinning 792 } 793 } 794 } 795 796 // hashCode() generation : 797 // 798 // Possibilities: 799 // * MD5Digest of {obj,stw_random} 800 // * CRC32 of {obj,stw_random} or any linear-feedback shift register function. 801 // * A DES- or AES-style SBox[] mechanism 802 // * One of the Phi-based schemes, such as: 803 // 2654435761 = 2^32 * Phi (golden ratio) 804 // HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stw_random ; 805 // * A variation of Marsaglia's shift-xor RNG scheme. 806 // * (obj ^ stw_random) is appealing, but can result 807 // in undesirable regularity in the hashCode values of adjacent objects 808 // (objects allocated back-to-back, in particular). This could potentially 809 // result in hashtable collisions and reduced hashtable efficiency. 810 // There are simple ways to "diffuse" the middle address bits over the 811 // generated hashCode values: 812 813 static inline intptr_t get_next_hash(Thread* current, oop obj) { 814 intptr_t value = 0; 815 if (hashCode == 0) { 816 // This form uses global Park-Miller RNG. 817 // On MP system we'll have lots of RW access to a global, so the 818 // mechanism induces lots of coherency traffic. 819 value = os::random(); 820 } else if (hashCode == 1) { 821 // This variation has the property of being stable (idempotent) 822 // between STW operations. This can be useful in some of the 1-0 823 // synchronization schemes. 824 intptr_t addr_bits = cast_from_oop<intptr_t>(obj) >> 3; 825 value = addr_bits ^ (addr_bits >> 5) ^ GVars.stw_random; 826 } else if (hashCode == 2) { 827 value = 1; // for sensitivity testing 828 } else if (hashCode == 3) { 829 value = ++GVars.hc_sequence; 830 } else if (hashCode == 4) { 831 value = cast_from_oop<intptr_t>(obj); 832 } else { 833 // Marsaglia's xor-shift scheme with thread-specific state 834 // This is probably the best overall implementation -- we'll 835 // likely make this the default in future releases. 836 unsigned t = current->_hashStateX; 837 t ^= (t << 11); 838 current->_hashStateX = current->_hashStateY; 839 current->_hashStateY = current->_hashStateZ; 840 current->_hashStateZ = current->_hashStateW; 841 unsigned v = current->_hashStateW; 842 v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)); 843 current->_hashStateW = v; 844 value = v; 845 } 846 847 value &= markWord::hash_mask; 848 if (value == 0) value = 0xBAD; 849 assert(value != markWord::no_hash, "invariant"); 850 return value; 851 } 852 853 intptr_t ObjectSynchronizer::FastHashCode(Thread* current, oop obj) { 854 if (UseBiasedLocking) { 855 // NOTE: many places throughout the JVM do not expect a safepoint 856 // to be taken here. However, we only ever bias Java instances and all 857 // of the call sites of identity_hash that might revoke biases have 858 // been checked to make sure they can handle a safepoint. The 859 // added check of the bias pattern is to avoid useless calls to 860 // thread-local storage. 861 if (obj->mark().has_bias_pattern()) { 862 // Handle for oop obj in case of STW safepoint 863 Handle hobj(current, obj); 864 if (SafepointSynchronize::is_at_safepoint()) { 865 BiasedLocking::revoke_at_safepoint(hobj); 866 } else { 867 BiasedLocking::revoke(current->as_Java_thread(), hobj); 868 } 869 obj = hobj(); 870 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 871 } 872 } 873 874 while (true) { 875 ObjectMonitor* monitor = NULL; 876 markWord temp, test; 877 intptr_t hash; 878 markWord mark = read_stable_mark(obj); 879 880 // object should remain ineligible for biased locking 881 assert(!mark.has_bias_pattern(), "invariant"); 882 883 if (mark.is_neutral()) { // if this is a normal header 884 hash = mark.hash(); 885 if (hash != 0) { // if it has a hash, just return it 886 return hash; 887 } 888 hash = get_next_hash(current, obj); // get a new hash 889 temp = mark.copy_set_hash(hash); // merge the hash into header 890 // try to install the hash 891 test = obj->cas_set_mark(temp, mark); 892 if (test == mark) { // if the hash was installed, return it 893 return hash; 894 } 895 // Failed to install the hash. It could be that another thread 896 // installed the hash just before our attempt or inflation has 897 // occurred or... so we fall thru to inflate the monitor for 898 // stability and then install the hash. 899 } else if (mark.has_monitor()) { 900 monitor = mark.monitor(); 901 temp = monitor->header(); 902 assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value()); 903 hash = temp.hash(); 904 if (hash != 0) { 905 // It has a hash. 906 907 // Separate load of dmw/header above from the loads in 908 // is_being_async_deflated(). 909 910 // dmw/header and _contentions may get written by different threads. 911 // Make sure to observe them in the same order when having several observers. 912 OrderAccess::loadload_for_IRIW(); 913 914 if (monitor->is_being_async_deflated()) { 915 // But we can't safely use the hash if we detect that async 916 // deflation has occurred. So we attempt to restore the 917 // header/dmw to the object's header so that we only retry 918 // once if the deflater thread happens to be slow. 919 monitor->install_displaced_markword_in_object(obj); 920 continue; 921 } 922 return hash; 923 } 924 // Fall thru so we only have one place that installs the hash in 925 // the ObjectMonitor. 926 } else if (current->is_lock_owned((address)mark.locker())) { 927 // This is a stack lock owned by the calling thread so fetch the 928 // displaced markWord from the BasicLock on the stack. 929 temp = mark.displaced_mark_helper(); 930 assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value()); 931 hash = temp.hash(); 932 if (hash != 0) { // if it has a hash, just return it 933 return hash; 934 } 935 // WARNING: 936 // The displaced header in the BasicLock on a thread's stack 937 // is strictly immutable. It CANNOT be changed in ANY cases. 938 // So we have to inflate the stack lock into an ObjectMonitor 939 // even if the current thread owns the lock. The BasicLock on 940 // a thread's stack can be asynchronously read by other threads 941 // during an inflate() call so any change to that stack memory 942 // may not propagate to other threads correctly. 943 } 944 945 // Inflate the monitor to set the hash. 946 947 // An async deflation can race after the inflate() call and before we 948 // can update the ObjectMonitor's header with the hash value below. 949 monitor = inflate(current, obj, inflate_cause_hash_code); 950 // Load ObjectMonitor's header/dmw field and see if it has a hash. 951 mark = monitor->header(); 952 assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value()); 953 hash = mark.hash(); 954 if (hash == 0) { // if it does not have a hash 955 hash = get_next_hash(current, obj); // get a new hash 956 temp = mark.copy_set_hash(hash) ; // merge the hash into header 957 assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value()); 958 uintptr_t v = Atomic::cmpxchg((volatile uintptr_t*)monitor->header_addr(), mark.value(), temp.value()); 959 test = markWord(v); 960 if (test != mark) { 961 // The attempt to update the ObjectMonitor's header/dmw field 962 // did not work. This can happen if another thread managed to 963 // merge in the hash just before our cmpxchg(). 964 // If we add any new usages of the header/dmw field, this code 965 // will need to be updated. 966 hash = test.hash(); 967 assert(test.is_neutral(), "invariant: header=" INTPTR_FORMAT, test.value()); 968 assert(hash != 0, "should only have lost the race to a thread that set a non-zero hash"); 969 } 970 if (monitor->is_being_async_deflated()) { 971 // If we detect that async deflation has occurred, then we 972 // attempt to restore the header/dmw to the object's header 973 // so that we only retry once if the deflater thread happens 974 // to be slow. 975 monitor->install_displaced_markword_in_object(obj); 976 continue; 977 } 978 } 979 // We finally get the hash. 980 return hash; 981 } 982 } 983 984 // Deprecated -- use FastHashCode() instead. 985 986 intptr_t ObjectSynchronizer::identity_hash_value_for(Handle obj) { 987 return FastHashCode(Thread::current(), obj()); 988 } 989 990 991 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* current, 992 Handle h_obj) { 993 if (UseBiasedLocking) { 994 BiasedLocking::revoke(current, h_obj); 995 assert(!h_obj->mark().has_bias_pattern(), "biases should be revoked by now"); 996 } 997 998 assert(current == JavaThread::current(), "Can only be called on current thread"); 999 oop obj = h_obj(); 1000 1001 markWord mark = read_stable_mark(obj); 1002 1003 // Uncontended case, header points to stack 1004 if (mark.has_locker()) { 1005 return current->is_lock_owned((address)mark.locker()); 1006 } 1007 // Contended case, header points to ObjectMonitor (tagged pointer) 1008 if (mark.has_monitor()) { 1009 // The first stage of async deflation does not affect any field 1010 // used by this comparison so the ObjectMonitor* is usable here. 1011 ObjectMonitor* monitor = mark.monitor(); 1012 return monitor->is_entered(current) != 0; 1013 } 1014 // Unlocked case, header in place 1015 assert(mark.is_neutral(), "sanity check"); 1016 return false; 1017 } 1018 1019 // FIXME: jvmti should call this 1020 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) { 1021 if (UseBiasedLocking) { 1022 if (SafepointSynchronize::is_at_safepoint()) { 1023 BiasedLocking::revoke_at_safepoint(h_obj); 1024 } else { 1025 BiasedLocking::revoke(JavaThread::current(), h_obj); 1026 } 1027 assert(!h_obj->mark().has_bias_pattern(), "biases should be revoked by now"); 1028 } 1029 1030 oop obj = h_obj(); 1031 address owner = NULL; 1032 1033 markWord mark = read_stable_mark(obj); 1034 1035 // Uncontended case, header points to stack 1036 if (mark.has_locker()) { 1037 owner = (address) mark.locker(); 1038 } 1039 1040 // Contended case, header points to ObjectMonitor (tagged pointer) 1041 else if (mark.has_monitor()) { 1042 // The first stage of async deflation does not affect any field 1043 // used by this comparison so the ObjectMonitor* is usable here. 1044 ObjectMonitor* monitor = mark.monitor(); 1045 assert(monitor != NULL, "monitor should be non-null"); 1046 owner = (address) monitor->owner(); 1047 } 1048 1049 if (owner != NULL) { 1050 // owning_thread_from_monitor_owner() may also return NULL here 1051 return Threads::owning_thread_from_monitor_owner(t_list, owner); 1052 } 1053 1054 // Unlocked case, header in place 1055 // Cannot have assertion since this object may have been 1056 // locked by another thread when reaching here. 1057 // assert(mark.is_neutral(), "sanity check"); 1058 1059 return NULL; 1060 } 1061 1062 // Visitors ... 1063 1064 void ObjectSynchronizer::monitors_iterate(MonitorClosure* closure, JavaThread* thread) { 1065 MonitorList::Iterator iter = _in_use_list.iterator(); 1066 while (iter.has_next()) { 1067 ObjectMonitor* mid = iter.next(); 1068 if (mid->owner() != thread) { 1069 continue; 1070 } 1071 if (!mid->is_being_async_deflated() && mid->object_peek() != NULL) { 1072 // Only process with closure if the object is set. 1073 1074 // monitors_iterate() is only called at a safepoint or when the 1075 // target thread is suspended or when the target thread is 1076 // operating on itself. The current closures in use today are 1077 // only interested in an owned ObjectMonitor and ownership 1078 // cannot be dropped under the calling contexts so the 1079 // ObjectMonitor cannot be async deflated. 1080 closure->do_monitor(mid); 1081 } 1082 } 1083 } 1084 1085 static bool monitors_used_above_threshold(MonitorList* list) { 1086 if (MonitorUsedDeflationThreshold == 0) { // disabled case is easy 1087 return false; 1088 } 1089 // Start with ceiling based on a per-thread estimate: 1090 size_t ceiling = ObjectSynchronizer::in_use_list_ceiling(); 1091 size_t old_ceiling = ceiling; 1092 if (ceiling < list->max()) { 1093 // The max used by the system has exceeded the ceiling so use that: 1094 ceiling = list->max(); 1095 } 1096 size_t monitors_used = list->count(); 1097 if (monitors_used == 0) { // empty list is easy 1098 return false; 1099 } 1100 if (NoAsyncDeflationProgressMax != 0 && 1101 _no_progress_cnt >= NoAsyncDeflationProgressMax) { 1102 float remainder = (100.0 - MonitorUsedDeflationThreshold) / 100.0; 1103 size_t new_ceiling = ceiling + (ceiling * remainder) + 1; 1104 ObjectSynchronizer::set_in_use_list_ceiling(new_ceiling); 1105 log_info(monitorinflation)("Too many deflations without progress; " 1106 "bumping in_use_list_ceiling from " SIZE_FORMAT 1107 " to " SIZE_FORMAT, old_ceiling, new_ceiling); 1108 _no_progress_cnt = 0; 1109 ceiling = new_ceiling; 1110 } 1111 1112 // Check if our monitor usage is above the threshold: 1113 size_t monitor_usage = (monitors_used * 100LL) / ceiling; 1114 if (int(monitor_usage) > MonitorUsedDeflationThreshold) { 1115 log_info(monitorinflation)("monitors_used=" SIZE_FORMAT ", ceiling=" SIZE_FORMAT 1116 ", monitor_usage=" SIZE_FORMAT ", threshold=" INTX_FORMAT, 1117 monitors_used, ceiling, monitor_usage, MonitorUsedDeflationThreshold); 1118 return true; 1119 } 1120 1121 return false; 1122 } 1123 1124 size_t ObjectSynchronizer::in_use_list_ceiling() { 1125 return _in_use_list_ceiling; 1126 } 1127 1128 void ObjectSynchronizer::dec_in_use_list_ceiling() { 1129 Atomic::sub(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate); 1130 } 1131 1132 void ObjectSynchronizer::inc_in_use_list_ceiling() { 1133 Atomic::add(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate); 1134 } 1135 1136 void ObjectSynchronizer::set_in_use_list_ceiling(size_t new_value) { 1137 _in_use_list_ceiling = new_value; 1138 } 1139 1140 bool ObjectSynchronizer::is_async_deflation_needed() { 1141 if (is_async_deflation_requested()) { 1142 // Async deflation request. 1143 log_info(monitorinflation)("Async deflation needed: explicit request"); 1144 return true; 1145 } 1146 1147 jlong time_since_last = time_since_last_async_deflation_ms(); 1148 1149 if (AsyncDeflationInterval > 0 && 1150 time_since_last > AsyncDeflationInterval && 1151 monitors_used_above_threshold(&_in_use_list)) { 1152 // It's been longer than our specified deflate interval and there 1153 // are too many monitors in use. We don't deflate more frequently 1154 // than AsyncDeflationInterval (unless is_async_deflation_requested) 1155 // in order to not swamp the MonitorDeflationThread. 1156 log_info(monitorinflation)("Async deflation needed: monitors used are above the threshold"); 1157 return true; 1158 } 1159 1160 if (GuaranteedAsyncDeflationInterval > 0 && 1161 time_since_last > GuaranteedAsyncDeflationInterval) { 1162 // It's been longer than our specified guaranteed deflate interval. 1163 // We need to clean up the used monitors even if the threshold is 1164 // not reached, to keep the memory utilization at bay when many threads 1165 // touched many monitors. 1166 log_info(monitorinflation)("Async deflation needed: guaranteed interval (" INTX_FORMAT " ms) " 1167 "is greater than time since last deflation (" JLONG_FORMAT " ms)", 1168 GuaranteedAsyncDeflationInterval, time_since_last); 1169 1170 // If this deflation has no progress, then it should not affect the no-progress 1171 // tracking, otherwise threshold heuristics would think it was triggered, experienced 1172 // no progress, and needs to backoff more aggressively. In this "no progress" case, 1173 // the generic code would bump the no-progress counter, and we compensate for that 1174 // by telling it to skip the update. 1175 // 1176 // If this deflation has progress, then it should let non-progress tracking 1177 // know about this, otherwise the threshold heuristics would kick in, potentially 1178 // experience no-progress due to aggressive cleanup by this deflation, and think 1179 // it is still in no-progress stride. In this "progress" case, the generic code would 1180 // zero the counter, and we allow it to happen. 1181 _no_progress_skip_increment = true; 1182 1183 return true; 1184 } 1185 1186 return false; 1187 } 1188 1189 bool ObjectSynchronizer::request_deflate_idle_monitors() { 1190 JavaThread* current = JavaThread::current(); 1191 bool ret_code = false; 1192 1193 jlong last_time = last_async_deflation_time_ns(); 1194 set_is_async_deflation_requested(true); 1195 { 1196 MonitorLocker ml(MonitorDeflation_lock, Mutex::_no_safepoint_check_flag); 1197 ml.notify_all(); 1198 } 1199 const int N_CHECKS = 5; 1200 for (int i = 0; i < N_CHECKS; i++) { // sleep for at most 5 seconds 1201 if (last_async_deflation_time_ns() > last_time) { 1202 log_info(monitorinflation)("Async Deflation happened after %d check(s).", i); 1203 ret_code = true; 1204 break; 1205 } 1206 { 1207 // JavaThread has to honor the blocking protocol. 1208 ThreadBlockInVM tbivm(current); 1209 os::naked_short_sleep(999); // sleep for almost 1 second 1210 } 1211 } 1212 if (!ret_code) { 1213 log_info(monitorinflation)("Async Deflation DID NOT happen after %d checks.", N_CHECKS); 1214 } 1215 1216 return ret_code; 1217 } 1218 1219 jlong ObjectSynchronizer::time_since_last_async_deflation_ms() { 1220 return (os::javaTimeNanos() - last_async_deflation_time_ns()) / (NANOUNITS / MILLIUNITS); 1221 } 1222 1223 static void post_monitor_inflate_event(EventJavaMonitorInflate* event, 1224 const oop obj, 1225 ObjectSynchronizer::InflateCause cause) { 1226 assert(event != NULL, "invariant"); 1227 assert(event->should_commit(), "invariant"); 1228 event->set_monitorClass(obj->klass()); 1229 event->set_address((uintptr_t)(void*)obj); 1230 event->set_cause((u1)cause); 1231 event->commit(); 1232 } 1233 1234 // Fast path code shared by multiple functions 1235 void ObjectSynchronizer::inflate_helper(oop obj) { 1236 markWord mark = obj->mark_acquire(); 1237 if (mark.has_monitor()) { 1238 ObjectMonitor* monitor = mark.monitor(); 1239 markWord dmw = monitor->header(); 1240 assert(dmw.is_neutral(), "sanity check: header=" INTPTR_FORMAT, dmw.value()); 1241 return; 1242 } 1243 (void)inflate(Thread::current(), obj, inflate_cause_vm_internal); 1244 } 1245 1246 ObjectMonitor* ObjectSynchronizer::inflate(Thread* current, oop object, 1247 const InflateCause cause) { 1248 EventJavaMonitorInflate event; 1249 1250 for (;;) { 1251 const markWord mark = object->mark_acquire(); 1252 assert(!mark.has_bias_pattern(), "invariant"); 1253 1254 // The mark can be in one of the following states: 1255 // * Inflated - just return 1256 // * Stack-locked - coerce it to inflated 1257 // * INFLATING - busy wait for conversion to complete 1258 // * Neutral - aggressively inflate the object. 1259 // * BIASED - Illegal. We should never see this 1260 1261 // CASE: inflated 1262 if (mark.has_monitor()) { 1263 ObjectMonitor* inf = mark.monitor(); 1264 markWord dmw = inf->header(); 1265 assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value()); 1266 return inf; 1267 } 1268 1269 // CASE: inflation in progress - inflating over a stack-lock. 1270 // Some other thread is converting from stack-locked to inflated. 1271 // Only that thread can complete inflation -- other threads must wait. 1272 // The INFLATING value is transient. 1273 // Currently, we spin/yield/park and poll the markword, waiting for inflation to finish. 1274 // We could always eliminate polling by parking the thread on some auxiliary list. 1275 if (mark == markWord::INFLATING()) { 1276 read_stable_mark(object); 1277 continue; 1278 } 1279 1280 // CASE: stack-locked 1281 // Could be stack-locked either by this thread or by some other thread. 1282 // 1283 // Note that we allocate the ObjectMonitor speculatively, _before_ attempting 1284 // to install INFLATING into the mark word. We originally installed INFLATING, 1285 // allocated the ObjectMonitor, and then finally STed the address of the 1286 // ObjectMonitor into the mark. This was correct, but artificially lengthened 1287 // the interval in which INFLATING appeared in the mark, thus increasing 1288 // the odds of inflation contention. 1289 1290 LogStreamHandle(Trace, monitorinflation) lsh; 1291 1292 if (mark.has_locker()) { 1293 ObjectMonitor* m = new ObjectMonitor(object); 1294 // Optimistically prepare the ObjectMonitor - anticipate successful CAS 1295 // We do this before the CAS in order to minimize the length of time 1296 // in which INFLATING appears in the mark. 1297 1298 markWord cmp = object->cas_set_mark(markWord::INFLATING(), mark); 1299 if (cmp != mark) { 1300 delete m; 1301 continue; // Interference -- just retry 1302 } 1303 1304 // We've successfully installed INFLATING (0) into the mark-word. 1305 // This is the only case where 0 will appear in a mark-word. 1306 // Only the singular thread that successfully swings the mark-word 1307 // to 0 can perform (or more precisely, complete) inflation. 1308 // 1309 // Why do we CAS a 0 into the mark-word instead of just CASing the 1310 // mark-word from the stack-locked value directly to the new inflated state? 1311 // Consider what happens when a thread unlocks a stack-locked object. 1312 // It attempts to use CAS to swing the displaced header value from the 1313 // on-stack BasicLock back into the object header. Recall also that the 1314 // header value (hash code, etc) can reside in (a) the object header, or 1315 // (b) a displaced header associated with the stack-lock, or (c) a displaced 1316 // header in an ObjectMonitor. The inflate() routine must copy the header 1317 // value from the BasicLock on the owner's stack to the ObjectMonitor, all 1318 // the while preserving the hashCode stability invariants. If the owner 1319 // decides to release the lock while the value is 0, the unlock will fail 1320 // and control will eventually pass from slow_exit() to inflate. The owner 1321 // will then spin, waiting for the 0 value to disappear. Put another way, 1322 // the 0 causes the owner to stall if the owner happens to try to 1323 // drop the lock (restoring the header from the BasicLock to the object) 1324 // while inflation is in-progress. This protocol avoids races that might 1325 // would otherwise permit hashCode values to change or "flicker" for an object. 1326 // Critically, while object->mark is 0 mark.displaced_mark_helper() is stable. 1327 // 0 serves as a "BUSY" inflate-in-progress indicator. 1328 1329 1330 // fetch the displaced mark from the owner's stack. 1331 // The owner can't die or unwind past the lock while our INFLATING 1332 // object is in the mark. Furthermore the owner can't complete 1333 // an unlock on the object, either. 1334 markWord dmw = mark.displaced_mark_helper(); 1335 // Catch if the object's header is not neutral (not locked and 1336 // not marked is what we care about here). 1337 assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value()); 1338 1339 // Setup monitor fields to proper values -- prepare the monitor 1340 m->set_header(dmw); 1341 1342 // Optimization: if the mark.locker stack address is associated 1343 // with this thread we could simply set m->_owner = current. 1344 // Note that a thread can inflate an object 1345 // that it has stack-locked -- as might happen in wait() -- directly 1346 // with CAS. That is, we can avoid the xchg-NULL .... ST idiom. 1347 m->set_owner_from(NULL, mark.locker()); 1348 // TODO-FIXME: assert BasicLock->dhw != 0. 1349 1350 // Must preserve store ordering. The monitor state must 1351 // be stable at the time of publishing the monitor address. 1352 guarantee(object->mark() == markWord::INFLATING(), "invariant"); 1353 // Release semantics so that above set_object() is seen first. 1354 object->release_set_mark(markWord::encode(m)); 1355 1356 // Once ObjectMonitor is configured and the object is associated 1357 // with the ObjectMonitor, it is safe to allow async deflation: 1358 _in_use_list.add(m); 1359 1360 // Hopefully the performance counters are allocated on distinct cache lines 1361 // to avoid false sharing on MP systems ... 1362 OM_PERFDATA_OP(Inflations, inc()); 1363 if (log_is_enabled(Trace, monitorinflation)) { 1364 ResourceMark rm(current); 1365 lsh.print_cr("inflate(has_locker): object=" INTPTR_FORMAT ", mark=" 1366 INTPTR_FORMAT ", type='%s'", p2i(object), 1367 object->mark().value(), object->klass()->external_name()); 1368 } 1369 if (event.should_commit()) { 1370 post_monitor_inflate_event(&event, object, cause); 1371 } 1372 return m; 1373 } 1374 1375 // CASE: neutral 1376 // TODO-FIXME: for entry we currently inflate and then try to CAS _owner. 1377 // If we know we're inflating for entry it's better to inflate by swinging a 1378 // pre-locked ObjectMonitor pointer into the object header. A successful 1379 // CAS inflates the object *and* confers ownership to the inflating thread. 1380 // In the current implementation we use a 2-step mechanism where we CAS() 1381 // to inflate and then CAS() again to try to swing _owner from NULL to current. 1382 // An inflateTry() method that we could call from enter() would be useful. 1383 1384 // Catch if the object's header is not neutral (not locked and 1385 // not marked is what we care about here). 1386 assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value()); 1387 ObjectMonitor* m = new ObjectMonitor(object); 1388 // prepare m for installation - set monitor to initial state 1389 m->set_header(mark); 1390 1391 if (object->cas_set_mark(markWord::encode(m), mark) != mark) { 1392 delete m; 1393 m = NULL; 1394 continue; 1395 // interference - the markword changed - just retry. 1396 // The state-transitions are one-way, so there's no chance of 1397 // live-lock -- "Inflated" is an absorbing state. 1398 } 1399 1400 // Once the ObjectMonitor is configured and object is associated 1401 // with the ObjectMonitor, it is safe to allow async deflation: 1402 _in_use_list.add(m); 1403 1404 // Hopefully the performance counters are allocated on distinct 1405 // cache lines to avoid false sharing on MP systems ... 1406 OM_PERFDATA_OP(Inflations, inc()); 1407 if (log_is_enabled(Trace, monitorinflation)) { 1408 ResourceMark rm(current); 1409 lsh.print_cr("inflate(neutral): object=" INTPTR_FORMAT ", mark=" 1410 INTPTR_FORMAT ", type='%s'", p2i(object), 1411 object->mark().value(), object->klass()->external_name()); 1412 } 1413 if (event.should_commit()) { 1414 post_monitor_inflate_event(&event, object, cause); 1415 } 1416 return m; 1417 } 1418 } 1419 1420 void ObjectSynchronizer::chk_for_block_req(JavaThread* current, const char* op_name, 1421 const char* cnt_name, size_t cnt, 1422 LogStream* ls, elapsedTimer* timer_p) { 1423 if (!SafepointMechanism::should_process(current)) { 1424 return; 1425 } 1426 1427 // A safepoint/handshake has started. 1428 if (ls != NULL) { 1429 timer_p->stop(); 1430 ls->print_cr("pausing %s: %s=" SIZE_FORMAT ", in_use_list stats: ceiling=" 1431 SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT, 1432 op_name, cnt_name, cnt, in_use_list_ceiling(), 1433 _in_use_list.count(), _in_use_list.max()); 1434 } 1435 1436 { 1437 // Honor block request. 1438 ThreadBlockInVM tbivm(current); 1439 } 1440 1441 if (ls != NULL) { 1442 ls->print_cr("resuming %s: in_use_list stats: ceiling=" SIZE_FORMAT 1443 ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT, op_name, 1444 in_use_list_ceiling(), _in_use_list.count(), _in_use_list.max()); 1445 timer_p->start(); 1446 } 1447 } 1448 1449 // Walk the in-use list and deflate (at most MonitorDeflationMax) idle 1450 // ObjectMonitors. Returns the number of deflated ObjectMonitors. 1451 size_t ObjectSynchronizer::deflate_monitor_list(Thread* current, LogStream* ls, 1452 elapsedTimer* timer_p) { 1453 MonitorList::Iterator iter = _in_use_list.iterator(); 1454 size_t deflated_count = 0; 1455 1456 while (iter.has_next()) { 1457 if (deflated_count >= (size_t)MonitorDeflationMax) { 1458 break; 1459 } 1460 ObjectMonitor* mid = iter.next(); 1461 if (mid->deflate_monitor()) { 1462 deflated_count++; 1463 } 1464 1465 if (current->is_Java_thread()) { 1466 // A JavaThread must check for a safepoint/handshake and honor it. 1467 chk_for_block_req(current->as_Java_thread(), "deflation", "deflated_count", 1468 deflated_count, ls, timer_p); 1469 } 1470 } 1471 1472 return deflated_count; 1473 } 1474 1475 class HandshakeForDeflation : public HandshakeClosure { 1476 public: 1477 HandshakeForDeflation() : HandshakeClosure("HandshakeForDeflation") {} 1478 1479 void do_thread(Thread* thread) { 1480 log_trace(monitorinflation)("HandshakeForDeflation::do_thread: thread=" 1481 INTPTR_FORMAT, p2i(thread)); 1482 } 1483 }; 1484 1485 // This function is called by the MonitorDeflationThread to deflate 1486 // ObjectMonitors. It is also called via do_final_audit_and_print_stats() 1487 // by the VMThread. 1488 size_t ObjectSynchronizer::deflate_idle_monitors() { 1489 Thread* current = Thread::current(); 1490 if (current->is_Java_thread()) { 1491 // The async deflation request has been processed. 1492 _last_async_deflation_time_ns = os::javaTimeNanos(); 1493 set_is_async_deflation_requested(false); 1494 } 1495 1496 LogStreamHandle(Debug, monitorinflation) lsh_debug; 1497 LogStreamHandle(Info, monitorinflation) lsh_info; 1498 LogStream* ls = NULL; 1499 if (log_is_enabled(Debug, monitorinflation)) { 1500 ls = &lsh_debug; 1501 } else if (log_is_enabled(Info, monitorinflation)) { 1502 ls = &lsh_info; 1503 } 1504 1505 elapsedTimer timer; 1506 if (ls != NULL) { 1507 ls->print_cr("begin deflating: in_use_list stats: ceiling=" SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT, 1508 in_use_list_ceiling(), _in_use_list.count(), _in_use_list.max()); 1509 timer.start(); 1510 } 1511 1512 // Deflate some idle ObjectMonitors. 1513 size_t deflated_count = deflate_monitor_list(current, ls, &timer); 1514 if (deflated_count > 0 || is_final_audit()) { 1515 // There are ObjectMonitors that have been deflated or this is the 1516 // final audit and all the remaining ObjectMonitors have been 1517 // deflated, BUT the MonitorDeflationThread blocked for the final 1518 // safepoint during unlinking. 1519 1520 // Unlink deflated ObjectMonitors from the in-use list. 1521 ResourceMark rm; 1522 GrowableArray<ObjectMonitor*> delete_list((int)deflated_count); 1523 size_t unlinked_count = _in_use_list.unlink_deflated(current, ls, &timer, 1524 &delete_list); 1525 if (current->is_Java_thread()) { 1526 if (ls != NULL) { 1527 timer.stop(); 1528 ls->print_cr("before handshaking: unlinked_count=" SIZE_FORMAT 1529 ", in_use_list stats: ceiling=" SIZE_FORMAT ", count=" 1530 SIZE_FORMAT ", max=" SIZE_FORMAT, 1531 unlinked_count, in_use_list_ceiling(), 1532 _in_use_list.count(), _in_use_list.max()); 1533 } 1534 1535 // A JavaThread needs to handshake in order to safely free the 1536 // ObjectMonitors that were deflated in this cycle. 1537 HandshakeForDeflation hfd_hc; 1538 Handshake::execute(&hfd_hc); 1539 1540 if (ls != NULL) { 1541 ls->print_cr("after handshaking: in_use_list stats: ceiling=" 1542 SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT, 1543 in_use_list_ceiling(), _in_use_list.count(), _in_use_list.max()); 1544 timer.start(); 1545 } 1546 } 1547 1548 NativeHeapTrimmer::SuspendMark sm("monitor deletion"); 1549 1550 // After the handshake, safely free the ObjectMonitors that were 1551 // deflated in this cycle. 1552 size_t deleted_count = 0; 1553 for (ObjectMonitor* monitor: delete_list) { 1554 delete monitor; 1555 deleted_count++; 1556 1557 if (current->is_Java_thread()) { 1558 // A JavaThread must check for a safepoint/handshake and honor it. 1559 chk_for_block_req(current->as_Java_thread(), "deletion", "deleted_count", 1560 deleted_count, ls, &timer); 1561 } 1562 } 1563 } 1564 1565 if (ls != NULL) { 1566 timer.stop(); 1567 if (deflated_count != 0 || log_is_enabled(Debug, monitorinflation)) { 1568 ls->print_cr("deflated " SIZE_FORMAT " monitors in %3.7f secs", 1569 deflated_count, timer.seconds()); 1570 } 1571 ls->print_cr("end deflating: in_use_list stats: ceiling=" SIZE_FORMAT ", count=" SIZE_FORMAT ", max=" SIZE_FORMAT, 1572 in_use_list_ceiling(), _in_use_list.count(), _in_use_list.max()); 1573 } 1574 1575 OM_PERFDATA_OP(MonExtant, set_value(_in_use_list.count())); 1576 OM_PERFDATA_OP(Deflations, inc(deflated_count)); 1577 1578 GVars.stw_random = os::random(); 1579 1580 if (deflated_count != 0) { 1581 _no_progress_cnt = 0; 1582 } else if (_no_progress_skip_increment) { 1583 _no_progress_skip_increment = false; 1584 } else { 1585 _no_progress_cnt++; 1586 } 1587 1588 return deflated_count; 1589 } 1590 1591 // Monitor cleanup on JavaThread::exit 1592 1593 // Iterate through monitor cache and attempt to release thread's monitors 1594 class ReleaseJavaMonitorsClosure: public MonitorClosure { 1595 private: 1596 JavaThread* _thread; 1597 1598 public: 1599 ReleaseJavaMonitorsClosure(JavaThread* thread) : _thread(thread) {} 1600 void do_monitor(ObjectMonitor* mid) { 1601 (void)mid->complete_exit(_thread); 1602 } 1603 }; 1604 1605 // Release all inflated monitors owned by current thread. Lightweight monitors are 1606 // ignored. This is meant to be called during JNI thread detach which assumes 1607 // all remaining monitors are heavyweight. All exceptions are swallowed. 1608 // Scanning the extant monitor list can be time consuming. 1609 // A simple optimization is to add a per-thread flag that indicates a thread 1610 // called jni_monitorenter() during its lifetime. 1611 // 1612 // Instead of NoSafepointVerifier it might be cheaper to 1613 // use an idiom of the form: 1614 // auto int tmp = SafepointSynchronize::_safepoint_counter ; 1615 // <code that must not run at safepoint> 1616 // guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ; 1617 // Since the tests are extremely cheap we could leave them enabled 1618 // for normal product builds. 1619 1620 void ObjectSynchronizer::release_monitors_owned_by_thread(JavaThread* current) { 1621 assert(current == JavaThread::current(), "must be current Java thread"); 1622 NoSafepointVerifier nsv; 1623 ReleaseJavaMonitorsClosure rjmc(current); 1624 ObjectSynchronizer::monitors_iterate(&rjmc, current); 1625 assert(!current->has_pending_exception(), "Should not be possible"); 1626 current->clear_pending_exception(); 1627 } 1628 1629 const char* ObjectSynchronizer::inflate_cause_name(const InflateCause cause) { 1630 switch (cause) { 1631 case inflate_cause_vm_internal: return "VM Internal"; 1632 case inflate_cause_monitor_enter: return "Monitor Enter"; 1633 case inflate_cause_wait: return "Monitor Wait"; 1634 case inflate_cause_notify: return "Monitor Notify"; 1635 case inflate_cause_hash_code: return "Monitor Hash Code"; 1636 case inflate_cause_jni_enter: return "JNI Monitor Enter"; 1637 case inflate_cause_jni_exit: return "JNI Monitor Exit"; 1638 default: 1639 ShouldNotReachHere(); 1640 } 1641 return "Unknown"; 1642 } 1643 1644 //------------------------------------------------------------------------------ 1645 // Debugging code 1646 1647 u_char* ObjectSynchronizer::get_gvars_addr() { 1648 return (u_char*)&GVars; 1649 } 1650 1651 u_char* ObjectSynchronizer::get_gvars_hc_sequence_addr() { 1652 return (u_char*)&GVars.hc_sequence; 1653 } 1654 1655 size_t ObjectSynchronizer::get_gvars_size() { 1656 return sizeof(SharedGlobals); 1657 } 1658 1659 u_char* ObjectSynchronizer::get_gvars_stw_random_addr() { 1660 return (u_char*)&GVars.stw_random; 1661 } 1662 1663 // Do the final audit and print of ObjectMonitor stats; must be done 1664 // by the VMThread at VM exit time. 1665 void ObjectSynchronizer::do_final_audit_and_print_stats() { 1666 assert(Thread::current()->is_VM_thread(), "sanity check"); 1667 1668 if (is_final_audit()) { // Only do the audit once. 1669 return; 1670 } 1671 set_is_final_audit(); 1672 log_info(monitorinflation)("Starting the final audit."); 1673 1674 if (log_is_enabled(Info, monitorinflation)) { 1675 // Do a deflation in order to reduce the in-use monitor population 1676 // that is reported by ObjectSynchronizer::log_in_use_monitor_details() 1677 // which is called by ObjectSynchronizer::audit_and_print_stats(). 1678 while (ObjectSynchronizer::deflate_idle_monitors() != 0) { 1679 ; // empty 1680 } 1681 // The other audit_and_print_stats() call is done at the Debug 1682 // level at a safepoint in SafepointSynchronize::do_cleanup_tasks. 1683 ObjectSynchronizer::audit_and_print_stats(true /* on_exit */); 1684 } 1685 } 1686 1687 // This function can be called at a safepoint or it can be called when 1688 // we are trying to exit the VM. When we are trying to exit the VM, the 1689 // list walker functions can run in parallel with the other list 1690 // operations so spin-locking is used for safety. 1691 // 1692 // Calls to this function can be added in various places as a debugging 1693 // aid; pass 'true' for the 'on_exit' parameter to have in-use monitor 1694 // details logged at the Info level and 'false' for the 'on_exit' 1695 // parameter to have in-use monitor details logged at the Trace level. 1696 // 1697 void ObjectSynchronizer::audit_and_print_stats(bool on_exit) { 1698 assert(on_exit || SafepointSynchronize::is_at_safepoint(), "invariant"); 1699 1700 LogStreamHandle(Debug, monitorinflation) lsh_debug; 1701 LogStreamHandle(Info, monitorinflation) lsh_info; 1702 LogStreamHandle(Trace, monitorinflation) lsh_trace; 1703 LogStream* ls = NULL; 1704 if (log_is_enabled(Trace, monitorinflation)) { 1705 ls = &lsh_trace; 1706 } else if (log_is_enabled(Debug, monitorinflation)) { 1707 ls = &lsh_debug; 1708 } else if (log_is_enabled(Info, monitorinflation)) { 1709 ls = &lsh_info; 1710 } 1711 assert(ls != NULL, "sanity check"); 1712 1713 int error_cnt = 0; 1714 1715 ls->print_cr("Checking in_use_list:"); 1716 chk_in_use_list(ls, &error_cnt); 1717 1718 if (error_cnt == 0) { 1719 ls->print_cr("No errors found in in_use_list checks."); 1720 } else { 1721 log_error(monitorinflation)("found in_use_list errors: error_cnt=%d", error_cnt); 1722 } 1723 1724 if ((on_exit && log_is_enabled(Info, monitorinflation)) || 1725 (!on_exit && log_is_enabled(Trace, monitorinflation))) { 1726 // When exiting this log output is at the Info level. When called 1727 // at a safepoint, this log output is at the Trace level since 1728 // there can be a lot of it. 1729 log_in_use_monitor_details(ls); 1730 } 1731 1732 ls->flush(); 1733 1734 guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt); 1735 } 1736 1737 // Check the in_use_list; log the results of the checks. 1738 void ObjectSynchronizer::chk_in_use_list(outputStream* out, int *error_cnt_p) { 1739 size_t l_in_use_count = _in_use_list.count(); 1740 size_t l_in_use_max = _in_use_list.max(); 1741 out->print_cr("count=" SIZE_FORMAT ", max=" SIZE_FORMAT, l_in_use_count, 1742 l_in_use_max); 1743 1744 size_t ck_in_use_count = 0; 1745 MonitorList::Iterator iter = _in_use_list.iterator(); 1746 while (iter.has_next()) { 1747 ObjectMonitor* mid = iter.next(); 1748 chk_in_use_entry(mid, out, error_cnt_p); 1749 ck_in_use_count++; 1750 } 1751 1752 if (l_in_use_count == ck_in_use_count) { 1753 out->print_cr("in_use_count=" SIZE_FORMAT " equals ck_in_use_count=" 1754 SIZE_FORMAT, l_in_use_count, ck_in_use_count); 1755 } else { 1756 out->print_cr("WARNING: in_use_count=" SIZE_FORMAT " is not equal to " 1757 "ck_in_use_count=" SIZE_FORMAT, l_in_use_count, 1758 ck_in_use_count); 1759 } 1760 1761 size_t ck_in_use_max = _in_use_list.max(); 1762 if (l_in_use_max == ck_in_use_max) { 1763 out->print_cr("in_use_max=" SIZE_FORMAT " equals ck_in_use_max=" 1764 SIZE_FORMAT, l_in_use_max, ck_in_use_max); 1765 } else { 1766 out->print_cr("WARNING: in_use_max=" SIZE_FORMAT " is not equal to " 1767 "ck_in_use_max=" SIZE_FORMAT, l_in_use_max, ck_in_use_max); 1768 } 1769 } 1770 1771 // Check an in-use monitor entry; log any errors. 1772 void ObjectSynchronizer::chk_in_use_entry(ObjectMonitor* n, outputStream* out, 1773 int* error_cnt_p) { 1774 if (n->owner_is_DEFLATER_MARKER()) { 1775 // This should not happen, but if it does, it is not fatal. 1776 out->print_cr("WARNING: monitor=" INTPTR_FORMAT ": in-use monitor is " 1777 "deflated.", p2i(n)); 1778 return; 1779 } 1780 if (n->header().value() == 0) { 1781 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor must " 1782 "have non-NULL _header field.", p2i(n)); 1783 *error_cnt_p = *error_cnt_p + 1; 1784 } 1785 const oop obj = n->object_peek(); 1786 if (obj != NULL) { 1787 const markWord mark = obj->mark(); 1788 if (!mark.has_monitor()) { 1789 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's " 1790 "object does not think it has a monitor: obj=" 1791 INTPTR_FORMAT ", mark=" INTPTR_FORMAT, p2i(n), 1792 p2i(obj), mark.value()); 1793 *error_cnt_p = *error_cnt_p + 1; 1794 } 1795 ObjectMonitor* const obj_mon = mark.monitor(); 1796 if (n != obj_mon) { 1797 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's " 1798 "object does not refer to the same monitor: obj=" 1799 INTPTR_FORMAT ", mark=" INTPTR_FORMAT ", obj_mon=" 1800 INTPTR_FORMAT, p2i(n), p2i(obj), mark.value(), p2i(obj_mon)); 1801 *error_cnt_p = *error_cnt_p + 1; 1802 } 1803 } 1804 } 1805 1806 // Log details about ObjectMonitors on the in_use_list. The 'BHL' 1807 // flags indicate why the entry is in-use, 'object' and 'object type' 1808 // indicate the associated object and its type. 1809 void ObjectSynchronizer::log_in_use_monitor_details(outputStream* out) { 1810 stringStream ss; 1811 if (_in_use_list.count() > 0) { 1812 out->print_cr("In-use monitor info:"); 1813 out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)"); 1814 out->print_cr("%18s %s %18s %18s", 1815 "monitor", "BHL", "object", "object type"); 1816 out->print_cr("================== === ================== =================="); 1817 MonitorList::Iterator iter = _in_use_list.iterator(); 1818 while (iter.has_next()) { 1819 ObjectMonitor* mid = iter.next(); 1820 const oop obj = mid->object_peek(); 1821 const markWord mark = mid->header(); 1822 ResourceMark rm; 1823 out->print(INTPTR_FORMAT " %d%d%d " INTPTR_FORMAT " %s", p2i(mid), 1824 mid->is_busy(), mark.hash() != 0, mid->owner() != NULL, 1825 p2i(obj), obj == NULL ? "" : obj->klass()->external_name()); 1826 if (mid->is_busy()) { 1827 out->print(" (%s)", mid->is_busy_to_string(&ss)); 1828 ss.reset(); 1829 } 1830 out->cr(); 1831 } 1832 } 1833 1834 out->flush(); 1835 }