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