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