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