1 /* 2 * Copyright (c) 1998, 2025, 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 "classfile/vmSymbols.hpp" 26 #include "gc/shared/collectedHeap.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/atomicAccess.hpp" 37 #include "runtime/basicLock.inline.hpp" 38 #include "runtime/frame.inline.hpp" 39 #include "runtime/globals.hpp" 40 #include "runtime/handles.inline.hpp" 41 #include "runtime/handshake.hpp" 42 #include "runtime/interfaceSupport.inline.hpp" 43 #include "runtime/javaThread.hpp" 44 #include "runtime/lightweightSynchronizer.hpp" 45 #include "runtime/lockStack.inline.hpp" 46 #include "runtime/mutexLocker.hpp" 47 #include "runtime/objectMonitor.inline.hpp" 48 #include "runtime/os.inline.hpp" 49 #include "runtime/osThread.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.inline.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/globalCounter.inline.hpp" 64 #include "utilities/globalDefinitions.hpp" 65 #include "utilities/linkedlist.hpp" 66 #include "utilities/preserveException.hpp" 67 68 class ObjectMonitorDeflationLogging; 69 70 void MonitorList::add(ObjectMonitor* m) { 71 ObjectMonitor* head; 72 do { 73 head = AtomicAccess::load(&_head); 74 m->set_next_om(head); 75 } while (AtomicAccess::cmpxchg(&_head, head, m) != head); 76 77 size_t count = AtomicAccess::add(&_count, 1u, memory_order_relaxed); 78 size_t old_max; 79 do { 80 old_max = AtomicAccess::load(&_max); 81 if (count <= old_max) { 82 break; 83 } 84 } while (AtomicAccess::cmpxchg(&_max, old_max, count, memory_order_relaxed) != old_max); 85 } 86 87 size_t MonitorList::count() const { 88 return AtomicAccess::load(&_count); 89 } 90 91 size_t MonitorList::max() const { 92 return AtomicAccess::load(&_max); 93 } 94 95 class ObjectMonitorDeflationSafepointer : public StackObj { 96 JavaThread* const _current; 97 ObjectMonitorDeflationLogging* const _log; 98 99 public: 100 ObjectMonitorDeflationSafepointer(JavaThread* current, ObjectMonitorDeflationLogging* log) 101 : _current(current), _log(log) {} 102 103 void block_for_safepoint(const char* op_name, const char* count_name, size_t counter); 104 }; 105 106 // Walk the in-use list and unlink deflated ObjectMonitors. 107 // Returns the number of unlinked ObjectMonitors. 108 size_t MonitorList::unlink_deflated(size_t deflated_count, 109 GrowableArray<ObjectMonitor*>* unlinked_list, 110 ObjectMonitorDeflationSafepointer* safepointer) { 111 size_t unlinked_count = 0; 112 ObjectMonitor* prev = nullptr; 113 ObjectMonitor* m = AtomicAccess::load_acquire(&_head); 114 115 while (m != nullptr) { 116 if (m->is_being_async_deflated()) { 117 // Find next live ObjectMonitor. Batch up the unlinkable monitors, so we can 118 // modify the list once per batch. The batch starts at "m". 119 size_t unlinked_batch = 0; 120 ObjectMonitor* next = m; 121 // Look for at most MonitorUnlinkBatch monitors, or the number of 122 // deflated and not unlinked monitors, whatever comes first. 123 assert(deflated_count >= unlinked_count, "Sanity: underflow"); 124 size_t unlinked_batch_limit = MIN2<size_t>(deflated_count - unlinked_count, MonitorUnlinkBatch); 125 do { 126 ObjectMonitor* next_next = next->next_om(); 127 unlinked_batch++; 128 unlinked_list->append(next); 129 next = next_next; 130 if (unlinked_batch >= unlinked_batch_limit) { 131 // Reached the max batch, so bail out of the gathering loop. 132 break; 133 } 134 if (prev == nullptr && AtomicAccess::load(&_head) != m) { 135 // Current batch used to be at head, but it is not at head anymore. 136 // Bail out and figure out where we currently are. This avoids long 137 // walks searching for new prev during unlink under heavy list inserts. 138 break; 139 } 140 } while (next != nullptr && next->is_being_async_deflated()); 141 142 // Unlink the found batch. 143 if (prev == nullptr) { 144 // The current batch is the first batch, so there is a chance that it starts at head. 145 // Optimistically assume no inserts happened, and try to unlink the entire batch from the head. 146 ObjectMonitor* prev_head = AtomicAccess::cmpxchg(&_head, m, next); 147 if (prev_head != m) { 148 // Something must have updated the head. Figure out the actual prev for this batch. 149 for (ObjectMonitor* n = prev_head; n != m; n = n->next_om()) { 150 prev = n; 151 } 152 assert(prev != nullptr, "Should have found the prev for the current batch"); 153 prev->set_next_om(next); 154 } 155 } else { 156 // The current batch is preceded by another batch. This guarantees the current batch 157 // does not start at head. Unlink the entire current batch without updating the head. 158 assert(AtomicAccess::load(&_head) != m, "Sanity"); 159 prev->set_next_om(next); 160 } 161 162 unlinked_count += unlinked_batch; 163 if (unlinked_count >= deflated_count) { 164 // Reached the max so bail out of the searching loop. 165 // There should be no more deflated monitors left. 166 break; 167 } 168 m = next; 169 } else { 170 prev = m; 171 m = m->next_om(); 172 } 173 174 // Must check for a safepoint/handshake and honor it. 175 safepointer->block_for_safepoint("unlinking", "unlinked_count", unlinked_count); 176 } 177 178 #ifdef ASSERT 179 // Invariant: the code above should unlink all deflated monitors. 180 // The code that runs after this unlinking does not expect deflated monitors. 181 // Notably, attempting to deflate the already deflated monitor would break. 182 { 183 ObjectMonitor* m = AtomicAccess::load_acquire(&_head); 184 while (m != nullptr) { 185 assert(!m->is_being_async_deflated(), "All deflated monitors should be unlinked"); 186 m = m->next_om(); 187 } 188 } 189 #endif 190 191 AtomicAccess::sub(&_count, unlinked_count); 192 return unlinked_count; 193 } 194 195 MonitorList::Iterator MonitorList::iterator() const { 196 return Iterator(AtomicAccess::load_acquire(&_head)); 197 } 198 199 ObjectMonitor* MonitorList::Iterator::next() { 200 ObjectMonitor* current = _current; 201 _current = current->next_om(); 202 return current; 203 } 204 205 // The "core" versions of monitor enter and exit reside in this file. 206 // The interpreter and compilers contain specialized transliterated 207 // variants of the enter-exit fast-path operations. See c2_MacroAssembler_x86.cpp 208 // fast_lock(...) for instance. If you make changes here, make sure to modify the 209 // interpreter, and both C1 and C2 fast-path inline locking code emission. 210 // 211 // ----------------------------------------------------------------------------- 212 213 #ifdef DTRACE_ENABLED 214 215 // Only bother with this argument setup if dtrace is available 216 // TODO-FIXME: probes should not fire when caller is _blocked. assert() accordingly. 217 218 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread) \ 219 char* bytes = nullptr; \ 220 int len = 0; \ 221 jlong jtid = SharedRuntime::get_java_tid(thread); \ 222 Symbol* klassname = obj->klass()->name(); \ 223 if (klassname != nullptr) { \ 224 bytes = (char*)klassname->bytes(); \ 225 len = klassname->utf8_length(); \ 226 } 227 228 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis) \ 229 { \ 230 if (DTraceMonitorProbes) { \ 231 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \ 232 HOTSPOT_MONITOR_WAIT(jtid, \ 233 (uintptr_t)(monitor), bytes, len, (millis)); \ 234 } \ 235 } 236 237 #define HOTSPOT_MONITOR_PROBE_notify HOTSPOT_MONITOR_NOTIFY 238 #define HOTSPOT_MONITOR_PROBE_notifyAll HOTSPOT_MONITOR_NOTIFYALL 239 #define HOTSPOT_MONITOR_PROBE_waited HOTSPOT_MONITOR_WAITED 240 241 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread) \ 242 { \ 243 if (DTraceMonitorProbes) { \ 244 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \ 245 HOTSPOT_MONITOR_PROBE_##probe(jtid, /* probe = waited */ \ 246 (uintptr_t)(monitor), bytes, len); \ 247 } \ 248 } 249 250 #else // ndef DTRACE_ENABLED 251 252 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon) {;} 253 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon) {;} 254 255 #endif // ndef DTRACE_ENABLED 256 257 // This exists only as a workaround of dtrace bug 6254741 258 static int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, JavaThread* thr) { 259 DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr); 260 return 0; 261 } 262 263 static constexpr size_t inflation_lock_count() { 264 return 256; 265 } 266 267 // Static storage for an array of PlatformMutex. 268 alignas(PlatformMutex) static uint8_t _inflation_locks[inflation_lock_count()][sizeof(PlatformMutex)]; 269 270 static inline PlatformMutex* inflation_lock(size_t index) { 271 return reinterpret_cast<PlatformMutex*>(_inflation_locks[index]); 272 } 273 274 void ObjectSynchronizer::initialize() { 275 for (size_t i = 0; i < inflation_lock_count(); i++) { 276 ::new(static_cast<void*>(inflation_lock(i))) PlatformMutex(); 277 } 278 // Start the ceiling with the estimate for one thread. 279 set_in_use_list_ceiling(AvgMonitorsPerThreadEstimate); 280 281 // Start the timer for deflations, so it does not trigger immediately. 282 _last_async_deflation_time_ns = os::javaTimeNanos(); 283 284 LightweightSynchronizer::initialize(); 285 } 286 287 MonitorList ObjectSynchronizer::_in_use_list; 288 // monitors_used_above_threshold() policy is as follows: 289 // 290 // The ratio of the current _in_use_list count to the ceiling is used 291 // to determine if we are above MonitorUsedDeflationThreshold and need 292 // to do an async monitor deflation cycle. The ceiling is increased by 293 // AvgMonitorsPerThreadEstimate when a thread is added to the system 294 // and is decreased by AvgMonitorsPerThreadEstimate when a thread is 295 // removed from the system. 296 // 297 // Note: If the _in_use_list max exceeds the ceiling, then 298 // monitors_used_above_threshold() will use the in_use_list max instead 299 // of the thread count derived ceiling because we have used more 300 // ObjectMonitors than the estimated average. 301 // 302 // Note: If deflate_idle_monitors() has NoAsyncDeflationProgressMax 303 // no-progress async monitor deflation cycles in a row, then the ceiling 304 // is adjusted upwards by monitors_used_above_threshold(). 305 // 306 // Start the ceiling with the estimate for one thread in initialize() 307 // which is called after cmd line options are processed. 308 static size_t _in_use_list_ceiling = 0; 309 bool volatile ObjectSynchronizer::_is_async_deflation_requested = false; 310 bool volatile ObjectSynchronizer::_is_final_audit = false; 311 jlong ObjectSynchronizer::_last_async_deflation_time_ns = 0; 312 static uintx _no_progress_cnt = 0; 313 static bool _no_progress_skip_increment = false; 314 315 // =====================> Quick functions 316 317 // The quick_* forms are special fast-path variants used to improve 318 // performance. In the simplest case, a "quick_*" implementation could 319 // simply return false, in which case the caller will perform the necessary 320 // state transitions and call the slow-path form. 321 // The fast-path is designed to handle frequently arising cases in an efficient 322 // manner and is just a degenerate "optimistic" variant of the slow-path. 323 // returns true -- to indicate the call was satisfied. 324 // returns false -- to indicate the call needs the services of the slow-path. 325 // A no-loitering ordinance is in effect for code in the quick_* family 326 // operators: safepoints or indefinite blocking (blocking that might span a 327 // safepoint) are forbidden. Generally the thread_state() is _in_Java upon 328 // entry. 329 // 330 // Consider: An interesting optimization is to have the JIT recognize the 331 // following common idiom: 332 // synchronized (someobj) { .... ; notify(); } 333 // That is, we find a notify() or notifyAll() call that immediately precedes 334 // the monitorexit operation. In that case the JIT could fuse the operations 335 // into a single notifyAndExit() runtime primitive. 336 337 bool ObjectSynchronizer::quick_notify(oopDesc* obj, JavaThread* current, bool all) { 338 assert(current->thread_state() == _thread_in_Java, "invariant"); 339 NoSafepointVerifier nsv; 340 if (obj == nullptr) return false; // slow-path for invalid obj 341 const markWord mark = obj->mark(); 342 343 if (mark.is_fast_locked() && current->lock_stack().contains(cast_to_oop(obj))) { 344 // Degenerate notify 345 // fast-locked by caller so by definition the implied waitset is empty. 346 return true; 347 } 348 349 if (mark.has_monitor()) { 350 ObjectMonitor* const mon = read_monitor(current, obj, mark); 351 if (mon == nullptr) { 352 // Racing with inflation/deflation go slow path 353 return false; 354 } 355 assert(mon->object() == oop(obj), "invariant"); 356 if (!mon->has_owner(current)) return false; // slow-path for IMS exception 357 358 if (mon->first_waiter() != nullptr) { 359 // We have one or more waiters. Since this is an inflated monitor 360 // that we own, we quickly notify them here and now, avoiding the slow-path. 361 if (all) { 362 mon->quick_notifyAll(current); 363 } else { 364 mon->quick_notify(current); 365 } 366 } 367 return true; 368 } 369 370 // other IMS exception states take the slow-path 371 return false; 372 } 373 374 // Handle notifications when synchronizing on value based classes 375 void ObjectSynchronizer::handle_sync_on_value_based_class(Handle obj, JavaThread* locking_thread) { 376 assert(locking_thread == Thread::current() || locking_thread->is_obj_deopt_suspend(), "must be"); 377 frame last_frame = locking_thread->last_frame(); 378 bool bcp_was_adjusted = false; 379 // Don't decrement bcp if it points to the frame's first instruction. This happens when 380 // handle_sync_on_value_based_class() is called because of a synchronized method. There 381 // is no actual monitorenter instruction in the byte code in this case. 382 if (last_frame.is_interpreted_frame() && 383 (last_frame.interpreter_frame_method()->code_base() < last_frame.interpreter_frame_bcp())) { 384 // adjust bcp to point back to monitorenter so that we print the correct line numbers 385 last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() - 1); 386 bcp_was_adjusted = true; 387 } 388 389 if (DiagnoseSyncOnValueBasedClasses == FATAL_EXIT) { 390 ResourceMark rm; 391 stringStream ss; 392 locking_thread->print_active_stack_on(&ss); 393 char* base = (char*)strstr(ss.base(), "at"); 394 char* newline = (char*)strchr(ss.base(), '\n'); 395 if (newline != nullptr) { 396 *newline = '\0'; 397 } 398 fatal("Synchronizing on object " INTPTR_FORMAT " of klass %s %s", p2i(obj()), obj->klass()->external_name(), base); 399 } else { 400 assert(DiagnoseSyncOnValueBasedClasses == LOG_WARNING, "invalid value for DiagnoseSyncOnValueBasedClasses"); 401 ResourceMark rm; 402 Log(valuebasedclasses) vblog; 403 404 vblog.info("Synchronizing on object " INTPTR_FORMAT " of klass %s", p2i(obj()), obj->klass()->external_name()); 405 if (locking_thread->has_last_Java_frame()) { 406 LogStream info_stream(vblog.info()); 407 locking_thread->print_active_stack_on(&info_stream); 408 } else { 409 vblog.info("Cannot find the last Java frame"); 410 } 411 412 EventSyncOnValueBasedClass event; 413 if (event.should_commit()) { 414 event.set_valueBasedClass(obj->klass()); 415 event.commit(); 416 } 417 } 418 419 if (bcp_was_adjusted) { 420 last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() + 1); 421 } 422 } 423 424 // ----------------------------------------------------------------------------- 425 // Monitor Enter/Exit 426 427 void ObjectSynchronizer::enter_for(Handle obj, BasicLock* lock, JavaThread* locking_thread) { 428 // When called with locking_thread != Thread::current() some mechanism must synchronize 429 // the locking_thread with respect to the current thread. Currently only used when 430 // deoptimizing and re-locking locks. See Deoptimization::relock_objects 431 assert(locking_thread == Thread::current() || locking_thread->is_obj_deopt_suspend(), "must be"); 432 return LightweightSynchronizer::enter_for(obj, lock, locking_thread); 433 } 434 435 // ----------------------------------------------------------------------------- 436 // JNI locks on java objects 437 // NOTE: must use heavy weight monitor to handle jni monitor enter 438 void ObjectSynchronizer::jni_enter(Handle obj, JavaThread* current) { 439 // Top native frames in the stack will not be seen if we attempt 440 // preemption, since we start walking from the last Java anchor. 441 NoPreemptMark npm(current); 442 443 if (obj->klass()->is_value_based()) { 444 handle_sync_on_value_based_class(obj, current); 445 } 446 447 // the current locking is from JNI instead of Java code 448 current->set_current_pending_monitor_is_from_java(false); 449 // An async deflation can race after the inflate() call and before 450 // enter() can make the ObjectMonitor busy. enter() returns false if 451 // we have lost the race to async deflation and we simply try again. 452 while (true) { 453 BasicLock lock; 454 if (LightweightSynchronizer::inflate_and_enter(obj(), &lock, inflate_cause_jni_enter, current, current) != nullptr) { 455 current->inc_held_monitor_count(1, true); 456 break; 457 } 458 } 459 current->set_current_pending_monitor_is_from_java(true); 460 } 461 462 // NOTE: must use heavy weight monitor to handle jni monitor exit 463 void ObjectSynchronizer::jni_exit(oop obj, TRAPS) { 464 JavaThread* current = THREAD; 465 466 ObjectMonitor* monitor; 467 monitor = LightweightSynchronizer::inflate_locked_or_imse(obj, inflate_cause_jni_exit, CHECK); 468 // If this thread has locked the object, exit the monitor. We 469 // intentionally do not use CHECK on check_owner because we must exit the 470 // monitor even if an exception was already pending. 471 if (monitor->check_owner(THREAD)) { 472 monitor->exit(current); 473 current->dec_held_monitor_count(1, true); 474 } 475 } 476 477 // ----------------------------------------------------------------------------- 478 // Internal VM locks on java objects 479 // standard constructor, allows locking failures 480 ObjectLocker::ObjectLocker(Handle obj, TRAPS) : _thread(THREAD), _obj(obj), 481 _npm(_thread, _thread->at_preemptable_init() /* ignore_mark */), _skip_exit(false) { 482 assert(!_thread->preempting(), ""); 483 484 _thread->check_for_valid_safepoint_state(); 485 486 if (_obj() != nullptr) { 487 ObjectSynchronizer::enter(_obj, &_lock, _thread); 488 489 if (_thread->preempting()) { 490 // If preemption was cancelled we acquired the monitor after freezing 491 // the frames. Redoing the vm call laterĀ in thaw will require us to 492 // release it since the call should look like the original one. We 493 // do it in ~ObjectLocker to reduce the window of time we hold the 494 // monitor since we can't do anything useful with it now, and would 495 // otherwise just force other vthreads to preempt in case they try 496 // to acquire this monitor. 497 _skip_exit = !_thread->preemption_cancelled(); 498 _thread->set_pending_preempted_exception(); 499 } 500 } 501 } 502 503 ObjectLocker::~ObjectLocker() { 504 if (_obj() != nullptr && !_skip_exit) { 505 ObjectSynchronizer::exit(_obj(), &_lock, _thread); 506 } 507 } 508 509 void ObjectLocker::wait_uninterruptibly(TRAPS) { 510 ObjectSynchronizer::waitUninterruptibly(_obj, 0, _thread); 511 if (_thread->preempting()) { 512 _skip_exit = true; 513 _thread->set_pending_preempted_exception(); 514 } 515 } 516 517 // ----------------------------------------------------------------------------- 518 // Wait/Notify/NotifyAll 519 // NOTE: must use heavy weight monitor to handle wait() 520 521 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) { 522 JavaThread* current = THREAD; 523 if (millis < 0) { 524 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative"); 525 } 526 527 ObjectMonitor* monitor; 528 monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_wait, CHECK_0); 529 530 DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), current, millis); 531 monitor->wait(millis, true, THREAD); // Not CHECK as we need following code 532 533 // This dummy call is in place to get around dtrace bug 6254741. Once 534 // that's fixed we can uncomment the following line, remove the call 535 // and change this function back into a "void" func. 536 // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD); 537 int ret_code = dtrace_waited_probe(monitor, obj, THREAD); 538 return ret_code; 539 } 540 541 void ObjectSynchronizer::waitUninterruptibly(Handle obj, jlong millis, TRAPS) { 542 assert(millis >= 0, "timeout value is negative"); 543 544 ObjectMonitor* monitor; 545 monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_wait, CHECK); 546 monitor->wait(millis, false, THREAD); 547 } 548 549 550 void ObjectSynchronizer::notify(Handle obj, TRAPS) { 551 JavaThread* current = THREAD; 552 553 markWord mark = obj->mark(); 554 if ((mark.is_fast_locked() && current->lock_stack().contains(obj()))) { 555 // Not inflated so there can't be any waiters to notify. 556 return; 557 } 558 ObjectMonitor* monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_notify, CHECK); 559 monitor->notify(CHECK); 560 } 561 562 // NOTE: see comment of notify() 563 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) { 564 JavaThread* current = THREAD; 565 566 markWord mark = obj->mark(); 567 if ((mark.is_fast_locked() && current->lock_stack().contains(obj()))) { 568 // Not inflated so there can't be any waiters to notify. 569 return; 570 } 571 572 ObjectMonitor* monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_notify, CHECK); 573 monitor->notifyAll(CHECK); 574 } 575 576 // ----------------------------------------------------------------------------- 577 // Hash Code handling 578 579 struct SharedGlobals { 580 char _pad_prefix[OM_CACHE_LINE_SIZE]; 581 // This is a highly shared mostly-read variable. 582 // To avoid false-sharing it needs to be the sole occupant of a cache line. 583 volatile int stw_random; 584 DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(volatile int)); 585 // Hot RW variable -- Sequester to avoid false-sharing 586 volatile int hc_sequence; 587 DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(volatile int)); 588 }; 589 590 static SharedGlobals GVars; 591 592 // hashCode() generation : 593 // 594 // Possibilities: 595 // * MD5Digest of {obj,stw_random} 596 // * CRC32 of {obj,stw_random} or any linear-feedback shift register function. 597 // * A DES- or AES-style SBox[] mechanism 598 // * One of the Phi-based schemes, such as: 599 // 2654435761 = 2^32 * Phi (golden ratio) 600 // HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stw_random ; 601 // * A variation of Marsaglia's shift-xor RNG scheme. 602 // * (obj ^ stw_random) is appealing, but can result 603 // in undesirable regularity in the hashCode values of adjacent objects 604 // (objects allocated back-to-back, in particular). This could potentially 605 // result in hashtable collisions and reduced hashtable efficiency. 606 // There are simple ways to "diffuse" the middle address bits over the 607 // generated hashCode values: 608 609 static intptr_t get_next_hash(Thread* current, oop obj) { 610 intptr_t value = 0; 611 if (hashCode == 0) { 612 // This form uses global Park-Miller RNG. 613 // On MP system we'll have lots of RW access to a global, so the 614 // mechanism induces lots of coherency traffic. 615 value = os::random(); 616 } else if (hashCode == 1) { 617 // This variation has the property of being stable (idempotent) 618 // between STW operations. This can be useful in some of the 1-0 619 // synchronization schemes. 620 intptr_t addr_bits = cast_from_oop<intptr_t>(obj) >> 3; 621 value = addr_bits ^ (addr_bits >> 5) ^ GVars.stw_random; 622 } else if (hashCode == 2) { 623 value = 1; // for sensitivity testing 624 } else if (hashCode == 3) { 625 value = ++GVars.hc_sequence; 626 } else if (hashCode == 4) { 627 value = cast_from_oop<intptr_t>(obj); 628 } else { 629 // Marsaglia's xor-shift scheme with thread-specific state 630 // This is probably the best overall implementation -- we'll 631 // likely make this the default in future releases. 632 unsigned t = current->_hashStateX; 633 t ^= (t << 11); 634 current->_hashStateX = current->_hashStateY; 635 current->_hashStateY = current->_hashStateZ; 636 current->_hashStateZ = current->_hashStateW; 637 unsigned v = current->_hashStateW; 638 v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)); 639 current->_hashStateW = v; 640 value = v; 641 } 642 643 value &= markWord::hash_mask; 644 if (value == 0) value = 0xBAD; 645 assert(value != markWord::no_hash, "invariant"); 646 return value; 647 } 648 649 static intptr_t install_hash_code(Thread* current, oop obj) { 650 assert(UseObjectMonitorTable, "must be"); 651 652 markWord mark = obj->mark_acquire(); 653 for (;;) { 654 intptr_t hash = mark.hash(); 655 if (hash != 0) { 656 return hash; 657 } 658 659 hash = get_next_hash(current, obj); 660 const markWord old_mark = mark; 661 const markWord new_mark = old_mark.copy_set_hash(hash); 662 663 mark = obj->cas_set_mark(new_mark, old_mark); 664 if (old_mark == mark) { 665 return hash; 666 } 667 } 668 } 669 670 intptr_t ObjectSynchronizer::FastHashCode(Thread* current, oop obj) { 671 if (UseObjectMonitorTable) { 672 // Since the monitor isn't in the object header, the hash can simply be 673 // installed in the object header. 674 return install_hash_code(current, obj); 675 } 676 677 while (true) { 678 ObjectMonitor* monitor = nullptr; 679 markWord temp, test; 680 intptr_t hash; 681 markWord mark = obj->mark_acquire(); 682 if (mark.is_unlocked() || mark.is_fast_locked()) { 683 hash = mark.hash(); 684 if (hash != 0) { // if it has a hash, just return it 685 return hash; 686 } 687 hash = get_next_hash(current, obj); // get a new hash 688 temp = mark.copy_set_hash(hash); // merge the hash into header 689 // try to install the hash 690 test = obj->cas_set_mark(temp, mark); 691 if (test == mark) { // if the hash was installed, return it 692 return hash; 693 } 694 // CAS failed, retry 695 continue; 696 697 // Failed to install the hash. It could be that another thread 698 // installed the hash just before our attempt or inflation has 699 // occurred or... so we fall thru to inflate the monitor for 700 // stability and then install the hash. 701 } else if (mark.has_monitor()) { 702 monitor = mark.monitor(); 703 temp = monitor->header(); 704 assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value()); 705 hash = temp.hash(); 706 if (hash != 0) { 707 // It has a hash. 708 709 // Separate load of dmw/header above from the loads in 710 // is_being_async_deflated(). 711 712 // dmw/header and _contentions may get written by different threads. 713 // Make sure to observe them in the same order when having several observers. 714 OrderAccess::loadload_for_IRIW(); 715 716 if (monitor->is_being_async_deflated()) { 717 // But we can't safely use the hash if we detect that async 718 // deflation has occurred. So we attempt to restore the 719 // header/dmw to the object's header so that we only retry 720 // once if the deflater thread happens to be slow. 721 monitor->install_displaced_markword_in_object(obj); 722 continue; 723 } 724 return hash; 725 } 726 // Fall thru so we only have one place that installs the hash in 727 // the ObjectMonitor. 728 } 729 730 // NOTE: an async deflation can race after we get the monitor and 731 // before we can update the ObjectMonitor's header with the hash 732 // value below. 733 assert(mark.has_monitor(), "must be"); 734 monitor = mark.monitor(); 735 736 // Load ObjectMonitor's header/dmw field and see if it has a hash. 737 mark = monitor->header(); 738 assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value()); 739 hash = mark.hash(); 740 if (hash == 0) { // if it does not have a hash 741 hash = get_next_hash(current, obj); // get a new hash 742 temp = mark.copy_set_hash(hash) ; // merge the hash into header 743 assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value()); 744 uintptr_t v = AtomicAccess::cmpxchg(monitor->metadata_addr(), mark.value(), temp.value()); 745 test = markWord(v); 746 if (test != mark) { 747 // The attempt to update the ObjectMonitor's header/dmw field 748 // did not work. This can happen if another thread managed to 749 // merge in the hash just before our cmpxchg(). 750 // If we add any new usages of the header/dmw field, this code 751 // will need to be updated. 752 hash = test.hash(); 753 assert(test.is_neutral(), "invariant: header=" INTPTR_FORMAT, test.value()); 754 assert(hash != 0, "should only have lost the race to a thread that set a non-zero hash"); 755 } 756 if (monitor->is_being_async_deflated() && !UseObjectMonitorTable) { 757 // If we detect that async deflation has occurred, then we 758 // attempt to restore the header/dmw to the object's header 759 // so that we only retry once if the deflater thread happens 760 // to be slow. 761 monitor->install_displaced_markword_in_object(obj); 762 continue; 763 } 764 } 765 // We finally get the hash. 766 return hash; 767 } 768 } 769 770 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* current, 771 Handle h_obj) { 772 assert(current == JavaThread::current(), "Can only be called on current thread"); 773 oop obj = h_obj(); 774 775 markWord mark = obj->mark_acquire(); 776 777 if (mark.is_fast_locked()) { 778 // fast-locking case, see if lock is in current's lock stack 779 return current->lock_stack().contains(h_obj()); 780 } 781 782 while (mark.has_monitor()) { 783 ObjectMonitor* monitor = read_monitor(current, obj, mark); 784 if (monitor != nullptr) { 785 return monitor->is_entered(current) != 0; 786 } 787 // Racing with inflation/deflation, retry 788 mark = obj->mark_acquire(); 789 790 if (mark.is_fast_locked()) { 791 // Some other thread fast_locked, current could not have held the lock 792 return false; 793 } 794 } 795 796 // Unlocked case, header in place 797 assert(mark.is_unlocked(), "sanity check"); 798 return false; 799 } 800 801 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) { 802 oop obj = h_obj(); 803 markWord mark = obj->mark_acquire(); 804 805 if (mark.is_fast_locked()) { 806 // fast-locked so get owner from the object. 807 // owning_thread_from_object() may also return null here: 808 return Threads::owning_thread_from_object(t_list, h_obj()); 809 } 810 811 while (mark.has_monitor()) { 812 ObjectMonitor* monitor = read_monitor(Thread::current(), obj, mark); 813 if (monitor != nullptr) { 814 return Threads::owning_thread_from_monitor(t_list, monitor); 815 } 816 // Racing with inflation/deflation, retry 817 mark = obj->mark_acquire(); 818 819 if (mark.is_fast_locked()) { 820 // Some other thread fast_locked 821 return Threads::owning_thread_from_object(t_list, h_obj()); 822 } 823 } 824 825 // Unlocked case, header in place 826 // Cannot have assertion since this object may have been 827 // locked by another thread when reaching here. 828 // assert(mark.is_unlocked(), "sanity check"); 829 830 return nullptr; 831 } 832 833 // Visitors ... 834 835 // Iterate over all ObjectMonitors. 836 template <typename Function> 837 void ObjectSynchronizer::monitors_iterate(Function function) { 838 MonitorList::Iterator iter = _in_use_list.iterator(); 839 while (iter.has_next()) { 840 ObjectMonitor* monitor = iter.next(); 841 function(monitor); 842 } 843 } 844 845 // Iterate ObjectMonitors owned by any thread and where the owner `filter` 846 // returns true. 847 template <typename OwnerFilter> 848 void ObjectSynchronizer::owned_monitors_iterate_filtered(MonitorClosure* closure, OwnerFilter filter) { 849 monitors_iterate([&](ObjectMonitor* monitor) { 850 // This function is only called at a safepoint or when the 851 // target thread is suspended or when the target thread is 852 // operating on itself. The current closures in use today are 853 // only interested in an owned ObjectMonitor and ownership 854 // cannot be dropped under the calling contexts so the 855 // ObjectMonitor cannot be async deflated. 856 if (monitor->has_owner() && filter(monitor)) { 857 assert(!monitor->is_being_async_deflated(), "Owned monitors should not be deflating"); 858 859 closure->do_monitor(monitor); 860 } 861 }); 862 } 863 864 // Iterate ObjectMonitors where the owner == thread; this does NOT include 865 // ObjectMonitors where owner is set to a stack-lock address in thread. 866 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure, JavaThread* thread) { 867 int64_t key = ObjectMonitor::owner_id_from(thread); 868 auto thread_filter = [&](ObjectMonitor* monitor) { return monitor->owner() == key; }; 869 return owned_monitors_iterate_filtered(closure, thread_filter); 870 } 871 872 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure, oop vthread) { 873 int64_t key = ObjectMonitor::owner_id_from(vthread); 874 auto thread_filter = [&](ObjectMonitor* monitor) { return monitor->owner() == key; }; 875 return owned_monitors_iterate_filtered(closure, thread_filter); 876 } 877 878 // Iterate ObjectMonitors owned by any thread. 879 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure) { 880 auto all_filter = [&](ObjectMonitor* monitor) { return true; }; 881 return owned_monitors_iterate_filtered(closure, all_filter); 882 } 883 884 static bool monitors_used_above_threshold(MonitorList* list) { 885 if (MonitorUsedDeflationThreshold == 0) { // disabled case is easy 886 return false; 887 } 888 size_t monitors_used = list->count(); 889 if (monitors_used == 0) { // empty list is easy 890 return false; 891 } 892 size_t old_ceiling = ObjectSynchronizer::in_use_list_ceiling(); 893 // Make sure that we use a ceiling value that is not lower than 894 // previous, not lower than the recorded max used by the system, and 895 // not lower than the current number of monitors in use (which can 896 // race ahead of max). The result is guaranteed > 0. 897 size_t ceiling = MAX3(old_ceiling, list->max(), monitors_used); 898 899 // Check if our monitor usage is above the threshold: 900 size_t monitor_usage = (monitors_used * 100LL) / ceiling; 901 if (int(monitor_usage) > MonitorUsedDeflationThreshold) { 902 // Deflate monitors if over the threshold percentage, unless no 903 // progress on previous deflations. 904 bool is_above_threshold = true; 905 906 // Check if it's time to adjust the in_use_list_ceiling up, due 907 // to too many async deflation attempts without any progress. 908 if (NoAsyncDeflationProgressMax != 0 && 909 _no_progress_cnt >= NoAsyncDeflationProgressMax) { 910 double remainder = (100.0 - MonitorUsedDeflationThreshold) / 100.0; 911 size_t delta = (size_t)(ceiling * remainder) + 1; 912 size_t new_ceiling = (ceiling > SIZE_MAX - delta) 913 ? SIZE_MAX // Overflow, let's clamp new_ceiling. 914 : ceiling + delta; 915 916 ObjectSynchronizer::set_in_use_list_ceiling(new_ceiling); 917 log_info(monitorinflation)("Too many deflations without progress; " 918 "bumping in_use_list_ceiling from %zu" 919 " to %zu", old_ceiling, new_ceiling); 920 _no_progress_cnt = 0; 921 ceiling = new_ceiling; 922 923 // Check if our monitor usage is still above the threshold: 924 monitor_usage = (monitors_used * 100LL) / ceiling; 925 is_above_threshold = int(monitor_usage) > MonitorUsedDeflationThreshold; 926 } 927 log_info(monitorinflation)("monitors_used=%zu, ceiling=%zu" 928 ", monitor_usage=%zu, threshold=%d", 929 monitors_used, ceiling, monitor_usage, MonitorUsedDeflationThreshold); 930 return is_above_threshold; 931 } 932 933 return false; 934 } 935 936 size_t ObjectSynchronizer::in_use_list_count() { 937 return _in_use_list.count(); 938 } 939 940 size_t ObjectSynchronizer::in_use_list_max() { 941 return _in_use_list.max(); 942 } 943 944 size_t ObjectSynchronizer::in_use_list_ceiling() { 945 return _in_use_list_ceiling; 946 } 947 948 void ObjectSynchronizer::dec_in_use_list_ceiling() { 949 AtomicAccess::sub(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate); 950 } 951 952 void ObjectSynchronizer::inc_in_use_list_ceiling() { 953 AtomicAccess::add(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate); 954 } 955 956 void ObjectSynchronizer::set_in_use_list_ceiling(size_t new_value) { 957 _in_use_list_ceiling = new_value; 958 } 959 960 bool ObjectSynchronizer::is_async_deflation_needed() { 961 if (is_async_deflation_requested()) { 962 // Async deflation request. 963 log_info(monitorinflation)("Async deflation needed: explicit request"); 964 return true; 965 } 966 967 jlong time_since_last = time_since_last_async_deflation_ms(); 968 969 if (AsyncDeflationInterval > 0 && 970 time_since_last > AsyncDeflationInterval && 971 monitors_used_above_threshold(&_in_use_list)) { 972 // It's been longer than our specified deflate interval and there 973 // are too many monitors in use. We don't deflate more frequently 974 // than AsyncDeflationInterval (unless is_async_deflation_requested) 975 // in order to not swamp the MonitorDeflationThread. 976 log_info(monitorinflation)("Async deflation needed: monitors used are above the threshold"); 977 return true; 978 } 979 980 if (GuaranteedAsyncDeflationInterval > 0 && 981 time_since_last > GuaranteedAsyncDeflationInterval) { 982 // It's been longer than our specified guaranteed deflate interval. 983 // We need to clean up the used monitors even if the threshold is 984 // not reached, to keep the memory utilization at bay when many threads 985 // touched many monitors. 986 log_info(monitorinflation)("Async deflation needed: guaranteed interval (%zd ms) " 987 "is greater than time since last deflation (" JLONG_FORMAT " ms)", 988 GuaranteedAsyncDeflationInterval, time_since_last); 989 990 // If this deflation has no progress, then it should not affect the no-progress 991 // tracking, otherwise threshold heuristics would think it was triggered, experienced 992 // no progress, and needs to backoff more aggressively. In this "no progress" case, 993 // the generic code would bump the no-progress counter, and we compensate for that 994 // by telling it to skip the update. 995 // 996 // If this deflation has progress, then it should let non-progress tracking 997 // know about this, otherwise the threshold heuristics would kick in, potentially 998 // experience no-progress due to aggressive cleanup by this deflation, and think 999 // it is still in no-progress stride. In this "progress" case, the generic code would 1000 // zero the counter, and we allow it to happen. 1001 _no_progress_skip_increment = true; 1002 1003 return true; 1004 } 1005 1006 return false; 1007 } 1008 1009 void ObjectSynchronizer::request_deflate_idle_monitors() { 1010 MonitorLocker ml(MonitorDeflation_lock, Mutex::_no_safepoint_check_flag); 1011 set_is_async_deflation_requested(true); 1012 ml.notify_all(); 1013 } 1014 1015 bool ObjectSynchronizer::request_deflate_idle_monitors_from_wb() { 1016 JavaThread* current = JavaThread::current(); 1017 bool ret_code = false; 1018 1019 jlong last_time = last_async_deflation_time_ns(); 1020 1021 request_deflate_idle_monitors(); 1022 1023 const int N_CHECKS = 5; 1024 for (int i = 0; i < N_CHECKS; i++) { // sleep for at most 5 seconds 1025 if (last_async_deflation_time_ns() > last_time) { 1026 log_info(monitorinflation)("Async Deflation happened after %d check(s).", i); 1027 ret_code = true; 1028 break; 1029 } 1030 { 1031 // JavaThread has to honor the blocking protocol. 1032 ThreadBlockInVM tbivm(current); 1033 os::naked_short_sleep(999); // sleep for almost 1 second 1034 } 1035 } 1036 if (!ret_code) { 1037 log_info(monitorinflation)("Async Deflation DID NOT happen after %d checks.", N_CHECKS); 1038 } 1039 1040 return ret_code; 1041 } 1042 1043 jlong ObjectSynchronizer::time_since_last_async_deflation_ms() { 1044 return (os::javaTimeNanos() - last_async_deflation_time_ns()) / (NANOUNITS / MILLIUNITS); 1045 } 1046 1047 // Walk the in-use list and deflate (at most MonitorDeflationMax) idle 1048 // ObjectMonitors. Returns the number of deflated ObjectMonitors. 1049 // 1050 size_t ObjectSynchronizer::deflate_monitor_list(ObjectMonitorDeflationSafepointer* safepointer) { 1051 MonitorList::Iterator iter = _in_use_list.iterator(); 1052 size_t deflated_count = 0; 1053 Thread* current = Thread::current(); 1054 1055 while (iter.has_next()) { 1056 if (deflated_count >= (size_t)MonitorDeflationMax) { 1057 break; 1058 } 1059 ObjectMonitor* mid = iter.next(); 1060 if (mid->deflate_monitor(current)) { 1061 deflated_count++; 1062 } 1063 1064 // Must check for a safepoint/handshake and honor it. 1065 safepointer->block_for_safepoint("deflation", "deflated_count", deflated_count); 1066 } 1067 1068 return deflated_count; 1069 } 1070 1071 class DeflationHandshakeClosure : public HandshakeClosure { 1072 public: 1073 DeflationHandshakeClosure() : HandshakeClosure("DeflationHandshakeClosure") {} 1074 1075 void do_thread(Thread* thread) { 1076 log_trace(monitorinflation)("DeflationHandshakeClosure::do_thread: thread=" 1077 INTPTR_FORMAT, p2i(thread)); 1078 if (thread->is_Java_thread()) { 1079 // Clear OM cache 1080 JavaThread* jt = JavaThread::cast(thread); 1081 jt->om_clear_monitor_cache(); 1082 } 1083 } 1084 }; 1085 1086 class VM_RendezvousGCThreads : public VM_Operation { 1087 public: 1088 bool evaluate_at_safepoint() const override { return false; } 1089 VMOp_Type type() const override { return VMOp_RendezvousGCThreads; } 1090 void doit() override { 1091 Universe::heap()->safepoint_synchronize_begin(); 1092 Universe::heap()->safepoint_synchronize_end(); 1093 }; 1094 }; 1095 1096 static size_t delete_monitors(GrowableArray<ObjectMonitor*>* delete_list, 1097 ObjectMonitorDeflationSafepointer* safepointer) { 1098 NativeHeapTrimmer::SuspendMark sm("monitor deletion"); 1099 size_t deleted_count = 0; 1100 for (ObjectMonitor* monitor: *delete_list) { 1101 delete monitor; 1102 deleted_count++; 1103 // A JavaThread must check for a safepoint/handshake and honor it. 1104 safepointer->block_for_safepoint("deletion", "deleted_count", deleted_count); 1105 } 1106 return deleted_count; 1107 } 1108 1109 class ObjectMonitorDeflationLogging: public StackObj { 1110 LogStreamHandle(Debug, monitorinflation) _debug; 1111 LogStreamHandle(Info, monitorinflation) _info; 1112 LogStream* _stream; 1113 elapsedTimer _timer; 1114 1115 size_t ceiling() const { return ObjectSynchronizer::in_use_list_ceiling(); } 1116 size_t count() const { return ObjectSynchronizer::in_use_list_count(); } 1117 size_t max() const { return ObjectSynchronizer::in_use_list_max(); } 1118 1119 public: 1120 ObjectMonitorDeflationLogging() 1121 : _debug(), _info(), _stream(nullptr) { 1122 if (_debug.is_enabled()) { 1123 _stream = &_debug; 1124 } else if (_info.is_enabled()) { 1125 _stream = &_info; 1126 } 1127 } 1128 1129 void begin() { 1130 if (_stream != nullptr) { 1131 _stream->print_cr("begin deflating: in_use_list stats: ceiling=%zu, count=%zu, max=%zu", 1132 ceiling(), count(), max()); 1133 _timer.start(); 1134 } 1135 } 1136 1137 void before_handshake(size_t unlinked_count) { 1138 if (_stream != nullptr) { 1139 _timer.stop(); 1140 _stream->print_cr("before handshaking: unlinked_count=%zu" 1141 ", in_use_list stats: ceiling=%zu, count=" 1142 "%zu, max=%zu", 1143 unlinked_count, ceiling(), count(), max()); 1144 } 1145 } 1146 1147 void after_handshake() { 1148 if (_stream != nullptr) { 1149 _stream->print_cr("after handshaking: in_use_list stats: ceiling=" 1150 "%zu, count=%zu, max=%zu", 1151 ceiling(), count(), max()); 1152 _timer.start(); 1153 } 1154 } 1155 1156 void end(size_t deflated_count, size_t unlinked_count) { 1157 if (_stream != nullptr) { 1158 _timer.stop(); 1159 if (deflated_count != 0 || unlinked_count != 0 || _debug.is_enabled()) { 1160 _stream->print_cr("deflated_count=%zu, {unlinked,deleted}_count=%zu monitors in %3.7f secs", 1161 deflated_count, unlinked_count, _timer.seconds()); 1162 } 1163 _stream->print_cr("end deflating: in_use_list stats: ceiling=%zu, count=%zu, max=%zu", 1164 ceiling(), count(), max()); 1165 } 1166 } 1167 1168 void before_block_for_safepoint(const char* op_name, const char* cnt_name, size_t cnt) { 1169 if (_stream != nullptr) { 1170 _timer.stop(); 1171 _stream->print_cr("pausing %s: %s=%zu, in_use_list stats: ceiling=" 1172 "%zu, count=%zu, max=%zu", 1173 op_name, cnt_name, cnt, ceiling(), count(), max()); 1174 } 1175 } 1176 1177 void after_block_for_safepoint(const char* op_name) { 1178 if (_stream != nullptr) { 1179 _stream->print_cr("resuming %s: in_use_list stats: ceiling=%zu" 1180 ", count=%zu, max=%zu", op_name, 1181 ceiling(), count(), max()); 1182 _timer.start(); 1183 } 1184 } 1185 }; 1186 1187 void ObjectMonitorDeflationSafepointer::block_for_safepoint(const char* op_name, const char* count_name, size_t counter) { 1188 if (!SafepointMechanism::should_process(_current)) { 1189 return; 1190 } 1191 1192 // A safepoint/handshake has started. 1193 _log->before_block_for_safepoint(op_name, count_name, counter); 1194 1195 { 1196 // Honor block request. 1197 ThreadBlockInVM tbivm(_current); 1198 } 1199 1200 _log->after_block_for_safepoint(op_name); 1201 } 1202 1203 // This function is called by the MonitorDeflationThread to deflate 1204 // ObjectMonitors. 1205 size_t ObjectSynchronizer::deflate_idle_monitors() { 1206 JavaThread* current = JavaThread::current(); 1207 assert(current->is_monitor_deflation_thread(), "The only monitor deflater"); 1208 1209 // The async deflation request has been processed. 1210 _last_async_deflation_time_ns = os::javaTimeNanos(); 1211 set_is_async_deflation_requested(false); 1212 1213 ObjectMonitorDeflationLogging log; 1214 ObjectMonitorDeflationSafepointer safepointer(current, &log); 1215 1216 log.begin(); 1217 1218 // Deflate some idle ObjectMonitors. 1219 size_t deflated_count = deflate_monitor_list(&safepointer); 1220 1221 // Unlink the deflated ObjectMonitors from the in-use list. 1222 size_t unlinked_count = 0; 1223 size_t deleted_count = 0; 1224 if (deflated_count > 0) { 1225 ResourceMark rm(current); 1226 GrowableArray<ObjectMonitor*> delete_list((int)deflated_count); 1227 unlinked_count = _in_use_list.unlink_deflated(deflated_count, &delete_list, &safepointer); 1228 1229 #ifdef ASSERT 1230 if (UseObjectMonitorTable) { 1231 for (ObjectMonitor* monitor : delete_list) { 1232 assert(!LightweightSynchronizer::contains_monitor(current, monitor), "Should have been removed"); 1233 } 1234 } 1235 #endif 1236 1237 log.before_handshake(unlinked_count); 1238 1239 // A JavaThread needs to handshake in order to safely free the 1240 // ObjectMonitors that were deflated in this cycle. 1241 DeflationHandshakeClosure dhc; 1242 Handshake::execute(&dhc); 1243 // Also, we sync and desync GC threads around the handshake, so that they can 1244 // safely read the mark-word and look-through to the object-monitor, without 1245 // being afraid that the object-monitor is going away. 1246 VM_RendezvousGCThreads sync_gc; 1247 VMThread::execute(&sync_gc); 1248 1249 log.after_handshake(); 1250 1251 // After the handshake, safely free the ObjectMonitors that were 1252 // deflated and unlinked in this cycle. 1253 1254 // Delete the unlinked ObjectMonitors. 1255 deleted_count = delete_monitors(&delete_list, &safepointer); 1256 assert(unlinked_count == deleted_count, "must be"); 1257 } 1258 1259 log.end(deflated_count, unlinked_count); 1260 1261 GVars.stw_random = os::random(); 1262 1263 if (deflated_count != 0) { 1264 _no_progress_cnt = 0; 1265 } else if (_no_progress_skip_increment) { 1266 _no_progress_skip_increment = false; 1267 } else { 1268 _no_progress_cnt++; 1269 } 1270 1271 return deflated_count; 1272 } 1273 1274 // Monitor cleanup on JavaThread::exit 1275 1276 // Iterate through monitor cache and attempt to release thread's monitors 1277 class ReleaseJavaMonitorsClosure: public MonitorClosure { 1278 private: 1279 JavaThread* _thread; 1280 1281 public: 1282 ReleaseJavaMonitorsClosure(JavaThread* thread) : _thread(thread) {} 1283 void do_monitor(ObjectMonitor* mid) { 1284 intx rec = mid->complete_exit(_thread); 1285 _thread->dec_held_monitor_count(rec + 1); 1286 } 1287 }; 1288 1289 // Release all inflated monitors owned by current thread. Lightweight monitors are 1290 // ignored. This is meant to be called during JNI thread detach which assumes 1291 // all remaining monitors are heavyweight. All exceptions are swallowed. 1292 // Scanning the extant monitor list can be time consuming. 1293 // A simple optimization is to add a per-thread flag that indicates a thread 1294 // called jni_monitorenter() during its lifetime. 1295 // 1296 // Instead of NoSafepointVerifier it might be cheaper to 1297 // use an idiom of the form: 1298 // auto int tmp = SafepointSynchronize::_safepoint_counter ; 1299 // <code that must not run at safepoint> 1300 // guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ; 1301 // Since the tests are extremely cheap we could leave them enabled 1302 // for normal product builds. 1303 1304 void ObjectSynchronizer::release_monitors_owned_by_thread(JavaThread* current) { 1305 assert(current == JavaThread::current(), "must be current Java thread"); 1306 NoSafepointVerifier nsv; 1307 ReleaseJavaMonitorsClosure rjmc(current); 1308 ObjectSynchronizer::owned_monitors_iterate(&rjmc, current); 1309 assert(!current->has_pending_exception(), "Should not be possible"); 1310 current->clear_pending_exception(); 1311 assert(current->held_monitor_count() == 0, "Should not be possible"); 1312 // All monitors (including entered via JNI) have been unlocked above, so we need to clear jni count. 1313 current->clear_jni_monitor_count(); 1314 } 1315 1316 const char* ObjectSynchronizer::inflate_cause_name(const InflateCause cause) { 1317 switch (cause) { 1318 case inflate_cause_vm_internal: return "VM Internal"; 1319 case inflate_cause_monitor_enter: return "Monitor Enter"; 1320 case inflate_cause_wait: return "Monitor Wait"; 1321 case inflate_cause_notify: return "Monitor Notify"; 1322 case inflate_cause_jni_enter: return "JNI Monitor Enter"; 1323 case inflate_cause_jni_exit: return "JNI Monitor Exit"; 1324 default: 1325 ShouldNotReachHere(); 1326 } 1327 return "Unknown"; 1328 } 1329 1330 //------------------------------------------------------------------------------ 1331 // Debugging code 1332 1333 u_char* ObjectSynchronizer::get_gvars_addr() { 1334 return (u_char*)&GVars; 1335 } 1336 1337 u_char* ObjectSynchronizer::get_gvars_hc_sequence_addr() { 1338 return (u_char*)&GVars.hc_sequence; 1339 } 1340 1341 size_t ObjectSynchronizer::get_gvars_size() { 1342 return sizeof(SharedGlobals); 1343 } 1344 1345 u_char* ObjectSynchronizer::get_gvars_stw_random_addr() { 1346 return (u_char*)&GVars.stw_random; 1347 } 1348 1349 // Do the final audit and print of ObjectMonitor stats; must be done 1350 // by the VMThread at VM exit time. 1351 void ObjectSynchronizer::do_final_audit_and_print_stats() { 1352 assert(Thread::current()->is_VM_thread(), "sanity check"); 1353 1354 if (is_final_audit()) { // Only do the audit once. 1355 return; 1356 } 1357 set_is_final_audit(); 1358 log_info(monitorinflation)("Starting the final audit."); 1359 1360 if (log_is_enabled(Info, monitorinflation)) { 1361 LogStreamHandle(Info, monitorinflation) ls; 1362 audit_and_print_stats(&ls, true /* on_exit */); 1363 } 1364 } 1365 1366 // This function can be called by the MonitorDeflationThread or it can be called when 1367 // we are trying to exit the VM. The list walker functions can run in parallel with 1368 // the other list operations. 1369 // Calls to this function can be added in various places as a debugging 1370 // aid. 1371 // 1372 void ObjectSynchronizer::audit_and_print_stats(outputStream* ls, bool on_exit) { 1373 int error_cnt = 0; 1374 1375 ls->print_cr("Checking in_use_list:"); 1376 chk_in_use_list(ls, &error_cnt); 1377 1378 if (error_cnt == 0) { 1379 ls->print_cr("No errors found in in_use_list checks."); 1380 } else { 1381 log_error(monitorinflation)("found in_use_list errors: error_cnt=%d", error_cnt); 1382 } 1383 1384 // When exiting, only log the interesting entries at the Info level. 1385 // When called at intervals by the MonitorDeflationThread, log output 1386 // at the Trace level since there can be a lot of it. 1387 if (!on_exit && log_is_enabled(Trace, monitorinflation)) { 1388 LogStreamHandle(Trace, monitorinflation) ls_tr; 1389 log_in_use_monitor_details(&ls_tr, true /* log_all */); 1390 } else if (on_exit) { 1391 log_in_use_monitor_details(ls, false /* log_all */); 1392 } 1393 1394 ls->flush(); 1395 1396 guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt); 1397 } 1398 1399 // Check the in_use_list; log the results of the checks. 1400 void ObjectSynchronizer::chk_in_use_list(outputStream* out, int *error_cnt_p) { 1401 size_t l_in_use_count = _in_use_list.count(); 1402 size_t l_in_use_max = _in_use_list.max(); 1403 out->print_cr("count=%zu, max=%zu", l_in_use_count, 1404 l_in_use_max); 1405 1406 size_t ck_in_use_count = 0; 1407 MonitorList::Iterator iter = _in_use_list.iterator(); 1408 while (iter.has_next()) { 1409 ObjectMonitor* mid = iter.next(); 1410 chk_in_use_entry(mid, out, error_cnt_p); 1411 ck_in_use_count++; 1412 } 1413 1414 if (l_in_use_count == ck_in_use_count) { 1415 out->print_cr("in_use_count=%zu equals ck_in_use_count=%zu", 1416 l_in_use_count, ck_in_use_count); 1417 } else { 1418 out->print_cr("WARNING: in_use_count=%zu is not equal to " 1419 "ck_in_use_count=%zu", l_in_use_count, 1420 ck_in_use_count); 1421 } 1422 1423 size_t ck_in_use_max = _in_use_list.max(); 1424 if (l_in_use_max == ck_in_use_max) { 1425 out->print_cr("in_use_max=%zu equals ck_in_use_max=%zu", 1426 l_in_use_max, ck_in_use_max); 1427 } else { 1428 out->print_cr("WARNING: in_use_max=%zu is not equal to " 1429 "ck_in_use_max=%zu", l_in_use_max, ck_in_use_max); 1430 } 1431 } 1432 1433 // Check an in-use monitor entry; log any errors. 1434 void ObjectSynchronizer::chk_in_use_entry(ObjectMonitor* n, outputStream* out, 1435 int* error_cnt_p) { 1436 if (n->owner_is_DEFLATER_MARKER()) { 1437 // This could happen when monitor deflation blocks for a safepoint. 1438 return; 1439 } 1440 1441 1442 if (n->metadata() == 0) { 1443 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor must " 1444 "have non-null _metadata (header/hash) field.", p2i(n)); 1445 *error_cnt_p = *error_cnt_p + 1; 1446 } 1447 1448 const oop obj = n->object_peek(); 1449 if (obj == nullptr) { 1450 return; 1451 } 1452 1453 const markWord mark = obj->mark(); 1454 if (!mark.has_monitor()) { 1455 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's " 1456 "object does not think it has a monitor: obj=" 1457 INTPTR_FORMAT ", mark=" INTPTR_FORMAT, p2i(n), 1458 p2i(obj), mark.value()); 1459 *error_cnt_p = *error_cnt_p + 1; 1460 return; 1461 } 1462 1463 ObjectMonitor* const obj_mon = read_monitor(Thread::current(), obj, mark); 1464 if (n != obj_mon) { 1465 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's " 1466 "object does not refer to the same monitor: obj=" 1467 INTPTR_FORMAT ", mark=" INTPTR_FORMAT ", obj_mon=" 1468 INTPTR_FORMAT, p2i(n), p2i(obj), mark.value(), p2i(obj_mon)); 1469 *error_cnt_p = *error_cnt_p + 1; 1470 } 1471 } 1472 1473 // Log details about ObjectMonitors on the in_use_list. The 'BHL' 1474 // flags indicate why the entry is in-use, 'object' and 'object type' 1475 // indicate the associated object and its type. 1476 void ObjectSynchronizer::log_in_use_monitor_details(outputStream* out, bool log_all) { 1477 if (_in_use_list.count() > 0) { 1478 stringStream ss; 1479 out->print_cr("In-use monitor info%s:", log_all ? "" : " (eliding idle monitors)"); 1480 out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)"); 1481 out->print_cr("%18s %s %18s %18s", 1482 "monitor", "BHL", "object", "object type"); 1483 out->print_cr("================== === ================== =================="); 1484 1485 auto is_interesting = [&](ObjectMonitor* monitor) { 1486 return log_all || monitor->has_owner() || monitor->is_busy(); 1487 }; 1488 1489 monitors_iterate([&](ObjectMonitor* monitor) { 1490 if (is_interesting(monitor)) { 1491 const oop obj = monitor->object_peek(); 1492 const intptr_t hash = UseObjectMonitorTable ? monitor->hash() : monitor->header().hash(); 1493 ResourceMark rm; 1494 out->print(INTPTR_FORMAT " %d%d%d " INTPTR_FORMAT " %s", p2i(monitor), 1495 monitor->is_busy(), hash != 0, monitor->has_owner(), 1496 p2i(obj), obj == nullptr ? "" : obj->klass()->external_name()); 1497 if (monitor->is_busy()) { 1498 out->print(" (%s)", monitor->is_busy_to_string(&ss)); 1499 ss.reset(); 1500 } 1501 out->cr(); 1502 } 1503 }); 1504 } 1505 1506 out->flush(); 1507 }