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