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