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