1 /*
   2  * Copyright (c) 1998, 2025, 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 "classfile/vmSymbols.hpp"
  26 #include "gc/shared/collectedHeap.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/atomicAccess.hpp"
  37 #include "runtime/basicLock.inline.hpp"
  38 #include "runtime/frame.inline.hpp"
  39 #include "runtime/globals.hpp"
  40 #include "runtime/handles.inline.hpp"
  41 #include "runtime/handshake.hpp"
  42 #include "runtime/interfaceSupport.inline.hpp"
  43 #include "runtime/javaThread.hpp"
  44 #include "runtime/lightweightSynchronizer.hpp"
  45 #include "runtime/lockStack.inline.hpp"
  46 #include "runtime/mutexLocker.hpp"
  47 #include "runtime/objectMonitor.inline.hpp"
  48 #include "runtime/os.inline.hpp"
  49 #include "runtime/osThread.hpp"
  50 #include "runtime/safepointMechanism.inline.hpp"
  51 #include "runtime/safepointVerifiers.hpp"
  52 #include "runtime/sharedRuntime.hpp"
  53 #include "runtime/stubRoutines.hpp"
  54 #include "runtime/synchronizer.inline.hpp"
  55 #include "runtime/threads.hpp"
  56 #include "runtime/timer.hpp"
  57 #include "runtime/trimNativeHeap.hpp"
  58 #include "runtime/vframe.hpp"
  59 #include "runtime/vmThread.hpp"
  60 #include "utilities/align.hpp"
  61 #include "utilities/dtrace.hpp"
  62 #include "utilities/events.hpp"
  63 #include "utilities/globalCounter.inline.hpp"
  64 #include "utilities/globalDefinitions.hpp"
  65 #include "utilities/linkedlist.hpp"
  66 #include "utilities/preserveException.hpp"
  67 
  68 class ObjectMonitorDeflationLogging;
  69 
  70 void MonitorList::add(ObjectMonitor* m) {
  71   ObjectMonitor* head;
  72   do {
  73     head = AtomicAccess::load(&_head);
  74     m->set_next_om(head);
  75   } while (AtomicAccess::cmpxchg(&_head, head, m) != head);
  76 
  77   size_t count = AtomicAccess::add(&_count, 1u, memory_order_relaxed);
  78   size_t old_max;
  79   do {
  80     old_max = AtomicAccess::load(&_max);
  81     if (count <= old_max) {
  82       break;
  83     }
  84   } while (AtomicAccess::cmpxchg(&_max, old_max, count, memory_order_relaxed) != old_max);
  85 }
  86 
  87 size_t MonitorList::count() const {
  88   return AtomicAccess::load(&_count);
  89 }
  90 
  91 size_t MonitorList::max() const {
  92   return AtomicAccess::load(&_max);
  93 }
  94 
  95 class ObjectMonitorDeflationSafepointer : public StackObj {
  96   JavaThread* const                    _current;
  97   ObjectMonitorDeflationLogging* const _log;
  98 
  99 public:
 100   ObjectMonitorDeflationSafepointer(JavaThread* current, ObjectMonitorDeflationLogging* log)
 101     : _current(current), _log(log) {}
 102 
 103   void block_for_safepoint(const char* op_name, const char* count_name, size_t counter);
 104 };
 105 
 106 // Walk the in-use list and unlink deflated ObjectMonitors.
 107 // Returns the number of unlinked ObjectMonitors.
 108 size_t MonitorList::unlink_deflated(size_t deflated_count,
 109                                     GrowableArray<ObjectMonitor*>* unlinked_list,
 110                                     ObjectMonitorDeflationSafepointer* safepointer) {
 111   size_t unlinked_count = 0;
 112   ObjectMonitor* prev = nullptr;
 113   ObjectMonitor* m = AtomicAccess::load_acquire(&_head);
 114 
 115   while (m != nullptr) {
 116     if (m->is_being_async_deflated()) {
 117       // Find next live ObjectMonitor. Batch up the unlinkable monitors, so we can
 118       // modify the list once per batch. The batch starts at "m".
 119       size_t unlinked_batch = 0;
 120       ObjectMonitor* next = m;
 121       // Look for at most MonitorUnlinkBatch monitors, or the number of
 122       // deflated and not unlinked monitors, whatever comes first.
 123       assert(deflated_count >= unlinked_count, "Sanity: underflow");
 124       size_t unlinked_batch_limit = MIN2<size_t>(deflated_count - unlinked_count, MonitorUnlinkBatch);
 125       do {
 126         ObjectMonitor* next_next = next->next_om();
 127         unlinked_batch++;
 128         unlinked_list->append(next);
 129         next = next_next;
 130         if (unlinked_batch >= unlinked_batch_limit) {
 131           // Reached the max batch, so bail out of the gathering loop.
 132           break;
 133         }
 134         if (prev == nullptr && AtomicAccess::load(&_head) != m) {
 135           // Current batch used to be at head, but it is not at head anymore.
 136           // Bail out and figure out where we currently are. This avoids long
 137           // walks searching for new prev during unlink under heavy list inserts.
 138           break;
 139         }
 140       } while (next != nullptr && next->is_being_async_deflated());
 141 
 142       // Unlink the found batch.
 143       if (prev == nullptr) {
 144         // The current batch is the first batch, so there is a chance that it starts at head.
 145         // Optimistically assume no inserts happened, and try to unlink the entire batch from the head.
 146         ObjectMonitor* prev_head = AtomicAccess::cmpxchg(&_head, m, next);
 147         if (prev_head != m) {
 148           // Something must have updated the head. Figure out the actual prev for this batch.
 149           for (ObjectMonitor* n = prev_head; n != m; n = n->next_om()) {
 150             prev = n;
 151           }
 152           assert(prev != nullptr, "Should have found the prev for the current batch");
 153           prev->set_next_om(next);
 154         }
 155       } else {
 156         // The current batch is preceded by another batch. This guarantees the current batch
 157         // does not start at head. Unlink the entire current batch without updating the head.
 158         assert(AtomicAccess::load(&_head) != m, "Sanity");
 159         prev->set_next_om(next);
 160       }
 161 
 162       unlinked_count += unlinked_batch;
 163       if (unlinked_count >= deflated_count) {
 164         // Reached the max so bail out of the searching loop.
 165         // There should be no more deflated monitors left.
 166         break;
 167       }
 168       m = next;
 169     } else {
 170       prev = m;
 171       m = m->next_om();
 172     }
 173 
 174     // Must check for a safepoint/handshake and honor it.
 175     safepointer->block_for_safepoint("unlinking", "unlinked_count", unlinked_count);
 176   }
 177 
 178 #ifdef ASSERT
 179   // Invariant: the code above should unlink all deflated monitors.
 180   // The code that runs after this unlinking does not expect deflated monitors.
 181   // Notably, attempting to deflate the already deflated monitor would break.
 182   {
 183     ObjectMonitor* m = AtomicAccess::load_acquire(&_head);
 184     while (m != nullptr) {
 185       assert(!m->is_being_async_deflated(), "All deflated monitors should be unlinked");
 186       m = m->next_om();
 187     }
 188   }
 189 #endif
 190 
 191   AtomicAccess::sub(&_count, unlinked_count);
 192   return unlinked_count;
 193 }
 194 
 195 MonitorList::Iterator MonitorList::iterator() const {
 196   return Iterator(AtomicAccess::load_acquire(&_head));
 197 }
 198 
 199 ObjectMonitor* MonitorList::Iterator::next() {
 200   ObjectMonitor* current = _current;
 201   _current = current->next_om();
 202   return current;
 203 }
 204 
 205 // The "core" versions of monitor enter and exit reside in this file.
 206 // The interpreter and compilers contain specialized transliterated
 207 // variants of the enter-exit fast-path operations.  See c2_MacroAssembler_x86.cpp
 208 // fast_lock(...) for instance.  If you make changes here, make sure to modify the
 209 // interpreter, and both C1 and C2 fast-path inline locking code emission.
 210 //
 211 // -----------------------------------------------------------------------------
 212 
 213 #ifdef DTRACE_ENABLED
 214 
 215 // Only bother with this argument setup if dtrace is available
 216 // TODO-FIXME: probes should not fire when caller is _blocked.  assert() accordingly.
 217 
 218 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread)                           \
 219   char* bytes = nullptr;                                                      \
 220   int len = 0;                                                             \
 221   jlong jtid = SharedRuntime::get_java_tid(thread);                        \
 222   Symbol* klassname = obj->klass()->name();                                \
 223   if (klassname != nullptr) {                                                 \
 224     bytes = (char*)klassname->bytes();                                     \
 225     len = klassname->utf8_length();                                        \
 226   }
 227 
 228 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis)            \
 229   {                                                                        \
 230     if (DTraceMonitorProbes) {                                             \
 231       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
 232       HOTSPOT_MONITOR_WAIT(jtid,                                           \
 233                            (uintptr_t)(monitor), bytes, len, (millis));    \
 234     }                                                                      \
 235   }
 236 
 237 #define HOTSPOT_MONITOR_PROBE_notify HOTSPOT_MONITOR_NOTIFY
 238 #define HOTSPOT_MONITOR_PROBE_notifyAll HOTSPOT_MONITOR_NOTIFYALL
 239 #define HOTSPOT_MONITOR_PROBE_waited HOTSPOT_MONITOR_WAITED
 240 
 241 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread)                  \
 242   {                                                                        \
 243     if (DTraceMonitorProbes) {                                             \
 244       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
 245       HOTSPOT_MONITOR_PROBE_##probe(jtid, /* probe = waited */             \
 246                                     (uintptr_t)(monitor), bytes, len);     \
 247     }                                                                      \
 248   }
 249 
 250 #else //  ndef DTRACE_ENABLED
 251 
 252 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon)    {;}
 253 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon)          {;}
 254 
 255 #endif // ndef DTRACE_ENABLED
 256 
 257 // This exists only as a workaround of dtrace bug 6254741
 258 static int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, JavaThread* thr) {
 259   DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
 260   return 0;
 261 }
 262 
 263 static constexpr size_t inflation_lock_count() {
 264   return 256;
 265 }
 266 
 267 // Static storage for an array of PlatformMutex.
 268 alignas(PlatformMutex) static uint8_t _inflation_locks[inflation_lock_count()][sizeof(PlatformMutex)];
 269 
 270 static inline PlatformMutex* inflation_lock(size_t index) {
 271   return reinterpret_cast<PlatformMutex*>(_inflation_locks[index]);
 272 }
 273 
 274 void ObjectSynchronizer::initialize() {
 275   for (size_t i = 0; i < inflation_lock_count(); i++) {
 276     ::new(static_cast<void*>(inflation_lock(i))) PlatformMutex();
 277   }
 278   // Start the ceiling with the estimate for one thread.
 279   set_in_use_list_ceiling(AvgMonitorsPerThreadEstimate);
 280 
 281   // Start the timer for deflations, so it does not trigger immediately.
 282   _last_async_deflation_time_ns = os::javaTimeNanos();
 283 
 284   LightweightSynchronizer::initialize();
 285 }
 286 
 287 MonitorList ObjectSynchronizer::_in_use_list;
 288 // monitors_used_above_threshold() policy is as follows:
 289 //
 290 // The ratio of the current _in_use_list count to the ceiling is used
 291 // to determine if we are above MonitorUsedDeflationThreshold and need
 292 // to do an async monitor deflation cycle. The ceiling is increased by
 293 // AvgMonitorsPerThreadEstimate when a thread is added to the system
 294 // and is decreased by AvgMonitorsPerThreadEstimate when a thread is
 295 // removed from the system.
 296 //
 297 // Note: If the _in_use_list max exceeds the ceiling, then
 298 // monitors_used_above_threshold() will use the in_use_list max instead
 299 // of the thread count derived ceiling because we have used more
 300 // ObjectMonitors than the estimated average.
 301 //
 302 // Note: If deflate_idle_monitors() has NoAsyncDeflationProgressMax
 303 // no-progress async monitor deflation cycles in a row, then the ceiling
 304 // is adjusted upwards by monitors_used_above_threshold().
 305 //
 306 // Start the ceiling with the estimate for one thread in initialize()
 307 // which is called after cmd line options are processed.
 308 static size_t _in_use_list_ceiling = 0;
 309 bool volatile ObjectSynchronizer::_is_async_deflation_requested = false;
 310 bool volatile ObjectSynchronizer::_is_final_audit = false;
 311 jlong ObjectSynchronizer::_last_async_deflation_time_ns = 0;
 312 static uintx _no_progress_cnt = 0;
 313 static bool _no_progress_skip_increment = false;
 314 
 315 // These checks are required for wait, notify and exit to avoid inflating the monitor to
 316 // find out this inline type object cannot be locked.
 317 #define CHECK_THROW_NOSYNC_IMSE(obj)  \
 318   if ((obj)->mark().is_inline_type()) {  \
 319     JavaThread* THREAD = current;           \
 320     ResourceMark rm(THREAD);                \
 321     THROW_MSG(vmSymbols::java_lang_IllegalMonitorStateException(), obj->klass()->external_name()); \
 322   }
 323 
 324 #define CHECK_THROW_NOSYNC_IMSE_0(obj)  \
 325   if ((obj)->mark().is_inline_type()) {  \
 326     JavaThread* THREAD = current;             \
 327     ResourceMark rm(THREAD);                  \
 328     THROW_MSG_0(vmSymbols::java_lang_IllegalMonitorStateException(), obj->klass()->external_name()); \
 329   }
 330 
 331 // =====================> Quick functions
 332 
 333 // The quick_* forms are special fast-path variants used to improve
 334 // performance.  In the simplest case, a "quick_*" implementation could
 335 // simply return false, in which case the caller will perform the necessary
 336 // state transitions and call the slow-path form.
 337 // The fast-path is designed to handle frequently arising cases in an efficient
 338 // manner and is just a degenerate "optimistic" variant of the slow-path.
 339 // returns true  -- to indicate the call was satisfied.
 340 // returns false -- to indicate the call needs the services of the slow-path.
 341 // A no-loitering ordinance is in effect for code in the quick_* family
 342 // operators: safepoints or indefinite blocking (blocking that might span a
 343 // safepoint) are forbidden. Generally the thread_state() is _in_Java upon
 344 // entry.
 345 //
 346 // Consider: An interesting optimization is to have the JIT recognize the
 347 // following common idiom:
 348 //   synchronized (someobj) { .... ; notify(); }
 349 // That is, we find a notify() or notifyAll() call that immediately precedes
 350 // the monitorexit operation.  In that case the JIT could fuse the operations
 351 // into a single notifyAndExit() runtime primitive.
 352 
 353 bool ObjectSynchronizer::quick_notify(oopDesc* obj, JavaThread* current, bool all) {
 354   assert(current->thread_state() == _thread_in_Java, "invariant");
 355   NoSafepointVerifier nsv;
 356   if (obj == nullptr) return false;  // slow-path for invalid obj
 357   assert(!obj->klass()->is_inline_klass(), "monitor op on inline type");
 358   const markWord mark = obj->mark();
 359 
 360   if (mark.is_fast_locked() && current->lock_stack().contains(cast_to_oop(obj))) {
 361     // Degenerate notify
 362     // fast-locked by caller so by definition the implied waitset is empty.
 363     return true;
 364   }
 365 
 366   if (mark.has_monitor()) {
 367     ObjectMonitor* const mon = read_monitor(current, obj, mark);
 368     if (mon == nullptr) {
 369       // Racing with inflation/deflation go slow path
 370       return false;
 371     }
 372     assert(mon->object() == oop(obj), "invariant");
 373     if (!mon->has_owner(current)) return false;  // slow-path for IMS exception
 374 
 375     if (mon->first_waiter() != nullptr) {
 376       // We have one or more waiters. Since this is an inflated monitor
 377       // that we own, we quickly notify them here and now, avoiding the slow-path.
 378       if (all) {
 379         mon->quick_notifyAll(current);
 380       } else {
 381         mon->quick_notify(current);
 382       }
 383     }
 384     return true;
 385   }
 386 
 387   // other IMS exception states take the slow-path
 388   return false;
 389 }
 390 
 391 // Handle notifications when synchronizing on value based classes
 392 void ObjectSynchronizer::handle_sync_on_value_based_class(Handle obj, JavaThread* locking_thread) {
 393   assert(locking_thread == Thread::current() || locking_thread->is_obj_deopt_suspend(), "must be");
 394   frame last_frame = locking_thread->last_frame();
 395   bool bcp_was_adjusted = false;
 396   // Don't decrement bcp if it points to the frame's first instruction.  This happens when
 397   // handle_sync_on_value_based_class() is called because of a synchronized method.  There
 398   // is no actual monitorenter instruction in the byte code in this case.
 399   if (last_frame.is_interpreted_frame() &&
 400       (last_frame.interpreter_frame_method()->code_base() < last_frame.interpreter_frame_bcp())) {
 401     // adjust bcp to point back to monitorenter so that we print the correct line numbers
 402     last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() - 1);
 403     bcp_was_adjusted = true;
 404   }
 405 
 406   if (DiagnoseSyncOnValueBasedClasses == FATAL_EXIT) {
 407     ResourceMark rm;
 408     stringStream ss;
 409     locking_thread->print_active_stack_on(&ss);
 410     char* base = (char*)strstr(ss.base(), "at");
 411     char* newline = (char*)strchr(ss.base(), '\n');
 412     if (newline != nullptr) {
 413       *newline = '\0';
 414     }
 415     fatal("Synchronizing on object " INTPTR_FORMAT " of klass %s %s", p2i(obj()), obj->klass()->external_name(), base);
 416   } else {
 417     assert(DiagnoseSyncOnValueBasedClasses == LOG_WARNING, "invalid value for DiagnoseSyncOnValueBasedClasses");
 418     ResourceMark rm;
 419     Log(valuebasedclasses) vblog;
 420 
 421     vblog.info("Synchronizing on object " INTPTR_FORMAT " of klass %s", p2i(obj()), obj->klass()->external_name());
 422     if (locking_thread->has_last_Java_frame()) {
 423       LogStream info_stream(vblog.info());
 424       locking_thread->print_active_stack_on(&info_stream);
 425     } else {
 426       vblog.info("Cannot find the last Java frame");
 427     }
 428 
 429     EventSyncOnValueBasedClass event;
 430     if (event.should_commit()) {
 431       event.set_valueBasedClass(obj->klass());
 432       event.commit();
 433     }
 434   }
 435 
 436   if (bcp_was_adjusted) {
 437     last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() + 1);
 438   }
 439 }
 440 
 441 // -----------------------------------------------------------------------------
 442 // Monitor Enter/Exit
 443 
 444 void ObjectSynchronizer::enter_for(Handle obj, BasicLock* lock, JavaThread* locking_thread) {
 445   // When called with locking_thread != Thread::current() some mechanism must synchronize
 446   // the locking_thread with respect to the current thread. Currently only used when
 447   // deoptimizing and re-locking locks. See Deoptimization::relock_objects
 448   assert(locking_thread == Thread::current() || locking_thread->is_obj_deopt_suspend(), "must be");
 449   assert(!obj->klass()->is_inline_klass(), "JITed code should never have locked an instance of a value class");
 450   return LightweightSynchronizer::enter_for(obj, lock, locking_thread);
 451 }
 452 
 453 // -----------------------------------------------------------------------------
 454 // JNI locks on java objects
 455 // NOTE: must use heavy weight monitor to handle jni monitor enter
 456 void ObjectSynchronizer::jni_enter(Handle obj, JavaThread* current) {
 457   JavaThread* THREAD = current;
 458   // Top native frames in the stack will not be seen if we attempt
 459   // preemption, since we start walking from the last Java anchor.
 460   NoPreemptMark npm(current);
 461 
 462   if (obj->klass()->is_value_based()) {
 463     handle_sync_on_value_based_class(obj, current);
 464   }
 465 
 466   if (obj->klass()->is_inline_klass()) {
 467     ResourceMark rm(THREAD);
 468     const char* desc = "Cannot synchronize on an instance of value class ";
 469     const char* className = obj->klass()->external_name();
 470     size_t msglen = strlen(desc) + strlen(className) + 1;
 471     char* message = NEW_RESOURCE_ARRAY(char, msglen);
 472     assert(message != nullptr, "NEW_RESOURCE_ARRAY should have called vm_exit_out_of_memory and not return nullptr");
 473     THROW_MSG(vmSymbols::java_lang_IdentityException(), className);
 474   }
 475 
 476   // the current locking is from JNI instead of Java code
 477   current->set_current_pending_monitor_is_from_java(false);
 478   // An async deflation can race after the inflate() call and before
 479   // enter() can make the ObjectMonitor busy. enter() returns false if
 480   // we have lost the race to async deflation and we simply try again.
 481   while (true) {
 482     BasicLock lock;
 483     if (LightweightSynchronizer::inflate_and_enter(obj(), &lock, inflate_cause_jni_enter, current, current) != nullptr) {
 484       break;
 485     }
 486   }
 487   current->set_current_pending_monitor_is_from_java(true);
 488 }
 489 
 490 // NOTE: must use heavy weight monitor to handle jni monitor exit
 491 void ObjectSynchronizer::jni_exit(oop obj, TRAPS) {
 492   JavaThread* current = THREAD;
 493   CHECK_THROW_NOSYNC_IMSE(obj);
 494 
 495   ObjectMonitor* monitor;
 496   monitor = LightweightSynchronizer::inflate_locked_or_imse(obj, inflate_cause_jni_exit, CHECK);
 497   // If this thread has locked the object, exit the monitor. We
 498   // intentionally do not use CHECK on check_owner because we must exit the
 499   // monitor even if an exception was already pending.
 500   if (monitor->check_owner(THREAD)) {
 501     monitor->exit(current);
 502   }
 503 }
 504 
 505 // -----------------------------------------------------------------------------
 506 // Internal VM locks on java objects
 507 // standard constructor, allows locking failures
 508 ObjectLocker::ObjectLocker(Handle obj, TRAPS) : _thread(THREAD), _obj(obj),
 509   _npm(_thread, _thread->at_preemptable_init() /* ignore_mark */), _skip_exit(false) {
 510   assert(!_thread->preempting(), "");
 511 
 512   _thread->check_for_valid_safepoint_state();
 513 
 514   if (_obj() != nullptr) {
 515     ObjectSynchronizer::enter(_obj, &_lock, _thread);
 516 
 517     if (_thread->preempting()) {
 518       // If preemption was cancelled we acquired the monitor after freezing
 519       // the frames. Redoing the vm call laterĀ in thaw will require us to
 520       // release it since the call should look like the original one. We
 521       // do it in ~ObjectLocker to reduce the window of time we hold the
 522       // monitor since we can't do anything useful with it now, and would
 523       // otherwise just force other vthreads to preempt in case they try
 524       // to acquire this monitor.
 525       _skip_exit = !_thread->preemption_cancelled();
 526       ObjectSynchronizer::read_monitor(_thread, _obj())->set_object_strong();
 527       _thread->set_pending_preempted_exception();
 528 
 529     }
 530   }
 531 }
 532 
 533 ObjectLocker::~ObjectLocker() {
 534   if (_obj() != nullptr && !_skip_exit) {
 535     ObjectSynchronizer::exit(_obj(), &_lock, _thread);
 536   }
 537 }
 538 
 539 void ObjectLocker::wait_uninterruptibly(TRAPS) {
 540   ObjectSynchronizer::waitUninterruptibly(_obj, 0, _thread);
 541   if (_thread->preempting()) {
 542     _skip_exit = true;
 543     ObjectSynchronizer::read_monitor(_thread, _obj())->set_object_strong();
 544     _thread->set_pending_preempted_exception();
 545   }
 546 }
 547 
 548 // -----------------------------------------------------------------------------
 549 //  Wait/Notify/NotifyAll
 550 // NOTE: must use heavy weight monitor to handle wait()
 551 
 552 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
 553   JavaThread* current = THREAD;
 554   CHECK_THROW_NOSYNC_IMSE_0(obj);
 555   if (millis < 0) {
 556     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 557   }
 558 
 559   ObjectMonitor* monitor;
 560   monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_wait, CHECK_0);
 561 
 562   DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), current, millis);
 563   monitor->wait(millis, true, THREAD); // Not CHECK as we need following code
 564 
 565   // This dummy call is in place to get around dtrace bug 6254741.  Once
 566   // that's fixed we can uncomment the following line, remove the call
 567   // and change this function back into a "void" func.
 568   // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
 569   int ret_code = dtrace_waited_probe(monitor, obj, THREAD);
 570   return ret_code;
 571 }
 572 
 573 void ObjectSynchronizer::waitUninterruptibly(Handle obj, jlong millis, TRAPS) {
 574   assert(millis >= 0, "timeout value is negative");
 575 
 576   ObjectMonitor* monitor;
 577   monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_wait, CHECK);
 578   monitor->wait(millis, false, THREAD);
 579 }
 580 
 581 
 582 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
 583   JavaThread* current = THREAD;
 584   CHECK_THROW_NOSYNC_IMSE(obj);
 585 
 586   markWord mark = obj->mark();
 587   if ((mark.is_fast_locked() && current->lock_stack().contains(obj()))) {
 588     // Not inflated so there can't be any waiters to notify.
 589     return;
 590   }
 591   ObjectMonitor* monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_notify, CHECK);
 592   monitor->notify(CHECK);
 593 }
 594 
 595 // NOTE: see comment of notify()
 596 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
 597   JavaThread* current = THREAD;
 598   CHECK_THROW_NOSYNC_IMSE(obj);
 599 
 600   markWord mark = obj->mark();
 601   if ((mark.is_fast_locked() && current->lock_stack().contains(obj()))) {
 602     // Not inflated so there can't be any waiters to notify.
 603     return;
 604   }
 605 
 606   ObjectMonitor* monitor = LightweightSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_notify, CHECK);
 607   monitor->notifyAll(CHECK);
 608 }
 609 
 610 // -----------------------------------------------------------------------------
 611 // Hash Code handling
 612 
 613 struct SharedGlobals {
 614   char         _pad_prefix[OM_CACHE_LINE_SIZE];
 615   // This is a highly shared mostly-read variable.
 616   // To avoid false-sharing it needs to be the sole occupant of a cache line.
 617   volatile int stw_random;
 618   DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 619   // Hot RW variable -- Sequester to avoid false-sharing
 620   volatile int hc_sequence;
 621   DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 622 };
 623 
 624 static SharedGlobals GVars;
 625 
 626 // hashCode() generation :
 627 //
 628 // Possibilities:
 629 // * MD5Digest of {obj,stw_random}
 630 // * CRC32 of {obj,stw_random} or any linear-feedback shift register function.
 631 // * A DES- or AES-style SBox[] mechanism
 632 // * One of the Phi-based schemes, such as:
 633 //   2654435761 = 2^32 * Phi (golden ratio)
 634 //   HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stw_random ;
 635 // * A variation of Marsaglia's shift-xor RNG scheme.
 636 // * (obj ^ stw_random) is appealing, but can result
 637 //   in undesirable regularity in the hashCode values of adjacent objects
 638 //   (objects allocated back-to-back, in particular).  This could potentially
 639 //   result in hashtable collisions and reduced hashtable efficiency.
 640 //   There are simple ways to "diffuse" the middle address bits over the
 641 //   generated hashCode values:
 642 
 643 static intptr_t get_next_hash(Thread* current, oop obj) {
 644   intptr_t value = 0;
 645   if (hashCode == 0) {
 646     // This form uses global Park-Miller RNG.
 647     // On MP system we'll have lots of RW access to a global, so the
 648     // mechanism induces lots of coherency traffic.
 649     value = os::random();
 650   } else if (hashCode == 1) {
 651     // This variation has the property of being stable (idempotent)
 652     // between STW operations.  This can be useful in some of the 1-0
 653     // synchronization schemes.
 654     intptr_t addr_bits = cast_from_oop<intptr_t>(obj) >> 3;
 655     value = addr_bits ^ (addr_bits >> 5) ^ GVars.stw_random;
 656   } else if (hashCode == 2) {
 657     value = 1;            // for sensitivity testing
 658   } else if (hashCode == 3) {
 659     value = ++GVars.hc_sequence;
 660   } else if (hashCode == 4) {
 661     value = cast_from_oop<intptr_t>(obj);
 662   } else {
 663     // Marsaglia's xor-shift scheme with thread-specific state
 664     // This is probably the best overall implementation -- we'll
 665     // likely make this the default in future releases.
 666     unsigned t = current->_hashStateX;
 667     t ^= (t << 11);
 668     current->_hashStateX = current->_hashStateY;
 669     current->_hashStateY = current->_hashStateZ;
 670     current->_hashStateZ = current->_hashStateW;
 671     unsigned v = current->_hashStateW;
 672     v = (v ^ (v >> 19)) ^ (t ^ (t >> 8));
 673     current->_hashStateW = v;
 674     value = v;
 675   }
 676 
 677   value &= markWord::hash_mask;
 678   if (value == 0) value = 0xBAD;
 679   assert(value != markWord::no_hash, "invariant");
 680   return value;
 681 }
 682 
 683 static intptr_t install_hash_code(Thread* current, oop obj) {
 684   assert(UseObjectMonitorTable, "must be");
 685 
 686   markWord mark = obj->mark_acquire();
 687   for (;;) {
 688     intptr_t hash = mark.hash();
 689     if (hash != 0) {
 690       return hash;
 691     }
 692 
 693     hash = get_next_hash(current, obj);
 694     const markWord old_mark = mark;
 695     const markWord new_mark = old_mark.copy_set_hash(hash);
 696 
 697     mark = obj->cas_set_mark(new_mark, old_mark);
 698     if (old_mark == mark) {
 699       return hash;
 700     }
 701   }
 702 }
 703 
 704 intptr_t ObjectSynchronizer::FastHashCode(Thread* current, oop obj) {
 705   // VM should be calling bootstrap method.
 706   assert(!obj->klass()->is_inline_klass(), "FastHashCode should not be called for inline classes");
 707 
 708   if (UseObjectMonitorTable) {
 709     // Since the monitor isn't in the object header, the hash can simply be
 710     // installed in the object header.
 711     return install_hash_code(current, obj);
 712   }
 713 
 714   while (true) {
 715     ObjectMonitor* monitor = nullptr;
 716     markWord temp, test;
 717     intptr_t hash;
 718     markWord mark = obj->mark_acquire();
 719     if (mark.is_unlocked() || mark.is_fast_locked()) {
 720       hash = mark.hash();
 721       if (hash != 0) {                     // if it has a hash, just return it
 722         return hash;
 723       }
 724       hash = get_next_hash(current, obj);  // get a new hash
 725       temp = mark.copy_set_hash(hash);     // merge the hash into header
 726                                            // try to install the hash
 727       test = obj->cas_set_mark(temp, mark);
 728       if (test == mark) {                  // if the hash was installed, return it
 729         return hash;
 730       }
 731       // CAS failed, retry
 732       continue;
 733 
 734       // Failed to install the hash. It could be that another thread
 735       // installed the hash just before our attempt or inflation has
 736       // occurred or... so we fall thru to inflate the monitor for
 737       // stability and then install the hash.
 738     } else if (mark.has_monitor()) {
 739       monitor = mark.monitor();
 740       temp = monitor->header();
 741       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
 742       hash = temp.hash();
 743       if (hash != 0) {
 744         // It has a hash.
 745 
 746         // Separate load of dmw/header above from the loads in
 747         // is_being_async_deflated().
 748 
 749         // dmw/header and _contentions may get written by different threads.
 750         // Make sure to observe them in the same order when having several observers.
 751         OrderAccess::loadload_for_IRIW();
 752 
 753         if (monitor->is_being_async_deflated()) {
 754           // But we can't safely use the hash if we detect that async
 755           // deflation has occurred. So we attempt to restore the
 756           // header/dmw to the object's header so that we only retry
 757           // once if the deflater thread happens to be slow.
 758           monitor->install_displaced_markword_in_object(obj);
 759           continue;
 760         }
 761         return hash;
 762       }
 763       // Fall thru so we only have one place that installs the hash in
 764       // the ObjectMonitor.
 765     }
 766 
 767     // NOTE: an async deflation can race after we get the monitor and
 768     // before we can update the ObjectMonitor's header with the hash
 769     // value below.
 770     assert(mark.has_monitor(), "must be");
 771     monitor = mark.monitor();
 772 
 773     // Load ObjectMonitor's header/dmw field and see if it has a hash.
 774     mark = monitor->header();
 775     assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value());
 776     hash = mark.hash();
 777     if (hash == 0) {                       // if it does not have a hash
 778       hash = get_next_hash(current, obj);  // get a new hash
 779       temp = mark.copy_set_hash(hash)   ;  // merge the hash into header
 780       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
 781       uintptr_t v = AtomicAccess::cmpxchg(monitor->metadata_addr(), mark.value(), temp.value());
 782       test = markWord(v);
 783       if (test != mark) {
 784         // The attempt to update the ObjectMonitor's header/dmw field
 785         // did not work. This can happen if another thread managed to
 786         // merge in the hash just before our cmpxchg().
 787         // If we add any new usages of the header/dmw field, this code
 788         // will need to be updated.
 789         hash = test.hash();
 790         assert(test.is_neutral(), "invariant: header=" INTPTR_FORMAT, test.value());
 791         assert(hash != 0, "should only have lost the race to a thread that set a non-zero hash");
 792       }
 793       if (monitor->is_being_async_deflated() && !UseObjectMonitorTable) {
 794         // If we detect that async deflation has occurred, then we
 795         // attempt to restore the header/dmw to the object's header
 796         // so that we only retry once if the deflater thread happens
 797         // to be slow.
 798         monitor->install_displaced_markword_in_object(obj);
 799         continue;
 800       }
 801     }
 802     // We finally get the hash.
 803     return hash;
 804   }
 805 }
 806 
 807 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* current,
 808                                                    Handle h_obj) {
 809   if (h_obj->mark().is_inline_type()) {
 810     return false;
 811   }
 812   assert(current == JavaThread::current(), "Can only be called on current thread");
 813   oop obj = h_obj();
 814 
 815   markWord mark = obj->mark_acquire();
 816 
 817   if (mark.is_fast_locked()) {
 818     // fast-locking case, see if lock is in current's lock stack
 819     return current->lock_stack().contains(h_obj());
 820   }
 821 
 822   while (mark.has_monitor()) {
 823     ObjectMonitor* monitor = read_monitor(current, obj, mark);
 824     if (monitor != nullptr) {
 825       return monitor->is_entered(current) != 0;
 826     }
 827     // Racing with inflation/deflation, retry
 828     mark = obj->mark_acquire();
 829 
 830     if (mark.is_fast_locked()) {
 831       // Some other thread fast_locked, current could not have held the lock
 832       return false;
 833     }
 834   }
 835 
 836   // Unlocked case, header in place
 837   assert(mark.is_unlocked(), "sanity check");
 838   return false;
 839 }
 840 
 841 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) {
 842   oop obj = h_obj();
 843   markWord mark = obj->mark_acquire();
 844 
 845   if (mark.is_fast_locked()) {
 846     // fast-locked so get owner from the object.
 847     // owning_thread_from_object() may also return null here:
 848     return Threads::owning_thread_from_object(t_list, h_obj());
 849   }
 850 
 851   while (mark.has_monitor()) {
 852     ObjectMonitor* monitor = read_monitor(Thread::current(), obj, mark);
 853     if (monitor != nullptr) {
 854       return Threads::owning_thread_from_monitor(t_list, monitor);
 855     }
 856     // Racing with inflation/deflation, retry
 857     mark = obj->mark_acquire();
 858 
 859     if (mark.is_fast_locked()) {
 860       // Some other thread fast_locked
 861       return Threads::owning_thread_from_object(t_list, h_obj());
 862     }
 863   }
 864 
 865   // Unlocked case, header in place
 866   // Cannot have assertion since this object may have been
 867   // locked by another thread when reaching here.
 868   // assert(mark.is_unlocked(), "sanity check");
 869 
 870   return nullptr;
 871 }
 872 
 873 // Visitors ...
 874 
 875 // Iterate over all ObjectMonitors.
 876 template <typename Function>
 877 void ObjectSynchronizer::monitors_iterate(Function function) {
 878   MonitorList::Iterator iter = _in_use_list.iterator();
 879   while (iter.has_next()) {
 880     ObjectMonitor* monitor = iter.next();
 881     function(monitor);
 882   }
 883 }
 884 
 885 // Iterate ObjectMonitors owned by any thread and where the owner `filter`
 886 // returns true.
 887 template <typename OwnerFilter>
 888 void ObjectSynchronizer::owned_monitors_iterate_filtered(MonitorClosure* closure, OwnerFilter filter) {
 889   monitors_iterate([&](ObjectMonitor* monitor) {
 890     // This function is only called at a safepoint or when the
 891     // target thread is suspended or when the target thread is
 892     // operating on itself. The current closures in use today are
 893     // only interested in an owned ObjectMonitor and ownership
 894     // cannot be dropped under the calling contexts so the
 895     // ObjectMonitor cannot be async deflated.
 896     if (monitor->has_owner() && filter(monitor)) {
 897       assert(!monitor->is_being_async_deflated(), "Owned monitors should not be deflating");
 898 
 899       closure->do_monitor(monitor);
 900     }
 901   });
 902 }
 903 
 904 // Iterate ObjectMonitors where the owner == thread; this does NOT include
 905 // ObjectMonitors where owner is set to a stack-lock address in thread.
 906 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure, JavaThread* thread) {
 907   int64_t key = ObjectMonitor::owner_id_from(thread);
 908   auto thread_filter = [&](ObjectMonitor* monitor) { return monitor->owner() == key; };
 909   return owned_monitors_iterate_filtered(closure, thread_filter);
 910 }
 911 
 912 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure, oop vthread) {
 913   int64_t key = ObjectMonitor::owner_id_from(vthread);
 914   auto thread_filter = [&](ObjectMonitor* monitor) { return monitor->owner() == key; };
 915   return owned_monitors_iterate_filtered(closure, thread_filter);
 916 }
 917 
 918 // Iterate ObjectMonitors owned by any thread.
 919 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure) {
 920   auto all_filter = [&](ObjectMonitor* monitor) { return true; };
 921   return owned_monitors_iterate_filtered(closure, all_filter);
 922 }
 923 
 924 static bool monitors_used_above_threshold(MonitorList* list) {
 925   if (MonitorUsedDeflationThreshold == 0) {  // disabled case is easy
 926     return false;
 927   }
 928   size_t monitors_used = list->count();
 929   if (monitors_used == 0) {  // empty list is easy
 930     return false;
 931   }
 932   size_t old_ceiling = ObjectSynchronizer::in_use_list_ceiling();
 933   // Make sure that we use a ceiling value that is not lower than
 934   // previous, not lower than the recorded max used by the system, and
 935   // not lower than the current number of monitors in use (which can
 936   // race ahead of max). The result is guaranteed > 0.
 937   size_t ceiling = MAX3(old_ceiling, list->max(), monitors_used);
 938 
 939   // Check if our monitor usage is above the threshold:
 940   size_t monitor_usage = (monitors_used * 100LL) / ceiling;
 941   if (int(monitor_usage) > MonitorUsedDeflationThreshold) {
 942     // Deflate monitors if over the threshold percentage, unless no
 943     // progress on previous deflations.
 944     bool is_above_threshold = true;
 945 
 946     // Check if it's time to adjust the in_use_list_ceiling up, due
 947     // to too many async deflation attempts without any progress.
 948     if (NoAsyncDeflationProgressMax != 0 &&
 949         _no_progress_cnt >= NoAsyncDeflationProgressMax) {
 950       double remainder = (100.0 - MonitorUsedDeflationThreshold) / 100.0;
 951       size_t delta = (size_t)(ceiling * remainder) + 1;
 952       size_t new_ceiling = (ceiling > SIZE_MAX - delta)
 953         ? SIZE_MAX         // Overflow, let's clamp new_ceiling.
 954         : ceiling + delta;
 955 
 956       ObjectSynchronizer::set_in_use_list_ceiling(new_ceiling);
 957       log_info(monitorinflation)("Too many deflations without progress; "
 958                                  "bumping in_use_list_ceiling from %zu"
 959                                  " to %zu", old_ceiling, new_ceiling);
 960       _no_progress_cnt = 0;
 961       ceiling = new_ceiling;
 962 
 963       // Check if our monitor usage is still above the threshold:
 964       monitor_usage = (monitors_used * 100LL) / ceiling;
 965       is_above_threshold = int(monitor_usage) > MonitorUsedDeflationThreshold;
 966     }
 967     log_info(monitorinflation)("monitors_used=%zu, ceiling=%zu"
 968                                ", monitor_usage=%zu, threshold=%d",
 969                                monitors_used, ceiling, monitor_usage, MonitorUsedDeflationThreshold);
 970     return is_above_threshold;
 971   }
 972 
 973   return false;
 974 }
 975 
 976 size_t ObjectSynchronizer::in_use_list_count() {
 977   return _in_use_list.count();
 978 }
 979 
 980 size_t ObjectSynchronizer::in_use_list_max() {
 981   return _in_use_list.max();
 982 }
 983 
 984 size_t ObjectSynchronizer::in_use_list_ceiling() {
 985   return _in_use_list_ceiling;
 986 }
 987 
 988 void ObjectSynchronizer::dec_in_use_list_ceiling() {
 989   AtomicAccess::sub(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate);
 990 }
 991 
 992 void ObjectSynchronizer::inc_in_use_list_ceiling() {
 993   AtomicAccess::add(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate);
 994 }
 995 
 996 void ObjectSynchronizer::set_in_use_list_ceiling(size_t new_value) {
 997   _in_use_list_ceiling = new_value;
 998 }
 999 
