1 /*
   2  * Copyright (c) 1998, 2026, 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/lockStack.inline.hpp"
  45 #include "runtime/mutexLocker.hpp"
  46 #include "runtime/objectMonitor.inline.hpp"
  47 #include "runtime/objectMonitorTable.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.hpp"
  55 #include "runtime/threads.hpp"
  56 #include "runtime/timer.hpp"
  57 #include "runtime/timerTrace.hpp"
  58 #include "runtime/trimNativeHeap.hpp"
  59 #include "runtime/vframe.hpp"
  60 #include "runtime/vmThread.hpp"
  61 #include "utilities/align.hpp"
  62 #include "utilities/concurrentHashTable.inline.hpp"
  63 #include "utilities/concurrentHashTableTasks.inline.hpp"
  64 #include "utilities/dtrace.hpp"
  65 #include "utilities/events.hpp"
  66 #include "utilities/globalCounter.inline.hpp"
  67 #include "utilities/globalDefinitions.hpp"
  68 #include "utilities/linkedlist.hpp"
  69 #include "utilities/preserveException.hpp"
  70 
  71 class ObjectMonitorDeflationLogging;
  72 
  73 void MonitorList::add(ObjectMonitor* m) {
  74   ObjectMonitor* head;
  75   do {
  76     head = AtomicAccess::load(&_head);
  77     m->set_next_om(head);
  78   } while (AtomicAccess::cmpxchg(&_head, head, m) != head);
  79 
  80   size_t count = AtomicAccess::add(&_count, 1u, memory_order_relaxed);
  81   size_t old_max;
  82   do {
  83     old_max = AtomicAccess::load(&_max);
  84     if (count <= old_max) {
  85       break;
  86     }
  87   } while (AtomicAccess::cmpxchg(&_max, old_max, count, memory_order_relaxed) != old_max);
  88 }
  89 
  90 size_t MonitorList::count() const {
  91   return AtomicAccess::load(&_count);
  92 }
  93 
  94 size_t MonitorList::max() const {
  95   return AtomicAccess::load(&_max);
  96 }
  97 
  98 class ObjectMonitorDeflationSafepointer : public StackObj {
  99   JavaThread* const                    _current;
 100   ObjectMonitorDeflationLogging* const _log;
 101 
 102 public:
 103   ObjectMonitorDeflationSafepointer(JavaThread* current, ObjectMonitorDeflationLogging* log)
 104     : _current(current), _log(log) {}
 105 
 106   void block_for_safepoint(const char* op_name, const char* count_name, size_t counter);
 107 };
 108 
 109 // Walk the in-use list and unlink deflated ObjectMonitors.
 110 // Returns the number of unlinked ObjectMonitors.
 111 size_t MonitorList::unlink_deflated(size_t deflated_count,
 112                                     GrowableArray<ObjectMonitor*>* unlinked_list,
 113                                     ObjectMonitorDeflationSafepointer* safepointer) {
 114   size_t unlinked_count = 0;
 115   ObjectMonitor* prev = nullptr;
 116   ObjectMonitor* m = AtomicAccess::load_acquire(&_head);
 117 
 118   while (m != nullptr) {
 119     if (m->is_being_async_deflated()) {
 120       // Find next live ObjectMonitor. Batch up the unlinkable monitors, so we can
 121       // modify the list once per batch. The batch starts at "m".
 122       size_t unlinked_batch = 0;
 123       ObjectMonitor* next = m;
 124       // Look for at most MonitorUnlinkBatch monitors, or the number of
 125       // deflated and not unlinked monitors, whatever comes first.
 126       assert(deflated_count >= unlinked_count, "Sanity: underflow");
 127       size_t unlinked_batch_limit = MIN2<size_t>(deflated_count - unlinked_count, MonitorUnlinkBatch);
 128       do {
 129         ObjectMonitor* next_next = next->next_om();
 130         unlinked_batch++;
 131         unlinked_list->append(next);
 132         next = next_next;
 133         if (unlinked_batch >= unlinked_batch_limit) {
 134           // Reached the max batch, so bail out of the gathering loop.
 135           break;
 136         }
 137         if (prev == nullptr && AtomicAccess::load(&_head) != m) {
 138           // Current batch used to be at head, but it is not at head anymore.
 139           // Bail out and figure out where we currently are. This avoids long
 140           // walks searching for new prev during unlink under heavy list inserts.
 141           break;
 142         }
 143       } while (next != nullptr && next->is_being_async_deflated());
 144 
 145       // Unlink the found batch.
 146       if (prev == nullptr) {
 147         // The current batch is the first batch, so there is a chance that it starts at head.
 148         // Optimistically assume no inserts happened, and try to unlink the entire batch from the head.
 149         ObjectMonitor* prev_head = AtomicAccess::cmpxchg(&_head, m, next);
 150         if (prev_head != m) {
 151           // Something must have updated the head. Figure out the actual prev for this batch.
 152           for (ObjectMonitor* n = prev_head; n != m; n = n->next_om()) {
 153             prev = n;
 154           }
 155           assert(prev != nullptr, "Should have found the prev for the current batch");
 156           prev->set_next_om(next);
 157         }
 158       } else {
 159         // The current batch is preceded by another batch. This guarantees the current batch
 160         // does not start at head. Unlink the entire current batch without updating the head.
 161         assert(AtomicAccess::load(&_head) != m, "Sanity");
 162         prev->set_next_om(next);
 163       }
 164 
 165       unlinked_count += unlinked_batch;
 166       if (unlinked_count >= deflated_count) {
 167         // Reached the max so bail out of the searching loop.
 168         // There should be no more deflated monitors left.
 169         break;
 170       }
 171       m = next;
 172     } else {
 173       prev = m;
 174       m = m->next_om();
 175     }
 176 
 177     // Must check for a safepoint/handshake and honor it.
 178     safepointer->block_for_safepoint("unlinking", "unlinked_count", unlinked_count);
 179   }
 180 
 181 #ifdef ASSERT
 182   // Invariant: the code above should unlink all deflated monitors.
 183   // The code that runs after this unlinking does not expect deflated monitors.
 184   // Notably, attempting to deflate the already deflated monitor would break.
 185   {
 186     ObjectMonitor* m = AtomicAccess::load_acquire(&_head);
 187     while (m != nullptr) {
 188       assert(!m->is_being_async_deflated(), "All deflated monitors should be unlinked");
 189       m = m->next_om();
 190     }
 191   }
 192 #endif
 193 
 194   AtomicAccess::sub(&_count, unlinked_count);
 195   return unlinked_count;
 196 }
 197 
 198 MonitorList::Iterator MonitorList::iterator() const {
 199   return Iterator(AtomicAccess::load_acquire(&_head));
 200 }
 201 
 202 ObjectMonitor* MonitorList::Iterator::next() {
 203   ObjectMonitor* current = _current;
 204   _current = current->next_om();
 205   return current;
 206 }
 207 
 208 // The "core" versions of monitor enter and exit reside in this file.
 209 // The interpreter and compilers contain specialized transliterated
 210 // variants of the enter-exit fast-path operations.  See c2_MacroAssembler_x86.cpp
 211 // fast_lock(...) for instance.  If you make changes here, make sure to modify the
 212 // interpreter, and both C1 and C2 fast-path inline locking code emission.
 213 //
 214 // -----------------------------------------------------------------------------
 215 
 216 #ifdef DTRACE_ENABLED
 217 
 218 // Only bother with this argument setup if dtrace is available
 219 // TODO-FIXME: probes should not fire when caller is _blocked.  assert() accordingly.
 220 
 221 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread)                           \
 222   char* bytes = nullptr;                                                      \
 223   int len = 0;                                                             \
 224   jlong jtid = SharedRuntime::get_java_tid(thread);                        \
 225   Symbol* klassname = obj->klass()->name();                                \
 226   if (klassname != nullptr) {                                                 \
 227     bytes = (char*)klassname->bytes();                                     \
 228     len = klassname->utf8_length();                                        \
 229   }
 230 
 231 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis)            \
 232   {                                                                        \
 233     if (DTraceMonitorProbes) {                                             \
 234       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
 235       HOTSPOT_MONITOR_WAIT(jtid,                                           \
 236                            (uintptr_t)(monitor), bytes, len, (millis));    \
 237     }                                                                      \
 238   }
 239 
 240 #define HOTSPOT_MONITOR_PROBE_notify HOTSPOT_MONITOR_NOTIFY
 241 #define HOTSPOT_MONITOR_PROBE_notifyAll HOTSPOT_MONITOR_NOTIFYALL
 242 #define HOTSPOT_MONITOR_PROBE_waited HOTSPOT_MONITOR_WAITED
 243 
 244 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread)                  \
 245   {                                                                        \
 246     if (DTraceMonitorProbes) {                                             \
 247       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
 248       HOTSPOT_MONITOR_PROBE_##probe(jtid, /* probe = waited */             \
 249                                     (uintptr_t)(monitor), bytes, len);     \
 250     }                                                                      \
 251   }
 252 
 253 #else //  ndef DTRACE_ENABLED
 254 
 255 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon)    {;}
 256 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon)          {;}
 257 
 258 #endif // ndef DTRACE_ENABLED
 259 
 260 // This exists only as a workaround of dtrace bug 6254741
 261 static int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, JavaThread* thr) {
 262   DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
 263   return 0;
 264 }
 265 
 266 static constexpr size_t inflation_lock_count() {
 267   return 256;
 268 }
 269 
 270 // Static storage for an array of PlatformMutex.
 271 alignas(PlatformMutex) static uint8_t _inflation_locks[inflation_lock_count()][sizeof(PlatformMutex)];
 272 
 273 static inline PlatformMutex* inflation_lock(size_t index) {
 274   return reinterpret_cast<PlatformMutex*>(_inflation_locks[index]);
 275 }
 276 
 277 void ObjectSynchronizer::initialize() {
 278   for (size_t i = 0; i < inflation_lock_count(); i++) {
 279     ::new(static_cast<void*>(inflation_lock(i))) PlatformMutex();
 280   }
 281   // Start the ceiling with the estimate for one thread.
 282   set_in_use_list_ceiling(AvgMonitorsPerThreadEstimate);
 283 
 284   // Start the timer for deflations, so it does not trigger immediately.
 285   _last_async_deflation_time_ns = os::javaTimeNanos();
 286 
 287   ObjectSynchronizer::create_om_table();
 288 }
 289 
 290 MonitorList ObjectSynchronizer::_in_use_list;
 291 // monitors_used_above_threshold() policy is as follows:
 292 //
 293 // The ratio of the current _in_use_list count to the ceiling is used
 294 // to determine if we are above MonitorUsedDeflationThreshold and need
 295 // to do an async monitor deflation cycle. The ceiling is increased by
 296 // AvgMonitorsPerThreadEstimate when a thread is added to the system
 297 // and is decreased by AvgMonitorsPerThreadEstimate when a thread is
 298 // removed from the system.
 299 //
 300 // Note: If the _in_use_list max exceeds the ceiling, then
 301 // monitors_used_above_threshold() will use the in_use_list max instead
 302 // of the thread count derived ceiling because we have used more
 303 // ObjectMonitors than the estimated average.
 304 //
 305 // Note: If deflate_idle_monitors() has NoAsyncDeflationProgressMax
 306 // no-progress async monitor deflation cycles in a row, then the ceiling
 307 // is adjusted upwards by monitors_used_above_threshold().
 308 //
 309 // Start the ceiling with the estimate for one thread in initialize()
 310 // which is called after cmd line options are processed.
 311 static size_t _in_use_list_ceiling = 0;
 312 bool volatile ObjectSynchronizer::_is_async_deflation_requested = false;
 313 bool volatile ObjectSynchronizer::_is_final_audit = false;
 314 jlong ObjectSynchronizer::_last_async_deflation_time_ns = 0;
 315 static uintx _no_progress_cnt = 0;
 316 static bool _no_progress_skip_increment = false;
 317 
 318 // These checks are required for wait, notify and exit to avoid inflating the monitor to
 319 // find out this inline type object cannot be locked.
 320 #define CHECK_THROW_NOSYNC_IMSE(obj)  \
 321   if ((obj)->mark().is_inline_type()) {  \
 322     JavaThread* THREAD = current;           \
 323     ResourceMark rm(THREAD);                \
 324     THROW_MSG(vmSymbols::java_lang_IllegalMonitorStateException(), obj->klass()->external_name()); \
 325   }
 326 
 327 #define CHECK_THROW_NOSYNC_IMSE_0(obj)  \
 328   if ((obj)->mark().is_inline_type()) {  \
 329     JavaThread* THREAD = current;             \
 330     ResourceMark rm(THREAD);                  \
 331     THROW_MSG_0(vmSymbols::java_lang_IllegalMonitorStateException(), obj->klass()->external_name()); \
 332   }
 333 
 334 // =====================> Quick functions
 335 
 336 // The quick_* forms are special fast-path variants used to improve
 337 // performance.  In the simplest case, a "quick_*" implementation could
 338 // simply return false, in which case the caller will perform the necessary
 339 // state transitions and call the slow-path form.
 340 // The fast-path is designed to handle frequently arising cases in an efficient
 341 // manner and is just a degenerate "optimistic" variant of the slow-path.
 342 // returns true  -- to indicate the call was satisfied.
 343 // returns false -- to indicate the call needs the services of the slow-path.
 344 // A no-loitering ordinance is in effect for code in the quick_* family
 345 // operators: safepoints or indefinite blocking (blocking that might span a
 346 // safepoint) are forbidden. Generally the thread_state() is _in_Java upon
 347 // entry.
 348 //
 349 // Consider: An interesting optimization is to have the JIT recognize the
 350 // following common idiom:
 351 //   synchronized (someobj) { .... ; notify(); }
 352 // That is, we find a notify() or notifyAll() call that immediately precedes
 353 // the monitorexit operation.  In that case the JIT could fuse the operations
 354 // into a single notifyAndExit() runtime primitive.
 355 
 356 bool ObjectSynchronizer::quick_notify(oopDesc* obj, JavaThread* current, bool all) {
 357   assert(current->thread_state() == _thread_in_Java, "invariant");
 358   NoSafepointVerifier nsv;
 359   if (obj == nullptr) return false;  // slow-path for invalid obj
 360   assert(!obj->klass()->is_inline_klass(), "monitor op on inline type");
 361   const markWord mark = obj->mark();
 362 
 363   if (mark.is_fast_locked() && current->lock_stack().contains(cast_to_oop(obj))) {
 364     // Degenerate notify
 365     // fast-locked by caller so by definition the implied waitset is empty.
 366     return true;
 367   }
 368 
 369   if (mark.has_monitor()) {
 370     ObjectMonitor* const mon = read_monitor(obj, mark);
 371     if (mon == nullptr) {
 372       // Racing with inflation/deflation go slow path
 373       return false;
 374     }
 375     assert(mon->object() == oop(obj), "invariant");
 376     if (!mon->has_owner(current)) return false;  // slow-path for IMS exception
 377 
 378     if (mon->first_waiter() != nullptr) {
 379       // We have one or more waiters. Since this is an inflated monitor
 380       // that we own, we quickly notify them here and now, avoiding the slow-path.
 381       if (all) {
 382         mon->quick_notifyAll(current);
 383       } else {
 384         mon->quick_notify(current);
 385       }
 386     }
 387     return true;
 388   }
 389 
 390   // other IMS exception states take the slow-path
 391   return false;
 392 }
 393 
 394 // Handle notifications when synchronizing on value based classes
 395 void ObjectSynchronizer::handle_sync_on_value_based_class(Handle obj, JavaThread* locking_thread) {
 396   assert(locking_thread == Thread::current() || locking_thread->is_obj_deopt_suspend(), "must be");
 397   frame last_frame = locking_thread->last_frame();
 398   bool bcp_was_adjusted = false;
 399   // Don't decrement bcp if it points to the frame's first instruction.  This happens when
 400   // handle_sync_on_value_based_class() is called because of a synchronized method.  There
 401   // is no actual monitorenter instruction in the byte code in this case.
 402   if (last_frame.is_interpreted_frame() &&
 403       (last_frame.interpreter_frame_method()->code_base() < last_frame.interpreter_frame_bcp())) {
 404     // adjust bcp to point back to monitorenter so that we print the correct line numbers
 405     last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() - 1);
 406     bcp_was_adjusted = true;
 407   }
 408 
 409   if (DiagnoseSyncOnValueBasedClasses == FATAL_EXIT) {
 410     ResourceMark rm;
 411     stringStream ss;
 412     locking_thread->print_active_stack_on(&ss);
 413     char* base = (char*)strstr(ss.base(), "at");
 414     char* newline = (char*)strchr(ss.base(), '\n');
 415     if (newline != nullptr) {
 416       *newline = '\0';
 417     }
 418     fatal("Synchronizing on object " INTPTR_FORMAT " of klass %s %s", p2i(obj()), obj->klass()->external_name(), base);
 419   } else {
 420     assert(DiagnoseSyncOnValueBasedClasses == LOG_WARNING, "invalid value for DiagnoseSyncOnValueBasedClasses");
 421     ResourceMark rm;
 422     Log(valuebasedclasses) vblog;
 423 
 424     vblog.info("Synchronizing on object " INTPTR_FORMAT " of klass %s", p2i(obj()), obj->klass()->external_name());
 425     if (locking_thread->has_last_Java_frame()) {
 426       LogStream info_stream(vblog.info());
 427       locking_thread->print_active_stack_on(&info_stream);
 428     } else {
 429       vblog.info("Cannot find the last Java frame");
 430     }
 431 
 432     EventSyncOnValueBasedClass event;
 433     if (event.should_commit()) {
 434       event.set_valueBasedClass(obj->klass());
 435       event.commit();
 436     }
 437   }
 438 
 439   if (bcp_was_adjusted) {
 440     last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() + 1);
 441   }
 442 }
 443 
 444 // -----------------------------------------------------------------------------
 445 // JNI locks on java objects
 446 // NOTE: must use heavy weight monitor to handle jni monitor enter
 447 void ObjectSynchronizer::jni_enter(Handle obj, JavaThread* current) {
 448   JavaThread* THREAD = current;
 449   // Top native frames in the stack will not be seen if we attempt
 450   // preemption, since we start walking from the last Java anchor.
 451   NoPreemptMark npm(current);
 452 
 453   if (obj->klass()->is_value_based()) {
 454     handle_sync_on_value_based_class(obj, current);
 455   }
 456 
 457   if (obj->klass()->is_inline_klass()) {
 458     ResourceMark rm(THREAD);
 459     stringStream ss;
 460     ss.print("Cannot synchronize on an instance of value class %s",
 461              obj->klass()->external_name());
 462     THROW_MSG(vmSymbols::java_lang_IdentityException(), ss.as_string());
 463   }
 464 
 465   // the current locking is from JNI instead of Java code
 466   current->set_current_pending_monitor_is_from_java(false);
 467   // An async deflation can race after the inflate() call and before
 468   // enter() can make the ObjectMonitor busy. enter() returns false if
 469   // we have lost the race to async deflation and we simply try again.
 470   while (true) {
 471     BasicLock lock;
 472     if (ObjectSynchronizer::inflate_and_enter(obj(), &lock, inflate_cause_jni_enter, current, current) != nullptr) {
 473       break;
 474     }
 475   }
 476   current->set_current_pending_monitor_is_from_java(true);
 477 }
 478 
 479 // NOTE: must use heavy weight monitor to handle jni monitor exit
 480 void ObjectSynchronizer::jni_exit(oop obj, TRAPS) {
 481   JavaThread* current = THREAD;
 482   CHECK_THROW_NOSYNC_IMSE(obj);
 483 
 484   ObjectMonitor* monitor;
 485   monitor = ObjectSynchronizer::inflate_locked_or_imse(obj, inflate_cause_jni_exit, CHECK);
 486   // If this thread has locked the object, exit the monitor. We
 487   // intentionally do not use CHECK on check_owner because we must exit the
 488   // monitor even if an exception was already pending.
 489   if (monitor->check_owner(THREAD)) {
 490     monitor->exit(current);
 491   }
 492 }
 493 
 494 // -----------------------------------------------------------------------------
 495 // Internal VM locks on java objects
 496 // standard constructor, allows locking failures
 497 ObjectLocker::ObjectLocker(Handle obj, TRAPS) : _thread(THREAD), _obj(obj),
 498   _npm(_thread, _thread->at_preemptable_init() /* ignore_mark */), _skip_exit(false) {
 499   assert(!_thread->preempting(), "");
 500 
 501   _thread->check_for_valid_safepoint_state();
 502 
 503   if (_obj() != nullptr) {
 504     ObjectSynchronizer::enter(_obj, &_lock, _thread);
 505 
 506     if (_thread->preempting()) {
 507       // If preemption was cancelled we acquired the monitor after freezing
 508       // the frames. Redoing the vm call laterĀ in thaw will require us to
 509       // release it since the call should look like the original one. We
 510       // do it in ~ObjectLocker to reduce the window of time we hold the
 511       // monitor since we can't do anything useful with it now, and would
 512       // otherwise just force other vthreads to preempt in case they try
 513       // to acquire this monitor.
 514       _skip_exit = !_thread->preemption_cancelled();
 515       ObjectSynchronizer::read_monitor(_obj())->set_object_strong();
 516       _thread->set_pending_preempted_exception();
 517 
 518     }
 519   }
 520 }
 521 
 522 ObjectLocker::~ObjectLocker() {
 523   if (_obj() != nullptr && !_skip_exit) {
 524     ObjectSynchronizer::exit(_obj(), &_lock, _thread);
 525   }
 526 }
 527 
 528 void ObjectLocker::wait_uninterruptibly(TRAPS) {
 529   ObjectSynchronizer::waitUninterruptibly(_obj, 0, _thread);
 530   if (_thread->preempting()) {
 531     _skip_exit = true;
 532     ObjectSynchronizer::read_monitor(_obj())->set_object_strong();
 533     _thread->set_pending_preempted_exception();
 534   }
 535 }
 536 
 537 // -----------------------------------------------------------------------------
 538 //  Wait/Notify/NotifyAll
 539 // NOTE: must use heavy weight monitor to handle wait()
 540 
 541 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
 542   JavaThread* current = THREAD;
 543   CHECK_THROW_NOSYNC_IMSE_0(obj);
 544   if (millis < 0) {
 545     THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
 546   }
 547 
 548   ObjectMonitor* monitor;
 549   monitor = ObjectSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_wait, CHECK_0);
 550 
 551   DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), current, millis);
 552   monitor->wait(millis, true, THREAD); // Not CHECK as we need following code
 553 
 554   // This dummy call is in place to get around dtrace bug 6254741.  Once
 555   // that's fixed we can uncomment the following line, remove the call
 556   // and change this function back into a "void" func.
 557   // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
 558   int ret_code = dtrace_waited_probe(monitor, obj, THREAD);
 559   return ret_code;
 560 }
 561 
 562 void ObjectSynchronizer::waitUninterruptibly(Handle obj, jlong millis, TRAPS) {
 563   assert(millis >= 0, "timeout value is negative");
 564 
 565   ObjectMonitor* monitor;
 566   monitor = ObjectSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_wait, CHECK);
 567   monitor->wait(millis, false, THREAD);
 568 }
 569 
 570 
 571 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
 572   JavaThread* current = THREAD;
 573   CHECK_THROW_NOSYNC_IMSE(obj);
 574 
 575   markWord mark = obj->mark();
 576   if ((mark.is_fast_locked() && current->lock_stack().contains(obj()))) {
 577     // Not inflated so there can't be any waiters to notify.
 578     return;
 579   }
 580   ObjectMonitor* monitor = ObjectSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_notify, CHECK);
 581   monitor->notify(CHECK);
 582 }
 583 
 584 // NOTE: see comment of notify()
 585 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
 586   JavaThread* current = THREAD;
 587   CHECK_THROW_NOSYNC_IMSE(obj);
 588 
 589   markWord mark = obj->mark();
 590   if ((mark.is_fast_locked() && current->lock_stack().contains(obj()))) {
 591     // Not inflated so there can't be any waiters to notify.
 592     return;
 593   }
 594 
 595   ObjectMonitor* monitor = ObjectSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_notify, CHECK);
 596   monitor->notifyAll(CHECK);
 597 }
 598 
 599 // -----------------------------------------------------------------------------
 600 // Hash Code handling
 601 
 602 struct SharedGlobals {
 603   char         _pad_prefix[OM_CACHE_LINE_SIZE];
 604   // This is a highly shared mostly-read variable.
 605   // To avoid false-sharing it needs to be the sole occupant of a cache line.
 606   volatile int stw_random;
 607   DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 608   // Hot RW variable -- Sequester to avoid false-sharing
 609   volatile int hc_sequence;
 610   DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(volatile int));
 611 };
 612 
 613 static SharedGlobals GVars;
 614 
 615 // hashCode() generation :
 616 //
 617 // Possibilities:
 618 // * MD5Digest of {obj,stw_random}
 619 // * CRC32 of {obj,stw_random} or any linear-feedback shift register function.
 620 // * A DES- or AES-style SBox[] mechanism
 621 // * One of the Phi-based schemes, such as:
 622 //   2654435761 = 2^32 * Phi (golden ratio)
 623 //   HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stw_random ;
 624 // * A variation of Marsaglia's shift-xor RNG scheme.
 625 // * (obj ^ stw_random) is appealing, but can result
 626 //   in undesirable regularity in the hashCode values of adjacent objects
 627 //   (objects allocated back-to-back, in particular).  This could potentially
 628 //   result in hashtable collisions and reduced hashtable efficiency.
 629 //   There are simple ways to "diffuse" the middle address bits over the
 630 //   generated hashCode values:
 631 
 632 static intptr_t get_next_hash(Thread* current, oop obj) {
 633   intptr_t value = 0;
 634   if (hashCode == 0) {
 635     // This form uses global Park-Miller RNG.
 636     // On MP system we'll have lots of RW access to a global, so the
 637     // mechanism induces lots of coherency traffic.
 638     value = os::random();
 639   } else if (hashCode == 1) {
 640     // This variation has the property of being stable (idempotent)
 641     // between STW operations.  This can be useful in some of the 1-0
 642     // synchronization schemes.
 643     intptr_t addr_bits = cast_from_oop<intptr_t>(obj) >> 3;
 644     value = addr_bits ^ (addr_bits >> 5) ^ GVars.stw_random;
 645   } else if (hashCode == 2) {
 646     value = 1;            // for sensitivity testing
 647   } else if (hashCode == 3) {
 648     value = ++GVars.hc_sequence;
 649   } else if (hashCode == 4) {
 650     value = cast_from_oop<intptr_t>(obj);
 651   } else {
 652     // Marsaglia's xor-shift scheme with thread-specific state
 653     // This is probably the best overall implementation -- we'll
 654     // likely make this the default in future releases.
 655     unsigned t = current->_hashStateX;
 656     t ^= (t << 11);
 657     current->_hashStateX = current->_hashStateY;
 658     current->_hashStateY = current->_hashStateZ;
 659     current->_hashStateZ = current->_hashStateW;
 660     unsigned v = current->_hashStateW;
 661     v = (v ^ (v >> 19)) ^ (t ^ (t >> 8));
 662     current->_hashStateW = v;
 663     value = v;
 664   }
 665 
 666   value &= markWord::hash_mask;
 667   if (value == 0) value = 0xBAD;
 668   assert(value != markWord::no_hash, "invariant");
 669   return value;
 670 }
 671 
 672 intptr_t ObjectSynchronizer::FastHashCode(Thread* current, oop obj) {
 673   // VM should be calling bootstrap method.
 674   assert(!obj->klass()->is_inline_klass(), "FastHashCode should not be called for inline classes");
 675 
 676   while (true) {
 677     ObjectMonitor* monitor = nullptr;
 678     markWord temp, test;
 679     intptr_t hash;
 680     markWord mark = obj->mark_acquire();
 681     // If UseObjectMonitorTable is set the hash can simply be installed in the
 682     // object header, since the monitor isn't in the object header.
 683     if (UseObjectMonitorTable || !mark.has_monitor()) {
 684       hash = mark.hash();
 685       if (hash != 0) {                     // if it has a hash, just return it
 686         return hash;
 687       }
 688       hash = get_next_hash(current, obj);  // get a new hash
 689       temp = mark.copy_set_hash(hash);     // merge the hash into header
 690                                            // try to install the hash
 691       test = obj->cas_set_mark(temp, mark);
 692       if (test == mark) {                  // if the hash was installed, return it
 693         return hash;
 694       }
 695       // CAS failed, retry
 696       continue;
 697 
 698       // Failed to install the hash. It could be that another thread
 699       // installed the hash just before our attempt or inflation has
 700       // occurred or... so we fall thru to inflate the monitor for
 701       // stability and then install the hash.
 702     } else {
 703       assert(!mark.is_unlocked() && !mark.is_fast_locked(), "invariant");
 704       monitor = mark.monitor();
 705       temp = monitor->header();
 706       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
 707       hash = temp.hash();
 708       if (hash != 0) {
 709         // It has a hash.
 710 
 711         // Separate load of dmw/header above from the loads in
 712         // is_being_async_deflated().
 713 
 714         // dmw/header and _contentions may get written by different threads.
 715         // Make sure to observe them in the same order when having several observers.
 716         OrderAccess::loadload_for_IRIW();
 717 
 718         if (monitor->is_being_async_deflated()) {
 719           // But we can't safely use the hash if we detect that async
 720           // deflation has occurred. So we attempt to restore the
 721           // header/dmw to the object's header so that we only retry
 722           // once if the deflater thread happens to be slow.
 723           monitor->install_displaced_markword_in_object(obj);
 724           continue;
 725         }
 726         return hash;
 727       }
 728       // Fall thru so we only have one place that installs the hash in
 729       // the ObjectMonitor.
 730     }
 731 
 732     // NOTE: an async deflation can race after we get the monitor and
 733     // before we can update the ObjectMonitor's header with the hash
 734     // value below.
 735     assert(mark.has_monitor(), "must be");
 736     monitor = mark.monitor();
 737 
 738     // Load ObjectMonitor's header/dmw field and see if it has a hash.
 739     mark = monitor->header();
 740     assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value());
 741     hash = mark.hash();
 742     if (hash == 0) {                       // if it does not have a hash
 743       hash = get_next_hash(current, obj);  // get a new hash
 744       temp = mark.copy_set_hash(hash)   ;  // merge the hash into header
 745       assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
 746       uintptr_t v = AtomicAccess::cmpxchg(monitor->metadata_addr(), mark.value(), temp.value());
 747       test = markWord(v);
 748       if (test != mark) {
 749         // The attempt to update the ObjectMonitor's header/dmw field
 750         // did not work. This can happen if another thread managed to
 751         // merge in the hash just before our cmpxchg().
 752         // If we add any new usages of the header/dmw field, this code
 753         // will need to be updated.
 754         hash = test.hash();
 755         assert(test.is_neutral(), "invariant: header=" INTPTR_FORMAT, test.value());
 756         assert(hash != 0, "should only have lost the race to a thread that set a non-zero hash");
 757       }
 758       if (monitor->is_being_async_deflated() && !UseObjectMonitorTable) {
 759         // If we detect that async deflation has occurred, then we
 760         // attempt to restore the header/dmw to the object's header
 761         // so that we only retry once if the deflater thread happens
 762         // to be slow.
 763         monitor->install_displaced_markword_in_object(obj);
 764         continue;
 765       }
 766     }
 767     // We finally get the hash.
 768     return hash;
 769   }
 770 }
 771 
 772 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* current,
 773                                                    Handle h_obj) {
 774   if (h_obj->mark().is_inline_type()) {
 775     return false;
 776   }
 777   assert(current == JavaThread::current(), "Can only be called on current thread");
 778   oop obj = h_obj();
 779 
 780   markWord mark = obj->mark_acquire();
 781 
 782   if (mark.is_fast_locked()) {
 783     // fast-locking case, see if lock is in current's lock stack
 784     return current->lock_stack().contains(h_obj());
 785   }
 786 
 787   while (mark.has_monitor()) {
 788     ObjectMonitor* monitor = read_monitor(obj, mark);
 789     if (monitor != nullptr) {
 790       return monitor->is_entered(current) != 0;
 791     }
 792     // Racing with inflation/deflation, retry
 793     mark = obj->mark_acquire();
 794 
 795     if (mark.is_fast_locked()) {
 796       // Some other thread fast_locked, current could not have held the lock
 797       return false;
 798     }
 799   }
 800 
 801   // Unlocked case, header in place
 802   assert(mark.is_unlocked(), "sanity check");
 803   return false;
 804 }
 805 
 806 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) {
 807   oop obj = h_obj();
 808   markWord mark = obj->mark_acquire();
 809 
 810   if (mark.is_fast_locked()) {
 811     // fast-locked so get owner from the object.
 812     // owning_thread_from_object() may also return null here:
 813     return Threads::owning_thread_from_object(t_list, h_obj());
 814   }
 815 
 816   while (mark.has_monitor()) {
 817     ObjectMonitor* monitor = read_monitor(obj, mark);
 818     if (monitor != nullptr) {
 819       return Threads::owning_thread_from_monitor(t_list, monitor);
 820     }
 821     // Racing with inflation/deflation, retry
 822     mark = obj->mark_acquire();
 823 
 824     if (mark.is_fast_locked()) {
 825       // Some other thread fast_locked
 826       return Threads::owning_thread_from_object(t_list, h_obj());
 827     }
 828   }
 829 
 830   // Unlocked case, header in place
 831   // Cannot have assertion since this object may have been
 832   // locked by another thread when reaching here.
 833   // assert(mark.is_unlocked(), "sanity check");
 834 
 835   return nullptr;
 836 }
 837 
 838 // Visitors ...
 839 
 840 // Iterate over all ObjectMonitors.
 841 template <typename Function>
 842 void ObjectSynchronizer::monitors_iterate(Function function) {
 843   MonitorList::Iterator iter = _in_use_list.iterator();
 844   while (iter.has_next()) {
 845     ObjectMonitor* monitor = iter.next();
 846     function(monitor);
 847   }
 848 }
 849 
 850 // Iterate ObjectMonitors owned by any thread and where the owner `filter`
 851 // returns true.
 852 template <typename OwnerFilter>
 853 void ObjectSynchronizer::owned_monitors_iterate_filtered(MonitorClosure* closure, OwnerFilter filter) {
 854   monitors_iterate([&](ObjectMonitor* monitor) {
 855     // This function is only called at a safepoint or when the
 856     // target thread is suspended or when the target thread is
 857     // operating on itself. The current closures in use today are
 858     // only interested in an owned ObjectMonitor and ownership
 859     // cannot be dropped under the calling contexts so the
 860     // ObjectMonitor cannot be async deflated.
 861     if (monitor->has_owner() && filter(monitor)) {
 862       assert(!monitor->is_being_async_deflated(), "Owned monitors should not be deflating");
 863 
 864       closure->do_monitor(monitor);
 865     }
 866   });
 867 }
 868 
 869 // Iterate ObjectMonitors where the owner == thread; this does NOT include
 870 // ObjectMonitors where owner is set to a stack-lock address in thread.
 871 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure, JavaThread* thread) {
 872   int64_t key = ObjectMonitor::owner_id_from(thread);
 873   auto thread_filter = [&](ObjectMonitor* monitor) { return monitor->owner() == key; };
 874   return owned_monitors_iterate_filtered(closure, thread_filter);
 875 }
 876 
 877 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure, oop vthread) {
 878   int64_t key = ObjectMonitor::owner_id_from(vthread);
 879   auto thread_filter = [&](ObjectMonitor* monitor) { return monitor->owner() == key; };
 880   return owned_monitors_iterate_filtered(closure, thread_filter);
 881 }
 882 
 883 // Iterate ObjectMonitors owned by any thread.
 884 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure) {
 885   auto all_filter = [&](ObjectMonitor* monitor) { return true; };
 886   return owned_monitors_iterate_filtered(closure, all_filter);
 887 }
 888 
 889 static bool monitors_used_above_threshold(MonitorList* list) {
 890   if (MonitorUsedDeflationThreshold == 0) {  // disabled case is easy
 891     return false;
 892   }
 893   size_t monitors_used = list->count();
 894   if (monitors_used == 0) {  // empty list is easy
 895     return false;
 896   }
 897   size_t old_ceiling = ObjectSynchronizer::in_use_list_ceiling();
 898   // Make sure that we use a ceiling value that is not lower than
 899   // previous, not lower than the recorded max used by the system, and
 900   // not lower than the current number of monitors in use (which can
 901   // race ahead of max). The result is guaranteed > 0.
 902   size_t ceiling = MAX3(old_ceiling, list->max(), monitors_used);
 903 
 904   // Check if our monitor usage is above the threshold:
 905   size_t monitor_usage = (monitors_used * 100LL) / ceiling;
 906   if (int(monitor_usage) > MonitorUsedDeflationThreshold) {
 907     // Deflate monitors if over the threshold percentage, unless no
 908     // progress on previous deflations.
 909     bool is_above_threshold = true;
 910 
 911     // Check if it's time to adjust the in_use_list_ceiling up, due
 912     // to too many async deflation attempts without any progress.
 913     if (NoAsyncDeflationProgressMax != 0 &&
 914         _no_progress_cnt >= NoAsyncDeflationProgressMax) {
 915       double remainder = (100.0 - MonitorUsedDeflationThreshold) / 100.0;
 916       size_t delta = (size_t)(ceiling * remainder) + 1;
 917       size_t new_ceiling = (ceiling > SIZE_MAX - delta)
 918         ? SIZE_MAX         // Overflow, let's clamp new_ceiling.
 919         : ceiling + delta;
 920 
 921       ObjectSynchronizer::set_in_use_list_ceiling(new_ceiling);
 922       log_info(monitorinflation)("Too many deflations without progress; "
 923                                  "bumping in_use_list_ceiling from %zu"
 924                                  " to %zu", old_ceiling, new_ceiling);
 925       _no_progress_cnt = 0;
 926       ceiling = new_ceiling;
 927 
 928       // Check if our monitor usage is still above the threshold:
 929       monitor_usage = (monitors_used * 100LL) / ceiling;
 930       is_above_threshold = int(monitor_usage) > MonitorUsedDeflationThreshold;
 931     }
 932     log_info(monitorinflation)("monitors_used=%zu, ceiling=%zu"
 933                                ", monitor_usage=%zu, threshold=%d",
 934                                monitors_used, ceiling, monitor_usage, MonitorUsedDeflationThreshold);
 935     return is_above_threshold;
 936   }
 937 
 938   return false;
 939 }
 940 
 941 size_t ObjectSynchronizer::in_use_list_count() {
 942   return _in_use_list.count();
 943 }
 944 
 945 size_t ObjectSynchronizer::in_use_list_max() {
 946   return _in_use_list.max();
 947 }
 948 
 949 size_t ObjectSynchronizer::in_use_list_ceiling() {
 950   return _in_use_list_ceiling;
 951 }
 952 
 953 void ObjectSynchronizer::dec_in_use_list_ceiling() {
 954   AtomicAccess::sub(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate);
 955 }
 956 
 957 void ObjectSynchronizer::inc_in_use_list_ceiling() {
 958   AtomicAccess::add(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate);
 959 }
 960 
 961 void ObjectSynchronizer::set_in_use_list_ceiling(size_t new_value) {
 962   _in_use_list_ceiling = new_value;
 963 }
 964 
 965 bool ObjectSynchronizer::is_async_deflation_needed() {
 966   if (is_async_deflation_requested()) {
 967     // Async deflation request.
 968     log_info(monitorinflation)("Async deflation needed: explicit request");
 969     return true;
 970   }
 971 
 972   jlong time_since_last = time_since_last_async_deflation_ms();
 973 
 974   if (AsyncDeflationInterval > 0 &&
 975       time_since_last > AsyncDeflationInterval &&
 976       monitors_used_above_threshold(&_in_use_list)) {
 977     // It's been longer than our specified deflate interval and there
 978     // are too many monitors in use. We don't deflate more frequently
 979     // than AsyncDeflationInterval (unless is_async_deflation_requested)
 980     // in order to not swamp the MonitorDeflationThread.
 981     log_info(monitorinflation)("Async deflation needed: monitors used are above the threshold");
 982     return true;
 983   }
 984 
 985   if (GuaranteedAsyncDeflationInterval > 0 &&
 986       time_since_last > GuaranteedAsyncDeflationInterval) {
 987     // It's been longer than our specified guaranteed deflate interval.
 988     // We need to clean up the used monitors even if the threshold is
 989     // not reached, to keep the memory utilization at bay when many threads
 990     // touched many monitors.
 991     log_info(monitorinflation)("Async deflation needed: guaranteed interval (%zd ms) "
 992                                "is greater than time since last deflation (" JLONG_FORMAT " ms)",
 993                                GuaranteedAsyncDeflationInterval, time_since_last);
 994 
 995     // If this deflation has no progress, then it should not affect the no-progress
 996     // tracking, otherwise threshold heuristics would think it was triggered, experienced
 997     // no progress, and needs to backoff more aggressively. In this "no progress" case,
 998     // the generic code would bump the no-progress counter, and we compensate for that
 999     // by telling it to skip the update.
1000     //
1001     // If this deflation has progress, then it should let non-progress tracking
1002     // know about this, otherwise the threshold heuristics would kick in, potentially
1003     // experience no-progress due to aggressive cleanup by this deflation, and think
1004     // it is still in no-progress stride. In this "progress" case, the generic code would
1005     // zero the counter, and we allow it to happen.
1006     _no_progress_skip_increment = true;
1007 
1008     return true;
1009   }
1010 
1011   return false;
1012 }
1013 
1014 void ObjectSynchronizer::request_deflate_idle_monitors() {
1015   MonitorLocker ml(MonitorDeflation_lock, Mutex::_no_safepoint_check_flag);
1016   set_is_async_deflation_requested(true);
1017   ml.notify_all();
1018 }
1019 
1020 bool ObjectSynchronizer::request_deflate_idle_monitors_from_wb() {
1021   JavaThread* current = JavaThread::current();
1022   bool ret_code = false;
1023 
1024   jlong last_time = last_async_deflation_time_ns();
1025 
1026   request_deflate_idle_monitors();
1027 
1028   const int N_CHECKS = 5;
1029   for (int i = 0; i < N_CHECKS; i++) {  // sleep for at most 5 seconds
1030     if (last_async_deflation_time_ns() > last_time) {
1031       log_info(monitorinflation)("Async Deflation happened after %d check(s).", i);
1032       ret_code = true;
1033       break;
1034     }
1035     {
1036       // JavaThread has to honor the blocking protocol.
1037       ThreadBlockInVM tbivm(current);
1038       os::naked_short_sleep(999);  // sleep for almost 1 second
1039     }
1040   }
1041   if (!ret_code) {
1042     log_info(monitorinflation)("Async Deflation DID NOT happen after %d checks.", N_CHECKS);
1043   }
1044 
1045   return ret_code;
1046 }
1047 
1048 jlong ObjectSynchronizer::time_since_last_async_deflation_ms() {
1049   return (os::javaTimeNanos() - last_async_deflation_time_ns()) / (NANOUNITS / MILLIUNITS);
1050 }
1051 
1052 // Walk the in-use list and deflate (at most MonitorDeflationMax) idle
1053 // ObjectMonitors. Returns the number of deflated ObjectMonitors.
1054 //
1055 size_t ObjectSynchronizer::deflate_monitor_list(ObjectMonitorDeflationSafepointer* safepointer) {
1056   MonitorList::Iterator iter = _in_use_list.iterator();
1057   size_t deflated_count = 0;
1058   Thread* current = Thread::current();
1059 
1060   while (iter.has_next()) {
1061     if (deflated_count >= (size_t)MonitorDeflationMax) {
1062       break;
1063     }
1064     ObjectMonitor* mid = iter.next();
1065     if (mid->deflate_monitor(current)) {
1066       deflated_count++;
1067     }
1068 
1069     // Must check for a safepoint/handshake and honor it.
1070     safepointer->block_for_safepoint("deflation", "deflated_count", deflated_count);
1071   }
1072 
1073   return deflated_count;
1074 }
1075 
1076 class DeflationHandshakeClosure : public HandshakeClosure {
1077  public:
1078   DeflationHandshakeClosure() : HandshakeClosure("DeflationHandshakeClosure") {}
1079 
1080   void do_thread(Thread* thread) {
1081     log_trace(monitorinflation)("DeflationHandshakeClosure::do_thread: thread="
1082                                 INTPTR_FORMAT, p2i(thread));
1083     if (thread->is_Java_thread()) {
1084       // Clear OM cache
1085       JavaThread* jt = JavaThread::cast(thread);
1086       jt->om_clear_monitor_cache();
1087     }
1088   }
1089 };
1090 
1091 class VM_RendezvousGCThreads : public VM_Operation {
1092 public:
1093   bool evaluate_at_safepoint() const override { return false; }
1094   VMOp_Type type() const override { return VMOp_RendezvousGCThreads; }
1095   void doit() override {
1096     Universe::heap()->safepoint_synchronize_begin();
1097     Universe::heap()->safepoint_synchronize_end();
1098   };
1099 };
1100 
1101 static size_t delete_monitors(GrowableArray<ObjectMonitor*>* delete_list,
1102                               ObjectMonitorDeflationSafepointer* safepointer) {
1103   NativeHeapTrimmer::SuspendMark sm("monitor deletion");
1104   size_t deleted_count = 0;
1105   for (ObjectMonitor* monitor: *delete_list) {
1106     delete monitor;
1107     deleted_count++;
1108     // A JavaThread must check for a safepoint/handshake and honor it.
1109     safepointer->block_for_safepoint("deletion", "deleted_count", deleted_count);
1110   }
1111   return deleted_count;
1112 }
1113 
1114 class ObjectMonitorDeflationLogging: public StackObj {
1115   LogStreamHandle(Debug, monitorinflation) _debug;
1116   LogStreamHandle(Info, monitorinflation)  _info;
1117   LogStream*                               _stream;
1118   elapsedTimer                             _timer;
1119 
1120   size_t ceiling() const { return ObjectSynchronizer::in_use_list_ceiling(); }
1121   size_t count() const   { return ObjectSynchronizer::in_use_list_count(); }
1122   size_t max() const     { return ObjectSynchronizer::in_use_list_max(); }
1123 
1124 public:
1125   ObjectMonitorDeflationLogging()
1126     : _debug(), _info(), _stream(nullptr) {
1127     if (_debug.is_enabled()) {
1128       _stream = &_debug;
1129     } else if (_info.is_enabled()) {
1130       _stream = &_info;
1131     }
1132   }
1133 
1134   void begin() {
1135     if (_stream != nullptr) {
1136       _stream->print_cr("begin deflating: in_use_list stats: ceiling=%zu, count=%zu, max=%zu",
1137                         ceiling(), count(), max());
1138       _timer.start();
1139     }
1140   }
1141 
1142   void before_handshake(size_t unlinked_count) {
1143     if (_stream != nullptr) {
1144       _timer.stop();
1145       _stream->print_cr("before handshaking: unlinked_count=%zu"
1146                         ", in_use_list stats: ceiling=%zu, count="
1147                         "%zu, max=%zu",
1148                         unlinked_count, ceiling(), count(), max());
1149     }
1150   }
1151 
1152   void after_handshake() {
1153     if (_stream != nullptr) {
1154       _stream->print_cr("after handshaking: in_use_list stats: ceiling="
1155                         "%zu, count=%zu, max=%zu",
1156                         ceiling(), count(), max());
1157       _timer.start();
1158     }
1159   }
1160 
1161   void end(size_t deflated_count, size_t unlinked_count) {
1162     if (_stream != nullptr) {
1163       _timer.stop();
1164       if (deflated_count != 0 || unlinked_count != 0 || _debug.is_enabled()) {
1165         _stream->print_cr("deflated_count=%zu, {unlinked,deleted}_count=%zu monitors in %3.7f secs",
1166                           deflated_count, unlinked_count, _timer.seconds());
1167       }
1168       _stream->print_cr("end deflating: in_use_list stats: ceiling=%zu, count=%zu, max=%zu",
1169                         ceiling(), count(), max());
1170     }
1171   }
1172 
1173   void before_block_for_safepoint(const char* op_name, const char* cnt_name, size_t cnt) {
1174     if (_stream != nullptr) {
1175       _timer.stop();
1176       _stream->print_cr("pausing %s: %s=%zu, in_use_list stats: ceiling="
1177                         "%zu, count=%zu, max=%zu",
1178                         op_name, cnt_name, cnt, ceiling(), count(), max());
1179     }
1180   }
1181 
1182   void after_block_for_safepoint(const char* op_name) {
1183     if (_stream != nullptr) {
1184       _stream->print_cr("resuming %s: in_use_list stats: ceiling=%zu"
1185                         ", count=%zu, max=%zu", op_name,
1186                         ceiling(), count(), max());
1187       _timer.start();
1188     }
1189   }
1190 };
1191 
1192 void ObjectMonitorDeflationSafepointer::block_for_safepoint(const char* op_name, const char* count_name, size_t counter) {
1193   if (!SafepointMechanism::should_process(_current)) {
1194     return;
1195   }
1196 
1197   // A safepoint/handshake has started.
1198   _log->before_block_for_safepoint(op_name, count_name, counter);
1199 
1200   {
1201     // Honor block request.
1202     ThreadBlockInVM tbivm(_current);
1203   }
1204 
1205   _log->after_block_for_safepoint(op_name);
1206 }
1207 
1208 // This function is called by the MonitorDeflationThread to deflate
1209 // ObjectMonitors.
1210 size_t ObjectSynchronizer::deflate_idle_monitors() {
1211   JavaThread* current = JavaThread::current();
1212   assert(current->is_monitor_deflation_thread(), "The only monitor deflater");
1213 
1214   // The async deflation request has been processed.
1215   _last_async_deflation_time_ns = os::javaTimeNanos();
1216   set_is_async_deflation_requested(false);
1217 
1218   ObjectMonitorDeflationLogging log;
1219   ObjectMonitorDeflationSafepointer safepointer(current, &log);
1220 
1221   log.begin();
1222 
1223   // Deflate some idle ObjectMonitors.
1224   size_t deflated_count = deflate_monitor_list(&safepointer);
1225 
1226   // Unlink the deflated ObjectMonitors from the in-use list.
1227   size_t unlinked_count = 0;
1228   size_t deleted_count = 0;
1229   if (deflated_count > 0) {
1230     ResourceMark rm(current);
1231     GrowableArray<ObjectMonitor*> delete_list((int)deflated_count);
1232     unlinked_count = _in_use_list.unlink_deflated(deflated_count, &delete_list, &safepointer);
1233 
1234     GrowableArray<ObjectMonitorTable::Table*> table_delete_list;
1235     if (UseObjectMonitorTable) {
1236       ObjectMonitorTable::rebuild(&table_delete_list);
1237     }
1238 
1239     log.before_handshake(unlinked_count);
1240 
1241     // A JavaThread needs to handshake in order to safely free the
1242     // ObjectMonitors that were deflated in this cycle.
1243     DeflationHandshakeClosure dhc;
1244     Handshake::execute(&dhc);
1245     // Also, we sync and desync GC threads around the handshake, so that they can
1246     // safely read the mark-word and look-through to the object-monitor, without
1247     // being afraid that the object-monitor is going away.
1248     VM_RendezvousGCThreads sync_gc;
1249     VMThread::execute(&sync_gc);
1250 
1251     log.after_handshake();
1252 
1253     // After the handshake, safely free the ObjectMonitors that were
1254     // deflated and unlinked in this cycle.
1255 
1256     // Delete the unlinked ObjectMonitors.
1257     deleted_count = delete_monitors(&delete_list, &safepointer);
1258     if (UseObjectMonitorTable) {
1259       ObjectMonitorTable::destroy(&table_delete_list);
1260     }
1261     assert(unlinked_count == deleted_count, "must be");
1262   }
1263 
1264   log.end(deflated_count, unlinked_count);
1265 
1266   GVars.stw_random = os::random();
1267 
1268   if (deflated_count != 0) {
1269     _no_progress_cnt = 0;
1270   } else if (_no_progress_skip_increment) {
1271     _no_progress_skip_increment = false;
1272   } else {
1273     _no_progress_cnt++;
1274   }
1275 
1276   return deflated_count;
1277 }
1278 
1279 // Monitor cleanup on JavaThread::exit
1280 
1281 // Iterate through monitor cache and attempt to release thread's monitors
1282 class ReleaseJavaMonitorsClosure: public MonitorClosure {
1283  private:
1284   JavaThread* _thread;
1285 
1286  public:
1287   ReleaseJavaMonitorsClosure(JavaThread* thread) : _thread(thread) {}
1288   void do_monitor(ObjectMonitor* mid) {
1289     mid->complete_exit(_thread);
1290   }
1291 };
1292 
1293 // Release all inflated monitors owned by current thread.  Lightweight monitors are
1294 // ignored.  This is meant to be called during JNI thread detach which assumes
1295 // all remaining monitors are heavyweight.  All exceptions are swallowed.
1296 // Scanning the extant monitor list can be time consuming.
1297 // A simple optimization is to add a per-thread flag that indicates a thread
1298 // called jni_monitorenter() during its lifetime.
1299 //
1300 // Instead of NoSafepointVerifier it might be cheaper to
1301 // use an idiom of the form:
1302 //   auto int tmp = SafepointSynchronize::_safepoint_counter ;
1303 //   <code that must not run at safepoint>
1304 //   guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ;
1305 // Since the tests are extremely cheap we could leave them enabled
1306 // for normal product builds.
1307 
1308 void ObjectSynchronizer::release_monitors_owned_by_thread(JavaThread* current) {
1309   assert(current == JavaThread::current(), "must be current Java thread");
1310   NoSafepointVerifier nsv;
1311   ReleaseJavaMonitorsClosure rjmc(current);
1312   ObjectSynchronizer::owned_monitors_iterate(&rjmc, current);
1313   assert(!current->has_pending_exception(), "Should not be possible");
1314   current->clear_pending_exception();
1315 }
1316 
1317 const char* ObjectSynchronizer::inflate_cause_name(const InflateCause cause) {
1318   switch (cause) {
1319     case inflate_cause_vm_internal:    return "VM Internal";
1320     case inflate_cause_monitor_enter:  return "Monitor Enter";
1321     case inflate_cause_wait:           return "Monitor Wait";
1322     case inflate_cause_notify:         return "Monitor Notify";
1323     case inflate_cause_jni_enter:      return "JNI Monitor Enter";
1324     case inflate_cause_jni_exit:       return "JNI Monitor Exit";
1325     default:
1326       ShouldNotReachHere();
1327   }
1328   return "Unknown";
1329 }
1330 
1331 //------------------------------------------------------------------------------
1332 // Debugging code
1333 
1334 u_char* ObjectSynchronizer::get_gvars_addr() {
1335   return (u_char*)&GVars;
1336 }
1337 
1338 u_char* ObjectSynchronizer::get_gvars_hc_sequence_addr() {
1339   return (u_char*)&GVars.hc_sequence;
1340 }
1341 
1342 size_t ObjectSynchronizer::get_gvars_size() {
1343   return sizeof(SharedGlobals);
1344 }
1345 
1346 u_char* ObjectSynchronizer::get_gvars_stw_random_addr() {
1347   return (u_char*)&GVars.stw_random;
1348 }
1349 
1350 // Do the final audit and print of ObjectMonitor stats; must be done
1351 // by the VMThread at VM exit time.
1352 void ObjectSynchronizer::do_final_audit_and_print_stats() {
1353   assert(Thread::current()->is_VM_thread(), "sanity check");
1354 
1355   if (is_final_audit()) {  // Only do the audit once.
1356     return;
1357   }
1358   set_is_final_audit();
1359   log_info(monitorinflation)("Starting the final audit.");
1360 
1361   if (log_is_enabled(Info, monitorinflation)) {
1362     LogStreamHandle(Info, monitorinflation) ls;
1363     audit_and_print_stats(&ls, true /* on_exit */);
1364   }
1365 }
1366 
1367 // This function can be called by the MonitorDeflationThread or it can be called when
1368 // we are trying to exit the VM. The list walker functions can run in parallel with
1369 // the other list operations.
1370 // Calls to this function can be added in various places as a debugging
1371 // aid.
1372 //
1373 void ObjectSynchronizer::audit_and_print_stats(outputStream* ls, bool on_exit) {
1374   int error_cnt = 0;
1375 
1376   ls->print_cr("Checking in_use_list:");
1377   chk_in_use_list(ls, &error_cnt);
1378 
1379   if (error_cnt == 0) {
1380     ls->print_cr("No errors found in in_use_list checks.");
1381   } else {
1382     log_error(monitorinflation)("found in_use_list errors: error_cnt=%d", error_cnt);
1383   }
1384 
1385   // When exiting, only log the interesting entries at the Info level.
1386   // When called at intervals by the MonitorDeflationThread, log output
1387   // at the Trace level since there can be a lot of it.
1388   if (!on_exit && log_is_enabled(Trace, monitorinflation)) {
1389     LogStreamHandle(Trace, monitorinflation) ls_tr;
1390     log_in_use_monitor_details(&ls_tr, true /* log_all */);
1391   } else if (on_exit) {
1392     log_in_use_monitor_details(ls, false /* log_all */);
1393   }
1394 
1395   ls->flush();
1396 
1397   guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt);
1398 }
1399 
1400 // Check the in_use_list; log the results of the checks.
1401 void ObjectSynchronizer::chk_in_use_list(outputStream* out, int *error_cnt_p) {
1402   size_t l_in_use_count = _in_use_list.count();
1403   size_t l_in_use_max = _in_use_list.max();
1404   out->print_cr("count=%zu, max=%zu", l_in_use_count,
1405                 l_in_use_max);
1406 
1407   size_t ck_in_use_count = 0;
1408   MonitorList::Iterator iter = _in_use_list.iterator();
1409   while (iter.has_next()) {
1410     ObjectMonitor* mid = iter.next();
1411     chk_in_use_entry(mid, out, error_cnt_p);
1412     ck_in_use_count++;
1413   }
1414 
1415   if (l_in_use_count == ck_in_use_count) {
1416     out->print_cr("in_use_count=%zu equals ck_in_use_count=%zu",
1417                   l_in_use_count, ck_in_use_count);
1418   } else {
1419     out->print_cr("WARNING: in_use_count=%zu is not equal to "
1420                   "ck_in_use_count=%zu", l_in_use_count,
1421                   ck_in_use_count);
1422   }
1423 
1424   size_t ck_in_use_max = _in_use_list.max();
1425   if (l_in_use_max == ck_in_use_max) {
1426     out->print_cr("in_use_max=%zu equals ck_in_use_max=%zu",
1427                   l_in_use_max, ck_in_use_max);
1428   } else {
1429     out->print_cr("WARNING: in_use_max=%zu is not equal to "
1430                   "ck_in_use_max=%zu", l_in_use_max, ck_in_use_max);
1431   }
1432 }
1433 
1434 // Check an in-use monitor entry; log any errors.
1435 void ObjectSynchronizer::chk_in_use_entry(ObjectMonitor* n, outputStream* out,
1436                                           int* error_cnt_p) {
1437   if (n->owner_is_DEFLATER_MARKER()) {
1438     // This could happen when monitor deflation blocks for a safepoint.
1439     return;
1440   }
1441 
1442 
1443   if (n->metadata() == 0) {
1444     out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor must "
1445                   "have non-null _metadata (header/hash) field.", p2i(n));
1446     *error_cnt_p = *error_cnt_p + 1;
1447   }
1448 
1449   const oop obj = n->object_peek();
1450   if (obj == nullptr) {
1451     return;
1452   }
1453 
1454   const markWord mark = obj->mark();
1455   if (!mark.has_monitor()) {
1456     out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's "
1457                   "object does not think it has a monitor: obj="
1458                   INTPTR_FORMAT ", mark=" INTPTR_FORMAT, p2i(n),
1459                   p2i(obj), mark.value());
1460     *error_cnt_p = *error_cnt_p + 1;
1461     return;
1462   }
1463 
1464   ObjectMonitor* const obj_mon = read_monitor(obj, mark);
1465   if (n != obj_mon) {
1466     out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's "
1467                   "object does not refer to the same monitor: obj="
1468                   INTPTR_FORMAT ", mark=" INTPTR_FORMAT ", obj_mon="
1469                   INTPTR_FORMAT, p2i(n), p2i(obj), mark.value(), p2i(obj_mon));
1470     *error_cnt_p = *error_cnt_p + 1;
1471   }
1472 }
1473 
1474 // Log details about ObjectMonitors on the in_use_list. The 'BHL'
1475 // flags indicate why the entry is in-use, 'object' and 'object type'
1476 // indicate the associated object and its type.
1477 void ObjectSynchronizer::log_in_use_monitor_details(outputStream* out, bool log_all) {
1478   if (_in_use_list.count() > 0) {
1479     stringStream ss;
1480     out->print_cr("In-use monitor info%s:", log_all ? "" : " (eliding idle monitors)");
1481     out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
1482     out->print_cr("%18s  %s  %18s  %18s",
1483                   "monitor", "BHL", "object", "object type");
1484     out->print_cr("==================  ===  ==================  ==================");
1485 
1486     auto is_interesting = [&](ObjectMonitor* monitor) {
1487       return log_all || monitor->has_owner() || monitor->is_busy();
1488     };
1489 
1490     monitors_iterate([&](ObjectMonitor* monitor) {
1491       if (is_interesting(monitor)) {
1492         const oop obj = monitor->object_peek();
1493         const intptr_t hash = UseObjectMonitorTable ? monitor->hash() : monitor->header().hash();
1494         ResourceMark rm;
1495         out->print(INTPTR_FORMAT "  %d%d%d  " INTPTR_FORMAT "  %s", p2i(monitor),
1496                    monitor->is_busy(), hash != 0, monitor->has_owner(),
1497                    p2i(obj), obj == nullptr ? "" : obj->klass()->external_name());
1498         if (monitor->is_busy()) {
1499           out->print(" (%s)", monitor->is_busy_to_string(&ss));
1500           ss.reset();
1501         }
1502         out->cr();
1503       }
1504     });
1505   }
1506 
1507   out->flush();
1508 }
1509 
1510 ObjectMonitor* ObjectSynchronizer::get_or_insert_monitor_from_table(oop object, bool* inserted) {
1511   ObjectMonitor* monitor = get_monitor_from_table(object);
1512   if (monitor != nullptr) {
1513     *inserted = false;
1514     return monitor;
1515   }
1516 
1517   ObjectMonitor* alloced_monitor = new ObjectMonitor(object);
1518   alloced_monitor->set_anonymous_owner();
1519 
1520   // Try insert monitor
1521   monitor = add_monitor(alloced_monitor, object);
1522 
1523   *inserted = alloced_monitor == monitor;
1524   if (!*inserted) {
1525     delete alloced_monitor;
1526   }
1527 
1528   return monitor;
1529 }
1530 
1531 static void log_inflate(Thread* current, oop object, ObjectSynchronizer::InflateCause cause) {
1532   if (log_is_enabled(Trace, monitorinflation)) {
1533     ResourceMark rm(current);
1534     log_trace(monitorinflation)("inflate: object=" INTPTR_FORMAT ", mark="
1535                                 INTPTR_FORMAT ", type='%s' cause=%s", p2i(object),
1536                                 object->mark().value(), object->klass()->external_name(),
1537                                 ObjectSynchronizer::inflate_cause_name(cause));
1538   }
1539 }
1540 
1541 static void post_monitor_inflate_event(EventJavaMonitorInflate* event,
1542                                        const oop obj,
1543                                        ObjectSynchronizer::InflateCause cause) {
1544   assert(event != nullptr, "invariant");
1545   const Klass* monitor_klass = obj->klass();
1546   if (ObjectMonitor::is_jfr_excluded(monitor_klass)) {
1547     return;
1548   }
1549   event->set_monitorClass(monitor_klass);
1550   event->set_address((uintptr_t)(void*)obj);
1551   event->set_cause((u1)cause);
1552   event->commit();
1553 }
1554 
1555 ObjectMonitor* ObjectSynchronizer::get_or_insert_monitor(oop object, JavaThread* current, ObjectSynchronizer::InflateCause cause) {
1556   assert(UseObjectMonitorTable, "must be");
1557 
1558   EventJavaMonitorInflate event;
1559 
1560   bool inserted;
1561   ObjectMonitor* monitor = get_or_insert_monitor_from_table(object, &inserted);
1562 
1563   if (inserted) {
1564     log_inflate(current, object, cause);
1565     if (event.should_commit()) {
1566       post_monitor_inflate_event(&event, object, cause);
1567     }
1568 
1569     // The monitor has an anonymous owner so it is safe from async deflation.
1570     ObjectSynchronizer::_in_use_list.add(monitor);
1571   }
1572 
1573   return monitor;
1574 }
1575 
1576 // Add the hashcode to the monitor to match the object and put it in the hashtable.
1577 ObjectMonitor* ObjectSynchronizer::add_monitor(ObjectMonitor* monitor, oop obj) {
1578   assert(UseObjectMonitorTable, "must be");
1579   assert(obj == monitor->object(), "must be");
1580 
1581   intptr_t hash = obj->mark().hash();
1582   assert(hash != 0, "must be set when claiming the object monitor");
1583   monitor->set_hash(hash);
1584 
1585   return ObjectMonitorTable::monitor_put_get(monitor, obj);
1586 }
1587 
1588 void ObjectSynchronizer::remove_monitor(ObjectMonitor* monitor, oop obj) {
1589   assert(UseObjectMonitorTable, "must be");
1590   assert(monitor->object_peek() == obj, "must be, cleared objects are removed by is_dead");
1591 
1592   ObjectMonitorTable::remove_monitor_entry(monitor);
1593 }
1594 
1595 void ObjectSynchronizer::deflate_mark_word(oop obj) {
1596   assert(UseObjectMonitorTable, "must be");
1597 
1598   markWord mark = obj->mark_acquire();
1599   assert(!mark.has_no_hash(), "obj with inflated monitor must have had a hash");
1600 
1601   while (mark.has_monitor()) {
1602     const markWord new_mark = mark.clear_lock_bits().set_unlocked();
1603     mark = obj->cas_set_mark(new_mark, mark);
1604   }
1605 }
1606 
1607 void ObjectSynchronizer::create_om_table() {
1608   if (!UseObjectMonitorTable) {
1609     return;
1610   }
1611   ObjectMonitorTable::create();
1612 }
1613 
1614 class ObjectSynchronizer::LockStackInflateContendedLocks : private OopClosure {
1615  private:
1616   oop _contended_oops[LockStack::CAPACITY];
1617   int _length;
1618 
1619   void do_oop(oop* o) final {
1620     oop obj = *o;
1621     if (obj->mark_acquire().has_monitor()) {
1622       if (_length > 0 && _contended_oops[_length - 1] == obj) {
1623         // Recursive
1624         return;
1625       }
1626       _contended_oops[_length++] = obj;
1627     }
1628   }
1629 
1630   void do_oop(narrowOop* o) final {
1631     ShouldNotReachHere();
1632   }
1633 
1634  public:
1635   LockStackInflateContendedLocks() :
1636     _contended_oops(),
1637     _length(0) {};
1638 
1639   void inflate(JavaThread* current) {
1640     assert(current == JavaThread::current(), "must be");
1641     current->lock_stack().oops_do(this);
1642     for (int i = 0; i < _length; i++) {
1643       ObjectSynchronizer::
1644         inflate_fast_locked_object(_contended_oops[i], ObjectSynchronizer::inflate_cause_vm_internal, current, current);
1645     }
1646   }
1647 };
1648 
1649 void ObjectSynchronizer::ensure_lock_stack_space(JavaThread* current) {
1650   assert(current == JavaThread::current(), "must be");
1651   LockStack& lock_stack = current->lock_stack();
1652 
1653   // Make room on lock_stack
1654   if (lock_stack.is_full()) {
1655     // Inflate contended objects
1656     LockStackInflateContendedLocks().inflate(current);
1657     if (lock_stack.is_full()) {
1658       // Inflate the oldest object
1659       inflate_fast_locked_object(lock_stack.bottom(), ObjectSynchronizer::inflate_cause_vm_internal, current, current);
1660     }
1661   }
1662 }
1663 
1664 class ObjectSynchronizer::CacheSetter : StackObj {
1665   JavaThread* const _thread;
1666   BasicLock* const _lock;
1667   ObjectMonitor* _monitor;
1668 
1669   NONCOPYABLE(CacheSetter);
1670 
1671  public:
1672   CacheSetter(JavaThread* thread, BasicLock* lock) :
1673     _thread(thread),
1674     _lock(lock),
1675     _monitor(nullptr) {}
1676 
1677   ~CacheSetter() {
1678     // Only use the cache if using the table.
1679     if (UseObjectMonitorTable) {
1680       if (_monitor != nullptr) {
1681         // If the monitor is already in the BasicLock cache then it is most
1682         // likely in the thread cache, do not set it again to avoid reordering.
1683         if (_monitor != _lock->object_monitor_cache()) {
1684           _thread->om_set_monitor_cache(_monitor);
1685           _lock->set_object_monitor_cache(_monitor);
1686         }
1687       } else {
1688         _lock->clear_object_monitor_cache();
1689       }
1690     }
1691   }
1692 
1693   void set_monitor(ObjectMonitor* monitor) {
1694     assert(_monitor == nullptr, "only set once");
1695     _monitor = monitor;
1696   }
1697 
1698 };
1699 
1700 // Reads first from the BasicLock cache then from the OMCache in the current thread.
1701 // C2 fast-path may have put the monitor in the cache in the BasicLock.
1702 inline static ObjectMonitor* read_caches(JavaThread* current, BasicLock* lock, oop object) {
1703   ObjectMonitor* monitor = lock->object_monitor_cache();
1704   if (monitor == nullptr) {
1705     monitor = current->om_get_from_monitor_cache(object);
1706   }
1707   return monitor;
1708 }
1709 
1710 class ObjectSynchronizer::VerifyThreadState {
1711   bool _no_safepoint;
1712 
1713  public:
1714   VerifyThreadState(JavaThread* locking_thread, JavaThread* current) : _no_safepoint(locking_thread != current) {
1715     assert(current == Thread::current(), "must be");
1716     assert(locking_thread == current || locking_thread->is_obj_deopt_suspend(), "locking_thread may not run concurrently");
1717     if (_no_safepoint) {
1718       DEBUG_ONLY(JavaThread::current()->inc_no_safepoint_count();)
1719     }
1720   }
1721   ~VerifyThreadState() {
1722     if (_no_safepoint){
1723       DEBUG_ONLY(JavaThread::current()->dec_no_safepoint_count();)
1724     }
1725   }
1726 };
1727 
1728 inline bool ObjectSynchronizer::fast_lock_try_enter(oop obj, LockStack& lock_stack, JavaThread* current) {
1729   markWord mark = obj->mark();
1730   while (mark.is_unlocked()) {
1731     ensure_lock_stack_space(current);
1732     assert(!lock_stack.is_full(), "must have made room on the lock stack");
1733     assert(!lock_stack.contains(obj), "thread must not already hold the lock");
1734     // Try to swing into 'fast-locked' state.
1735     markWord locked_mark = mark.set_fast_locked();
1736     markWord old_mark = mark;
1737     mark = obj->cas_set_mark(locked_mark, old_mark);
1738     if (old_mark == mark) {
1739       // Successfully fast-locked, push object to lock-stack and return.
1740       lock_stack.push(obj);
1741       return true;
1742     }
1743   }
1744   return false;
1745 }
1746 
1747 bool ObjectSynchronizer::fast_lock_spin_enter(oop obj, LockStack& lock_stack, JavaThread* current, bool observed_deflation) {
1748   assert(UseObjectMonitorTable, "must be");
1749   // Will spin with exponential backoff with an accumulative O(2^spin_limit) spins.
1750   const int log_spin_limit = os::is_MP() ? FastLockingSpins : 1;
1751   const int log_min_safepoint_check_interval = 10;
1752 
1753   markWord mark = obj->mark();
1754   const auto should_spin = [&]() {
1755     if (!mark.has_monitor()) {
1756       // Spin while not inflated.
1757       return true;
1758     } else if (observed_deflation) {
1759       // Spin while monitor is being deflated.
1760       ObjectMonitor* monitor = ObjectSynchronizer::read_monitor(obj, mark);
1761       return monitor == nullptr || monitor->is_being_async_deflated();
1762     }
1763     // Else stop spinning.
1764     return false;
1765   };
1766   // Always attempt to lock once even when safepoint synchronizing.
1767   bool should_process = false;
1768   for (int i = 0; should_spin() && !should_process && i < log_spin_limit; i++) {
1769     // Spin with exponential backoff.
1770     const int total_spin_count = 1 << i;
1771     const int inner_spin_count = MIN2(1 << log_min_safepoint_check_interval, total_spin_count);
1772     const int outer_spin_count = total_spin_count / inner_spin_count;
1773     for (int outer = 0; outer < outer_spin_count; outer++) {
1774       should_process = SafepointMechanism::should_process(current);
1775       if (should_process) {
1776         // Stop spinning for safepoint.
1777         break;
1778       }
1779       for (int inner = 1; inner < inner_spin_count; inner++) {
1780         SpinPause();
1781       }
1782     }
1783 
1784     if (fast_lock_try_enter(obj, lock_stack, current)) return true;
1785   }
1786   return false;
1787 }
1788 
1789 void ObjectSynchronizer::enter_for(Handle obj, BasicLock* lock, JavaThread* locking_thread) {
1790   // When called with locking_thread != Thread::current() some mechanism must synchronize
1791   // the locking_thread with respect to the current thread. Currently only used when
1792   // deoptimizing and re-locking locks. See Deoptimization::relock_objects
1793   assert(locking_thread == Thread::current() || locking_thread->is_obj_deopt_suspend(), "must be");
1794 
1795   assert(!UseObjectMonitorTable || lock->object_monitor_cache() == nullptr, "must be cleared");
1796   JavaThread* current = JavaThread::current();
1797   VerifyThreadState vts(locking_thread, current);
1798 
1799   if (obj->klass()->is_value_based()) {
1800     ObjectSynchronizer::handle_sync_on_value_based_class(obj, locking_thread);
1801   }
1802 
1803   LockStack& lock_stack = locking_thread->lock_stack();
1804 
1805   ObjectMonitor* monitor = nullptr;
1806   if (lock_stack.contains(obj())) {
1807     monitor = inflate_fast_locked_object(obj(), ObjectSynchronizer::inflate_cause_monitor_enter, locking_thread, current);
1808     bool entered = monitor->enter_for(locking_thread);
1809     assert(entered, "recursive ObjectMonitor::enter_for must succeed");
1810   } else {
1811     do {
1812       // It is assumed that enter_for must enter on an object without contention.
1813       monitor = inflate_and_enter(obj(), lock, ObjectSynchronizer::inflate_cause_monitor_enter, locking_thread, current);
1814       // But there may still be a race with deflation.
1815     } while (monitor == nullptr);
1816   }
1817 
1818   assert(monitor != nullptr, "ObjectSynchronizer::enter_for must succeed");
1819   assert(!UseObjectMonitorTable || lock->object_monitor_cache() == nullptr, "unused. already cleared");
1820 }
1821 
1822 void ObjectSynchronizer::enter(Handle obj, BasicLock* lock, JavaThread* current) {
1823   assert(current == JavaThread::current(), "must be");
1824 
1825   if (obj->klass()->is_value_based()) {
1826     ObjectSynchronizer::handle_sync_on_value_based_class(obj, current);
1827   }
1828 
1829   CacheSetter cache_setter(current, lock);
1830 
1831   // Used when deflation is observed. Progress here requires progress
1832   // from the deflator. After observing that the deflator is not
1833   // making progress (after two yields), switch to sleeping.
1834   SpinYield spin_yield(0, 2);
1835   bool observed_deflation = false;
1836 
1837   LockStack& lock_stack = current->lock_stack();
1838 
1839   if (!lock_stack.is_full() && lock_stack.try_recursive_enter(obj())) {
1840     // Recursively fast locked
1841     return;
1842   }
1843 
1844   if (lock_stack.contains(obj())) {
1845     ObjectMonitor* monitor = inflate_fast_locked_object(obj(), ObjectSynchronizer::inflate_cause_monitor_enter, current, current);
1846     bool entered = monitor->enter(current);
1847     assert(entered, "recursive ObjectMonitor::enter must succeed");
1848     cache_setter.set_monitor(monitor);
1849     return;
1850   }
1851 
1852   while (true) {
1853     // Fast-locking does not use the 'lock' argument.
1854     // Fast-lock spinning to avoid inflating for short critical sections.
1855     // The goal is to only inflate when the extra cost of using ObjectMonitors
1856     // is worth it.
1857     // If deflation has been observed we also spin while deflation is ongoing.
1858     if (fast_lock_try_enter(obj(), lock_stack, current)) {
1859       return;
1860     } else if (UseObjectMonitorTable && fast_lock_spin_enter(obj(), lock_stack, current, observed_deflation)) {
1861       return;
1862     }
1863 
1864     if (observed_deflation) {
1865       spin_yield.wait();
1866     }
1867 
1868     ObjectMonitor* monitor = inflate_and_enter(obj(), lock, ObjectSynchronizer::inflate_cause_monitor_enter, current, current);
1869     if (monitor != nullptr) {
1870       cache_setter.set_monitor(monitor);
1871       return;
1872     }
1873 
1874     // If inflate_and_enter returns nullptr it is because a deflated monitor
1875     // was encountered. Fallback to fast locking. The deflater is responsible
1876     // for clearing out the monitor and transitioning the markWord back to
1877     // fast locking.
1878     observed_deflation = true;
1879   }
1880 }
1881 
1882 void ObjectSynchronizer::exit(oop object, BasicLock* lock, JavaThread* current) {
1883   assert(current == Thread::current(), "must be");
1884 
1885   markWord mark = object->mark();
1886   assert(!mark.is_unlocked(), "must be");
1887 
1888   LockStack& lock_stack = current->lock_stack();
1889   if (mark.is_fast_locked()) {
1890     if (lock_stack.try_recursive_exit(object)) {
1891       // This is a recursive exit which succeeded
1892       return;
1893     }
1894     if (lock_stack.is_recursive(object)) {
1895       // Must inflate recursive locks if try_recursive_exit fails
1896       // This happens for un-structured unlocks, could potentially
1897       // fix try_recursive_exit to handle these.
1898       inflate_fast_locked_object(object, ObjectSynchronizer::inflate_cause_vm_internal, current, current);
1899     }
1900   }
1901 
1902   while (mark.is_fast_locked()) {
1903     markWord unlocked_mark = mark.set_unlocked();
1904     markWord old_mark = mark;
1905     mark = object->cas_set_mark(unlocked_mark, old_mark);
1906     if (old_mark == mark) {
1907       // CAS successful, remove from lock_stack
1908       size_t recursion = lock_stack.remove(object) - 1;
1909       assert(recursion == 0, "Should not have unlocked here");
1910       return;
1911     }
1912   }
1913 
1914   assert(mark.has_monitor(), "must be");
1915   // The monitor exists
1916   ObjectMonitor* monitor;
1917   if (UseObjectMonitorTable) {
1918     monitor = read_caches(current, lock, object);
1919     if (monitor == nullptr) {
1920       monitor = get_monitor_from_table(object);
1921     }
1922   } else {
1923     monitor = ObjectSynchronizer::read_monitor(mark);
1924   }
1925   if (monitor->has_anonymous_owner()) {
1926     assert(current->lock_stack().contains(object), "current must have object on its lock stack");
1927     monitor->set_owner_from_anonymous(current);
1928     monitor->set_recursions(current->lock_stack().remove(object) - 1);
1929   }
1930 
1931   monitor->exit(current);
1932 }
1933 
1934 // ObjectSynchronizer::inflate_locked_or_imse is used to get an
1935 // inflated ObjectMonitor* from contexts which require that, such as
1936 // notify/wait and jni_exit. Fast locking keeps the invariant that it
1937 // only inflates if it is already locked by the current thread or the current
1938 // thread is in the process of entering. To maintain this invariant we need to
1939 // throw a java.lang.IllegalMonitorStateException before inflating if the
1940 // current thread is not the owner.
1941 ObjectMonitor* ObjectSynchronizer::inflate_locked_or_imse(oop obj, ObjectSynchronizer::InflateCause cause, TRAPS) {
1942   JavaThread* current = THREAD;
1943 
1944   for (;;) {
1945     markWord mark = obj->mark_acquire();
1946     if (mark.is_unlocked()) {
1947       // No lock, IMSE.
1948       THROW_MSG_(vmSymbols::java_lang_IllegalMonitorStateException(),
1949                  "current thread is not owner", nullptr);
1950     }
1951 
1952     if (mark.is_fast_locked()) {
1953       if (!current->lock_stack().contains(obj)) {
1954         // Fast locked by other thread, IMSE.
1955         THROW_MSG_(vmSymbols::java_lang_IllegalMonitorStateException(),
1956                    "current thread is not owner", nullptr);
1957       } else {
1958         // Current thread owns the lock, must inflate
1959         return inflate_fast_locked_object(obj, cause, current, current);
1960       }
1961     }
1962 
1963     assert(mark.has_monitor(), "must be");
1964     ObjectMonitor* monitor = ObjectSynchronizer::read_monitor(obj, mark);
1965     if (monitor != nullptr) {
1966       if (monitor->has_anonymous_owner()) {
1967         LockStack& lock_stack = current->lock_stack();
1968         if (lock_stack.contains(obj)) {
1969           // Current thread owns the lock but someone else inflated it.
1970           // Fix owner and pop lock stack.
1971           monitor->set_owner_from_anonymous(current);
1972           monitor->set_recursions(lock_stack.remove(obj) - 1);
1973         } else {
1974           // Fast locked (and inflated) by other thread, or deflation in progress, IMSE.
1975           THROW_MSG_(vmSymbols::java_lang_IllegalMonitorStateException(),
1976                      "current thread is not owner", nullptr);
1977         }
1978       }
1979       return monitor;
1980     }
1981   }
1982 }
1983 
1984 ObjectMonitor* ObjectSynchronizer::inflate_into_object_header(oop object, ObjectSynchronizer::InflateCause cause, JavaThread* locking_thread, Thread* current) {
1985 
1986   // The JavaThread* locking parameter requires that the locking_thread == JavaThread::current,
1987   // or is suspended throughout the call by some other mechanism.
1988   // Even with fast locking the thread might be nullptr when called from a non
1989   // JavaThread. (As may still be the case from FastHashCode). However it is only
1990   // important for the correctness of the fast locking algorithm that the thread
1991   // is set when called from ObjectSynchronizer::enter from the owning thread,
1992   // ObjectSynchronizer::enter_for from any thread, or ObjectSynchronizer::exit.
1993   EventJavaMonitorInflate event;
1994 
1995   for (;;) {
1996     const markWord mark = object->mark_acquire();
1997 
1998     // The mark can be in one of the following states:
1999     // *  inflated     - Just return if using stack-locking.
2000     //                   If using fast-locking and the ObjectMonitor owner
2001     //                   is anonymous and the locking_thread owns the
2002     //                   object lock, then we make the locking_thread
2003     //                   the ObjectMonitor owner and remove the lock from
2004     //                   the locking_thread's lock stack.
2005     // *  fast-locked  - Coerce it to inflated from fast-locked.
2006     // *  unlocked     - Aggressively inflate the object.
2007 
2008     // CASE: inflated
2009     if (mark.has_monitor()) {
2010       ObjectMonitor* inf = mark.monitor();
2011       markWord dmw = inf->header();
2012       assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value());
2013       if (inf->has_anonymous_owner() &&
2014           locking_thread != nullptr && locking_thread->lock_stack().contains(object)) {
2015         inf->set_owner_from_anonymous(locking_thread);
2016         size_t removed = locking_thread->lock_stack().remove(object);
2017         inf->set_recursions(removed - 1);
2018       }
2019       return inf;
2020     }
2021 
2022     // CASE: fast-locked
2023     // Could be fast-locked either by the locking_thread or by some other thread.
2024     //
2025     // Note that we allocate the ObjectMonitor speculatively, _before_
2026     // attempting to set the object's mark to the new ObjectMonitor. If
2027     // the locking_thread owns the monitor, then we set the ObjectMonitor's
2028     // owner to the locking_thread. Otherwise, we set the ObjectMonitor's owner
2029     // to anonymous. If we lose the race to set the object's mark to the
2030     // new ObjectMonitor, then we just delete it and loop around again.
2031     //
2032     if (mark.is_fast_locked()) {
2033       ObjectMonitor* monitor = new ObjectMonitor(object);
2034       monitor->set_header(mark.set_unlocked());
2035       bool own = locking_thread != nullptr && locking_thread->lock_stack().contains(object);
2036       if (own) {
2037         // Owned by locking_thread.
2038         monitor->set_owner(locking_thread);
2039       } else {
2040         // Owned by somebody else.
2041         monitor->set_anonymous_owner();
2042       }
2043       markWord monitor_mark = markWord::encode(monitor);
2044       markWord old_mark = object->cas_set_mark(monitor_mark, mark);
2045       if (old_mark == mark) {
2046         // Success! Return inflated monitor.
2047         if (own) {
2048           size_t removed = locking_thread->lock_stack().remove(object);
2049           monitor->set_recursions(removed - 1);
2050         }
2051         // Once the ObjectMonitor is configured and object is associated
2052         // with the ObjectMonitor, it is safe to allow async deflation:
2053         ObjectSynchronizer::_in_use_list.add(monitor);
2054 
2055         log_inflate(current, object, cause);
2056         if (event.should_commit()) {
2057           post_monitor_inflate_event(&event, object, cause);
2058         }
2059         return monitor;
2060       } else {
2061         delete monitor;
2062         continue;  // Interference -- just retry
2063       }
2064     }
2065 
2066     // CASE: unlocked
2067     // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
2068     // If we know we're inflating for entry it's better to inflate by swinging a
2069     // pre-locked ObjectMonitor pointer into the object header.   A successful
2070     // CAS inflates the object *and* confers ownership to the inflating thread.
2071     // In the current implementation we use a 2-step mechanism where we CAS()
2072     // to inflate and then CAS() again to try to swing _owner from null to current.
2073     // An inflateTry() method that we could call from enter() would be useful.
2074 
2075     assert(mark.is_unlocked(), "invariant: header=" INTPTR_FORMAT, mark.value());
2076     ObjectMonitor* m = new ObjectMonitor(object);
2077     // prepare m for installation - set monitor to initial state
2078     m->set_header(mark);
2079 
2080     if (object->cas_set_mark(markWord::encode(m), mark) != mark) {
2081       delete m;
2082       m = nullptr;
2083       continue;
2084       // interference - the markword changed - just retry.
2085       // The state-transitions are one-way, so there's no chance of
2086       // live-lock -- "Inflated" is an absorbing state.
2087     }
2088 
2089     // Once the ObjectMonitor is configured and object is associated
2090     // with the ObjectMonitor, it is safe to allow async deflation:
2091     ObjectSynchronizer::_in_use_list.add(m);
2092 
2093     log_inflate(current, object, cause);
2094     if (event.should_commit()) {
2095       post_monitor_inflate_event(&event, object, cause);
2096     }
2097     return m;
2098   }
2099 }
2100 
2101 ObjectMonitor* ObjectSynchronizer::inflate_fast_locked_object(oop object, ObjectSynchronizer::InflateCause cause, JavaThread* locking_thread, JavaThread* current) {
2102   VerifyThreadState vts(locking_thread, current);
2103   assert(locking_thread->lock_stack().contains(object), "locking_thread must have object on its lock stack");
2104 
2105   ObjectMonitor* monitor;
2106 
2107   if (!UseObjectMonitorTable) {
2108     return inflate_into_object_header(object, cause, locking_thread, current);
2109   }
2110 
2111   // Inflating requires a hash code
2112   ObjectSynchronizer::FastHashCode(current, object);
2113 
2114   markWord mark = object->mark_acquire();
2115   assert(!mark.is_unlocked(), "Cannot be unlocked");
2116 
2117   for (;;) {
2118     // Fetch the monitor from the table
2119     monitor = get_or_insert_monitor(object, current, cause);
2120 
2121     // ObjectMonitors are always inserted as anonymously owned, this thread is
2122     // the current holder of the monitor. So unless the entry is stale and
2123     // contains a deflating monitor it must be anonymously owned.
2124     if (monitor->has_anonymous_owner()) {
2125       // The monitor must be anonymously owned if it was added
2126       assert(monitor == get_monitor_from_table(object), "The monitor must be found");
2127       // New fresh monitor
2128       break;
2129     }
2130 
2131     // If the monitor was not anonymously owned then we got a deflating monitor
2132     // from the table. We need to let the deflator make progress and remove this
2133     // entry before we are allowed to add a new one.
2134     os::naked_yield();
2135     assert(monitor->is_being_async_deflated(), "Should be the reason");
2136   }
2137 
2138   // Set the mark word; loop to handle concurrent updates to other parts of the mark word
2139   while (mark.is_fast_locked()) {
2140     mark = object->cas_set_mark(mark.set_has_monitor(), mark);
2141   }
2142 
2143   // Indicate that the monitor now has a known owner
2144   monitor->set_owner_from_anonymous(locking_thread);
2145 
2146   // Remove the entry from the thread's lock stack
2147   monitor->set_recursions(locking_thread->lock_stack().remove(object) - 1);
2148 
2149   if (locking_thread == current) {
2150     // Only change the thread local state of the current thread.
2151     locking_thread->om_set_monitor_cache(monitor);
2152   }
2153 
2154   return monitor;
2155 }
2156 
2157 ObjectMonitor* ObjectSynchronizer::inflate_and_enter(oop object, BasicLock* lock, ObjectSynchronizer::InflateCause cause, JavaThread* locking_thread, JavaThread* current) {
2158   VerifyThreadState vts(locking_thread, current);
2159 
2160   // Note: In some paths (deoptimization) the 'current' thread inflates and
2161   // enters the lock on behalf of the 'locking_thread' thread.
2162 
2163   ObjectMonitor* monitor = nullptr;
2164 
2165   if (!UseObjectMonitorTable) {
2166     // Do the old inflate and enter.
2167     monitor = inflate_into_object_header(object, cause, locking_thread, current);
2168 
2169     bool entered;
2170     if (locking_thread == current) {
2171       entered = monitor->enter(locking_thread);
2172     } else {
2173       entered = monitor->enter_for(locking_thread);
2174     }
2175 
2176     // enter returns false for deflation found.
2177     return entered ? monitor : nullptr;
2178   }
2179 
2180   NoSafepointVerifier nsv;
2181 
2182   // Try to get the monitor from the thread-local cache.
2183   // There's no need to use the cache if we are locking
2184   // on behalf of another thread.
2185   if (current == locking_thread) {
2186     monitor = read_caches(current, lock, object);
2187   }
2188 
2189   // Get or create the monitor
2190   if (monitor == nullptr) {
2191     // Lightweight monitors require that hash codes are installed first
2192     ObjectSynchronizer::FastHashCode(locking_thread, object);
2193     monitor = get_or_insert_monitor(object, current, cause);
2194   }
2195 
2196   if (monitor->try_enter(locking_thread)) {
2197     return monitor;
2198   }
2199 
2200   // Holds is_being_async_deflated() stable throughout this function.
2201   ObjectMonitorContentionMark contention_mark(monitor);
2202 
2203   /// First handle the case where the monitor from the table is deflated
2204   if (monitor->is_being_async_deflated()) {
2205     // The MonitorDeflation thread is deflating the monitor. The locking thread
2206     // must spin until further progress has been made.
2207 
2208     // Clear the BasicLock cache as it may contain this monitor.
2209     lock->clear_object_monitor_cache();
2210 
2211     const markWord mark = object->mark_acquire();
2212 
2213     if (mark.has_monitor()) {
2214       // Waiting on the deflation thread to remove the deflated monitor from the table.
2215       os::naked_yield();
2216 
2217     } else if (mark.is_fast_locked()) {
2218       // Some other thread managed to fast-lock the lock, or this is a
2219       // recursive lock from the same thread; yield for the deflation
2220       // thread to remove the deflated monitor from the table.
2221       os::naked_yield();
2222 
2223     } else {
2224       assert(mark.is_unlocked(), "Implied");
2225       // Retry immediately
2226     }
2227 
2228     // Retry
2229     return nullptr;
2230   }
2231 
2232   for (;;) {
2233     const markWord mark = object->mark_acquire();
2234     // The mark can be in one of the following states:
2235     // *  inflated     - If the ObjectMonitor owner is anonymous
2236     //                   and the locking_thread owns the object
2237     //                   lock, then we make the locking_thread
2238     //                   the ObjectMonitor owner and remove the
2239     //                   lock from the locking_thread's lock stack.
2240     // *  fast-locked  - Coerce it to inflated from fast-locked.
2241     // *  neutral      - Inflate the object. Successful CAS is locked
2242 
2243     // CASE: inflated
2244     if (mark.has_monitor()) {
2245       LockStack& lock_stack = locking_thread->lock_stack();
2246       if (monitor->has_anonymous_owner() && lock_stack.contains(object)) {
2247         // The lock is fast-locked by the locking thread,
2248         // convert it to a held monitor with a known owner.
2249         monitor->set_owner_from_anonymous(locking_thread);
2250         monitor->set_recursions(lock_stack.remove(object) - 1);
2251       }
2252 
2253       break; // Success
2254     }
2255 
2256     // CASE: fast-locked
2257     // Could be fast-locked either by locking_thread or by some other thread.
2258     //
2259     if (mark.is_fast_locked()) {
2260       markWord old_mark = object->cas_set_mark(mark.set_has_monitor(), mark);
2261       if (old_mark != mark) {
2262         // CAS failed
2263         continue;
2264       }
2265 
2266       // Success! Return inflated monitor.
2267       LockStack& lock_stack = locking_thread->lock_stack();
2268       if (lock_stack.contains(object)) {
2269         // The lock is fast-locked by the locking thread,
2270         // convert it to a held monitor with a known owner.
2271         monitor->set_owner_from_anonymous(locking_thread);
2272         monitor->set_recursions(lock_stack.remove(object) - 1);
2273       }
2274 
2275       break; // Success
2276     }
2277 
2278     // CASE: neutral (unlocked)
2279 
2280     // Catch if the object's header is not neutral (not locked and
2281     // not marked is what we care about here).
2282     assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value());
2283     markWord old_mark = object->cas_set_mark(mark.set_has_monitor(), mark);
2284     if (old_mark != mark) {
2285       // CAS failed
2286       continue;
2287     }
2288 
2289     // Transitioned from unlocked to monitor means locking_thread owns the lock.
2290     monitor->set_owner_from_anonymous(locking_thread);
2291 
2292     return monitor;
2293   }
2294 
2295   if (current == locking_thread) {
2296     // One round of spinning
2297     if (monitor->spin_enter(locking_thread)) {
2298       return monitor;
2299     }
2300 
2301     // Monitor is contended, take the time before entering to fix the lock stack.
2302     LockStackInflateContendedLocks().inflate(current);
2303   }
2304 
2305   // enter can block for safepoints; clear the unhandled object oop
2306   PauseNoSafepointVerifier pnsv(&nsv);
2307   object = nullptr;
2308 
2309   if (current == locking_thread) {
2310     monitor->enter_with_contention_mark(locking_thread, contention_mark);
2311   } else {
2312     monitor->enter_for_with_contention_mark(locking_thread, contention_mark);
2313   }
2314 
2315   return monitor;
2316 }
2317 
2318 void ObjectSynchronizer::deflate_monitor(oop obj, ObjectMonitor* monitor) {
2319   if (obj != nullptr) {
2320     deflate_mark_word(obj);
2321     remove_monitor(monitor, obj);
2322   }
2323 }
2324 
2325 ObjectMonitor* ObjectSynchronizer::get_monitor_from_table(oop obj) {
2326   assert(UseObjectMonitorTable, "must be");
2327   return ObjectMonitorTable::monitor_get(obj);
2328 }
2329 
2330 ObjectMonitor* ObjectSynchronizer::read_monitor(markWord mark) {
2331   return mark.monitor();
2332 }
2333 
2334 ObjectMonitor* ObjectSynchronizer::read_monitor(oop obj) {
2335   return ObjectSynchronizer::read_monitor(obj, obj->mark());
2336 }
2337 
2338 ObjectMonitor* ObjectSynchronizer::read_monitor(oop obj, markWord mark) {
2339   if (!UseObjectMonitorTable) {
2340     return read_monitor(mark);
2341   } else {
2342     return ObjectSynchronizer::get_monitor_from_table(obj);
2343   }
2344 }
2345 
2346 bool ObjectSynchronizer::quick_enter_internal(oop obj, BasicLock* lock, JavaThread* current) {
2347   assert(current->thread_state() == _thread_in_Java, "must be");
2348   assert(obj != nullptr, "must be");
2349   NoSafepointVerifier nsv;
2350 
2351   LockStack& lock_stack = current->lock_stack();
2352   if (lock_stack.is_full()) {
2353     // Always go into runtime if the lock stack is full.
2354     return false;
2355   }
2356 
2357   const markWord mark = obj->mark();
2358 
2359 #ifndef _LP64
2360   // Only for 32bit which has limited support for fast locking outside the runtime.
2361   if (lock_stack.try_recursive_enter(obj)) {
2362     // Recursive lock successful.
2363     return true;
2364   }
2365 
2366   if (mark.is_unlocked()) {
2367     markWord locked_mark = mark.set_fast_locked();
2368     if (obj->cas_set_mark(locked_mark, mark) == mark) {
2369       // Successfully fast-locked, push object to lock-stack and return.
2370       lock_stack.push(obj);
2371       return true;
2372     }
2373   }
2374 #endif
2375 
2376   if (mark.has_monitor()) {
2377     ObjectMonitor* monitor;
2378     if (UseObjectMonitorTable) {
2379       monitor = read_caches(current, lock, obj);
2380     } else {
2381       monitor = ObjectSynchronizer::read_monitor(mark);
2382     }
2383 
2384     if (monitor == nullptr) {
2385       // Take the slow-path on a cache miss.
2386       return false;
2387     }
2388 
2389     if (UseObjectMonitorTable) {
2390       // Set the monitor regardless of success.
2391       // Either we successfully lock on the monitor, or we retry with the
2392       // monitor in the slow path. If the monitor gets deflated, it will be
2393       // cleared, either by the CacheSetter if we fast lock in enter or in
2394       // inflate_and_enter when we see that the monitor is deflated.
2395       lock->set_object_monitor_cache(monitor);
2396     }
2397 
2398     if (monitor->spin_enter(current)) {
2399       return true;
2400     }
2401   }
2402 
2403   // Slow-path.
2404   return false;
2405 }
2406 
2407 bool ObjectSynchronizer::quick_enter(oop obj, BasicLock* lock, JavaThread* current) {
2408   assert(current->thread_state() == _thread_in_Java, "invariant");
2409   NoSafepointVerifier nsv;
2410   if (obj == nullptr) return false;       // Need to throw NPE
2411 
2412   if (obj->klass()->is_value_based()) {
2413     return false;
2414   }
2415 
2416   return ObjectSynchronizer::quick_enter_internal(obj, lock, current);
2417 }