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