1000 bool ObjectSynchronizer::is_async_deflation_needed() {
1001   if (is_async_deflation_requested()) {
1002     // Async deflation request.
1003     log_info(monitorinflation)("Async deflation needed: explicit request");
1004     return true;
1005   }
1006 
1007   jlong time_since_last = time_since_last_async_deflation_ms();
1008 
1009   if (AsyncDeflationInterval > 0 &&
1010       time_since_last > AsyncDeflationInterval &&
1011       monitors_used_above_threshold(&_in_use_list)) {
1012     // It's been longer than our specified deflate interval and there
1013     // are too many monitors in use. We don't deflate more frequently
1014     // than AsyncDeflationInterval (unless is_async_deflation_requested)
1015     // in order to not swamp the MonitorDeflationThread.
1016     log_info(monitorinflation)("Async deflation needed: monitors used are above the threshold");
1017     return true;
1018   }
1019 
1020   if (GuaranteedAsyncDeflationInterval > 0 &&
1021       time_since_last > GuaranteedAsyncDeflationInterval) {
1022     // It's been longer than our specified guaranteed deflate interval.
1023     // We need to clean up the used monitors even if the threshold is
1024     // not reached, to keep the memory utilization at bay when many threads
1025     // touched many monitors.
1026     log_info(monitorinflation)("Async deflation needed: guaranteed interval (%zd ms) "
1027                                "is greater than time since last deflation (" JLONG_FORMAT " ms)",
1028                                GuaranteedAsyncDeflationInterval, time_since_last);
1029 
1030     // If this deflation has no progress, then it should not affect the no-progress
1031     // tracking, otherwise threshold heuristics would think it was triggered, experienced
1032     // no progress, and needs to backoff more aggressively. In this "no progress" case,
1033     // the generic code would bump the no-progress counter, and we compensate for that
1034     // by telling it to skip the update.
1035     //
1036     // If this deflation has progress, then it should let non-progress tracking
1037     // know about this, otherwise the threshold heuristics would kick in, potentially
1038     // experience no-progress due to aggressive cleanup by this deflation, and think
1039     // it is still in no-progress stride. In this "progress" case, the generic code would
1040     // zero the counter, and we allow it to happen.
1041     _no_progress_skip_increment = true;
1042 
1043     return true;
1044   }
1045 
1046   return false;
1047 }
1048 
1049 void ObjectSynchronizer::request_deflate_idle_monitors() {
1050   MonitorLocker ml(MonitorDeflation_lock, Mutex::_no_safepoint_check_flag);
1051   set_is_async_deflation_requested(true);
1052   ml.notify_all();
1053 }
1054 
1055 bool ObjectSynchronizer::request_deflate_idle_monitors_from_wb() {
1056   JavaThread* current = JavaThread::current();
1057   bool ret_code = false;
1058 
1059   jlong last_time = last_async_deflation_time_ns();
1060 
1061   request_deflate_idle_monitors();
1062 
1063   const int N_CHECKS = 5;
1064   for (int i = 0; i < N_CHECKS; i++) {  // sleep for at most 5 seconds
1065     if (last_async_deflation_time_ns() > last_time) {
1066       log_info(monitorinflation)("Async Deflation happened after %d check(s).", i);
1067       ret_code = true;
1068       break;
1069     }
1070     {
1071       // JavaThread has to honor the blocking protocol.
1072       ThreadBlockInVM tbivm(current);
1073       os::naked_short_sleep(999);  // sleep for almost 1 second
1074     }
1075   }
1076   if (!ret_code) {
1077     log_info(monitorinflation)("Async Deflation DID NOT happen after %d checks.", N_CHECKS);
1078   }
1079 
1080   return ret_code;
1081 }
1082 
1083 jlong ObjectSynchronizer::time_since_last_async_deflation_ms() {
1084   return (os::javaTimeNanos() - last_async_deflation_time_ns()) / (NANOUNITS / MILLIUNITS);
1085 }
1086 
1087 // Walk the in-use list and deflate (at most MonitorDeflationMax) idle
1088 // ObjectMonitors. Returns the number of deflated ObjectMonitors.
1089 //
1090 size_t ObjectSynchronizer::deflate_monitor_list(ObjectMonitorDeflationSafepointer* safepointer) {
1091   MonitorList::Iterator iter = _in_use_list.iterator();
1092   size_t deflated_count = 0;
1093   Thread* current = Thread::current();
1094 
1095   while (iter.has_next()) {
1096     if (deflated_count >= (size_t)MonitorDeflationMax) {
1097       break;
1098     }
1099     ObjectMonitor* mid = iter.next();
1100     if (mid->deflate_monitor(current)) {
1101       deflated_count++;
1102     }
1103 
1104     // Must check for a safepoint/handshake and honor it.
1105     safepointer->block_for_safepoint("deflation", "deflated_count", deflated_count);
1106   }
1107 
1108   return deflated_count;
1109 }
1110 
1111 class DeflationHandshakeClosure : public HandshakeClosure {
1112  public:
1113   DeflationHandshakeClosure() : HandshakeClosure("DeflationHandshakeClosure") {}
1114 
1115   void do_thread(Thread* thread) {
1116     log_trace(monitorinflation)("DeflationHandshakeClosure::do_thread: thread="
1117                                 INTPTR_FORMAT, p2i(thread));
1118     if (thread->is_Java_thread()) {
1119       // Clear OM cache
1120       JavaThread* jt = JavaThread::cast(thread);
1121       jt->om_clear_monitor_cache();
1122     }
1123   }
1124 };
1125 
1126 class VM_RendezvousGCThreads : public VM_Operation {
1127 public:
1128   bool evaluate_at_safepoint() const override { return false; }
1129   VMOp_Type type() const override { return VMOp_RendezvousGCThreads; }
1130   void doit() override {
1131     Universe::heap()->safepoint_synchronize_begin();
1132     Universe::heap()->safepoint_synchronize_end();
1133   };
1134 };
1135 
1136 static size_t delete_monitors(GrowableArray<ObjectMonitor*>* delete_list,
1137                               ObjectMonitorDeflationSafepointer* safepointer) {
1138   NativeHeapTrimmer::SuspendMark sm("monitor deletion");
1139   size_t deleted_count = 0;
1140   for (ObjectMonitor* monitor: *delete_list) {
1141     delete monitor;
1142     deleted_count++;
1143     // A JavaThread must check for a safepoint/handshake and honor it.
1144     safepointer->block_for_safepoint("deletion", "deleted_count", deleted_count);
1145   }
1146   return deleted_count;
1147 }
1148 
1149 class ObjectMonitorDeflationLogging: public StackObj {
1150   LogStreamHandle(Debug, monitorinflation) _debug;
1151   LogStreamHandle(Info, monitorinflation)  _info;
1152   LogStream*                               _stream;
1153   elapsedTimer                             _timer;
1154 
1155   size_t ceiling() const { return ObjectSynchronizer::in_use_list_ceiling(); }
1156   size_t count() const   { return ObjectSynchronizer::in_use_list_count(); }
1157   size_t max() const     { return ObjectSynchronizer::in_use_list_max(); }
1158 
1159 public:
1160   ObjectMonitorDeflationLogging()
1161     : _debug(), _info(), _stream(nullptr) {
1162     if (_debug.is_enabled()) {
1163       _stream = &_debug;
1164     } else if (_info.is_enabled()) {
1165       _stream = &_info;
1166     }
1167   }
1168 
1169   void begin() {
1170     if (_stream != nullptr) {
1171       _stream->print_cr("begin deflating: in_use_list stats: ceiling=%zu, count=%zu, max=%zu",
1172                         ceiling(), count(), max());
1173       _timer.start();
1174     }
1175   }
1176 
1177   void before_handshake(size_t unlinked_count) {
1178     if (_stream != nullptr) {
1179       _timer.stop();
1180       _stream->print_cr("before handshaking: unlinked_count=%zu"
1181                         ", in_use_list stats: ceiling=%zu, count="
1182                         "%zu, max=%zu",
1183                         unlinked_count, ceiling(), count(), max());
1184     }
1185   }
1186 
1187   void after_handshake() {
1188     if (_stream != nullptr) {
1189       _stream->print_cr("after handshaking: in_use_list stats: ceiling="
1190                         "%zu, count=%zu, max=%zu",
1191                         ceiling(), count(), max());
1192       _timer.start();
1193     }
1194   }
1195 
1196   void end(size_t deflated_count, size_t unlinked_count) {
1197     if (_stream != nullptr) {
1198       _timer.stop();
1199       if (deflated_count != 0 || unlinked_count != 0 || _debug.is_enabled()) {
1200         _stream->print_cr("deflated_count=%zu, {unlinked,deleted}_count=%zu monitors in %3.7f secs",
1201                           deflated_count, unlinked_count, _timer.seconds());
1202       }
1203       _stream->print_cr("end deflating: in_use_list stats: ceiling=%zu, count=%zu, max=%zu",
1204                         ceiling(), count(), max());
1205     }
1206   }
1207 
1208   void before_block_for_safepoint(const char* op_name, const char* cnt_name, size_t cnt) {
1209     if (_stream != nullptr) {
1210       _timer.stop();
1211       _stream->print_cr("pausing %s: %s=%zu, in_use_list stats: ceiling="
1212                         "%zu, count=%zu, max=%zu",
1213                         op_name, cnt_name, cnt, ceiling(), count(), max());
1214     }
1215   }
1216 
1217   void after_block_for_safepoint(const char* op_name) {
1218     if (_stream != nullptr) {
1219       _stream->print_cr("resuming %s: in_use_list stats: ceiling=%zu"
1220                         ", count=%zu, max=%zu", op_name,
1221                         ceiling(), count(), max());
1222       _timer.start();
1223     }
1224   }
1225 };
1226 
1227 void ObjectMonitorDeflationSafepointer::block_for_safepoint(const char* op_name, const char* count_name, size_t counter) {
1228   if (!SafepointMechanism::should_process(_current)) {
1229     return;
1230   }
1231 
1232   // A safepoint/handshake has started.
1233   _log->before_block_for_safepoint(op_name, count_name, counter);
1234 
1235   {
1236     // Honor block request.
1237     ThreadBlockInVM tbivm(_current);
1238   }
1239 
1240   _log->after_block_for_safepoint(op_name);
1241 }
1242 
1243 // This function is called by the MonitorDeflationThread to deflate
1244 // ObjectMonitors.
1245 size_t ObjectSynchronizer::deflate_idle_monitors() {
1246   JavaThread* current = JavaThread::current();
1247   assert(current->is_monitor_deflation_thread(), "The only monitor deflater");
1248 
1249   // The async deflation request has been processed.
1250   _last_async_deflation_time_ns = os::javaTimeNanos();
1251   set_is_async_deflation_requested(false);
1252 
1253   ObjectMonitorDeflationLogging log;
1254   ObjectMonitorDeflationSafepointer safepointer(current, &log);
1255 
1256   log.begin();
1257 
1258   // Deflate some idle ObjectMonitors.
1259   size_t deflated_count = deflate_monitor_list(&safepointer);
1260 
1261   // Unlink the deflated ObjectMonitors from the in-use list.
1262   size_t unlinked_count = 0;
1263   size_t deleted_count = 0;
1264   if (deflated_count > 0) {
1265     ResourceMark rm(current);
1266     GrowableArray<ObjectMonitor*> delete_list((int)deflated_count);
1267     unlinked_count = _in_use_list.unlink_deflated(deflated_count, &delete_list, &safepointer);
1268 
1269 #ifdef ASSERT
1270     if (UseObjectMonitorTable) {
1271       for (ObjectMonitor* monitor : delete_list) {
1272         assert(!LightweightSynchronizer::contains_monitor(current, monitor), "Should have been removed");
1273       }
1274     }
1275 #endif
1276 
1277     log.before_handshake(unlinked_count);
1278 
1279     // A JavaThread needs to handshake in order to safely free the
1280     // ObjectMonitors that were deflated in this cycle.
1281     DeflationHandshakeClosure dhc;
1282     Handshake::execute(&dhc);
1283     // Also, we sync and desync GC threads around the handshake, so that they can
1284     // safely read the mark-word and look-through to the object-monitor, without
1285     // being afraid that the object-monitor is going away.
1286     VM_RendezvousGCThreads sync_gc;
1287     VMThread::execute(&sync_gc);
1288 
1289     log.after_handshake();
1290 
1291     // After the handshake, safely free the ObjectMonitors that were
1292     // deflated and unlinked in this cycle.
1293 
1294     // Delete the unlinked ObjectMonitors.
1295     deleted_count = delete_monitors(&delete_list, &safepointer);
1296     assert(unlinked_count == deleted_count, "must be");
1297   }
1298 
1299   log.end(deflated_count, unlinked_count);
1300 
1301   GVars.stw_random = os::random();
1302 
1303   if (deflated_count != 0) {
1304     _no_progress_cnt = 0;
1305   } else if (_no_progress_skip_increment) {
1306     _no_progress_skip_increment = false;
1307   } else {
1308     _no_progress_cnt++;
1309   }
1310 
1311   return deflated_count;
1312 }
1313 
1314 // Monitor cleanup on JavaThread::exit
1315 
1316 // Iterate through monitor cache and attempt to release thread's monitors
1317 class ReleaseJavaMonitorsClosure: public MonitorClosure {
1318  private:
1319   JavaThread* _thread;
1320 
1321  public:
1322   ReleaseJavaMonitorsClosure(JavaThread* thread) : _thread(thread) {}
1323   void do_monitor(ObjectMonitor* mid) {
1324     mid->complete_exit(_thread);
1325   }
1326 };
1327 
1328 // Release all inflated monitors owned by current thread.  Lightweight monitors are
1329 // ignored.  This is meant to be called during JNI thread detach which assumes
1330 // all remaining monitors are heavyweight.  All exceptions are swallowed.
1331 // Scanning the extant monitor list can be time consuming.
1332 // A simple optimization is to add a per-thread flag that indicates a thread
1333 // called jni_monitorenter() during its lifetime.
1334 //
1335 // Instead of NoSafepointVerifier it might be cheaper to
1336 // use an idiom of the form:
1337 //   auto int tmp = SafepointSynchronize::_safepoint_counter ;
1338 //   <code that must not run at safepoint>
1339 //   guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ;
1340 // Since the tests are extremely cheap we could leave them enabled
1341 // for normal product builds.
1342 
1343 void ObjectSynchronizer::release_monitors_owned_by_thread(JavaThread* current) {
1344   assert(current == JavaThread::current(), "must be current Java thread");
1345   NoSafepointVerifier nsv;
1346   ReleaseJavaMonitorsClosure rjmc(current);
1347   ObjectSynchronizer::owned_monitors_iterate(&rjmc, current);
1348   assert(!current->has_pending_exception(), "Should not be possible");
1349   current->clear_pending_exception();
1350 }
1351 
1352 const char* ObjectSynchronizer::inflate_cause_name(const InflateCause cause) {
1353   switch (cause) {
1354     case inflate_cause_vm_internal:    return "VM Internal";
1355     case inflate_cause_monitor_enter:  return "Monitor Enter";
1356     case inflate_cause_wait:           return "Monitor Wait";
1357     case inflate_cause_notify:         return "Monitor Notify";
1358     case inflate_cause_jni_enter:      return "JNI Monitor Enter";
1359     case inflate_cause_jni_exit:       return "JNI Monitor Exit";
1360     default:
1361       ShouldNotReachHere();
1362   }
1363   return "Unknown";
1364 }
1365 
1366 //------------------------------------------------------------------------------
1367 // Debugging code
1368 
1369 u_char* ObjectSynchronizer::get_gvars_addr() {
1370   return (u_char*)&GVars;
1371 }
1372 
1373 u_char* ObjectSynchronizer::get_gvars_hc_sequence_addr() {
1374   return (u_char*)&GVars.hc_sequence;
1375 }
1376 
1377 size_t ObjectSynchronizer::get_gvars_size() {
1378   return sizeof(SharedGlobals);
1379 }
1380 
1381 u_char* ObjectSynchronizer::get_gvars_stw_random_addr() {
1382   return (u_char*)&GVars.stw_random;
1383 }
1384 
1385 // Do the final audit and print of ObjectMonitor stats; must be done
1386 // by the VMThread at VM exit time.
1387 void ObjectSynchronizer::do_final_audit_and_print_stats() {
1388   assert(Thread::current()->is_VM_thread(), "sanity check");
1389 
1390   if (is_final_audit()) {  // Only do the audit once.
1391     return;
1392   }
1393   set_is_final_audit();
1394   log_info(monitorinflation)("Starting the final audit.");
1395 
1396   if (log_is_enabled(Info, monitorinflation)) {
1397     LogStreamHandle(Info, monitorinflation) ls;
1398     audit_and_print_stats(&ls, true /* on_exit */);
1399   }
1400 }
1401 
1402 // This function can be called by the MonitorDeflationThread or it can be called when
1403 // we are trying to exit the VM. The list walker functions can run in parallel with
1404 // the other list operations.
1405 // Calls to this function can be added in various places as a debugging
1406 // aid.
1407 //
1408 void ObjectSynchronizer::audit_and_print_stats(outputStream* ls, bool on_exit) {
1409   int error_cnt = 0;
1410 
1411   ls->print_cr("Checking in_use_list:");
1412   chk_in_use_list(ls, &error_cnt);
1413 
1414   if (error_cnt == 0) {
1415     ls->print_cr("No errors found in in_use_list checks.");
1416   } else {
1417     log_error(monitorinflation)("found in_use_list errors: error_cnt=%d", error_cnt);
1418   }
1419 
1420   // When exiting, only log the interesting entries at the Info level.
1421   // When called at intervals by the MonitorDeflationThread, log output
1422   // at the Trace level since there can be a lot of it.
1423   if (!on_exit && log_is_enabled(Trace, monitorinflation)) {
1424     LogStreamHandle(Trace, monitorinflation) ls_tr;
1425     log_in_use_monitor_details(&ls_tr, true /* log_all */);
1426   } else if (on_exit) {
1427     log_in_use_monitor_details(ls, false /* log_all */);
1428   }
1429 
1430   ls->flush();
1431 
1432   guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt);
1433 }
1434 
1435 // Check the in_use_list; log the results of the checks.
1436 void ObjectSynchronizer::chk_in_use_list(outputStream* out, int *error_cnt_p) {
1437   size_t l_in_use_count = _in_use_list.count();
1438   size_t l_in_use_max = _in_use_list.max();
1439   out->print_cr("count=%zu, max=%zu", l_in_use_count,
1440                 l_in_use_max);
1441 
1442   size_t ck_in_use_count = 0;
1443   MonitorList::Iterator iter = _in_use_list.iterator();
1444   while (iter.has_next()) {
1445     ObjectMonitor* mid = iter.next();
1446     chk_in_use_entry(mid, out, error_cnt_p);
1447     ck_in_use_count++;
1448   }
1449 
1450   if (l_in_use_count == ck_in_use_count) {
1451     out->print_cr("in_use_count=%zu equals ck_in_use_count=%zu",
1452                   l_in_use_count, ck_in_use_count);
1453   } else {
1454     out->print_cr("WARNING: in_use_count=%zu is not equal to "
1455                   "ck_in_use_count=%zu", l_in_use_count,
1456                   ck_in_use_count);
1457   }
1458 
1459   size_t ck_in_use_max = _in_use_list.max();
1460   if (l_in_use_max == ck_in_use_max) {
1461     out->print_cr("in_use_max=%zu equals ck_in_use_max=%zu",
1462                   l_in_use_max, ck_in_use_max);
1463   } else {
1464     out->print_cr("WARNING: in_use_max=%zu is not equal to "
1465                   "ck_in_use_max=%zu", l_in_use_max, ck_in_use_max);
1466   }
1467 }
1468 
1469 // Check an in-use monitor entry; log any errors.
1470 void ObjectSynchronizer::chk_in_use_entry(ObjectMonitor* n, outputStream* out,
1471                                           int* error_cnt_p) {
1472   if (n->owner_is_DEFLATER_MARKER()) {
1473     // This could happen when monitor deflation blocks for a safepoint.
1474     return;
1475   }
1476 
1477 
1478   if (n->metadata() == 0) {
1479     out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor must "
1480                   "have non-null _metadata (header/hash) field.", p2i(n));
1481     *error_cnt_p = *error_cnt_p + 1;
1482   }
1483 
1484   const oop obj = n->object_peek();
1485   if (obj == nullptr) {
1486     return;
1487   }
1488 
1489   const markWord mark = obj->mark();
1490   if (!mark.has_monitor()) {
1491     out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's "
1492                   "object does not think it has a monitor: obj="
1493                   INTPTR_FORMAT ", mark=" INTPTR_FORMAT, p2i(n),
1494                   p2i(obj), mark.value());
1495     *error_cnt_p = *error_cnt_p + 1;
1496     return;
1497   }
1498 
1499   ObjectMonitor* const obj_mon = read_monitor(Thread::current(), obj, mark);
1500   if (n != obj_mon) {
1501     out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's "
1502                   "object does not refer to the same monitor: obj="
1503                   INTPTR_FORMAT ", mark=" INTPTR_FORMAT ", obj_mon="
1504                   INTPTR_FORMAT, p2i(n), p2i(obj), mark.value(), p2i(obj_mon));
1505     *error_cnt_p = *error_cnt_p + 1;
1506   }
1507 }
1508 
1509 // Log details about ObjectMonitors on the in_use_list. The 'BHL'
1510 // flags indicate why the entry is in-use, 'object' and 'object type'
1511 // indicate the associated object and its type.
1512 void ObjectSynchronizer::log_in_use_monitor_details(outputStream* out, bool log_all) {
1513   if (_in_use_list.count() > 0) {
1514     stringStream ss;
1515     out->print_cr("In-use monitor info%s:", log_all ? "" : " (eliding idle monitors)");
1516     out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
1517     out->print_cr("%18s  %s  %18s  %18s",
1518                   "monitor", "BHL", "object", "object type");
1519     out->print_cr("==================  ===  ==================  ==================");
1520 
1521     auto is_interesting = [&](ObjectMonitor* monitor) {
1522       return log_all || monitor->has_owner() || monitor->is_busy();
1523     };
1524 
1525     monitors_iterate([&](ObjectMonitor* monitor) {
1526       if (is_interesting(monitor)) {
1527         const oop obj = monitor->object_peek();
1528         const intptr_t hash = UseObjectMonitorTable ? monitor->hash() : monitor->header().hash();
1529         ResourceMark rm;
1530         out->print(INTPTR_FORMAT "  %d%d%d  " INTPTR_FORMAT "  %s", p2i(monitor),
1531                    monitor->is_busy(), hash != 0, monitor->has_owner(),
1532                    p2i(obj), obj == nullptr ? "" : obj->klass()->external_name());
1533         if (monitor->is_busy()) {
1534           out->print(" (%s)", monitor->is_busy_to_string(&ss));
1535           ss.reset();
1536         }
1537         out->cr();
1538       }
1539     });
1540   }
1541 
1542   out->flush();
1543 }